pytest-dst-vectors 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Plainfold
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-dst-vectors
3
+ Version: 0.1.0
4
+ Summary: pytest plugin: parametrize tests over DST gap, overlap and normal local times (dst-test-vectors). Offline, MIT.
5
+ Author-email: Plainfold <plainfoldhq@proton.me>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/plainfoldhq/pytest-dst-vectors
8
+ Project-URL: Source, https://github.com/plainfoldhq/pytest-dst-vectors
9
+ Project-URL: Issues, https://github.com/plainfoldhq/pytest-dst-vectors/issues
10
+ Keywords: pytest,dst,daylight saving time,timezone,time zone,zoneinfo,test vectors,ambiguous time,nonexistent time
11
+ Classifier: Framework :: Pytest
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: dst-test-vectors==0.1.1
20
+ Requires-Dist: pytest>=7
21
+ Dynamic: license-file
22
+
23
+ # pytest-dst-vectors
24
+
25
+ [![tests](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml/badge.svg)](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml)
26
+
27
+ A pytest plugin that runs your tests over DST edge cases: local wall times that do not exist (spring-forward gap), that happen twice (fall-back overlap), and the seconds right next to a change. Use it when you test code that converts local wall times to UTC around DST changes.
28
+
29
+ The cases come from [`dst-test-vectors`](https://pypi.org/project/dst-test-vectors/) (pinned to 0.1.1). This plugin adds no data of its own and never uses the network. Python 3.10+, pytest 7+.
30
+
31
+ ## Install
32
+
33
+ ```
34
+ pip install pytest-dst-vectors
35
+ ```
36
+
37
+ The plugin loads itself (pytest11 entry point). A test that has a `dst_case` argument is run once per case.
38
+
39
+ ## Examples
40
+
41
+ Every Python example below is run by the test suite (`tests/test_readme.py` extracts the code blocks and runs them with pytest).
42
+
43
+ ### 1. Gaps and overlaps with `zoneinfo`
44
+
45
+ ```python
46
+ from datetime import timezone
47
+ from zoneinfo import ZoneInfo
48
+
49
+ import pytest
50
+
51
+
52
+ @pytest.mark.dst_vectors(kind="gap")
53
+ def test_gap_fold(dst_case):
54
+ zone = ZoneInfo(dst_case.zone)
55
+ before = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
56
+ after = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
57
+ assert before == dst_case.compatible # fold=0 uses the offset before the change
58
+ assert after == dst_case.earlier # fold=1 uses the offset after it
59
+
60
+
61
+ @pytest.mark.dst_vectors(kind="overlap", zone="America/New_York")
62
+ def test_overlap_fold(dst_case):
63
+ zone = ZoneInfo(dst_case.zone)
64
+ first = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
65
+ second = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
66
+ assert (first, second) == (dst_case.earlier, dst_case.later)
67
+ ```
68
+
69
+ ### 2. Test your own `to_utc` with `dst_check`
70
+
71
+ `dst_check(func, policy=..., **filters)` calls `func(zone, naive_local_datetime)` for every matching case and returns the mismatches (an empty list means all agree). Policies are `compatible` (default), `earlier`, `later` and `raise` (gaps must raise); see `dst-test-vectors` for details.
72
+
73
+ ```python
74
+ from datetime import timezone
75
+ from zoneinfo import ZoneInfo
76
+
77
+
78
+ def to_utc(zone, local):
79
+ return local.replace(tzinfo=ZoneInfo(zone)).astimezone(timezone.utc)
80
+
81
+
82
+ def to_utc_later(zone, local):
83
+ return local.replace(tzinfo=ZoneInfo(zone), fold=1).astimezone(timezone.utc)
84
+
85
+
86
+ def test_to_utc_earlier(dst_check):
87
+ assert dst_check(to_utc, policy="earlier") == []
88
+
89
+
90
+ def test_to_utc_later_in_overlaps(dst_check):
91
+ assert dst_check(to_utc_later, policy="later", kind="overlap") == []
92
+ ```
93
+
94
+ ### 3. Run against a full vectors file
95
+
96
+ The plugin uses the bundled sample by default. To run the same tests against another file in the same format, such as the full 2000-2050 set (`dst_test_vectors.json`), pass it on the command line:
97
+
98
+ ```
99
+ pytest --dst-vectors=dst_test_vectors.json
100
+ ```
101
+
102
+ or set it in `pytest.ini` (`pyproject.toml` works the same under `[tool.pytest.ini_options]`):
103
+
104
+ ```ini
105
+ [pytest]
106
+ dst_vectors_file = dst_test_vectors.json
107
+ ```
108
+
109
+ ```python
110
+ import pytest
111
+
112
+
113
+ @pytest.mark.dst_vectors(zone="Europe/London", year=2026)
114
+ def test_london_2026(dst_case):
115
+ assert dst_case.zone == "Europe/London"
116
+ assert dst_case.local.year == 2026
117
+ ```
118
+
119
+ The test suite runs this example with a small stand-in file named `dst_test_vectors.json`, once with `--dst-vectors=dst_test_vectors.json` and once with the ini line above.
120
+
121
+ ## Marker
122
+
123
+ `@pytest.mark.dst_vectors(kind=None, zone=None, tag=None, year=None)`, keyword arguments only:
124
+
125
+ | Argument | Meaning |
126
+ |---|---|
127
+ | `kind` | `"gap"`, `"overlap"` or `"normal"` |
128
+ | `zone` | IANA zone name, or a list of names |
129
+ | `tag` | e.g. `"midnight"`, `"odd_offset"`, `"delta_30min"`, `"dst"` |
130
+ | `year` | local year |
131
+
132
+ A test that takes `dst_case` without the marker gets every case. `dst_case` is a `dst_test_vectors.Case` (`zone`, `local`, `kind`, `utc`, `earlier`, `later`, `compatible`, `transition_utc`, `tags`, `note`).
133
+
134
+ If the filters match 0 cases, or `kind` is not one of the three kinds, collection of that test fails with a message that names the filters. Unknown marker arguments fail the same way.
135
+
136
+ ## Test ids
137
+
138
+ Ids are `Case.id`: zone, local time, kind.
139
+
140
+ ```
141
+ test_gap_fold[America/New_York 2026-03-08T02:00:00 gap]
142
+ test_overlap_fold[America/New_York 2026-11-01T01:30:00 overlap]
143
+ ```
144
+
145
+ Select one with `-k "New_York and overlap"`.
146
+
147
+ ## Options
148
+
149
+ | Option | Ini | Meaning |
150
+ |---|---|---|
151
+ | `--dst-vectors=PATH` | `dst_vectors_file` | Vectors JSON file in the `dst-test-vectors` format. Default: the bundled sample. A relative ini path is taken from the rootdir. |
152
+
153
+ The report header shows what is active, for example `dst-vectors: bundled sample, tzdata 2026f, 36 cases`. An unreadable file stops pytest with a usage error.
154
+
155
+ ## What the bundled sample covers
156
+
157
+ 36 cases for 2026 in 5 zones (America/New_York, Europe/London, America/Havana, Australia/Lord_Howe, Pacific/Chatham), generated from IANA tzdata 2026f: gaps, overlaps and the seconds next to each change, including a 30-minute change (Lord Howe), +12:45/+13:45 (Chatham) and changes at midnight (Havana). Cases are unchanged from the `dst-test-vectors` bundle. The expected values only match a machine whose tz database is as new as the vectors, so an older system tzdata can fail a few cases; install `tzdata` to pin one.
158
+
159
+ ## Full set
160
+
161
+ The full set has 51,404 vectors for 2000-2050 in every zone, in the same JSON format: https://github.com/plainfoldhq/tz-transitions (paid; the sample above is free). DST dates by country: https://plainfoldhq.github.io/dst-dates/
162
+
163
+ ## About
164
+
165
+ Plainfold is an AI-run business; this package was written and tested by AI agents.
166
+
167
+ MIT license. Questions: plainfoldhq@proton.me.
@@ -0,0 +1,145 @@
1
+ # pytest-dst-vectors
2
+
3
+ [![tests](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml/badge.svg)](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml)
4
+
5
+ A pytest plugin that runs your tests over DST edge cases: local wall times that do not exist (spring-forward gap), that happen twice (fall-back overlap), and the seconds right next to a change. Use it when you test code that converts local wall times to UTC around DST changes.
6
+
7
+ The cases come from [`dst-test-vectors`](https://pypi.org/project/dst-test-vectors/) (pinned to 0.1.1). This plugin adds no data of its own and never uses the network. Python 3.10+, pytest 7+.
8
+
9
+ ## Install
10
+
11
+ ```
12
+ pip install pytest-dst-vectors
13
+ ```
14
+
15
+ The plugin loads itself (pytest11 entry point). A test that has a `dst_case` argument is run once per case.
16
+
17
+ ## Examples
18
+
19
+ Every Python example below is run by the test suite (`tests/test_readme.py` extracts the code blocks and runs them with pytest).
20
+
21
+ ### 1. Gaps and overlaps with `zoneinfo`
22
+
23
+ ```python
24
+ from datetime import timezone
25
+ from zoneinfo import ZoneInfo
26
+
27
+ import pytest
28
+
29
+
30
+ @pytest.mark.dst_vectors(kind="gap")
31
+ def test_gap_fold(dst_case):
32
+ zone = ZoneInfo(dst_case.zone)
33
+ before = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
34
+ after = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
35
+ assert before == dst_case.compatible # fold=0 uses the offset before the change
36
+ assert after == dst_case.earlier # fold=1 uses the offset after it
37
+
38
+
39
+ @pytest.mark.dst_vectors(kind="overlap", zone="America/New_York")
40
+ def test_overlap_fold(dst_case):
41
+ zone = ZoneInfo(dst_case.zone)
42
+ first = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
43
+ second = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
44
+ assert (first, second) == (dst_case.earlier, dst_case.later)
45
+ ```
46
+
47
+ ### 2. Test your own `to_utc` with `dst_check`
48
+
49
+ `dst_check(func, policy=..., **filters)` calls `func(zone, naive_local_datetime)` for every matching case and returns the mismatches (an empty list means all agree). Policies are `compatible` (default), `earlier`, `later` and `raise` (gaps must raise); see `dst-test-vectors` for details.
50
+
51
+ ```python
52
+ from datetime import timezone
53
+ from zoneinfo import ZoneInfo
54
+
55
+
56
+ def to_utc(zone, local):
57
+ return local.replace(tzinfo=ZoneInfo(zone)).astimezone(timezone.utc)
58
+
59
+
60
+ def to_utc_later(zone, local):
61
+ return local.replace(tzinfo=ZoneInfo(zone), fold=1).astimezone(timezone.utc)
62
+
63
+
64
+ def test_to_utc_earlier(dst_check):
65
+ assert dst_check(to_utc, policy="earlier") == []
66
+
67
+
68
+ def test_to_utc_later_in_overlaps(dst_check):
69
+ assert dst_check(to_utc_later, policy="later", kind="overlap") == []
70
+ ```
71
+
72
+ ### 3. Run against a full vectors file
73
+
74
+ The plugin uses the bundled sample by default. To run the same tests against another file in the same format, such as the full 2000-2050 set (`dst_test_vectors.json`), pass it on the command line:
75
+
76
+ ```
77
+ pytest --dst-vectors=dst_test_vectors.json
78
+ ```
79
+
80
+ or set it in `pytest.ini` (`pyproject.toml` works the same under `[tool.pytest.ini_options]`):
81
+
82
+ ```ini
83
+ [pytest]
84
+ dst_vectors_file = dst_test_vectors.json
85
+ ```
86
+
87
+ ```python
88
+ import pytest
89
+
90
+
91
+ @pytest.mark.dst_vectors(zone="Europe/London", year=2026)
92
+ def test_london_2026(dst_case):
93
+ assert dst_case.zone == "Europe/London"
94
+ assert dst_case.local.year == 2026
95
+ ```
96
+
97
+ The test suite runs this example with a small stand-in file named `dst_test_vectors.json`, once with `--dst-vectors=dst_test_vectors.json` and once with the ini line above.
98
+
99
+ ## Marker
100
+
101
+ `@pytest.mark.dst_vectors(kind=None, zone=None, tag=None, year=None)`, keyword arguments only:
102
+
103
+ | Argument | Meaning |
104
+ |---|---|
105
+ | `kind` | `"gap"`, `"overlap"` or `"normal"` |
106
+ | `zone` | IANA zone name, or a list of names |
107
+ | `tag` | e.g. `"midnight"`, `"odd_offset"`, `"delta_30min"`, `"dst"` |
108
+ | `year` | local year |
109
+
110
+ A test that takes `dst_case` without the marker gets every case. `dst_case` is a `dst_test_vectors.Case` (`zone`, `local`, `kind`, `utc`, `earlier`, `later`, `compatible`, `transition_utc`, `tags`, `note`).
111
+
112
+ If the filters match 0 cases, or `kind` is not one of the three kinds, collection of that test fails with a message that names the filters. Unknown marker arguments fail the same way.
113
+
114
+ ## Test ids
115
+
116
+ Ids are `Case.id`: zone, local time, kind.
117
+
118
+ ```
119
+ test_gap_fold[America/New_York 2026-03-08T02:00:00 gap]
120
+ test_overlap_fold[America/New_York 2026-11-01T01:30:00 overlap]
121
+ ```
122
+
123
+ Select one with `-k "New_York and overlap"`.
124
+
125
+ ## Options
126
+
127
+ | Option | Ini | Meaning |
128
+ |---|---|---|
129
+ | `--dst-vectors=PATH` | `dst_vectors_file` | Vectors JSON file in the `dst-test-vectors` format. Default: the bundled sample. A relative ini path is taken from the rootdir. |
130
+
131
+ The report header shows what is active, for example `dst-vectors: bundled sample, tzdata 2026f, 36 cases`. An unreadable file stops pytest with a usage error.
132
+
133
+ ## What the bundled sample covers
134
+
135
+ 36 cases for 2026 in 5 zones (America/New_York, Europe/London, America/Havana, Australia/Lord_Howe, Pacific/Chatham), generated from IANA tzdata 2026f: gaps, overlaps and the seconds next to each change, including a 30-minute change (Lord Howe), +12:45/+13:45 (Chatham) and changes at midnight (Havana). Cases are unchanged from the `dst-test-vectors` bundle. The expected values only match a machine whose tz database is as new as the vectors, so an older system tzdata can fail a few cases; install `tzdata` to pin one.
136
+
137
+ ## Full set
138
+
139
+ The full set has 51,404 vectors for 2000-2050 in every zone, in the same JSON format: https://github.com/plainfoldhq/tz-transitions (paid; the sample above is free). DST dates by country: https://plainfoldhq.github.io/dst-dates/
140
+
141
+ ## About
142
+
143
+ Plainfold is an AI-run business; this package was written and tested by AI agents.
144
+
145
+ MIT license. Questions: plainfoldhq@proton.me.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pytest-dst-vectors"
7
+ version = "0.1.0"
8
+ description = "pytest plugin: parametrize tests over DST gap, overlap and normal local times (dst-test-vectors). Offline, MIT."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Plainfold", email = "plainfoldhq@proton.me" }]
14
+ keywords = ["pytest", "dst", "daylight saving time", "timezone", "time zone", "zoneinfo", "test vectors", "ambiguous time", "nonexistent time"]
15
+ classifiers = [
16
+ "Framework :: Pytest",
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Intended Audience :: Developers",
20
+ "Topic :: Software Development :: Testing",
21
+ ]
22
+ dependencies = [
23
+ "dst-test-vectors==0.1.1",
24
+ "pytest>=7",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/plainfoldhq/pytest-dst-vectors"
29
+ Source = "https://github.com/plainfoldhq/pytest-dst-vectors"
30
+ Issues = "https://github.com/plainfoldhq/pytest-dst-vectors/issues"
31
+
32
+ [project.entry-points.pytest11]
33
+ dst_vectors = "pytest_dst_vectors.plugin"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """pytest plugin that parametrizes tests over the DST test vectors of dst-test-vectors."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,96 @@
1
+ """pytest plugin: `dst_case` parametrization, `dst_check` fixture, `--dst-vectors` option.
2
+
3
+ Adds no data of its own and never uses the network; all cases come from dst_test_vectors.
4
+ """
5
+ import os
6
+
7
+ import dst_test_vectors as dtv
8
+ import pytest
9
+
10
+ _FILTERS = ("kind", "zone", "tag", "year")
11
+ _PATH_KEY = pytest.StashKey[object]()
12
+
13
+
14
+ def pytest_addoption(parser):
15
+ group = parser.getgroup("dst-vectors", "DST test vectors")
16
+ group.addoption("--dst-vectors", dest="dst_vectors", default=None, metavar="PATH",
17
+ help="vectors JSON file in the dst-test-vectors format "
18
+ "(default: the sample bundled with dst-test-vectors)")
19
+ parser.addini("dst_vectors_file", "vectors JSON file (same as --dst-vectors; "
20
+ "relative paths are taken from the rootdir)")
21
+
22
+
23
+ def _resolve_path(config):
24
+ """Absolute path of the vectors file, or None for the bundled sample."""
25
+ cli = config.getoption("dst_vectors")
26
+ if cli:
27
+ return os.path.abspath(cli)
28
+ ini = config.getini("dst_vectors_file")
29
+ if ini:
30
+ return os.path.normpath(os.path.join(str(config.rootpath), ini))
31
+ return None
32
+
33
+
34
+ def pytest_configure(config):
35
+ config.addinivalue_line(
36
+ "markers",
37
+ "dst_vectors(kind=None, zone=None, tag=None, year=None): parametrize the test's "
38
+ "`dst_case` argument over the matching DST test vectors")
39
+ path = _resolve_path(config)
40
+ try:
41
+ meta, loaded = dtv.load(path)
42
+ except (OSError, ValueError, KeyError) as e:
43
+ raise pytest.UsageError(f"dst-vectors: cannot read vectors file {path!r}: {e!r}") from e
44
+ config.stash[_PATH_KEY] = path
45
+
46
+
47
+ def _path(config):
48
+ return config.stash[_PATH_KEY]
49
+
50
+
51
+ def pytest_report_header(config):
52
+ path = _path(config)
53
+ meta, loaded = dtv.load(path)
54
+ return (f"dst-vectors: {path or 'bundled sample'}, tzdata {meta.get('tzdata_version')}, "
55
+ f"{len(loaded)} cases")
56
+
57
+
58
+ def _filters(metafunc):
59
+ marker = metafunc.definition.get_closest_marker("dst_vectors")
60
+ if marker is None:
61
+ return {}
62
+ if marker.args:
63
+ pytest.fail(f"{metafunc.definition.nodeid}: dst_vectors takes keyword arguments only "
64
+ f"({', '.join(_FILTERS)}), got positional {marker.args!r}", pytrace=False)
65
+ unknown = sorted(set(marker.kwargs) - set(_FILTERS))
66
+ if unknown:
67
+ pytest.fail(f"{metafunc.definition.nodeid}: unknown dst_vectors argument(s) "
68
+ f"{', '.join(unknown)}; allowed: {', '.join(_FILTERS)}", pytrace=False)
69
+ return {k: v for k, v in marker.kwargs.items() if v is not None}
70
+
71
+
72
+ def pytest_generate_tests(metafunc):
73
+ if "dst_case" not in metafunc.fixturenames:
74
+ return
75
+ filters = _filters(metafunc)
76
+ where = metafunc.definition.nodeid
77
+ try:
78
+ selected = dtv.cases(path=_path(metafunc.config), **filters)
79
+ except ValueError as e:
80
+ pytest.fail(f"{where}: bad dst_vectors filter {filters!r}: {e}", pytrace=False)
81
+ if not selected:
82
+ pytest.fail(f"{where}: dst_vectors filters {filters!r} match 0 cases in "
83
+ f"{_path(metafunc.config) or 'the bundled sample'}", pytrace=False)
84
+ metafunc.parametrize("dst_case", selected, ids=[c.id for c in selected])
85
+
86
+
87
+ @pytest.fixture
88
+ def dst_check(request):
89
+ """dst_test_vectors.check bound to the active vectors file:
90
+ dst_check(func, policy="compatible", **filters) -> list of mismatches."""
91
+ path = _path(request.config)
92
+
93
+ def bound(func, policy="compatible", **filters):
94
+ return dtv.check(func, policy, path=path, **filters)
95
+
96
+ return bound
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-dst-vectors
3
+ Version: 0.1.0
4
+ Summary: pytest plugin: parametrize tests over DST gap, overlap and normal local times (dst-test-vectors). Offline, MIT.
5
+ Author-email: Plainfold <plainfoldhq@proton.me>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/plainfoldhq/pytest-dst-vectors
8
+ Project-URL: Source, https://github.com/plainfoldhq/pytest-dst-vectors
9
+ Project-URL: Issues, https://github.com/plainfoldhq/pytest-dst-vectors/issues
10
+ Keywords: pytest,dst,daylight saving time,timezone,time zone,zoneinfo,test vectors,ambiguous time,nonexistent time
11
+ Classifier: Framework :: Pytest
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: dst-test-vectors==0.1.1
20
+ Requires-Dist: pytest>=7
21
+ Dynamic: license-file
22
+
23
+ # pytest-dst-vectors
24
+
25
+ [![tests](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml/badge.svg)](https://github.com/plainfoldhq/pytest-dst-vectors/actions/workflows/tests.yml)
26
+
27
+ A pytest plugin that runs your tests over DST edge cases: local wall times that do not exist (spring-forward gap), that happen twice (fall-back overlap), and the seconds right next to a change. Use it when you test code that converts local wall times to UTC around DST changes.
28
+
29
+ The cases come from [`dst-test-vectors`](https://pypi.org/project/dst-test-vectors/) (pinned to 0.1.1). This plugin adds no data of its own and never uses the network. Python 3.10+, pytest 7+.
30
+
31
+ ## Install
32
+
33
+ ```
34
+ pip install pytest-dst-vectors
35
+ ```
36
+
37
+ The plugin loads itself (pytest11 entry point). A test that has a `dst_case` argument is run once per case.
38
+
39
+ ## Examples
40
+
41
+ Every Python example below is run by the test suite (`tests/test_readme.py` extracts the code blocks and runs them with pytest).
42
+
43
+ ### 1. Gaps and overlaps with `zoneinfo`
44
+
45
+ ```python
46
+ from datetime import timezone
47
+ from zoneinfo import ZoneInfo
48
+
49
+ import pytest
50
+
51
+
52
+ @pytest.mark.dst_vectors(kind="gap")
53
+ def test_gap_fold(dst_case):
54
+ zone = ZoneInfo(dst_case.zone)
55
+ before = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
56
+ after = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
57
+ assert before == dst_case.compatible # fold=0 uses the offset before the change
58
+ assert after == dst_case.earlier # fold=1 uses the offset after it
59
+
60
+
61
+ @pytest.mark.dst_vectors(kind="overlap", zone="America/New_York")
62
+ def test_overlap_fold(dst_case):
63
+ zone = ZoneInfo(dst_case.zone)
64
+ first = dst_case.local.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
65
+ second = dst_case.local.replace(tzinfo=zone, fold=1).astimezone(timezone.utc)
66
+ assert (first, second) == (dst_case.earlier, dst_case.later)
67
+ ```
68
+
69
+ ### 2. Test your own `to_utc` with `dst_check`
70
+
71
+ `dst_check(func, policy=..., **filters)` calls `func(zone, naive_local_datetime)` for every matching case and returns the mismatches (an empty list means all agree). Policies are `compatible` (default), `earlier`, `later` and `raise` (gaps must raise); see `dst-test-vectors` for details.
72
+
73
+ ```python
74
+ from datetime import timezone
75
+ from zoneinfo import ZoneInfo
76
+
77
+
78
+ def to_utc(zone, local):
79
+ return local.replace(tzinfo=ZoneInfo(zone)).astimezone(timezone.utc)
80
+
81
+
82
+ def to_utc_later(zone, local):
83
+ return local.replace(tzinfo=ZoneInfo(zone), fold=1).astimezone(timezone.utc)
84
+
85
+
86
+ def test_to_utc_earlier(dst_check):
87
+ assert dst_check(to_utc, policy="earlier") == []
88
+
89
+
90
+ def test_to_utc_later_in_overlaps(dst_check):
91
+ assert dst_check(to_utc_later, policy="later", kind="overlap") == []
92
+ ```
93
+
94
+ ### 3. Run against a full vectors file
95
+
96
+ The plugin uses the bundled sample by default. To run the same tests against another file in the same format, such as the full 2000-2050 set (`dst_test_vectors.json`), pass it on the command line:
97
+
98
+ ```
99
+ pytest --dst-vectors=dst_test_vectors.json
100
+ ```
101
+
102
+ or set it in `pytest.ini` (`pyproject.toml` works the same under `[tool.pytest.ini_options]`):
103
+
104
+ ```ini
105
+ [pytest]
106
+ dst_vectors_file = dst_test_vectors.json
107
+ ```
108
+
109
+ ```python
110
+ import pytest
111
+
112
+
113
+ @pytest.mark.dst_vectors(zone="Europe/London", year=2026)
114
+ def test_london_2026(dst_case):
115
+ assert dst_case.zone == "Europe/London"
116
+ assert dst_case.local.year == 2026
117
+ ```
118
+
119
+ The test suite runs this example with a small stand-in file named `dst_test_vectors.json`, once with `--dst-vectors=dst_test_vectors.json` and once with the ini line above.
120
+
121
+ ## Marker
122
+
123
+ `@pytest.mark.dst_vectors(kind=None, zone=None, tag=None, year=None)`, keyword arguments only:
124
+
125
+ | Argument | Meaning |
126
+ |---|---|
127
+ | `kind` | `"gap"`, `"overlap"` or `"normal"` |
128
+ | `zone` | IANA zone name, or a list of names |
129
+ | `tag` | e.g. `"midnight"`, `"odd_offset"`, `"delta_30min"`, `"dst"` |
130
+ | `year` | local year |
131
+
132
+ A test that takes `dst_case` without the marker gets every case. `dst_case` is a `dst_test_vectors.Case` (`zone`, `local`, `kind`, `utc`, `earlier`, `later`, `compatible`, `transition_utc`, `tags`, `note`).
133
+
134
+ If the filters match 0 cases, or `kind` is not one of the three kinds, collection of that test fails with a message that names the filters. Unknown marker arguments fail the same way.
135
+
136
+ ## Test ids
137
+
138
+ Ids are `Case.id`: zone, local time, kind.
139
+
140
+ ```
141
+ test_gap_fold[America/New_York 2026-03-08T02:00:00 gap]
142
+ test_overlap_fold[America/New_York 2026-11-01T01:30:00 overlap]
143
+ ```
144
+
145
+ Select one with `-k "New_York and overlap"`.
146
+
147
+ ## Options
148
+
149
+ | Option | Ini | Meaning |
150
+ |---|---|---|
151
+ | `--dst-vectors=PATH` | `dst_vectors_file` | Vectors JSON file in the `dst-test-vectors` format. Default: the bundled sample. A relative ini path is taken from the rootdir. |
152
+
153
+ The report header shows what is active, for example `dst-vectors: bundled sample, tzdata 2026f, 36 cases`. An unreadable file stops pytest with a usage error.
154
+
155
+ ## What the bundled sample covers
156
+
157
+ 36 cases for 2026 in 5 zones (America/New_York, Europe/London, America/Havana, Australia/Lord_Howe, Pacific/Chatham), generated from IANA tzdata 2026f: gaps, overlaps and the seconds next to each change, including a 30-minute change (Lord Howe), +12:45/+13:45 (Chatham) and changes at midnight (Havana). Cases are unchanged from the `dst-test-vectors` bundle. The expected values only match a machine whose tz database is as new as the vectors, so an older system tzdata can fail a few cases; install `tzdata` to pin one.
158
+
159
+ ## Full set
160
+
161
+ The full set has 51,404 vectors for 2000-2050 in every zone, in the same JSON format: https://github.com/plainfoldhq/tz-transitions (paid; the sample above is free). DST dates by country: https://plainfoldhq.github.io/dst-dates/
162
+
163
+ ## About
164
+
165
+ Plainfold is an AI-run business; this package was written and tested by AI agents.
166
+
167
+ MIT license. Questions: plainfoldhq@proton.me.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pytest_dst_vectors/__init__.py
5
+ src/pytest_dst_vectors/plugin.py
6
+ src/pytest_dst_vectors.egg-info/PKG-INFO
7
+ src/pytest_dst_vectors.egg-info/SOURCES.txt
8
+ src/pytest_dst_vectors.egg-info/dependency_links.txt
9
+ src/pytest_dst_vectors.egg-info/entry_points.txt
10
+ src/pytest_dst_vectors.egg-info/requires.txt
11
+ src/pytest_dst_vectors.egg-info/top_level.txt
12
+ tests/test_plugin.py
13
+ tests/test_readme.py
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ dst_vectors = pytest_dst_vectors.plugin
@@ -0,0 +1,2 @@
1
+ dst-test-vectors==0.1.1
2
+ pytest>=7
@@ -0,0 +1 @@
1
+ pytest_dst_vectors
@@ -0,0 +1,311 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+ from datetime import datetime, timezone
7
+ from zoneinfo import ZoneInfo
8
+
9
+ import dst_test_vectors as dtv
10
+ import pytest
11
+
12
+ SAMPLE_JSON = os.path.join(os.path.dirname(dtv.__file__), "data", "sample.json")
13
+
14
+ TEST_SRC = """
15
+ import pytest
16
+
17
+ @pytest.mark.dst_vectors({args})
18
+ def test_it(dst_case):
19
+ assert dst_case.zone
20
+ """
21
+
22
+ FILTER_SETS = [
23
+ {"kind": "gap"},
24
+ {"kind": "overlap"},
25
+ {"kind": "normal"},
26
+ {"zone": "Europe/London"},
27
+ {"zone": ["America/New_York", "Pacific/Chatham"]},
28
+ {"tag": "midnight"},
29
+ {"tag": "delta_30min", "kind": "gap"},
30
+ {"year": 2026, "kind": "overlap"},
31
+ {"zone": "America/Havana", "kind": "normal", "tag": "dst"},
32
+ ]
33
+
34
+
35
+ def _args(filters):
36
+ return ", ".join(f"{k}={v!r}" for k, v in filters.items())
37
+
38
+
39
+ def _write_small_file(path):
40
+ data = json.load(open(SAMPLE_JSON, encoding="utf-8"))
41
+ picked = []
42
+ for kind_flag in ("gap", "overlap", "normal"):
43
+ for raw in data["cases"]:
44
+ c = dtv.Case(raw)
45
+ if c.kind == kind_flag and c.zone == "America/New_York":
46
+ picked.append(raw)
47
+ break
48
+ data["cases"] = picked
49
+ data["tzdata_version"] = "test-9"
50
+ path.write_text(json.dumps(data), encoding="utf-8")
51
+ return picked
52
+
53
+
54
+ @pytest.mark.parametrize("filters", FILTER_SETS, ids=lambda f: _args(f))
55
+ def test_marker_count_matches_cases(pytester, filters):
56
+ pytester.makepyfile(TEST_SRC.format(args=_args(filters)))
57
+ result = pytester.runpytest()
58
+ expected = len(dtv.cases(**filters))
59
+ assert expected > 0
60
+ result.assert_outcomes(passed=expected)
61
+
62
+
63
+ def test_no_marker_gets_all_cases(pytester):
64
+ pytester.makepyfile("def test_it(dst_case):\n assert dst_case.kind in ('gap', 'overlap', 'normal')\n")
65
+ pytester.runpytest().assert_outcomes(passed=len(dtv.cases()))
66
+
67
+
68
+ def test_ids_are_case_ids(pytester):
69
+ pytester.makepyfile(TEST_SRC.format(args='kind="overlap", zone="America/New_York"'))
70
+ result = pytester.runpytest("--collect-only", "-q")
71
+ want = [f"test_ids_are_case_ids.py::test_it[{c.id}]" for c in dtv.cases(kind="overlap", zone="America/New_York")]
72
+ assert want and result.outlines[: len(want)] == want
73
+
74
+
75
+ def test_dst_case_is_case_object(pytester):
76
+ pytester.makepyfile(
77
+ "import dst_test_vectors as dtv\n"
78
+ "def test_it(dst_case):\n assert isinstance(dst_case, dtv.Case)\n")
79
+ pytester.runpytest().assert_outcomes(passed=len(dtv.cases()))
80
+
81
+
82
+ def test_marker_registered(pytester):
83
+ result = pytester.runpytest("--markers")
84
+ result.stdout.fnmatch_lines(["@pytest.mark.dst_vectors(kind=None, zone=None, tag=None, year=None):*"])
85
+ pytester.makepyfile(TEST_SRC.format(args='kind="gap"'))
86
+ pytester.runpytest("--strict-markers").assert_outcomes(passed=len(dtv.cases(kind="gap")))
87
+
88
+
89
+ def test_header_default(pytester):
90
+ result = pytester.runpytest("--collect-only")
91
+ result.stdout.fnmatch_lines([f"dst-vectors: bundled sample, tzdata {dtv.TZDATA_VERSION}, 36 cases"])
92
+
93
+
94
+ def test_option_file(pytester):
95
+ f = pytester.path / "small.json"
96
+ picked = _write_small_file(f)
97
+ pytester.makepyfile("def test_it(dst_case):\n assert dst_case.zone == 'America/New_York'\n")
98
+ result = pytester.runpytest(f"--dst-vectors={f}")
99
+ result.assert_outcomes(passed=3)
100
+ result.stdout.fnmatch_lines([f"dst-vectors: {f}, tzdata test-9, 3 cases"])
101
+ assert len(picked) == 3
102
+
103
+
104
+ def test_option_relative_path_and_marker_filters(pytester):
105
+ _write_small_file(pytester.path / "small.json")
106
+ pytester.makepyfile(TEST_SRC.format(args='kind="gap"'))
107
+ pytester.runpytest("--dst-vectors=small.json").assert_outcomes(passed=1)
108
+
109
+
110
+ def test_ini_option(pytester):
111
+ _write_small_file(pytester.path / "small.json")
112
+ pytester.makeini("[pytest]\ndst_vectors_file = small.json\n")
113
+ pytester.makepyfile("def test_it(dst_case):\n pass\n")
114
+ result = pytester.runpytest()
115
+ result.assert_outcomes(passed=3)
116
+ result.stdout.fnmatch_lines(["dst-vectors: *small.json, tzdata test-9, 3 cases"])
117
+
118
+
119
+ def test_cli_beats_ini(pytester):
120
+ _write_small_file(pytester.path / "small.json")
121
+ pytester.makeini("[pytest]\ndst_vectors_file = small.json\n")
122
+ pytester.makepyfile("def test_it(dst_case):\n pass\n")
123
+ pytester.runpytest(f"--dst-vectors={SAMPLE_JSON}").assert_outcomes(passed=36)
124
+
125
+
126
+ def test_missing_file_is_usage_error(pytester):
127
+ result = pytester.runpytest("--dst-vectors=nope.json")
128
+ assert result.ret != 0
129
+ result.stderr.fnmatch_lines(["*cannot read vectors file*nope.json*"])
130
+
131
+
132
+ def test_dst_check_uses_active_file(pytester):
133
+ _write_small_file(pytester.path / "small.json")
134
+ pytester.makepyfile(
135
+ "import dst_test_vectors as dtv\n"
136
+ "def test_it(dst_check):\n"
137
+ " seen = []\n"
138
+ " def f(zone, local):\n"
139
+ " seen.append(zone)\n"
140
+ " return dtv.to_utc(local, zone)\n"
141
+ " assert dst_check(f) == []\n"
142
+ " assert len(seen) == 3\n"
143
+ " assert dst_check(lambda z, l: dtv.to_utc(l, z), kind='gap') == []\n")
144
+ pytester.runpytest("--dst-vectors=small.json").assert_outcomes(passed=1)
145
+
146
+
147
+ def test_dst_check_reports_mismatch(pytester):
148
+ pytester.makepyfile(
149
+ "from datetime import datetime, timezone\n"
150
+ "def test_it(dst_check):\n"
151
+ " bad = dst_check(lambda z, l: datetime(2000, 1, 1, tzinfo=timezone.utc), kind='gap')\n"
152
+ " assert len(bad) == 10\n")
153
+ pytester.runpytest().assert_outcomes(passed=1)
154
+
155
+
156
+ def test_zero_match_fails_collection(pytester):
157
+ pytester.makepyfile(TEST_SRC.format(args='zone="Mars/Olympus", kind="gap"'))
158
+ result = pytester.runpytest()
159
+ result.assert_outcomes(errors=1)
160
+ result.stdout.fnmatch_lines(["*dst_vectors filters*Mars/Olympus*match 0 cases*"])
161
+
162
+
163
+ def test_zero_match_names_file(pytester):
164
+ f = pytester.path / "small.json"
165
+ _write_small_file(f)
166
+ pytester.makepyfile(TEST_SRC.format(args='year=2031'))
167
+ result = pytester.runpytest(f"--dst-vectors={f}")
168
+ result.assert_outcomes(errors=1)
169
+ result.stdout.fnmatch_lines(["*'year': 2031*match 0 cases in*small.json*"])
170
+
171
+
172
+ def test_bad_kind(pytester):
173
+ pytester.makepyfile(TEST_SRC.format(args='kind="spring"'))
174
+ result = pytester.runpytest()
175
+ result.assert_outcomes(errors=1)
176
+ result.stdout.fnmatch_lines(["*bad dst_vectors filter*spring*kind must be one of*"])
177
+
178
+
179
+ def test_unknown_marker_argument(pytester):
180
+ pytester.makepyfile(TEST_SRC.format(args='colour="red"'))
181
+ result = pytester.runpytest()
182
+ result.assert_outcomes(errors=1)
183
+ result.stdout.fnmatch_lines(["*unknown dst_vectors argument*colour*"])
184
+
185
+
186
+ def test_positional_marker_argument(pytester):
187
+ pytester.makepyfile(TEST_SRC.format(args='"gap"'))
188
+ result = pytester.runpytest()
189
+ result.assert_outcomes(errors=1)
190
+ result.stdout.fnmatch_lines(["*keyword arguments only*"])
191
+
192
+
193
+ def test_tests_without_dst_case_untouched(pytester):
194
+ pytester.makepyfile(
195
+ "import pytest\n"
196
+ "@pytest.mark.dst_vectors(kind='gap')\n"
197
+ "def test_plain():\n pass\n")
198
+ pytester.runpytest().assert_outcomes(passed=1)
199
+
200
+
201
+ # ---- independent checks of the bundled sample ---------------------------------------------
202
+
203
+ SAMPLE_ZONES = ["America/New_York", "Europe/London", "America/Havana", "Australia/Lord_Howe",
204
+ "Pacific/Chatham"]
205
+
206
+
207
+ def _tzdata_versions():
208
+ """Versions of the tz databases in use: (zoneinfo's, zdump's)."""
209
+ import zoneinfo
210
+ zi = None
211
+ for d in zoneinfo.TZPATH:
212
+ p = os.path.join(d, "tzdata.zi")
213
+ if os.path.exists(p):
214
+ zi = open(p).readline().split()[-1]
215
+ break
216
+ if zi is None:
217
+ try:
218
+ from importlib.metadata import version
219
+ y, n = version("tzdata").split(".")[:2]
220
+ zi = y + chr(ord("a") + int(n) - 1)
221
+ except Exception: # noqa: BLE001
222
+ zi = None
223
+ sysp = "/usr/share/zoneinfo/tzdata.zi"
224
+ sys_v = open(sysp).readline().split()[-1] if os.path.exists(sysp) else None
225
+ return zi, sys_v
226
+
227
+
228
+ def _agree_or_skip(db_version, fn):
229
+ """Run fn; an AssertionError fails the test, unless the tz database in use is not the version
230
+ the vectors were built from (then a difference is expected, so skip)."""
231
+ try:
232
+ fn()
233
+ except AssertionError:
234
+ if db_version != dtv.TZDATA_VERSION:
235
+ pytest.skip(f"tz database is {db_version}, vectors are {dtv.TZDATA_VERSION}: may differ")
236
+ raise
237
+
238
+
239
+ def test_zoneinfo_fold_semantics_agree_with_every_case():
240
+ """Python zoneinfo (PEP 495 fold) vs every bundled gap/overlap case. Independent of dtv.check."""
241
+ zi_v, _ = _tzdata_versions()
242
+
243
+ def run():
244
+ n = 0
245
+ for c in dtv.cases():
246
+ if c.kind == "normal":
247
+ continue
248
+ z = ZoneInfo(c.zone)
249
+ f0 = c.local.replace(tzinfo=z, fold=0).astimezone(timezone.utc)
250
+ f1 = c.local.replace(tzinfo=z, fold=1).astimezone(timezone.utc)
251
+ if c.kind == "overlap":
252
+ assert (f0, f1) == (c.earlier, c.later), c.id
253
+ else: # gap: fold=0 -> offset before (later instant), fold=1 -> offset after (earlier)
254
+ assert (f0, f1) == (c.later, c.earlier), c.id
255
+ assert c.compatible == f0, c.id
256
+ n += 1
257
+ assert n == len(dtv.cases(kind="gap")) + len(dtv.cases(kind="overlap")) == 18
258
+
259
+ _agree_or_skip(zi_v, run)
260
+
261
+
262
+ def _zdump(zone):
263
+ out = subprocess.run(["zdump", "-v", "-c", "2026,2027", zone], capture_output=True, text=True,
264
+ check=True).stdout
265
+ rows = []
266
+ for line in out.splitlines():
267
+ m = re.match(r"\S+\s+\w+ (\w+) +(\d+) (\d+):(\d+):(\d+) (\d{4}) UT = .* isdst=\d gmtoff=(-?\d+)$", line)
268
+ if m:
269
+ mon, day, hh, mm, ss, yr, off = m.groups()
270
+ t = datetime.strptime(f"{yr} {mon} {day} {hh}:{mm}:{ss}", "%Y %b %d %H:%M:%S").replace(tzinfo=timezone.utc)
271
+ rows.append((t, int(off)))
272
+ # some zdump builds also print far-future sentinel lines (years like 2147485547): skipped by \d{4}
273
+ return rows
274
+
275
+
276
+ def _zdump_transitions(zone):
277
+ """[(instant, offset_before_s, offset_after_s)] where the UTC offset changes, 2026."""
278
+ rows = _zdump(zone)
279
+ out = []
280
+ for (t0, o0), (t1, o1) in zip(rows, rows[1:]):
281
+ if (t1 - t0).total_seconds() == 1 and o0 != o1:
282
+ out.append((t1, o0, o1))
283
+ return out
284
+
285
+
286
+ @pytest.mark.skipif(shutil.which("zdump") is None, reason="zdump not installed")
287
+ @pytest.mark.parametrize("zone", SAMPLE_ZONES)
288
+ def test_zdump_agrees_with_gap_and_overlap_cases(zone):
289
+ """Transition instants and offsets from `zdump -v` vs the bundled cases, in 2026."""
290
+ _, sys_v = _tzdata_versions()
291
+ from datetime import timedelta
292
+
293
+ def run():
294
+ trans = {t: (b, a) for t, b, a in _zdump_transitions(zone)}
295
+ zone_cases = [c for c in dtv.cases(zone=zone) if c.kind in ("gap", "overlap")]
296
+ assert zone_cases
297
+ # every transition named by a case is a transition zdump reports
298
+ assert {c.transition_utc for c in zone_cases} <= set(trans)
299
+ for c in zone_cases:
300
+ before, after = (timedelta(seconds=s) for s in trans[c.transition_utc])
301
+ naive_utc = c.local.replace(tzinfo=timezone.utc)
302
+ if c.kind == "gap":
303
+ assert after > before, c.id
304
+ assert naive_utc - before == c.compatible == c.later, c.id
305
+ assert naive_utc - after == c.earlier, c.id
306
+ else:
307
+ assert before > after, c.id
308
+ assert naive_utc - before == c.earlier, c.id
309
+ assert naive_utc - after == c.later, c.id
310
+
311
+ _agree_or_skip(sys_v, run)
@@ -0,0 +1,46 @@
1
+ """Runs every Python code block of README.md as a test file under the plugin."""
2
+ import json
3
+ import os
4
+ import re
5
+
6
+ import pytest
7
+
8
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
9
+ README = open(os.path.join(ROOT, "README.md"), encoding="utf-8").read()
10
+ BLOCKS = re.findall(r"```python\n(.*?)```", README, re.S)
11
+
12
+ FULLFILE = "dst_test_vectors.json"
13
+
14
+
15
+ def _stand_in(pytester):
16
+ import dst_test_vectors as dtv
17
+ sample = os.path.join(os.path.dirname(dtv.__file__), "data", "sample.json")
18
+ pytester.path.joinpath(FULLFILE).write_text(open(sample, encoding="utf-8").read(), encoding="utf-8")
19
+
20
+
21
+ def test_readme_has_three_examples():
22
+ assert len(BLOCKS) == 3
23
+
24
+
25
+ @pytest.mark.parametrize("i", range(len(BLOCKS)))
26
+ def test_readme_block(pytester, i):
27
+ code = BLOCKS[i]
28
+ assert "def test_" in code
29
+ pytester.makepyfile(**{f"test_readme_{i}": code})
30
+ _stand_in(pytester)
31
+ result = pytester.runpytest()
32
+ assert result.ret == 0, result.stdout.str()
33
+ assert "passed" in result.stdout.str()
34
+ if "Europe/London" in code: # example 3: also with option and ini, as the README shows
35
+ for args in (["--dst-vectors=" + FULLFILE], []):
36
+ if not args:
37
+ ini = re.search(r"```ini\n(.*?)```", README, re.S).group(1)
38
+ pytester.makeini(ini)
39
+ r = pytester.runpytest(*args)
40
+ r.assert_outcomes(passed=8)
41
+ r.stdout.fnmatch_lines([f"dst-vectors: *{FULLFILE}, tzdata 2026f, 36 cases"])
42
+
43
+
44
+ def test_readme_cli_line_matches():
45
+ assert "pytest --dst-vectors=dst_test_vectors.json" in README
46
+ assert "dst_vectors_file = dst_test_vectors.json" in README