|
| 1 | +import pytest |
| 2 | +import os |
| 3 | +from unittest.mock import patch |
| 4 | +import shutil |
| 5 | +import json |
| 6 | +import xarray as xr |
| 7 | +from pandas import DatetimeIndex |
| 8 | + |
| 9 | +# This fixture temporarily sets the working directory |
| 10 | +# to the dir containing the test file. This means |
| 11 | +# realative file locations can be used for each test |
| 12 | +# file. |
| 13 | +# NOTE: autouse=True means this applies to ALL tests. |
| 14 | +# Code that updates the cwd inside test is now redundant |
| 15 | +# and can be deleted. |
| 16 | +@pytest.fixture(autouse=True) |
| 17 | +def change_test_dir(request, monkeypatch): |
| 18 | + monkeypatch.chdir(request.fspath.dirname) |
| 19 | + |
| 20 | + |
| 21 | +@pytest.fixture(autouse=True) |
| 22 | +def patch_CompareImages(request): |
| 23 | + """This fixture controls the use of CompareImages in the |
| 24 | + test suite. By default, all calls to CompareImages will |
| 25 | + result in the test skipping. To change this behaviour set |
| 26 | + an env var METPLOTPY_COMPAREIMAGES |
| 27 | + """ |
| 28 | + if bool(os.getenv("METPLOTPY_COMPAREIMAGES")): |
| 29 | + yield |
| 30 | + else: |
| 31 | + class mock_CompareImages: |
| 32 | + def __init__(self, img1, img2): |
| 33 | + # TODO: rather than skip we could inject an alternative |
| 34 | + # comparison that is more relaxed. To do this, extend |
| 35 | + # this this class to generate a self.mssim value. |
| 36 | + pytest.skip("CompareImages not enabled in pytest. " |
| 37 | + "To enable `export METPLOTPY_COMPAREIMAGES=$true`") |
| 38 | + try: |
| 39 | + with patch.object(request.module, 'CompareImages', mock_CompareImages) as mock_ci: |
| 40 | + yield mock_ci |
| 41 | + except AttributeError: |
| 42 | + # test module doesn't import CompareImages. Do nothing. |
| 43 | + yield |
| 44 | + |
| 45 | + |
| 46 | +def ordered(obj): |
| 47 | + """Recursive function to sort JSON, even lists of dicts with the same keys""" |
| 48 | + if isinstance(obj, dict): |
| 49 | + return sorted((k, ordered(v)) for k, v in obj.items()) |
| 50 | + if isinstance(obj, list): |
| 51 | + return sorted(ordered(x) for x in obj) |
| 52 | + else: |
| 53 | + return obj |
| 54 | + |
| 55 | +@pytest.fixture |
| 56 | +def assert_json_equal(): |
| 57 | + def compare_json(fig, expected_json_file): |
| 58 | + """Takes a plotly figure and a json file |
| 59 | + """ |
| 60 | + # Treat everything as str for comparison purposes. |
| 61 | + actual = json.loads(fig.to_json(), parse_float=str, parse_int=str) |
| 62 | + with open(expected_json_file) as f: |
| 63 | + expected = json.load(f,parse_float=str, parse_int=str) |
| 64 | + # Fail with a nice message |
| 65 | + if ordered(actual) == ordered(expected): |
| 66 | + return True |
| 67 | + else: |
| 68 | + message = "This test will fail when there have been changes to plot code but the corresponding" \ |
| 69 | + "json test file hasn't been updates. To update the test file run `fig.write_json`"\ |
| 70 | + " e.g. `scatter.figure.write_json('custom_scatter_expected.json')`" |
| 71 | + raise AssertionError(message) |
| 72 | + |
| 73 | + return compare_json |
| 74 | + |
| 75 | + |
| 76 | +@pytest.fixture |
| 77 | +def setup_env(): |
| 78 | + def set_environ(test_dir): |
| 79 | + print("Setting up environment") |
| 80 | + os.environ['METPLOTPY_BASE'] = f"{test_dir}/../../" |
| 81 | + os.environ['TEST_DIR'] = test_dir |
| 82 | + return set_environ |
| 83 | + |
| 84 | + |
| 85 | +@pytest.fixture() |
| 86 | +def remove_files(): |
| 87 | + def remove_the_files(test_dir, file_list): |
| 88 | + print("Removing the files") |
| 89 | + # loop over list of files under test_dir and remove them |
| 90 | + for file in file_list: |
| 91 | + try: |
| 92 | + os.remove(os.path.join(test_dir, file)) |
| 93 | + except OSError: |
| 94 | + pass |
| 95 | + |
| 96 | + # also remove intermed_files directory if it exists |
| 97 | + print("Removing intermed_files directory if it exists") |
| 98 | + try: |
| 99 | + shutil.rmtree(f"{test_dir}/intermed_files") |
| 100 | + except FileNotFoundError: |
| 101 | + pass |
| 102 | + |
| 103 | + return remove_the_files |
| 104 | + |
| 105 | + |
| 106 | +# data for netCDF file |
| 107 | +TEST_NC_DATA = xr.Dataset( |
| 108 | + { |
| 109 | + "precip": xr.DataArray( |
| 110 | + [ |
| 111 | + [[0.1, 0.2, 0.3], [0, 1.3, 4], [0, 20, 0]], |
| 112 | + [[0, 0, 0], [0, 0, 0], [0, 0, 0]], |
| 113 | + ], |
| 114 | + coords={ |
| 115 | + "lat": [-1, 0, 1], |
| 116 | + "lon": [112, 113, 114], |
| 117 | + "time": DatetimeIndex(["2024-09-25 00:00:00", "2024-09-25 03:00:33"]), |
| 118 | + }, |
| 119 | + dims=["time", "lat", "lon"], |
| 120 | + attrs={"long_name": "variable long name"}, |
| 121 | + ), |
| 122 | + }, |
| 123 | + attrs={"Conventions": "CF-99.9", "history": "History string"}, |
| 124 | +) |
| 125 | + |
| 126 | +@pytest.fixture() |
| 127 | +def nc_test_file(tmp_path_factory): |
| 128 | + """Create a netCDF file with a very small amount of data. |
| 129 | + File is written to a temp directory and the path to the |
| 130 | + file returned as the fixture value. |
| 131 | + """ |
| 132 | + file_name = tmp_path_factory.mktemp("data") / "test_data.nc" |
| 133 | + TEST_NC_DATA.to_netcdf(file_name) |
| 134 | + return file_name |
| 135 | + |
0 commit comments