Software Testing and Testing Automation with Python

Test Fixtures

Purpose

Test fixtures are a good way to encapsulate data or setup needs that are used for multiple tests. We’ve got plotting tests that we just wrote that are currently making calls to the web to get plotting data. That isn’t great as we are depending on external contact. What if a server goes down, what if the tests are run on a machine with no network connection, what if we don’t want to make API calls because they are expensive? Let’s make this a fixture instead.

Make the fixture by downloading the data for a staticdata directory in the top level of the repo. Data are here.

from pathlib import Path

@pytest.fixture
def load_example_asos():
    """
    Fixture to load example data from a csv file for testing.
    """
    example_data_path = Path(__file__).resolve().parent / '..' / '..' / 'staticdata'
    data_path = example_data_path / 'AMW_example_data.csv'
    return meteogram.download_asos_data(data_path)

Modify the test functions to use our fixture.

@pytest.mark.mpl_image_compare(remove_text=True)
def test_plotting_meteogram_defaults(load_example_asos):
    """Test default meteogram plotting."""
    # Setup
    df = load_example_asos


    # Exercise
    fig, _, _, _ = meteogram.plot_meteogram(df)

    # Verify - Done by decorator when run with -mpl flag

    # Cleanup - none necessary

    return fig

#
# Exercise 5 - Modify plotting routine and add tests
#
@pytest.mark.mpl_image_compare(remove_text=True)
def test_plotting_meteogram_direction_fiducials(load_example_asos):
    """Test meteogram plotting with fiducial lines."""
    # Setup
    df = load_example_asos


    # Exercise
    fig, _, _, _ = meteogram.plot_meteogram(df, direction_markers=True)

    # Verify - Done by decorator when run with -mpl flag

    # Cleanup - none necessary

    return fig

Home