File: conftest.py

package info (click to toggle)
fdb 5.20.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 89,268 kB
  • sloc: cpp: 40,830; python: 5,079; sh: 4,996; makefile: 32; ansic: 8
file content (231 lines) | stat: -rw-r--r-- 7,925 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# (C) Copyright 2011- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.

import logging
import pathlib
from typing import Generator

import datetime

import pytest
import itertools
import shutil
import yaml
import git

import eccodes as ec

import pyfdb

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())


@pytest.fixture
def test_logger():
    return logger


@pytest.fixture(scope="function")
def data_path() -> pathlib.Path:
    """
    Provides path to test data
    """
    path = pathlib.Path(__file__).resolve().parent / "data"
    assert path.exists()
    return path


@pytest.fixture(scope="function")
def test_data_path() -> pathlib.Path:
    """
    Provides path to test data
    """

    git_repo = git.Repo(__file__, search_parent_directories=True)
    git_root = pathlib.Path(git_repo.git.rev_parse("--show-toplevel"))
    path = git_root / "tests" / "pyfdb" / "data"
    assert path.exists()
    return path


@pytest.fixture(scope="session")
def session_tmp(tmp_path_factory) -> Generator[pathlib.Path, None, None]:
    """Temporary folder for use in a single session"""
    tmp_dir = tmp_path_factory.mktemp("session_data")
    yield tmp_dir
    shutil.rmtree(str(tmp_dir))


@pytest.fixture(scope="function")
def function_tmp(tmp_path_factory) -> Generator[pathlib.Path, None, None]:
    """Temporary folder for use in a single function"""
    tmp_function_dir = tmp_path_factory.mktemp("test_data", numbered=True)
    yield tmp_function_dir
    shutil.rmtree(str(tmp_function_dir))


@pytest.fixture(scope="function")
def build_grib_messages(data_path, session_tmp) -> pathlib.Path:
    """This fixture is setting up a certain set of GRIB files by using a template GRIB file.
    For every triple of dates, times and parameters as stated below a new field is created
    and written to a file. This file path is returned at the end of the method to be usable
    in other fixtures.
    """
    template_grib = data_path / "template.grib"
    assert template_grib.is_file()
    template_grib_fd = open(template_grib, "rb")
    gid = ec.codes_grib_new_from_file(template_grib_fd)
    template_grib_fd.close()
    count_data_points = int(ec.codes_get(gid, "numberOfDataPoints"))
    count_values = int(ec.codes_get(gid, "numberOfValues"))
    count_missing = int(ec.codes_get(gid, "numberOfMissing"))

    # This only supports messages without missing datapoints
    assert count_data_points == count_values
    assert count_missing == 0

    # Set common keys / data "pattern"
    ec.codes_set_string(gid, "type", "an")
    ec.codes_set_string(gid, "class", "ea")
    ec.codes_set_string(gid, "expver", "0001")
    ec.codes_set_string(gid, "stream", "oper")
    ec.codes_set_string(gid, "levtype", "sfc")
    ec.codes_set_values(gid, list(range(0, count_values)))

    dates = [20200101, 20200102, 20200103, 20200104]
    times = [0, 300, 600, 900, 1200, 1500, 1800, 2100]
    parameters = [167, 131, 132]

    messages = session_tmp / "test_data.grib"
    with open(messages, "wb") as out:
        for date, time, parameter in itertools.product(dates, times, parameters):
            ec.codes_set(gid, "date", date)
            ec.codes_set(gid, "time", time)
            ec.codes_set(gid, "paramId", parameter)
            ec.codes_write(gid, out)

    ec.codes_release(gid)
    return messages


