Unit tests using PyTest (with PyCharm)

purpose

There are a lot of articles on the Internet introducing Pytest, but they are seldom combined with the actual development, mostly simple demo. Here’s how to use it in conjunction with a real project.

The main content

  • Create a normal project
  • Add a PyTest dependency
  • Create the test directory
  • Perform the test
  • Combining with the PyCharm
  • reference

Create a normal project

Create a project root directory “pytest-demo”

Add project files with the following directory structure


pytest-demo

  • demo

    • \_\_init\_\_.py

      • utils

        • \_\_init\_\_.py
        • math_helper.py

Math_helper. Py is as follows

Class MathHelper(object): def Addition (self, first, second): """ If not isinstance(first, (int, float)): Raise valueError ("first parameter must be a value ") if not isinstance(second, (int, float)): Raise valueError ("second parameter must be numeric ") # return first + second

Add a PyTest dependency

$ pip install pytest

Add the unit test directory

Create the unit test directory “tests” in the root directory (note to make it a package for full testing).

To add a test class, the file name of the test class must be test_.py or _test.py. See the official Pytest documentation for naming rules

The final directory structure is as follows


pytest-demo

  • demo

    • \_\_init\_\_.py

      • utils

        • \_\_init\_\_.py
        • math_helper.py
  • tests

    • demo

      • \_\_init\_\_.py

        • utils

          • \_\_init\_\_.py
          • test_math_helper.py

Test_math_helper. Py is as follows

import pytest from demo.utils.math_helper import MathHelper def test_addition(): # initialization helper = MathHelper() # input error type, expect to receive ValueError report with PyTest. raises(ValueError): helper.addition("1", 2) with pytest.raises(ValueError): Helper. addition(1, "2") # Correct call result = helper.addition(1, 2) # Assert result == 3

Execute the test cases

$ pytest

You can run all the tests and give the results

Combining with the PyCharm

  • Sets the PyCharm default test type
  1. > Settings > Tools > Python Integrated Tools > Testing > Default test runner
  2. Change the drop-down box to “PyTest”
  3. Right-click on the unit test file and click “Run” to execute the test. The corresponding test results are also displayed in the “Run” window at the bottom
  • Set all tests to run
  1. Right click on the “tests” folder and select “Run”
  2. The next step is to go directly to all the test cases in the directory. You can see the test information in the “Run” window at the bottom
  3. If the module cannot be found in the error report, you need to open the edit startup item in the upper right corner, delete the old information first, otherwise there will be caching

reference

Pytest official documentation