Wednesday, 10 October 2018

Comparison in Python assert statement

After checking few python open source projects I found examples where same function have test cases with assert <> and assert <> is True.

And I cannot find answer about best practices of using assert statement with and without full condition.

For example function

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

can be tested in such way

assert is_even(6) is True 
assert is_even(6) == True

but also it can be tested like

assert is_even(6)

And here I see problem cause if function is_even will be changed on

def is_even(number):
    if number % 2 == 0:
        return <>
    else:
        return False

Where <> can be changed on any number(except 0) or non empty string - last test will pass. But this will be another function.

I saw this and this SO question about assert usage but seems they don't fully cover my question.

From another side PEP 8 specification have such example

  • Don't compare boolean values to True or False using ==

    Yes:   if greeting:
    No:    if greeting == True:
    Worse: if greeting is True:
    
    

But is it also about assert usage?



from Comparison in Python assert statement

1 comment: