Python Testing

  1. pytest
    1. https://docs.pytest.org/en/stable/
    2. https://realpython.com/pytest-python-testing/
    3. Specifying tests / selecting tests https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests Pytest supports several ways to run and select tests from the command-line.
      1. Run tests in a module
        pytest test_mod.py
        
      2. Run tests in a directory
        pytest testing/
        
      3. Run tests by keyword expressions
        pytest -k "MyClass and not method"
        
        This will run tests which contain names that match the given string expression, which can include Python operators that use filenames, class names and function names as variables. The example above will run TestMyClass.test_something but not TestMyClass.test_method_simple.
      4. Run tests by node ids Each collected test is assigned a unique nodeid which consist of the module filename followed by specifiers like class names, function names and parameters from parametrization, separated by :: characters.
      5. To run a specific test within a module:
        pytest test_mod.py::test_func
        
        Another example specifying a test method in the command line:
        pytest test_mod.py::TestClass::test_method
        
      6. Run tests with print statements
        pytest -s test_mod.py::TestClass::test_method
        
      7. Run tests with breakpoints
        pytest -pdb test_mod.py::TestClass::test_method
        
        This will allow you to step through the code with pdb.
      8. Run tests by marker expressions
        pytest -m slow
        
        Will run all tests which are decorated with the @pytest.mark.slow decorator. For more information see marks.
      9. Run tests from packages
        pytest --pyargs pkg.testing
        
        This will import pkg.testing and use its filesystem location to find and run tests from.
  2. Debugging
    1. https://docs.python.org/3/library/pdb.html
  3. Mocking
    1. https://realpython.com/python-mock-library/
  4. unittest
    1. https://docs.python.org/3/library/unittest.html

Links to this note