pythonunit-testingtestingautomated-tests

how to write a test function for a function in python, WITHOUT class


I want to test a function.

I found many answers such as how to write a unit testing function for my function? & unittest

But they all write the test functions under a certain class, while mine function isn't a member a any class.

for example I have this under readTool.py:

def extract_frame_dr(dr, frameID):
    return dr[0, frameID], dr[1, frameID]

How do I write a test_extract_frame_dr for it? I want to have the feature of Auto-discovery of test modules and functions: Run all the tests in readTool.py at once without calling them one by one in the main function.


Solution

  • You may write very clear tests with functions using pytest. To do so,

    1. Make your python modules to be importable in the test files (an example given in part 1)
    2. Create test_x.py modules with test_y() functions, and run them with python -m pytest.

    1. Folder structure & setup for writing tests

    When writing code that you want to be tested, you need to ensure that your modules are importable by the test modules. Easiest way to do it would be to use folder structure like this:

    .
    │   setup.py
    │   
    ├───mypackage
    │       readTool.py
    │       __init__.py
    │
    ├───tests
    │       test_readtool.py
    │
    └───venv
    

    where setup.py is a file used to make your package installable. In this example, the file contents would be just

    import setuptools
    
    setuptools.setup(
        name='mypackage',
        packages=setuptools.find_packages(),
    )
    

    You also probably want to create a virtual environment (venv), activate it, and then install your package (mypackage) in an editable state with

    pip install -e .
    

    Then, install pytest

    pip install pytest
    

    (for more information on the usage of setup.py, see for example this answer)

    2. Testing functions with functions

    Write into tests/test_readtool.py:

    from mypackage.readTool import extract_frame_dr
    
    
    def test_extract_frame_dr():
        frame_id = 1963
        
        dr_who = {
            (0, frame_id): 'William Hartnell',
            (1, frame_id): 'Patrick Troughton',
        }
    
        extracted = extract_frame_dr(dr_who, frame_id)
        assert extracted[0] == 'William Hartnell'
        assert extracted[1] == 'Patrick Troughton'
    
    
    

    and run the tests using

    python -m pytest
    

    (with just running pytest you may encounter into ModuleNotFoundErrors)

    3. Auto-discovery of test modules and functions

    This is part of pytest. Just