|
9 | 9 | # obtain one at https://mozilla.org/MPL/2.0/. |
10 | 10 |
|
11 | 11 | import ast |
| 12 | +import hashlib |
12 | 13 | import inspect |
13 | 14 | import subprocess |
14 | 15 | import sys |
| 16 | +import tempfile |
15 | 17 | import textwrap |
| 18 | +from pathlib import Path |
16 | 19 | from types import ModuleType |
17 | 20 |
|
18 | 21 | import pytest |
19 | 22 |
|
20 | 23 | from hypothesis import example, given, note, settings, strategies as st |
| 24 | +from hypothesis.configuration import set_hypothesis_home_dir, storage_directory |
21 | 25 | from hypothesis.internal.compat import PYPY |
22 | 26 | from hypothesis.internal.constants_ast import ( |
23 | 27 | Constants, |
@@ -317,3 +321,36 @@ def test_module_too_large(tmp_path): |
317 | 321 | module.__file__ = str(p) |
318 | 322 | assert constants_from_module(module) == Constants() |
319 | 323 | assert constants_from_module(module, limit=False) == Constants(integers={constant}) |
| 324 | + |
| 325 | + |
| 326 | +@skipif_threading # concurrent writes to the same file |
| 327 | +def test_cache_file_is_written_via_a_temporary_file(tmp_path, monkeypatch): |
| 328 | + constant = 18710297 |
| 329 | + p = tmp_path / "cached_constants.py" |
| 330 | + p.write_text(f"a = {constant}\n", encoding="utf-8") |
| 331 | + module = ModuleType("cached_constants") |
| 332 | + module.__file__ = str(p) |
| 333 | + |
| 334 | + temp_paths = [] |
| 335 | + real_mkstemp = tempfile.mkstemp |
| 336 | + |
| 337 | + def recording_mkstemp(*args, **kwargs): |
| 338 | + fd, path = real_mkstemp(*args, **kwargs) |
| 339 | + temp_paths.append(path) |
| 340 | + return fd, path |
| 341 | + |
| 342 | + monkeypatch.setattr(tempfile, "mkstemp", recording_mkstemp) |
| 343 | + # use an empty storage directory, so the cache file can't already exist |
| 344 | + previous_home_dir = storage_directory().path |
| 345 | + set_hypothesis_home_dir(tmp_path / "hypothesis_home") |
| 346 | + try: |
| 347 | + assert constants_from_module(module) == Constants(integers={constant}) |
| 348 | + source_hash = hashlib.sha1(p.read_bytes()).hexdigest()[:16] |
| 349 | + cache_p = storage_directory("constants").path / source_hash |
| 350 | + cached = _constants_from_source(cache_p.read_bytes(), limit=True) |
| 351 | + finally: |
| 352 | + set_hypothesis_home_dir(previous_home_dir) |
| 353 | + |
| 354 | + assert cached == Constants(integers={constant}) |
| 355 | + assert len(temp_paths) == 1 |
| 356 | + assert not Path(temp_paths[0]).exists() |
0 commit comments