Debian Codegraph @

hypothesis-python/tests/cover/test_settings.py

raw
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 datetime
12 import os
13 import subprocess
14 import sys
15 from contextlib import contextmanager
16 from threading import RLock
17 from unittest import TestCase
18
19 import pytest
20
21 from hypothesis import example, given, strategies as st
22 from hypothesis._settings import (
23 _CI_VARS,
24 HealthCheck,
25 Phase,
26 Verbosity,
27 default_variable,
28 local_settings,
29 settings,
30 )
31 from hypothesis.database import InMemoryExampleDatabase
32 from hypothesis.errors import (
33 HypothesisDeprecationWarning,
34 InvalidArgument,
35 )
36 from hypothesis.stateful import RuleBasedStateMachine, rule
37 from hypothesis.utils.conventions import not_set
38 from hypothesis.utils.deprecation import note_deprecation
39
40 from tests.common.utils import (
41 checks_deprecated_behaviour,
42 counts_calls,
43 fails_with,
44 skipif_emscripten,
45 skipif_threading,
46 validate_deprecation,
47 )
48
49 original_default = settings.get_profile("default").max_examples
50 _temp_register_profile_lock = RLock()
51
52
53 @contextmanager
54 def temp_register_profile(name, parent, **kwargs):
55 with _temp_register_profile_lock:
56 try:
57 settings.register_profile(name, parent, **kwargs)
58 yield
59 finally:
60 settings._profiles.pop(name)
61
62
63 _restore_profile_lock = RLock()
64
65
66 @contextmanager
67 def restore_profile():
68 with _restore_profile_lock:
69 # avoid polluting global state by resetting the loaded profile back to its
70 # previous value in tests which use load_profile
71 current_profile = settings.get_current_profile_name()
72 try:
73 yield
74 finally:
75 settings.load_profile(current_profile)
76
77
78 def test_cannot_set_non_settings():
79 s = settings()
80 with pytest.raises(AttributeError):
81 s.databas_file = "some_file"
82
83
84 def test_settings_uses_defaults():
85 s = settings()
86 assert s.max_examples == settings.default.max_examples
87
88
89 def test_raises_attribute_error():
90 with pytest.raises(AttributeError):
91 settings().kittens
92
93
94 def test_respects_none_database():
95 assert settings(database=None).database is None
96
97
98 def test_can_repeatedly_push_the_same_thing():
99 s = settings(max_examples=12)
100 t = settings(max_examples=17)
101 original = settings().max_examples
102 with local_settings(s):
103 assert settings().max_examples == 12
104 with local_settings(t):
105 assert settings().max_examples == 17
106 with local_settings(s):
107 assert settings().max_examples == 12
108 with local_settings(t):
109 assert settings().max_examples == 17
110 assert settings().max_examples == 12
111 assert settings().max_examples == 17
112 assert settings().max_examples == 12
113 assert settings().max_examples == original
114
115
116 def test_can_set_verbosity():
117 settings(verbosity=Verbosity.quiet)
118 settings(verbosity=Verbosity.normal)
119 settings(verbosity=Verbosity.verbose)
120 settings(verbosity=Verbosity.debug)
121
122
123 def test_can_not_set_verbosity_to_non_verbosity():
124 with pytest.raises(InvalidArgument):
125 settings(verbosity="kittens")
126
127
128 @pytest.mark.parametrize("db", [None, InMemoryExampleDatabase()])
129 def test_inherits_an_empty_database(db):
130 with local_settings(settings(database=InMemoryExampleDatabase())):
131 assert settings.default.database is not None
132 s = settings(database=db)
133 assert s.database is db
134 with local_settings(s):
135 t = settings()
136 assert t.database is db
137
138
139 @pytest.mark.parametrize("db", [None, InMemoryExampleDatabase()])
140 def test_can_assign_database(db):
141 x = settings(database=db)
142 assert x.database is db
143
144
145 def test_will_reload_profile_when_default_is_absent():
146 original = settings.default
147 default_variable.value = None
148 assert settings.default is original
149
150
151 def test_load_profile():
152 with restore_profile():
153 settings.load_profile("default")
154 assert settings.default.max_examples == original_default
155 assert settings.default.stateful_step_count == 50
156
157 settings.register_profile(
158 "test", settings(max_examples=10), stateful_step_count=5
159 )
160 settings.load_profile("test")
161
162 assert settings.default.max_examples == 10
163 assert settings.default.stateful_step_count == 5
164
165 settings.load_profile("default")
166
167 assert settings.default.max_examples == original_default
168 assert settings.default.stateful_step_count == 50
169
170
171 def test_profile_names_must_be_strings():
172 with pytest.raises(InvalidArgument):
173 settings.register_profile(5)
174 with pytest.raises(InvalidArgument):
175 settings.get_profile(5)
176 with pytest.raises(InvalidArgument):
177 settings.load_profile(5)
178
179
180 def test_loading_profile_keeps_expected_behaviour():
181 with restore_profile():
182 settings.register_profile("ci", settings(max_examples=10000))
183 settings.load_profile("ci")
184 assert settings().max_examples == 10000
185 with local_settings(settings(max_examples=5)):
186 assert settings().max_examples == 5
187 assert settings().max_examples == 10000
188
189
190 def test_load_non_existent_profile():
191 with pytest.raises(InvalidArgument):
192 settings.get_profile("nonsense")
193
194
195 def test_cannot_set_settings():
196 x = settings()
197 with pytest.raises(AttributeError):
198 x.max_examples = "foo"
199 with pytest.raises(AttributeError):
200 x.database = "foo"
201 assert x.max_examples != "foo"
202 assert x.database != "foo"
203
204
205 def test_can_have_none_database():
206 assert settings(database=None).database is None
207
208
209 @pytest.mark.parametrize("db", [None, InMemoryExampleDatabase()])
210 @pytest.mark.parametrize("bad_db", [":memory:", ".hypothesis/examples"])
211 def test_database_type_must_be_ExampleDatabase(db, bad_db):
212 with local_settings(settings(database=db)):
213 settings_property_db = settings.database
214 with pytest.raises(InvalidArgument):
215 settings(database=bad_db)
216 assert settings.database is settings_property_db
217
218
219 def test_cannot_assign_default():
220 with pytest.raises(AttributeError):
221 settings.default = settings(max_examples=3)
222 assert settings().max_examples != 3
223
224
225 @settings(max_examples=7)
226 @given(st.builds(lambda: settings.default))
227 def test_settings_in_strategies_are_from_test_scope(s):
228 assert s.max_examples == 7
229
230
231 TEST_SETTINGS_ALONE = """
232 from hypothesis import settings
233 from hypothesis.strategies import integers
234
235 @settings()
236 def test_settings_alone():
237 pass
238 """
239
240
241 # runpytest_inprocess uses invalidate_caches in pytest, which is not thread safe
242 # (I presume; produces keyerrors).
243 @skipif_threading
244 def test_settings_alone(pytester):
245 # Disable cacheprovider, since we don't need it and it's flaky on pyodide
246 script = pytester.makepyfile(TEST_SETTINGS_ALONE)
247 result = pytester.runpytest_inprocess(script, "-p", "no:cacheprovider")
248 out = "\n".join(result.stdout.lines)
249 msg = "Using `@settings` on a test without `@given` is completely pointless."
250 assert msg in out
251 assert "InvalidArgument" in out
252 assert result.ret == 1
253
254
255 @fails_with(InvalidArgument)
256 def test_settings_applied_twice_is_error():
257 @given(st.integers())
258 @settings()
259 @settings()
260 def test_nothing(x):
261 pass
262
263
264 @settings()
265 @given(st.integers())
266 def test_outer_ok(x):
267 pass
268
269
270 @given(st.integers())
271 @settings()
272 def test_inner_ok(x):
273 pass
274
275
276 def test_settings_as_decorator_must_be_on_callable():
277 with pytest.raises(InvalidArgument):
278 settings()(1)
279
280
281 ASSERT_DATABASE_PATH = """
282 import tempfile
283 from hypothesis import settings
284 from hypothesis.configuration import set_hypothesis_home_dir
285 from hypothesis.database import DirectoryBasedExampleDatabase
286
287 settings.load_profile("default")
288 settings.default.database
289
290 if __name__ == '__main__':
291 new_home = tempfile.mkdtemp()
292 set_hypothesis_home_dir(new_home)
293 db = settings.default.database
294 assert isinstance(db, DirectoryBasedExampleDatabase), db
295 assert db.path.is_relative_to(new_home), (db.path, new_home)
296 """
297
298
299 @skipif_emscripten
300 def test_puts_the_database_in_the_home_dir_by_default(tmp_path):
301 script = tmp_path / "assertlocation.py"
302 script.write_text(ASSERT_DATABASE_PATH, encoding="utf-8")
303 subprocess.check_call([sys.executable, str(script)])
304
305
306 def test_database_is_reference_preserved():
307 s = settings(database=not_set)
308
309 assert s.database is s.database
310
311
312 @settings(verbosity=Verbosity.verbose)
313 @example(x=99)
314 @given(st.integers())
315 def test_settings_apply_for_explicit_examples(x):
316 # Regression test for #1521
317 assert settings.default.verbosity == Verbosity.verbose
318
319
320 class TestGivenExampleSettingsExplicitCalled(TestCase):
321 """Real nasty edge case here.
322
323 in #2160, if ``example`` is after ``given`` but before ``settings``,
324 it will be completely ignored.
325
326 If we set phases to only ``explicit``, the test case will never be called!
327
328 We have to run an assertion outside of the test case itself.
329 """
330
331 @counts_calls
332 def call_target(self):
333 pass
334
335 @given(st.booleans())
336 @example(True)
337 @settings(phases=[Phase.explicit])
338 # counts_calls is not thread safe (modifying global f.calls attr)
339 @skipif_threading
340 def test_example_explicit(self, x):
341 self.call_target()
342
343 def tearDown(self):
344 # In #2160, this is 0.
345 assert self.call_target.calls == 1
346
347
348 def test_setattr_on_settings_singleton_is_error():
349 # https://github.com/pandas-dev/pandas/pull/22679#issuecomment-420750921
350 # Should be setting attributes on settings.default, not settings!
351 with pytest.raises(AttributeError):
352 settings.max_examples = 10
353
354
355 def test_deadline_given_none():
356 x = settings(deadline=None).deadline
357 assert x is None
358
359
360 def test_deadline_given_valid_int():
361 x = settings(deadline=1000).deadline
362 assert isinstance(x, datetime.timedelta)
363 assert x.days == 0
364 assert x.seconds == 1
365 assert x.microseconds == 0
366
367
368 def test_deadline_given_valid_float():
369 x = settings(deadline=2050.25).deadline
370 assert isinstance(x, datetime.timedelta)
371 assert x.days == 0
372 assert x.seconds == 2
373 assert x.microseconds == 50250
374
375
376 def test_deadline_given_valid_timedelta():
377 x = settings(deadline=datetime.timedelta(days=1, microseconds=15030000)).deadline
378 assert isinstance(x, datetime.timedelta)
379 assert x.days == 1
380 assert x.seconds == 15
381 assert x.microseconds == 30000
382
383
384 @pytest.mark.parametrize("value", ["always"])
385 def test_can_not_set_print_blob_to_non_print_settings(value):
386 with pytest.raises(InvalidArgument):
387 settings(print_blob=value)
388
389
390 settings_step_count = 1
391
392
393 @settings(stateful_step_count=settings_step_count)
394 class StepCounter(RuleBasedStateMachine):
395 def __init__(self):
396 super().__init__()
397 self.step_count = 0
398
399 @rule()
400 def count_step(self):
401 self.step_count += 1
402
403 def teardown(self):
404 assert self.step_count <= settings_step_count
405
406
407 test_settings_decorator_applies_to_rule_based_state_machine_class = StepCounter.TestCase
408
409
410 def test_two_settings_decorators_applied_to_state_machine_class_raises_error():
411 with pytest.raises(InvalidArgument):
412
413 @settings()
414 @settings()
415 class StatefulTest(RuleBasedStateMachine):
416 pass
417
418
419 def test_settings_decorator_applied_to_non_state_machine_class_raises_error():
420 with pytest.raises(InvalidArgument):
421
422 @settings()
423 class NonStateMachine:
424 pass
425
426
427 def test_assigning_to_settings_attribute_on_state_machine_raises_error():
428 class StateMachine(RuleBasedStateMachine):
429 @rule(x=st.none())
430 def a_rule(self, x):
431 assert x is None
432
433 with pytest.raises(AttributeError):
434 StateMachine.settings = settings()
435
436 state_machine_instance = StateMachine()
437 state_machine_instance.settings = "any value"
438
439
440 def test_derandomise_with_explicit_database_is_invalid():
441 with pytest.raises(InvalidArgument):
442 settings(derandomize=True, database=InMemoryExampleDatabase())
443
444
445 @pytest.mark.parametrize(
446 "kwargs",
447 [
448 {"max_examples": -1},
449 {"max_examples": 2.5},
450 {"stateful_step_count": -1},
451 {"stateful_step_count": 2.5},
452 {"deadline": -1},
453 {"deadline": 0},
454 {"deadline": -0.7},
455 {"deadline": 86400000000000000.2},
456 {"deadline": datetime.timedelta(microseconds=-1)},
457 {"deadline": datetime.timedelta(0)},
458 {"deadline": True},
459 {"deadline": False},
460 {"backend": "nonexistent_backend"},
461 {"suppress_health_check": ["nonexistent_healthcheck"]},
462 {"phases": ["nonexistent_phase"]},
463 {"phases": 0},
464 {"verbosity": -1},
465 {"verbosity": "nonexistent_verbosity"},
466 ],
467 )
468 def test_invalid_settings_are_errors(kwargs):
469 with pytest.raises(InvalidArgument):
470 settings(**kwargs)
471
472
473 def test_invalid_parent():
474 class NotSettings:
475 def __repr__(self):
476 return "(not settings repr)"
477
478 not_settings = NotSettings()
479
480 with pytest.raises(InvalidArgument, match=r"parent=\(not settings repr\)"):
481 settings(not_settings)
482
483
484 def test_default_settings_do_not_use_ci():
485 assert settings.get_profile("default").suppress_health_check == ()
486
487
488 def test_show_changed():
489 s = settings(settings.get_profile("default"), max_examples=999, database=None)
490 assert s.show_changed() == "database=None, max_examples=999"
491
492
493 def test_note_deprecation_checks_date():
494 with pytest.warns(HypothesisDeprecationWarning) as rec:
495 note_deprecation("This is bad", since="RELEASEDAY", has_codemod=False)
496 assert len(rec) == 1
497 with pytest.raises(AssertionError):
498 note_deprecation("This is way too old", since="1999-12-31", has_codemod=False)
499
500
501 def test_note_deprecation_checks_has_codemod():
502 with pytest.warns(
503 HypothesisDeprecationWarning,
504 match="The `hypothesis codemod` command-line tool",
505 ):
506 note_deprecation("This is bad", since="2021-01-01", has_codemod=True)
507
508
509 def test_deprecated_settings_warn_on_set_settings():
510 with validate_deprecation():
511 settings(suppress_health_check=[HealthCheck.return_value])
512 with validate_deprecation():
513 settings(suppress_health_check=[HealthCheck.not_a_test_method])
514
515
516 @checks_deprecated_behaviour
517 def test_deprecated_settings_not_in_settings_all_list():
518 al = HealthCheck.all()
519 ls = list(HealthCheck)
520 assert al == ls
521 assert HealthCheck.return_value not in ls
522 assert HealthCheck.not_a_test_method not in ls
523
524
525 @skipif_emscripten
526 def test_check_defaults_to_derandomize_when_running_on_ci():
527 env = dict(os.environ)
528 env["CI"] = "true"
529
530 assert (
531 subprocess.check_output(
532 [
533 sys.executable,
534 "-c",
535 "from hypothesis import settings\nprint(settings().derandomize)",
536 ],
537 env=env,
538 text=True,
539 encoding="utf-8",
540 ).strip()
541 == "True"
542 )
543
544
545 @skipif_emscripten
546 def test_check_defaults_to_randomize_when_not_running_on_ci():
547 env = dict(os.environ)
548 for key in _CI_VARS:
549 env.pop(key, None)
550
551 assert (
552 subprocess.check_output(
553 [
554 sys.executable,
555 "-c",
556 "from hypothesis import settings\nprint(settings().derandomize)",
557 ],
558 env=env,
559 text=True,
560 encoding="utf-8",
561 ).strip()
562 == "False"
563 )
564
565
566 @skipif_threading # modifying global state (profiles) during testing
567 def test_reloads_the_loaded_profile_if_registered_again():
568 with restore_profile():
569 test_profile = "some nonsense profile purely for this test"
570 test_value = 123456
571 settings.register_profile(test_profile, settings(max_examples=test_value))
572 settings.load_profile(test_profile)
573 assert settings.default.max_examples == test_value
574 test_value_2 = 42
575 settings.register_profile(test_profile, settings(max_examples=test_value_2))
576 assert settings.default.max_examples == test_value_2
577
578
579 CI_TESTING_SCRIPT = """
580 from hypothesis import settings
581
582 if __name__ == '__main__':
583 settings.register_profile("ci", settings(max_examples=42))
584 assert settings.default.max_examples == 42
585 """
586
587
588 @skipif_emscripten
589 def test_will_automatically_pick_up_changes_to_ci_profile_in_ci():
590 env = dict(os.environ)
591 env["CI"] = "true"
592 subprocess.check_call(
593 [sys.executable, "-c", CI_TESTING_SCRIPT],
594 env=env,
595 text=True,
596 encoding="utf-8",
597 )
598
599
600 def test_register_profile_avoids_intermediate_profiles():
601 parent = settings()
602 s = settings(parent, max_examples=10)
603 with temp_register_profile("for_intermediate_test", s):
604 assert settings.get_profile("for_intermediate_test")._fallback is parent
605
606
607 @checks_deprecated_behaviour
608 @settings(max_examples=10)
609 @given(st.integers())
610 def test_cannot_register_profile_from_inside_test(x):
611 settings.register_profile("problematic", settings(max_examples=20))
612
613
614 def test_can_set_verbosity_to_strings():
615 assert settings(verbosity="quiet").verbosity is Verbosity.quiet
616 assert settings(verbosity="normal").verbosity is Verbosity.normal
617 assert settings(verbosity="verbose").verbosity is Verbosity.verbose
618 assert settings(verbosity="debug").verbosity is Verbosity.debug
619
620
621 def test_can_set_phase_to_strings():
622 assert settings(phases=["reuse"]).phases == (Phase.reuse,)
623 assert settings(phases=["reuse", "explicit"]).phases == (
624 Phase.explicit,
625 Phase.reuse,
626 )
627
628
629 def test_can_set_suppressions_to_strings():
630 assert settings(
631 suppress_health_check=["filter_too_much"]
632 ).suppress_health_check == (HealthCheck.filter_too_much,)
633 assert settings(
634 suppress_health_check=["filter_too_much", "too_slow"]
635 ).suppress_health_check == (HealthCheck.filter_too_much, HealthCheck.too_slow)
636
637
638 def test_verbosity_is_comparable():
639 assert Verbosity.quiet < Verbosity.normal
640 assert Verbosity.quiet <= Verbosity.quiet
641 assert Verbosity.quiet == Verbosity.quiet
642 assert Verbosity.quiet >= Verbosity.quiet
643 assert Verbosity.debug > Verbosity.quiet
644
645 # make sure we're comparing by int value, not by str value
646 assert Verbosity.quiet < Verbosity.normal < Verbosity.verbose < Verbosity.debug
647
648 # also comparable with other ints
649 assert Verbosity.quiet < 1
650 assert Verbosity.quiet <= 1
651 assert Verbosity.quiet == 0
652 assert Verbosity.quiet >= 0
653 assert Verbosity.normal > 0
654
655
656 @checks_deprecated_behaviour
657 def test_can_set_verbosity_to_integers():
658 assert Verbosity(0) is Verbosity.quiet
659 assert Verbosity(1) is Verbosity.normal
660 assert Verbosity(2) is Verbosity.verbose
661 assert Verbosity(3) is Verbosity.debug
662
663
664 @checks_deprecated_behaviour
665 def test_can_set_phase_to_integers():
666 assert Phase(0) is Phase.explicit
667 assert Phase(1) is Phase.reuse
668 assert Phase(2) is Phase.generate
669 assert Phase(4) is Phase.shrink
670
671
672 @checks_deprecated_behaviour
673 def test_can_set_suppressions_to_integers():
674 assert HealthCheck(1) is HealthCheck.data_too_large
675 assert HealthCheck(2) is HealthCheck.filter_too_much
676 assert HealthCheck(3) is HealthCheck.too_slow
677
678
679 def test_invalid_integer_phase_raises():
680 with pytest.raises(ValueError):
681 Phase(99)
682
683
684 def test_invalid_integer_healthcheck_raises():
685 with pytest.raises(ValueError):
686 HealthCheck(99)