@pytest.fixture(scope="function", autouse=False)
def empty_fdb_setup(data_path, session_tmp, function_tmp) -> pathlib.Path:
    """
    Creates a FDB setup in this tests temp directory.
    This setup can be shared between tests
    """
    schema_path_src = data_path / "schema"
    assert schema_path_src.is_file()
    schema_path = session_tmp / "schema"
    shutil.copy(schema_path_src, schema_path)

    db_store_path = session_tmp / function_tmp / "db_store"
    db_store_path.mkdir()
    fdb_config = dict(
        type="local",
        engine="toc",
        schema=str(schema_path),
        spaces=[
            dict(
                handler="Default",
                roots=[
                    {"path": str(db_store_path)},
                ],
            )
        ],
    )
    fdb_config_str = yaml.dump(fdb_config)
    fdb_config_path = session_tmp / "fdb_config.yaml"
    fdb_config_path.write_text(fdb_config_str)
    return fdb_config_path


@pytest.fixture(scope="function", autouse=False)
def read_only_fdb_setup(empty_fdb_setup, build_grib_messages) -> pathlib.Path:
    """
    Creates a FDB setup in this tests temp directory.
    Test FDB currently reads all grib files in `tests/data`
    This setup can be shared between tests as we will only read
    data from this FDB
    """

    logger.debug("***********READ ONLY FDB SETUP*******************")
    with pyfdb.FDB(empty_fdb_setup) as fdb:
        fdb.archive(build_grib_messages.read_bytes())
        fdb.flush()

    return empty_fdb_setup


@pytest.fixture(scope="function", autouse=False)
def read_write_fdb_setup(empty_fdb_setup, build_grib_messages) -> pathlib.Path:
    """
    Creates a FDB setup in this tests temp directory.
    This setup can be shared between tests as we will only read
    data from this FDB
    """
    with pyfdb.FDB(empty_fdb_setup) as fdb:
        fdb.archive(build_grib_messages.read_bytes())
        fdb.flush()
    return empty_fdb_setup


@pytest.fixture(scope="function")
def build_grib_messages_relative_dates(data_path, session_tmp) -> pathlib.Path:
    """This fixture is setting up a certain set of GRIB files by using a template GRIB file.
    For every triple of dates, times and parameters as stated below a new field is created
    and written to a file. This file path is returned at the end of the method to be usable
    in other fixtures.

    Note:
    This is the same as the build_grib_messages fixture but sets the dates to be relative
    to today.
    """
    template_grib = data_path / "template.grib"
    assert template_grib.is_file()
    template_grib_fd = open(template_grib, "rb")
    gid = ec.codes_grib_new_from_file(template_grib_fd)
    template_grib_fd.close()
    count_data_points = int(ec.codes_get(gid, "numberOfDataPoints"))
    count_values = int(ec.codes_get(gid, "numberOfValues"))
    count_missing = int(ec.codes_get(gid, "numberOfMissing"))

    # This only supports messages without missing datapoints
    assert count_data_points == count_values
    assert count_missing == 0

    # Set common keys / data "pattern"
    ec.codes_set_string(gid, "type", "an")
    ec.codes_set_string(gid, "class", "ea")
    ec.codes_set_string(gid, "expver", "0001")
    ec.codes_set_string(gid, "stream", "oper")
    ec.codes_set_string(gid, "levtype", "sfc")
    ec.codes_set_values(gid, list(range(0, count_values)))

    today_date = datetime.date.today()

    today = int(today_date.strftime("%Y%m%d"))
    yesterday = int((today_date - datetime.timedelta(days=1)).strftime("%Y%m%d"))
    before_yesterday = int((today_date - datetime.timedelta(days=2)).strftime("%Y%m%d"))
    before_before_yesterday = int((today_date - datetime.timedelta(days=3)).strftime("%Y%m%d"))

    dates = [before_before_yesterday, before_yesterday, yesterday, today]
    times = [0, 300, 600, 900, 1200, 1500, 1800, 2100]
    parameters = [167, 131, 132]

    messages = session_tmp / "test_data.grib"
    with open(messages, "wb") as out:
        for date, time, parameter in itertools.product(dates, times, parameters):
            ec.codes_set(gid, "date", date)
            ec.codes_set(gid, "time", time)
            ec.codes_set(gid, "paramId", parameter)
            ec.codes_write(gid, out)

    ec.codes_release(gid)
    return messages