From the course: Testing Python Data Science Code
pytest overview - Python Tutorial
From the course: Testing Python Data Science Code
pytest overview
- [Instructor] We are going to use pytest throughout this course. Pytest is an external library. You will need to install it, but it is the testing library in the Python world these days, and it has many features and extensions you can use. Let's take a look at a simple test case. Let's assume you have a scale function which scales several values inside a NumPy array. And now we can write our test. We are going to write test_scale inside test_transformers. Pytest is a discovery-based testing framework. It will look for all the files that start with test_ and ends with a py. And inside we look at all function that starts with test and run them. In our example, we have test_scale. We create an array and then an output, calculate the expected, and we use numpy.allclose to make sure that the expected is close enough to the output. If you're working with Visual Studio Code, you need to configure a test runner. You can do it from the View menu in the command palette. There is Python: Configure Tests. And you need to tell it to use pytest and from the root directory. Once you have that, Visual Studio Code will be able to use pytest to run the tests. If it's the first time you're running the test, you're going to see a small triangle here. Otherwise, you're going to see this button, which you can click on, and then it is going to run the test. And now we moved to the testing pane, and you can see here that our test is fine. Another way to run the test is from the command line. It is important to know how to run the test from the command line, since this is what the CI, or the continuous integration system, is going to do. So python -m pytest, and I'm going to add a -v flag to show the tests as they are being processed. And we see that our test is passing.