Testing demo: pytest without classes


In the previous example we used a test-class to write our tests, but in reality in many cases we don't need the classes. We could just as well write plain test-functions as in this example.

Test-functions without a class around them are easier to write and understand and they are a lot simplert to graps. So unless you really need the features a class can provide I'd recommend you use functions only. After all our test code should be a lot more simple than our application code.


examples/testing-demo/test_with_pytest.py
import mymath

def test_math():
    assert mymath.add(2, 2) == 4

def test_more_math():
    assert mymath.add(3, 3) == 6

============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-5.1.1, py-1.8.0, pluggy-0.13.0
rootdir: /home/gabor/work/slides/python/examples/testing-demo
plugins: flake8-1.0.4
collected 2 items

test_with_pytest.py .F                                                   [100%]

=================================== FAILURES ===================================
________________________________ test_more_math ________________________________

    def test_more_math():
>       assert mymath.add(3, 3) == 6
E       assert 9 == 6
E        +  where 9 = <function add at 0x7f36e78db0d0>(3, 3)
E        +    where <function add at 0x7f36e78db0d0> = mymath.add

test_with_pytest.py:7: AssertionError
========================= 1 failed, 1 passed in 0.02s ==========================


$ pytest test_with_pytest.py
$ echo $?
1


> pytest test_with_pytest.py
> echo %ERRORLEVEL%
1