| 1 |
# This file is part of Hypothesis, which may be found at |
| 2 |
# https://github.com/HypothesisWorks/hypothesis/ |
| 3 |
# |
| 4 |
# Copyright the Hypothesis Authors. |
| 5 |
# Individual contributors are listed in AUTHORS.rst and the git log. |
| 6 |
# |
| 7 |
# This Source Code Form is subject to the terms of the Mozilla Public License, |
| 8 |
# v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 9 |
# obtain one at https://mozilla.org/MPL/2.0/. |
| 10 |
|
| 11 |
import os |
| 12 |
import re |
| 13 |
import shutil |
| 14 |
import tempfile |
| 15 |
import time |
| 16 |
import zipfile |
| 17 |
from collections import Counter |
| 18 |
from collections.abc import Iterable, Iterator |
| 19 |
from contextlib import contextmanager, nullcontext |
| 20 |
from datetime import datetime, timedelta, timezone |
| 21 |
from pathlib import Path |
| 22 |
from shutil import make_archive, rmtree |
| 23 |
|
| 24 |
import pytest |
| 25 |
|
| 26 |
from hypothesis import ( |
| 27 |
HealthCheck, |
| 28 |
configuration, |
| 29 |
example, |
| 30 |
given, |
| 31 |
settings, |
| 32 |
strategies as st, |
| 33 |
) |
| 34 |
from hypothesis.database import ( |
| 35 |
BackgroundWriteDatabase, |
| 36 |
DirectoryBasedExampleDatabase, |
| 37 |
ExampleDatabase, |
| 38 |
GitHubArtifactDatabase, |
| 39 |
InMemoryExampleDatabase, |
| 40 |
MultiplexedDatabase, |
| 41 |
ReadOnlyDatabase, |
| 42 |
_db_for_path, |
| 43 |
_pack_uleb128, |
| 44 |
_unpack_uleb128, |
| 45 |
choices_from_bytes, |
| 46 |
choices_to_bytes, |
| 47 |
) |
| 48 |
from hypothesis.errors import HypothesisDeprecationWarning, HypothesisWarning |
| 49 |
from hypothesis.internal.compat import WINDOWS |
| 50 |
from hypothesis.internal.conjecture.choice import choice_equal |
| 51 |
from hypothesis.stateful import ( |
| 52 |
Bundle, |
| 53 |
RuleBasedStateMachine, |
| 54 |
invariant, |
| 55 |
precondition, |
| 56 |
rule, |
| 57 |
run_state_machine_as_test, |
| 58 |
) |
| 59 |
from hypothesis.strategies import binary, lists, tuples |
| 60 |
from hypothesis.utils.conventions import not_set |
| 61 |
|
| 62 |
from tests.common.utils import ( |
| 63 |
checks_deprecated_behaviour, |
| 64 |
skipif_emscripten, |
| 65 |
skipif_threading, |
| 66 |
wait_for, |
| 67 |
) |
| 68 |
from tests.conjecture.common import nodes, nodes_inline |
| 69 |
|
| 70 |
# we need real time here, not monkeypatched for CI |
| 71 |
time_sleep = time.sleep |
| 72 |
|
| 73 |
|
| 74 |
@given(lists(tuples(binary(), binary()))) |
| 75 |
@settings(max_examples=50) |
| 76 |
def test_backend_returns_what_you_put_in(xs): |
| 77 |
backend = InMemoryExampleDatabase() |
| 78 |
mapping = {} |
| 79 |
for key, value in xs: |
| 80 |
mapping.setdefault(key, set()).add(value) |
| 81 |
backend.save(key, value) |
| 82 |
for key, values in mapping.items(): |
| 83 |
backend_contents = list(backend.fetch(key)) |
| 84 |
distinct_backend_contents = set(backend_contents) |
| 85 |
assert len(backend_contents) == len(distinct_backend_contents) |
| 86 |
assert distinct_backend_contents == set(values) |
| 87 |
|
| 88 |
|
| 89 |
def test_can_delete_keys(): |
| 90 |
backend = InMemoryExampleDatabase() |
| 91 |
backend.save(b"foo", b"bar") |
| 92 |
backend.save(b"foo", b"baz") |
| 93 |
backend.delete(b"foo", b"bar") |
| 94 |
assert list(backend.fetch(b"foo")) == [b"baz"] |
| 95 |
|
| 96 |
|
| 97 |
def test_default_database_is_in_memory(): |
| 98 |
with pytest.warns(HypothesisDeprecationWarning): |
| 99 |
assert isinstance(ExampleDatabase(), InMemoryExampleDatabase) |
| 100 |
|
| 101 |
|
| 102 |
def test_default_on_disk_database_is_dir(tmp_path): |
| 103 |
with pytest.warns(HypothesisDeprecationWarning): |
| 104 |
assert isinstance( |
| 105 |
ExampleDatabase(tmp_path.joinpath("foo")), DirectoryBasedExampleDatabase |
| 106 |
) |
| 107 |
|
| 108 |
|
| 109 |
def test_does_not_error_when_fetching_when_not_exist(tmp_path): |
| 110 |
db = DirectoryBasedExampleDatabase(tmp_path / "examples") |
| 111 |
db.fetch(b"foo") |
| 112 |
|
| 113 |
|
| 114 |
@pytest.fixture(scope="function", params=["memory", "directory"]) |
| 115 |
def exampledatabase(request, tmp_path): |
| 116 |
if request.param == "memory": |
| 117 |
return InMemoryExampleDatabase() |
| 118 |
assert request.param == "directory" |
| 119 |
return DirectoryBasedExampleDatabase(tmp_path / "examples") |
| 120 |
|
| 121 |
|
| 122 |
def test_can_delete_a_key_that_is_not_present(exampledatabase): |
| 123 |
exampledatabase.delete(b"foo", b"bar") |
| 124 |
|
| 125 |
|
| 126 |
def test_can_fetch_a_key_that_is_not_present(exampledatabase): |
| 127 |
assert list(exampledatabase.fetch(b"foo")) == [] |
| 128 |
|
| 129 |
|
| 130 |
def test_saving_a_key_twice_fetches_it_once(exampledatabase): |
| 131 |
exampledatabase.save(b"foo", b"bar") |
| 132 |
exampledatabase.save(b"foo", b"bar") |
| 133 |
assert list(exampledatabase.fetch(b"foo")) == [b"bar"] |
| 134 |
|
| 135 |
|
| 136 |
def test_can_close_a_database_after_saving(exampledatabase): |
| 137 |
exampledatabase.save(b"foo", b"bar") |
| 138 |
|
| 139 |
|
| 140 |
def test_class_name_is_in_repr(exampledatabase): |
| 141 |
assert type(exampledatabase).__name__ in repr(exampledatabase) |
| 142 |
|
| 143 |
|
| 144 |
def test_an_absent_value_is_present_after_it_moves(exampledatabase): |
| 145 |
exampledatabase.move(b"a", b"b", b"c") |
| 146 |
assert next(exampledatabase.fetch(b"b")) == b"c" |
| 147 |
|
| 148 |
|
| 149 |
def test_an_absent_value_is_present_after_it_moves_to_self(exampledatabase): |
| 150 |
exampledatabase.move(b"a", b"a", b"b") |
| 151 |
assert next(exampledatabase.fetch(b"a")) == b"b" |
| 152 |
|
| 153 |
|
| 154 |
@skipif_threading |
| 155 |
def test_two_directory_databases_can_interact(tmp_path): |
| 156 |
db1 = DirectoryBasedExampleDatabase(tmp_path) |
| 157 |
db2 = DirectoryBasedExampleDatabase(tmp_path) |
| 158 |
db1.save(b"foo", b"bar") |
| 159 |
assert list(db2.fetch(b"foo")) == [b"bar"] |
| 160 |
db2.save(b"foo", b"bar") |
| 161 |
db2.save(b"foo", b"baz") |
| 162 |
assert sorted(db1.fetch(b"foo")) == [b"bar", b"baz"] |
| 163 |
|
| 164 |
|
| 165 |
def test_can_handle_disappearing_files(tmp_path, monkeypatch): |
| 166 |
db = DirectoryBasedExampleDatabase(tmp_path) |
| 167 |
db.save(b"foo", b"bar") |
| 168 |
base_listdir = os.listdir |
| 169 |
monkeypatch.setattr( |
| 170 |
os, "listdir", lambda d: [*base_listdir(d), "this-does-not-exist"] |
| 171 |
) |
| 172 |
assert list(db.fetch(b"foo")) == [b"bar"] |
| 173 |
|
| 174 |
|
| 175 |
def test_readonly_db_is_not_writable(): |
| 176 |
inner = InMemoryExampleDatabase() |
| 177 |
wrapped = ReadOnlyDatabase(inner) |
| 178 |
inner.save(b"key", b"value") |
| 179 |
inner.save(b"key", b"value2") |
| 180 |
wrapped.delete(b"key", b"value") |
| 181 |
wrapped.move(b"key", b"key2", b"value2") |
| 182 |
wrapped.save(b"key", b"value3") |
| 183 |
assert set(wrapped.fetch(b"key")) == {b"value", b"value2"} |
| 184 |
assert set(wrapped.fetch(b"key2")) == set() |
| 185 |
|
| 186 |
|
| 187 |
def test_multiplexed_dbs_read_and_write_all(): |
| 188 |
a = InMemoryExampleDatabase() |
| 189 |
b = InMemoryExampleDatabase() |
| 190 |
multi = MultiplexedDatabase(a, b) |
| 191 |
a.save(b"a", b"aa") |
| 192 |
b.save(b"b", b"bb") |
| 193 |
multi.save(b"c", b"cc") |
| 194 |
multi.move(b"a", b"b", b"aa") |
| 195 |
for db in (a, b, multi): |
| 196 |
assert set(db.fetch(b"a")) == set() |
| 197 |
assert set(db.fetch(b"c")) == {b"cc"} |
| 198 |
got = list(multi.fetch(b"b")) |
| 199 |
assert len(got) == 2 |
| 200 |
assert set(got) == {b"aa", b"bb"} |
| 201 |
multi.delete(b"c", b"cc") |
| 202 |
for db in (a, b, multi): |
| 203 |
assert set(db.fetch(b"c")) == set() |
| 204 |
|
| 205 |
|
| 206 |
def test_ga_require_readonly_wrapping(): |
| 207 |
"""Test that GitHubArtifactDatabase requires wrapping around ReadOnlyDatabase""" |
| 208 |
database = GitHubArtifactDatabase("test", "test") |
| 209 |
# save, move and delete can only be called when wrapped around ReadonlyDatabase |
| 210 |
with pytest.raises(RuntimeError, match=re.escape(database._read_only_message)): |
| 211 |
database.save(b"foo", b"bar") |
| 212 |
with pytest.raises(RuntimeError): |
| 213 |
database.move(b"foo", b"bar", b"foobar") |
| 214 |
with pytest.raises(RuntimeError): |
| 215 |
database.delete(b"foo", b"bar") |
| 216 |
|
| 217 |
# check that the database silently ignores writes when wrapped around ReadOnlyDatabase |
| 218 |
database = ReadOnlyDatabase(database) |
| 219 |
database.save(b"foo", b"bar") |
| 220 |
database.move(b"foo", b"bar", b"foobar") |
| 221 |
database.delete(b"foo", b"bar") |
| 222 |
|
| 223 |
|
| 224 |
@contextmanager |
| 225 |
def ga_empty_artifact( |
| 226 |
date: datetime | None = None, path: Path | None = None |
| 227 |
) -> Iterator[tuple[Path, Path]]: |
| 228 |
"""Creates an empty GitHub artifact.""" |
| 229 |
if date: |
| 230 |
timestamp = date.isoformat().replace(":", "_") |
| 231 |
else: |
| 232 |
timestamp = datetime.now(timezone.utc).isoformat().replace(":", "_") |
| 233 |
|
| 234 |
temp_dir = None |
| 235 |
if not path: |
| 236 |
temp_dir = tempfile.mkdtemp() |
| 237 |
path = Path(temp_dir) / "github-artifacts" |
| 238 |
|
| 239 |
path.mkdir(parents=True, exist_ok=True) |
| 240 |
zip_path = path / f"{timestamp}.zip" |
| 241 |
|
| 242 |
with zipfile.ZipFile(zip_path, "w"): |
| 243 |
pass |
| 244 |
|
| 245 |
try: |
| 246 |
yield (path, zip_path) |
| 247 |
finally: |
| 248 |
if temp_dir: |
| 249 |
rmtree(temp_dir) |
| 250 |
|
| 251 |
|
| 252 |
def test_ga_empty_read(): |
| 253 |
"""Tests that an inexistent key returns nothing.""" |
| 254 |
with ga_empty_artifact() as (path, _): |
| 255 |
database = GitHubArtifactDatabase("test", "test", path=path) |
| 256 |
assert list(database.fetch(b"foo")) == [] |
| 257 |
|
| 258 |
|
| 259 |
def test_ga_initialize(): |
| 260 |
""" |
| 261 |
Tests that the database is initialized when a new artifact is found. |
| 262 |
As well that initialization doesn't happen again on the next fetch. |
| 263 |
""" |
| 264 |
now = datetime.now(timezone.utc) |
| 265 |
with ga_empty_artifact(date=(now - timedelta(hours=2))) as (path, _): |
| 266 |
database = GitHubArtifactDatabase("test", "test", path=path) |
| 267 |
# Trigger initialization |
| 268 |
list(database.fetch(b"")) |
| 269 |
initial_artifact = database._artifact |
| 270 |
assert initial_artifact |
| 271 |
assert database._artifact |
| 272 |
assert database._access_cache is not None |
| 273 |
with ga_empty_artifact(date=now, path=path) as (path, _): |
| 274 |
# Initialization shouldn't happen again |
| 275 |
list(database.fetch(b"")) |
| 276 |
assert database._initialized |
| 277 |
assert database._artifact == initial_artifact |
| 278 |
|
| 279 |
|
| 280 |
def test_ga_no_artifact(tmp_path): |
| 281 |
"""Tests that the database is disabled when no artifact is found.""" |
| 282 |
database = GitHubArtifactDatabase("test", "test", path=tmp_path) |
| 283 |
# Check that the database raises a warning |
| 284 |
with pytest.warns(HypothesisWarning): |
| 285 |
assert list(database.fetch(b"")) == [] |
| 286 |
assert database._disabled is True |
| 287 |
assert list(database.fetch(b"")) == [] |
| 288 |
|
| 289 |
|
| 290 |
def test_ga_corrupted_artifact(): |
| 291 |
"""Tests that corrupted artifacts are properly detected and warned about.""" |
| 292 |
with ga_empty_artifact() as (path, zip_path): |
| 293 |
# Corrupt the CRC of the zip file |
| 294 |
with open(zip_path, "rb+") as f: |
| 295 |
f.write(b"\x00\x01\x00\x01") |
| 296 |
|
| 297 |
database = GitHubArtifactDatabase("test", "test", path=path) |
| 298 |
# Check that the database raises a warning |
| 299 |
with pytest.warns(HypothesisWarning): |
| 300 |
assert list(database.fetch(b"")) == [] |
| 301 |
assert database._disabled is True |
| 302 |
|
| 303 |
|
| 304 |
def test_ga_deletes_old_artifacts(): |
| 305 |
"""Tests that old artifacts are automatically deleted.""" |
| 306 |
now = datetime.now(timezone.utc) |
| 307 |
with ( |
| 308 |
ga_empty_artifact(date=now) as (path, file_now), |
| 309 |
ga_empty_artifact(date=now - timedelta(hours=2), path=path) as ( |
| 310 |
_, |
| 311 |
file_old, |
| 312 |
), |
| 313 |
): |
| 314 |
database = GitHubArtifactDatabase("test", "test", path=path) |
| 315 |
# Trigger initialization |
| 316 |
list(database.fetch(b"")) |
| 317 |
assert file_now.exists() |
| 318 |
assert not file_old.exists() |
| 319 |
|
| 320 |
|
| 321 |
@skipif_threading |
| 322 |
def test_ga_triggers_fetching(monkeypatch, tmp_path): |
| 323 |
"""Tests whether an artifact fetch is triggered, and an expired artifact is deleted.""" |
| 324 |
with ga_empty_artifact() as (_, artifact): |
| 325 |
# We patch the _fetch_artifact method to return our artifact |
| 326 |
def fake_fetch_artifact(self) -> Path | None: |
| 327 |
return artifact |
| 328 |
|
| 329 |
monkeypatch.setattr( |
| 330 |
GitHubArtifactDatabase, "_fetch_artifact", fake_fetch_artifact |
| 331 |
) |
| 332 |
|
| 333 |
database = GitHubArtifactDatabase( |
| 334 |
"test", "test", path=tmp_path, cache_timeout=timedelta(days=1) |
| 335 |
) |
| 336 |
|
| 337 |
# Test without an existing artifact |
| 338 |
list(database.fetch(b"")) |
| 339 |
|
| 340 |
assert not database._disabled |
| 341 |
assert database._initialized |
| 342 |
assert database._artifact == artifact |
| 343 |
|
| 344 |
# Now we'll see if the DB also fetched correctly with an expired artifact |
| 345 |
now = datetime.now(timezone.utc) |
| 346 |
# We create an expired artifact |
| 347 |
with ga_empty_artifact(date=now - timedelta(days=2)) as ( |
| 348 |
path_with_artifact, |
| 349 |
old_artifact, |
| 350 |
): |
| 351 |
database = GitHubArtifactDatabase( |
| 352 |
"test", "test", path=path_with_artifact, cache_timeout=timedelta(days=1) |
| 353 |
) |
| 354 |
|
| 355 |
# Trigger initialization |
| 356 |
list(database.fetch(b"")) |
| 357 |
assert not database._disabled |
| 358 |
assert database._initialized |
| 359 |
assert database._artifact == artifact |
| 360 |
|
| 361 |
# Check that the artifact was deleted |
| 362 |
assert not old_artifact.exists() |
| 363 |
|
| 364 |
|
| 365 |
def test_ga_fallback_expired(monkeypatch): |
| 366 |
""" |
| 367 |
Tests that the fallback to an expired artifact is triggered |
| 368 |
if fetching a new one fails. This allows for (by example) offline development. |
| 369 |
""" |
| 370 |
now = datetime.now(timezone.utc) |
| 371 |
with ga_empty_artifact(date=now - timedelta(days=2)) as (path, artifact): |
| 372 |
database = GitHubArtifactDatabase( |
| 373 |
"test", "test", path=path, cache_timeout=timedelta(days=1) |
| 374 |
) |
| 375 |
|
| 376 |
# This should trigger the fallback |
| 377 |
def fake_fetch_artifact(self) -> Path | None: |
| 378 |
return None |
| 379 |
|
| 380 |
monkeypatch.setattr( |
| 381 |
GitHubArtifactDatabase, "_fetch_artifact", fake_fetch_artifact |
| 382 |
) |
| 383 |
|
| 384 |
# Trigger initialization |
| 385 |
with pytest.warns(HypothesisWarning): |
| 386 |
list(database.fetch(b"")) |
| 387 |
|
| 388 |
assert not database._disabled |
| 389 |
assert database._initialized |
| 390 |
assert database._artifact == artifact |
| 391 |
|
| 392 |
|
| 393 |
class GitHubArtifactMocks(RuleBasedStateMachine): |
| 394 |
""" |
| 395 |
This is a state machine that tests agreement of GitHubArtifactDatabase |
| 396 |
with DirectoryBasedExampleDatabase (as a reference implementation). |
| 397 |
""" |
| 398 |
|
| 399 |
def __init__(self): |
| 400 |
super().__init__() |
| 401 |
self.temp_directory = Path(tempfile.mkdtemp()) |
| 402 |
self.path = self.temp_directory / "github-artifacts" |
| 403 |
|
| 404 |
# This is where we will store the contents for the zip file |
| 405 |
timestamp = datetime.now(timezone.utc).isoformat().replace(":", "_") |
| 406 |
self.zip_destination = self.path / f"{timestamp}.zip" |
| 407 |
|
| 408 |
# And this is where we want to create it |
| 409 |
self.zip_content_path = self.path / timestamp |
| 410 |
self.zip_content_path.mkdir(parents=True, exist_ok=True) |
| 411 |
|
| 412 |
# We use a DirectoryBasedExampleDatabase to create the contents |
| 413 |
self.directory_db = DirectoryBasedExampleDatabase(str(self.zip_content_path)) |
| 414 |
self.zip_db = GitHubArtifactDatabase("mock", "mock", path=self.path) |
| 415 |
|
| 416 |
# Create zip file for the first time |
| 417 |
self._archive_directory_db() |
| 418 |
self.zip_db._initialize_db() |
| 419 |
|
| 420 |
def _make_zip(self, tree_path: Path, zip_path: Path): |
| 421 |
destination = zip_path.parent.absolute() / zip_path.stem |
| 422 |
make_archive( |
| 423 |
str(destination), |
| 424 |
"zip", |
| 425 |
root_dir=tree_path, |
| 426 |
) |
| 427 |
|
| 428 |
def _archive_directory_db(self): |
| 429 |
# Delete all of the zip files in the directory |
| 430 |
for file in self.path.glob("*.zip"): |
| 431 |
file.unlink() |
| 432 |
|
| 433 |
self._make_zip(self.zip_content_path, self.zip_destination) |
| 434 |
|
| 435 |
keys = Bundle("keys") |
| 436 |
values = Bundle("values") |
| 437 |
|
| 438 |
@rule(target=keys, k=st.binary()) |
| 439 |
def k(self, k): |
| 440 |
return k |
| 441 |
|
| 442 |
@rule(target=values, v=st.binary()) |
| 443 |
def v(self, v): |
| 444 |
return v |
| 445 |
|
| 446 |
@rule(k=keys, v=values) |
| 447 |
def save(self, k, v): |
| 448 |
self.directory_db.save(k, v) |
| 449 |
self._archive_directory_db() |
| 450 |
self.zip_db = GitHubArtifactDatabase("mock", "mock", path=self.path) |
| 451 |
self.zip_db._initialize_db() |
| 452 |
|
| 453 |
@rule(k=keys) |
| 454 |
def values_agree(self, k): |
| 455 |
v1 = set(self.directory_db.fetch(k)) |
| 456 |
v2 = set(self.zip_db.fetch(k)) |
| 457 |
|
| 458 |
assert v1 == v2 |
| 459 |
|
| 460 |
def teardown(self): |
| 461 |
shutil.rmtree(self.temp_directory) |
| 462 |
|
| 463 |
|
| 464 |
TestGADReads = GitHubArtifactMocks.TestCase |
| 465 |
|
| 466 |
|
| 467 |
def test_gadb_coverage(): |
| 468 |
# Ensure that we always cover the nonempty-archive case, which can otherwise |
| 469 |
# cause rare incomplete-coverage failures. |
| 470 |
state = GitHubArtifactMocks() |
| 471 |
state.save(b"key", b"value") |
| 472 |
state.values_agree(b"key") |
| 473 |
|
| 474 |
|
| 475 |
@pytest.mark.parametrize("dirs", [[], ["subdir"]]) |
| 476 |
def test_database_directory_inaccessible(dirs, tmp_path, monkeypatch): |
| 477 |
monkeypatch.setattr( |
| 478 |
configuration, "__hypothesis_home_directory", tmp_path.joinpath(*dirs) |
| 479 |
) |
| 480 |
try: |
| 481 |
tmp_path.chmod(0o000) |
| 482 |
with ( |
| 483 |
nullcontext() |
| 484 |
if WINDOWS |
| 485 |
else pytest.warns( |
| 486 |
HypothesisWarning, match=".*the default location is unusable" |
| 487 |
) |
| 488 |
): |
| 489 |
database = _db_for_path(not_set) |
| 490 |
database.save(b"fizz", b"buzz") |
| 491 |
finally: |
| 492 |
tmp_path.chmod(0o600) # So that pytest can clean up tmp_path later |
| 493 |
|
| 494 |
|
| 495 |
@skipif_emscripten |
| 496 |
def test_background_write_database(): |
| 497 |
db = BackgroundWriteDatabase(InMemoryExampleDatabase()) |
| 498 |
db.save(b"a", b"b") |
| 499 |
db.save(b"a", b"c") |
| 500 |
db.save(b"a", b"d") |
| 501 |
assert set(db.fetch(b"a")) == {b"b", b"c", b"d"} |
| 502 |
|
| 503 |
db.move(b"a", b"a2", b"b") |
| 504 |
assert set(db.fetch(b"a")) == {b"c", b"d"} |
| 505 |
assert set(db.fetch(b"a2")) == {b"b"} |
| 506 |
|
| 507 |
db.delete(b"a", b"c") |
| 508 |
assert set(db.fetch(b"a")) == {b"d"} |
| 509 |
|
| 510 |
|
| 511 |
@given(lists(nodes())) |
| 512 |
# covering examples |
| 513 |
@example(nodes_inline(True)) |
| 514 |
@example(nodes_inline(1)) |
| 515 |
@example(nodes_inline(0.0)) |
| 516 |
@example(nodes_inline(-0.0)) |
| 517 |
@example(nodes_inline("a")) |
| 518 |
@example(nodes_inline(b"a")) |
| 519 |
@example(nodes_inline(b"a" * 50)) |
| 520 |
@example(nodes_inline(b"1" * 100_000)) # really long bytes |
| 521 |
def test_nodes_roundtrips(nodes1): |
| 522 |
s1 = choices_to_bytes([n.value for n in nodes1]) |
| 523 |
assert isinstance(s1, bytes) |
| 524 |
ir2 = choices_from_bytes(s1) |
| 525 |
assert len(nodes1) == len(ir2) |
| 526 |
|
| 527 |
for n1, v2 in zip(nodes1, ir2, strict=True): |
| 528 |
assert choice_equal(n1.value, v2) |
| 529 |
|
| 530 |
s2 = choices_to_bytes(ir2) |
| 531 |
assert s1 == s2 |
| 532 |
|
| 533 |
|
| 534 |
@given(st.integers(min_value=0)) |
| 535 |
def test_uleb_128_roundtrips(n1): |
| 536 |
buffer1 = _pack_uleb128(n1) |
| 537 |
idx, n2 = _unpack_uleb128(buffer1) |
| 538 |
assert idx == len(buffer1) |
| 539 |
assert n1 == n2 |
| 540 |
|
| 541 |
|
| 542 |
def _database_conforms_to_listener_api( |
| 543 |
create_db, |
| 544 |
*, |
| 545 |
flush=None, |
| 546 |
supports_value_delete=True, |
| 547 |
parent_settings=None, |
| 548 |
): |
| 549 |
# this function is a big mess to support a bunch of different special cases |
| 550 |
# for different databases, sorry. In return, we get one big stateful test |
| 551 |
# we can use to test the listener api for all of our databases. |
| 552 |
# |
| 553 |
# * create_db is a callable which accepts one argument (a path to a temporary |
| 554 |
# directory) and returns a database instance. |
| 555 |
# * flush is a callable which takes the instantiated db as an argument, and |
| 556 |
# is called on every step as an invariant. This lets the database do things |
| 557 |
# like, time.sleep to give time for events to fire. |
| 558 |
# * suports_value_delete is True if the db supports passing |
| 559 |
# the exact value of a deleted key in "delete" events. The directory database |
| 560 |
# notably does not support this, and passes None instead. |
| 561 |
|
| 562 |
@settings(parent_settings, suppress_health_check=[HealthCheck.too_slow]) |
| 563 |
class TestDatabaseListener(RuleBasedStateMachine): |
| 564 |
# this tests that if we call .delete, .save, or .move in a database, and |
| 565 |
# that operation changes the state of the database, any registered listeners |
| 566 |
# get called a corresponding number of times. |
| 567 |
keys = Bundle("keys") |
| 568 |
values = Bundle("values") |
| 569 |
|
| 570 |
def __init__(self): |
| 571 |
super().__init__() |
| 572 |
|
| 573 |
self.temp_dir = Path(tempfile.mkdtemp()) |
| 574 |
self.db = create_db(self.temp_dir) |
| 575 |
self.expected_events = [] |
| 576 |
self.actual_events = [] |
| 577 |
|
| 578 |
def listener(event): |
| 579 |
self.actual_events.append(event) |
| 580 |
|
| 581 |
self.listener = listener |
| 582 |
self.active_listeners = [] |
| 583 |
self.add_listener() |
| 584 |
|
| 585 |
def _expect_event(self, event_type, args): |
| 586 |
for _ in range(len(self.active_listeners)): |
| 587 |
self.expected_events.append((event_type, args)) |
| 588 |
|
| 589 |
def _expect_delete(self, k, v): |
| 590 |
if not supports_value_delete: |
| 591 |
v = None |
| 592 |
self._expect_event("delete", (k, v)) |
| 593 |
|
| 594 |
def _expect_save(self, k, v): |
| 595 |
self._expect_event("save", (k, v)) |
| 596 |
|
| 597 |
@rule(target=keys, k=st.binary()) |
| 598 |
def k(self, k): |
| 599 |
return k |
| 600 |
|
| 601 |
@rule(target=values, v=st.binary()) |
| 602 |
def v(self, v): |
| 603 |
return v |
| 604 |
|
| 605 |
@precondition(lambda self: not self.active_listeners) |
| 606 |
@rule() |
| 607 |
def add_listener(self): |
| 608 |
self.db.add_listener(self.listener) |
| 609 |
# wait for watchdog to initialize the listener asynchronously |
| 610 |
time_sleep(0.1) |
| 611 |
self.active_listeners.append(self.listener) |
| 612 |
|
| 613 |
@precondition(lambda self: self.listener in self.active_listeners) |
| 614 |
@rule() |
| 615 |
def remove_listener(self): |
| 616 |
self.db.remove_listener(self.listener) |
| 617 |
self.active_listeners.remove(self.listener) |
| 618 |
|
| 619 |
@rule() |
| 620 |
def clear_listeners(self): |
| 621 |
self.db.clear_listeners() |
| 622 |
self.active_listeners.clear() |
| 623 |
|
| 624 |
@rule(k=keys) |
| 625 |
def fetch(self, k): |
| 626 |
# we don't expect this to do anything, but that's the point. if this |
| 627 |
# fires a listener call then that's bad and will fail. |
| 628 |
self.db.fetch(k) |
| 629 |
|
| 630 |
@rule(k=keys, v=values) |
| 631 |
def save(self, k, v): |
| 632 |
changed = v not in set(self.db.fetch(k)) |
| 633 |
self.db.save(k, v) |
| 634 |
|
| 635 |
if changed: |
| 636 |
self._expect_save(k, v) |
| 637 |
|
| 638 |
@rule(k=keys, v=values) |
| 639 |
def delete(self, k, v): |
| 640 |
changed = v in set(self.db.fetch(k)) |
| 641 |
self.db.delete(k, v) |
| 642 |
|
| 643 |
if changed: |
| 644 |
self._expect_delete(k, v) |
| 645 |
|
| 646 |
@rule(k1=keys, k2=keys, v=values) |
| 647 |
def move(self, k1, k2, v): |
| 648 |
in_k1 = v in set(self.db.fetch(k1)) |
| 649 |
save_changed = v not in set(self.db.fetch(k2)) |
| 650 |
delete_changed = k1 != k2 and in_k1 |
| 651 |
self.db.move(k1, k2, v) |
| 652 |
|
| 653 |
# A move gets emitted as a delete followed by a save. The |
| 654 |
# delete may be omitted if k1==k2, and the save if v in db.fetch(k2). |
| 655 |
if delete_changed: |
| 656 |
self._expect_delete(k1, v) |
| 657 |
if save_changed: |
| 658 |
self._expect_save(k2, v) |
| 659 |
|
| 660 |
# it would be nice if this was an @rule, but that runs into race condition |
| 661 |
# failures where an event listener is removed immediately after a |
| 662 |
# save/delete/move operation, before the listener can fire. This is only |
| 663 |
# relevant for DirectoryBasedExampleDatabase. |
| 664 |
@invariant() |
| 665 |
def events_agree(self): |
| 666 |
if flush is not None: |
| 667 |
flush(self.db) |
| 668 |
|
| 669 |
wait_for( |
| 670 |
lambda: len(self.expected_events) == len(self.actual_events), timeout=60 |
| 671 |
) |
| 672 |
# events *generally* don't arrive out of order, but we've had |
| 673 |
# flakes reported here, especially on weirder / older machines. |
| 674 |
# see https://github.com/HypothesisWorks/hypothesis/issues/4274 |
| 675 |
assert Counter(self.expected_events) == Counter(self.actual_events) |
| 676 |
|
| 677 |
def teardown(self): |
| 678 |
shutil.rmtree(self.temp_dir) |
| 679 |
|
| 680 |
run_state_machine_as_test(TestDatabaseListener) |
| 681 |
|
| 682 |
|
| 683 |
def test_database_listener_memory(): |
| 684 |
_database_conforms_to_listener_api( |
| 685 |
lambda path: InMemoryExampleDatabase(), |
| 686 |
parent_settings=settings(max_examples=5, stateful_step_count=10), |
| 687 |
) |
| 688 |
|
| 689 |
|
| 690 |
@skipif_emscripten |
| 691 |
@pytest.mark.skipif( |
| 692 |
settings.get_current_profile_name() == "crosshair", reason="takes ages" |
| 693 |
) |
| 694 |
def test_database_listener_background_write(): |
| 695 |
_database_conforms_to_listener_api( |
| 696 |
lambda path: BackgroundWriteDatabase(InMemoryExampleDatabase()), |
| 697 |
flush=lambda db: db._join(), |
| 698 |
parent_settings=settings(max_examples=5, stateful_step_count=10), |
| 699 |
) |
| 700 |
|
| 701 |
|
| 702 |
def test_can_remove_nonexistent_listener(): |
| 703 |
db = InMemoryExampleDatabase() |
| 704 |
db.remove_listener(lambda event: event) |
| 705 |
|
| 706 |
|
| 707 |
class DoesNotSupportListening(ExampleDatabase): |
| 708 |
def save(self, key: bytes, value: bytes) -> None: ... |
| 709 |
def fetch(self, key: bytes) -> Iterable[bytes]: ... |
| 710 |
def delete(self, key: bytes, value: bytes) -> None: ... |
| 711 |
|
| 712 |
|
| 713 |
def test_warns_when_listening_not_supported(): |
| 714 |
db = DoesNotSupportListening() |
| 715 |
listener = lambda event: event |
| 716 |
|
| 717 |
with pytest.warns( |
| 718 |
HypothesisWarning, match="does not support listening for changes" |
| 719 |
): |
| 720 |
db.add_listener(listener) |
| 721 |
|
| 722 |
with pytest.warns( |
| 723 |
HypothesisWarning, match="does not support stopping listening for changes" |
| 724 |
): |
| 725 |
db.remove_listener(listener) |
| 726 |
|
| 727 |
|
| 728 |
def test_readonly_listener(): |
| 729 |
db = ReadOnlyDatabase(InMemoryExampleDatabase()) |
| 730 |
|
| 731 |
def listener(event): |
| 732 |
raise AssertionError("ReadOnlyDatabase never fires change events") |
| 733 |
|
| 734 |
db.add_listener(listener) |
| 735 |
db.save(b"a", b"a") |
| 736 |
|
| 737 |
db.remove_listener(listener) |
| 738 |
db.save(b"b", b"b") |
| 739 |
|
| 740 |
|
| 741 |
@skipif_threading |
| 742 |
def test_metakeys_move_into_existing_key(tmp_path): |
| 743 |
db = DirectoryBasedExampleDatabase(tmp_path) |
| 744 |
db.save(b"k1", b"v1") |
| 745 |
db.save(b"k1", b"v2") |
| 746 |
db.save(b"k2", b"v3") |
| 747 |
assert set(db.fetch(db._metakeys_name)) == {b"k1", b"k2"} |
| 748 |
|
| 749 |
db.move(b"k1", b"k2", b"v2") |
| 750 |
assert set(db.fetch(db._metakeys_name)) == {b"k1", b"k2"} |
| 751 |
|
| 752 |
|
| 753 |
@skipif_threading |
| 754 |
def test_metakeys_move_into_nonexistent_key(tmp_path): |
| 755 |
db = DirectoryBasedExampleDatabase(tmp_path) |
| 756 |
db.save(b"k1", b"v1") |
| 757 |
assert set(db.fetch(db._metakeys_name)) == {b"k1"} |
| 758 |
|
| 759 |
db.move(b"k1", b"k2", b"v1") |
| 760 |
assert set(db.fetch(db._metakeys_name)) == {b"k1", b"k2"} |
| 761 |
|
| 762 |
|
| 763 |
@skipif_threading |
| 764 |
def test_metakeys(tmp_path): |
| 765 |
db = DirectoryBasedExampleDatabase(tmp_path) |
| 766 |
|
| 767 |
db.save(b"k1", b"v1") |
| 768 |
assert set(db.fetch(db._metakeys_name)) == {b"k1"} |
| 769 |
|
| 770 |
db.save(b"k1", b"v2") |
| 771 |
assert set(db.fetch(db._metakeys_name)) == {b"k1"} |
| 772 |
|
| 773 |
# deleting all the values from a key removes that metakey |
| 774 |
db.delete(b"k1", b"v1") |
| 775 |
db.delete(b"k1", b"v2") |
| 776 |
assert set(db.fetch(db._metakeys_name)) == set() |
| 777 |
|
| 778 |
db.save(b"k2", b"v1") |
| 779 |
assert set(db.fetch(db._metakeys_name)) == {b"k2"} |
| 780 |
|
| 781 |
|
| 782 |
class TracksListens(ExampleDatabase): |
| 783 |
def __init__(self): |
| 784 |
super().__init__() |
| 785 |
self.starts = 0 |
| 786 |
self.ends = 0 |
| 787 |
|
| 788 |
def save(self, key: bytes, value: bytes) -> None: ... |
| 789 |
def fetch(self, key: bytes) -> Iterable[bytes]: ... |
| 790 |
def delete(self, key: bytes, value: bytes) -> None: ... |
| 791 |
|
| 792 |
def _start_listening(self): |
| 793 |
self.starts += 1 |
| 794 |
|
| 795 |
def _stop_listening(self): |
| 796 |
self.ends += 1 |
| 797 |
|
| 798 |
|
| 799 |
def test_start_end_listening(): |
| 800 |
db = TracksListens() |
| 801 |
|
| 802 |
def listener1(event): |
| 803 |
pass |
| 804 |
|
| 805 |
def listener2(event): |
| 806 |
pass |
| 807 |
|
| 808 |
assert db.starts == 0 |
| 809 |
db.add_listener(listener1) |
| 810 |
assert db.starts == 1 |
| 811 |
db.add_listener(listener2) |
| 812 |
assert db.starts == 1 |
| 813 |
|
| 814 |
assert db.ends == 0 |
| 815 |
db.remove_listener(listener2) |
| 816 |
assert db.ends == 0 |
| 817 |
db.remove_listener(listener1) |
| 818 |
assert db.ends == 1 |
| 819 |
|
| 820 |
db.clear_listeners() |
| 821 |
assert db.ends == 1 |
| 822 |
|
| 823 |
|
| 824 |
@checks_deprecated_behaviour |
| 825 |
def test_deprecated_example_database_path(tmp_path): |
| 826 |
ExampleDatabase(tmp_path) |
| 827 |
|
| 828 |
|
| 829 |
@checks_deprecated_behaviour |
| 830 |
def test_deprecated_example_database_memory(): |
| 831 |
ExampleDatabase(":memory:") |
| 832 |
|
| 833 |
|
| 834 |
@checks_deprecated_behaviour |
| 835 |
def test_deprecated_example_database_no_args(): |
| 836 |
ExampleDatabase() |
| 837 |
|
| 838 |
|
| 839 |
@pytest.mark.parametrize( |
| 840 |
"db1, db2", |
| 841 |
[ |
| 842 |
(DirectoryBasedExampleDatabase("a"), DirectoryBasedExampleDatabase("a")), |
| 843 |
( |
| 844 |
MultiplexedDatabase( |
| 845 |
DirectoryBasedExampleDatabase("a"), DirectoryBasedExampleDatabase("b") |
| 846 |
), |
| 847 |
MultiplexedDatabase( |
| 848 |
DirectoryBasedExampleDatabase("a"), DirectoryBasedExampleDatabase("b") |
| 849 |
), |
| 850 |
), |
| 851 |
( |
| 852 |
ReadOnlyDatabase(DirectoryBasedExampleDatabase("a")), |
| 853 |
ReadOnlyDatabase(DirectoryBasedExampleDatabase("a")), |
| 854 |
), |
| 855 |
( |
| 856 |
GitHubArtifactDatabase("owner1", "repo1"), |
| 857 |
GitHubArtifactDatabase("owner1", "repo1"), |
| 858 |
), |
| 859 |
], |
| 860 |
) |
| 861 |
def test_database_equal(db1, db2): |
| 862 |
assert db1 == db2 |
| 863 |
|
| 864 |
|
| 865 |
@pytest.mark.parametrize( |
| 866 |
"db1, db2", |
| 867 |
[ |
| 868 |
(InMemoryExampleDatabase(), InMemoryExampleDatabase()), |
| 869 |
(InMemoryExampleDatabase(), DirectoryBasedExampleDatabase("a")), |
| 870 |
(BackgroundWriteDatabase(InMemoryExampleDatabase()), InMemoryExampleDatabase()), |
| 871 |
(DirectoryBasedExampleDatabase("a"), DirectoryBasedExampleDatabase("b")), |
| 872 |
( |
| 873 |
ReadOnlyDatabase(DirectoryBasedExampleDatabase("a")), |
| 874 |
ReadOnlyDatabase(DirectoryBasedExampleDatabase("b")), |
| 875 |
), |
| 876 |
( |
| 877 |
GitHubArtifactDatabase("owner1", "repo1"), |
| 878 |
GitHubArtifactDatabase("owner2", "repo2"), |
| 879 |
), |
| 880 |
], |
| 881 |
) |
| 882 |
def test_database_not_equal(db1, db2): |
| 883 |
assert db1 != db2 |
| 884 |
|
| 885 |
|
| 886 |
@skipif_threading # race in tmp_path |
| 887 |
def test_directory_db_removes_empty_dirs(tmp_path): |
| 888 |
db = DirectoryBasedExampleDatabase(tmp_path) |
| 889 |
db.save(b"k1", b"v1") |
| 890 |
db.save(b"k1", b"v2") |
| 891 |
assert db._key_path(b"k1").exists() |
| 892 |
assert set(db.fetch(db._metakeys_name)) == {b"k1"} |
| 893 |
|
| 894 |
db.delete(b"k1", b"v1") |
| 895 |
assert db._key_path(b"k1").exists() |
| 896 |
assert set(db.fetch(db._metakeys_name)) == {b"k1"} |
| 897 |
|
| 898 |
db.delete(b"k1", b"v2") |
| 899 |
assert not db._key_path(b"k1").exists() |
| 900 |
assert set(db.fetch(db._metakeys_name)) == set() |