This article covers the concept of Unit Testing in Python. Testing in Python is a huge topic and can come with a lot of complexity, but it doesn't need to be hard. You can get started creating simple tests for your application in a few easy steps and then build on it from there.
Here, You'll learn about the tools available to write and execute tests, check your application's performance, and even look for security issues.
pytest supports execution of unittest test cases. The real advantage of pytest comes by writing pytest test cases. pytest test cases are a series of functions in a Python file starting with the name test_.
pytest has some other great features:
1. Support for the built-in assert statement instead of using special self.assert*() methods
2. Support for filtering for test cases
3. Ability to rerun from the last failing test
4. An ecosystem of hundreds of plugins to extend the functionality
Running Your Tests From Visual Studio Code
If you're using the Microsoft Visual Studio Code IDE, support for unittest, nose, and pytest execution is built into the Python plugin.
If you have the Python plugin installed, you can set up the configuration of your tests by opening the Command Palette with Ctrl+Shift+P and typing "Python test".
How to Use unittest and Flask
Flask requires that the app be imported and then set in test mode. You can instantiate a test client and use the test client to make requests to any routes in your application.
All of the test client instantiation is done in the setUp method of your test case. In the following example, my_app is the name of the application. Don’t worry if you don’t know what setUp does. You’ll learn about that in the More Advanced Testing Scenarios section.
The code within your test file should look like this:
my_app.app.testing = True
self.app = my_app.app.test_client()
result = self.app.get('/')
# Make your assertions
You can then execute the test cases using the python -m unittest discover command.