DEV Community

yaellevy
yaellevy

Posted on • Edited on

Pytest & unit test in python

Session 11: Testing with PyTest
useful links:
Testing Demo
Testing with Pytest
what we learned:
testing with pytest
test methods
testing demo tools in Python
AUT-application under test
Regression test
doctest
unit test
pytest
pytest run doctest
test coverage
pytest setup
examples test
expected exception
change text
pytest missing exception
exception raised
exercise-test exceptions
multiple failures
selective running of test functions
stop on the first failure
examples:

Image description
_**import unittest
Now to make our class declaration:
class TestingClass(unittest.TestCase):

Inside the class add our first function:
def test_first(self):
test_var = 9 + 1
self.assertEqual(11,test_var)**_
self.assertEqual is a method given by the previously inherited class (unittest.TestCase). This method tests if the 2 variables are equally of the same value.

Adding our test runner. This is what makes our unit test run:
unittest.main()
This is what the completed code should look like:

The above code demonstrates testing if 9 + 1 is equal to 11. If you know any basic math you should know that 9+1 = 10. Hence this test case would fail.

_Output:

As you should have already guessed. Failure!

The fix is simple. Modify the code to:
test_var = 9 + 2
Output:

Testing Outside Functions
For testing outside of functions, the previous example might not be realistic. Let’s replace the test_var values to now come from a function. We will add a functional declaration to the top of our file.
def add(a,b):
return a + b
This function adds 2 numbers together. Replace 9 + 2 with the function call add(9,2) and then run your code.

Top comments (0)