pytest-check
pytest-check copied to clipboard
Create single method to assert value and type (e.g. float != Decimal)
Hi Brian (et al.) 👋
I'm a big fan of this package, particularly when doing a lot of asserts when converting a large dict to a non primitive type/class instance. I thought about creating a PR, but thought this would be worth a discussion. I'm trying to assert that a value has been correctly cast to Decimal in a single check.
All example tests below assume the following imports:
from decimal import Decimal
import pytest_check as check
Some examples that illustrate the paradigm with the currently available options
Test 1 — This test passes, but does not check if the type is correct.
def test__use__check_equal():
float_input = 1.25
decimal_value = Decimal(float_input)
check.equal(float_input, decimal_value) # Passes
Test 2 — This test passes, but requires 2 checks, which is cumbersome when you are converting a lot of values
def test__use__check_equal__and__is_instance():
float_input = 1.25
decimal_value = Decimal(float_input)
check.equal(float_input, decimal_value) # Passes
check.is_instance(decimal_value, Decimal) # Passes
Test 3 — This (understandably) fails with the message assert Decimal('1.25') is Decimal('1.25')
def test__use__check_is_():
float_input = 1.25
decimal_value = Decimal(float_input)
check.is_(decimal_value, Decimal(1.25)) # Fails
This is my attempt at a proposed addition. Not great, but figured it might get the conversation rolling.
A passing test...
def test__use__check_equal_with_type__show_passing_example():
float_input = 1.25
decimal_value = Decimal(float_input)
check.equal_with_type(decimal_value, Decimal(1.25)) # Passes
A failing test...
def test__use__check_equal_with_type__show_failing_example():
float_input = 1.25
decimal_value = Decimal(float_input)
check.equal_with_type(decimal_value, 1.25) # Fails
Implementation might look something like
@check_func
def equal_with_type(a, b, msg=""):
assert a == b and type(a) is type(b), msg