forked from HypothesisWorks/hypothesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_settings.py
484 lines (346 loc) · 12.9 KB
/
test_settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Copyright the Hypothesis Authors.
# Individual contributors are listed in AUTHORS.rst and the git log.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
import datetime
import subprocess
import sys
from unittest import TestCase
import pytest
from hypothesis import example, given, strategies as st
from hypothesis._settings import (
Phase,
Verbosity,
default_variable,
local_settings,
note_deprecation,
settings,
)
from hypothesis.database import ExampleDatabase
from hypothesis.errors import (
HypothesisDeprecationWarning,
InvalidArgument,
InvalidState,
)
from hypothesis.stateful import RuleBasedStateMachine, rule
from hypothesis.utils.conventions import not_set
from tests.common.utils import counts_calls, fails_with
def test_has_docstrings():
assert settings.verbosity.__doc__
original_default = settings.get_profile("default").max_examples
def setup_function(fn):
settings.load_profile("default")
settings.register_profile("test_settings", settings())
settings.load_profile("test_settings")
def test_cannot_set_non_settings():
s = settings()
with pytest.raises(AttributeError):
s.databas_file = "some_file"
def test_settings_uses_defaults():
s = settings()
assert s.max_examples == settings.default.max_examples
def test_raises_attribute_error():
with pytest.raises(AttributeError):
settings().kittens
def test_respects_none_database():
assert settings(database=None).database is None
def test_can_repeatedly_push_the_same_thing():
s = settings(max_examples=12)
t = settings(max_examples=17)
assert settings().max_examples == original_default
with local_settings(s):
assert settings().max_examples == 12
with local_settings(t):
assert settings().max_examples == 17
with local_settings(s):
assert settings().max_examples == 12
with local_settings(t):
assert settings().max_examples == 17
assert settings().max_examples == 12
assert settings().max_examples == 17
assert settings().max_examples == 12
assert settings().max_examples == original_default
def test_can_set_verbosity():
settings(verbosity=Verbosity.quiet)
settings(verbosity=Verbosity.normal)
settings(verbosity=Verbosity.verbose)
settings(verbosity=Verbosity.debug)
def test_can_not_set_verbosity_to_non_verbosity():
with pytest.raises(InvalidArgument):
settings(verbosity="kittens")
@pytest.mark.parametrize("db", [None, ExampleDatabase()])
def test_inherits_an_empty_database(db):
assert settings.default.database is not None
s = settings(database=db)
assert s.database is db
with local_settings(s):
t = settings()
assert t.database is db
@pytest.mark.parametrize("db", [None, ExampleDatabase()])
def test_can_assign_database(db):
x = settings(database=db)
assert x.database is db
def test_will_reload_profile_when_default_is_absent():
original = settings.default
default_variable.value = None
assert settings.default is original
def test_load_profile():
settings.load_profile("default")
assert settings.default.max_examples == original_default
assert settings.default.stateful_step_count == 50
settings.register_profile("test", settings(max_examples=10), stateful_step_count=5)
settings.load_profile("test")
assert settings.default.max_examples == 10
assert settings.default.stateful_step_count == 5
settings.load_profile("default")
assert settings.default.max_examples == original_default
assert settings.default.stateful_step_count == 50
def test_profile_names_must_be_strings():
with pytest.raises(InvalidArgument):
settings.register_profile(5)
with pytest.raises(InvalidArgument):
settings.get_profile(5)
with pytest.raises(InvalidArgument):
settings.load_profile(5)
def test_loading_profile_keeps_expected_behaviour():
settings.register_profile("ci", settings(max_examples=10000))
settings.load_profile("ci")
assert settings().max_examples == 10000
with local_settings(settings(max_examples=5)):
assert settings().max_examples == 5
assert settings().max_examples == 10000
def test_load_non_existent_profile():
with pytest.raises(InvalidArgument):
settings.get_profile("nonsense")
def test_cannot_delete_a_setting():
x = settings()
with pytest.raises(AttributeError):
del x.max_examples
x.max_examples
x = settings()
with pytest.raises(AttributeError):
del x.foo
def test_cannot_set_settings():
x = settings()
with pytest.raises(AttributeError):
x.max_examples = "foo"
with pytest.raises(AttributeError):
x.database = "foo"
assert x.max_examples != "foo"
assert x.database != "foo"
def test_can_have_none_database():
assert settings(database=None).database is None
@pytest.mark.parametrize("db", [None, ExampleDatabase(":memory:")])
@pytest.mark.parametrize("bad_db", [":memory:", ".hypothesis/examples"])
def test_database_type_must_be_ExampleDatabase(db, bad_db):
with local_settings(settings(database=db)):
settings_property_db = settings.database
with pytest.raises(InvalidArgument):
settings(database=bad_db)
assert settings.database is settings_property_db
def test_cannot_define_settings_once_locked():
with pytest.raises(InvalidState):
settings._define_setting("hi", "there", 4)
def test_cannot_assign_default():
with pytest.raises(AttributeError):
settings.default = settings(max_examples=3)
assert settings().max_examples != 3
@settings(max_examples=7)
@given(st.builds(lambda: settings.default))
def test_settings_in_strategies_are_from_test_scope(s):
assert s.max_examples == 7
TEST_SETTINGS_ALONE = """
from hypothesis import settings
from hypothesis.strategies import integers
@settings()
def test_settings_alone():
pass
"""
def test_settings_alone(testdir):
script = testdir.makepyfile(TEST_SETTINGS_ALONE)
result = testdir.runpytest(script)
out = "\n".join(result.stdout.lines)
assert (
"Using `@settings` on a test without `@given` is completely pointless." in out
)
assert "InvalidArgument" in out
assert result.ret == 1
@fails_with(InvalidArgument)
def test_settings_applied_twice_is_error():
@given(st.integers())
@settings()
@settings()
def test_nothing(x):
pass
@settings()
@given(st.integers())
def test_outer_ok(x):
pass
@given(st.integers())
@settings()
def test_inner_ok(x):
pass
def test_settings_as_decorator_must_be_on_callable():
with pytest.raises(InvalidArgument):
settings()(1)
ASSERT_DATABASE_PATH = """
import tempfile
from hypothesis import settings
from hypothesis.configuration import set_hypothesis_home_dir
from hypothesis.database import DirectoryBasedExampleDatabase
settings.default.database
if __name__ == '__main__':
new_home = tempfile.mkdtemp()
set_hypothesis_home_dir(new_home)
db = settings.default.database
assert isinstance(db, DirectoryBasedExampleDatabase), db
assert db.path.startswith(new_home), (db.path, new_home)
"""
def test_puts_the_database_in_the_home_dir_by_default(tmpdir):
script = tmpdir.join("assertlocation.py")
script.write(ASSERT_DATABASE_PATH)
subprocess.check_call([sys.executable, str(script)])
def test_database_is_reference_preserved():
s = settings(database=not_set)
assert s.database is s.database
@settings(verbosity=Verbosity.verbose)
@example(x=99)
@given(st.integers())
def test_settings_apply_for_explicit_examples(x):
# Regression test for #1521
assert settings.default.verbosity == Verbosity.verbose
class TestGivenExampleSettingsExplicitCalled(TestCase):
"""Real nasty edge case here.
in #2160, if ``example`` is after ``given`` but before ``settings``,
it will be completely ignored.
If we set phases to only ``explicit``, the test case will never be called!
We have to run an assertion outside of the test case itself.
"""
@counts_calls
def call_target(self):
pass
@given(st.booleans())
@example(True)
@settings(phases=[Phase.explicit])
def test_example_explicit(self, x):
self.call_target()
def tearDown(self):
# In #2160, this is 0.
assert self.call_target.calls == 1
def test_setattr_on_settings_singleton_is_error():
# https://github.com/pandas-dev/pandas/pull/22679#issuecomment-420750921
# Should be setting attributes on settings.default, not settings!
with pytest.raises(AttributeError):
settings.max_examples = 10
def test_deadline_given_none():
x = settings(deadline=None).deadline
assert x is None
def test_deadline_given_valid_int():
x = settings(deadline=1000).deadline
assert isinstance(x, datetime.timedelta)
assert x.days == 0 and x.seconds == 1 and x.microseconds == 0
def test_deadline_given_valid_float():
x = settings(deadline=2050.25).deadline
assert isinstance(x, datetime.timedelta)
assert x.days == 0 and x.seconds == 2 and x.microseconds == 50250
def test_deadline_given_valid_timedelta():
x = settings(deadline=datetime.timedelta(days=1, microseconds=15030000)).deadline
assert isinstance(x, datetime.timedelta)
assert x.days == 1 and x.seconds == 15 and x.microseconds == 30000
@pytest.mark.parametrize(
"x",
[
0,
-0.7,
-1,
86400000000000000.2,
datetime.timedelta(microseconds=-1),
datetime.timedelta(0),
],
)
def test_invalid_deadline(x):
with pytest.raises(InvalidArgument):
settings(deadline=x)
@pytest.mark.parametrize("value", ["always"])
def test_can_not_set_print_blob_to_non_print_settings(value):
with pytest.raises(InvalidArgument):
settings(print_blob=value)
settings_step_count = 1
@settings(stateful_step_count=settings_step_count)
class StepCounter(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.step_count = 0
@rule()
def count_step(self):
self.step_count += 1
def teardown(self):
assert self.step_count <= settings_step_count
test_settings_decorator_applies_to_rule_based_state_machine_class = StepCounter.TestCase
def test_two_settings_decorators_applied_to_state_machine_class_raises_error():
with pytest.raises(InvalidArgument):
@settings()
@settings()
class StatefulTest(RuleBasedStateMachine):
pass
def test_settings_decorator_applied_to_non_state_machine_class_raises_error():
with pytest.raises(InvalidArgument):
@settings()
class NonStateMachine:
pass
def test_assigning_to_settings_attribute_on_state_machine_raises_error():
with pytest.raises(AttributeError):
class StateMachine(RuleBasedStateMachine):
@rule(x=st.none())
def a_rule(self, x):
assert x is None
StateMachine.settings = settings()
state_machine_instance = StateMachine()
state_machine_instance.settings = "any value"
def test_derandomise_with_explicit_database_is_invalid():
with pytest.raises(InvalidArgument):
settings(derandomize=True, database=ExampleDatabase(":memory:"))
@pytest.mark.parametrize(
"kwargs",
[
{"max_examples": -1},
{"max_examples": 2.5},
{"stateful_step_count": -1},
{"stateful_step_count": 2.5},
{"deadline": -1},
{"deadline": 0},
{"deadline": True},
{"deadline": False},
],
)
def test_invalid_settings_are_errors(kwargs):
with pytest.raises(InvalidArgument):
settings(**kwargs)
def test_invalid_parent():
class NotSettings:
def __repr__(self):
return "(not settings repr)"
not_settings = NotSettings()
with pytest.raises(InvalidArgument) as excinfo:
settings(not_settings)
assert "parent=(not settings repr)" in str(excinfo.value)
def test_show_changed():
s = settings(max_examples=999, database=None, phases=tuple(Phase)[:-1])
assert s.show_changed() == "database=None, max_examples=999"
def test_note_deprecation_checks_date():
with pytest.warns(HypothesisDeprecationWarning) as rec:
note_deprecation("This is bad", since="RELEASEDAY", has_codemod=False)
assert len(rec) == 1
with pytest.raises(AssertionError):
note_deprecation("This is way too old", since="1999-12-31", has_codemod=False)
def test_note_deprecation_checks_has_codemod():
with pytest.warns(
HypothesisDeprecationWarning,
match="The `hypothesis codemod` command-line tool",
):
note_deprecation("This is bad", since="2021-01-01", has_codemod=True)