Tutorial Introduction to PyTest

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Install PyTest with …

pip install pytest

Run it by …

py.test

You should get result saying …

collected 0 items

because it did not find any test in the directory.

Create a Class to Test

Suppose we have this GreetWidget class with method “greet” that we want to test…

Then create the test class with a test method. They both should start with “test” so PyTest can find it…

PyTest will automatically run test_greet() in TestGreetWidget because they both start with “test”. Before running test_greet, it will run “setup” class method (you don’t have to name it this) because this method is decorated with a pytest.fixture with autouse set to True.

This time, we run with -s (show statements) and -v (verbose) flags …

py.test -s -v 

and get …

It found one test and it always passes. Because we did not have any assert. You can also run a particular test file like this …

py.test test_greet_widget.py

Let’s add one assert statement now…

PyTest fixtures

The method of the fixture can have a yield statement. The statements after the yield will run after the test. The statements before the yield will run before the test.


Related Posts

Tags

Share This