-
Notifications
You must be signed in to change notification settings - Fork 27
/
pytest_freezegun.py
65 lines (50 loc) · 1.54 KB
/
pytest_freezegun.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
# -*- coding: utf-8 -*-
import pytest
from distutils.version import LooseVersion
from freezegun import freeze_time
MARKER_NAME = 'freeze_time'
FIXTURE_NAME = 'freezer'
def get_closest_marker(node, name):
"""
Get our marker, regardless of pytest version
"""
if LooseVersion(pytest.__version__) < LooseVersion('3.6.0'):
return node.get_marker('freeze_time')
else:
return node.get_closest_marker('freeze_time')
@pytest.fixture(name=FIXTURE_NAME)
def freezer_fixture(request):
"""
Freeze time and make it available to the test
"""
args = []
kwargs = {}
ignore = []
# If we've got a marker, use the arguments provided there
marker = get_closest_marker(request.node, MARKER_NAME)
if marker:
ignore = marker.kwargs.pop('ignore', [])
args = marker.args
kwargs = marker.kwargs
# Always want to ignore _pytest
ignore.append('_pytest.terminal')
ignore.append('_pytest.runner')
# Freeze time around the test
freezer = freeze_time(*args, ignore=ignore, **kwargs)
frozen_time = freezer.start()
yield frozen_time
freezer.stop()
def pytest_collection_modifyitems(items):
"""
Inject our fixture into any tests with our marker
"""
for item in items:
if get_closest_marker(item, MARKER_NAME):
item.fixturenames.insert(0, FIXTURE_NAME)
def pytest_configure(config):
"""
Register our marker
"""
config.addinivalue_line(
"markers", "{}(...): use freezegun to freeze time".format(MARKER_NAME)
)