Search code examples
pythonpython-3.xpytestassert

Python assert with conditions


I ran into a unique issue while writing test cases with pytest If we write a test as:-

a = 4
b = 5
c = 4

def match_test():
    assert a == (b or c) # (fails with `AssertionError`)

Now if we do the same using constants

def match_test():
    assert a == (4 or 5)  (passes)

But passes if we breakdown the assert as:-

def match_test():
    assert a == b or a == c # (passed)

The same happens with strings, curious if anyone can explain why this unique behaviour, PS I am new to Pytest and assert statements.


Solution

  • They are not the same. (4 or 5) is evaluated to 4, so

    assert a == (4 or 5)
    

    passes since 4 == 4.

    (b or c) is evaluated to 5 (b is 5) so

    assert a == (b or c)
    

    fails since 4 != 5. assert a == (c or b) will pass.

    assert a == b or a == c
    

    pass because the assert evaluates the entire expression, True or False is True.