本文整理汇总了Python中freezegun.freeze_time方法的典型用法代码示例。如果您正苦于以下问题:Python freezegun.freeze_time方法的具体用法?Python freezegun.freeze_time怎么用?Python freezegun.freeze_time使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类freezegun
的用法示例。
在下文中一共展示了freezegun.freeze_time方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_should_refresh
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_should_refresh(self):
""" Unit test _should_refresh private method """
# without max age
ref = Refreshable(None)
self.assertFalse(ref._should_refresh())
# with max age and no data
ref = Refreshable(max_age=10)
self.assertTrue(ref._should_refresh())
# manually force refresh time
ref._last_refresh_time = datetime.utcnow()
# with max age and last refreshed date OK
self.assertFalse(ref._should_refresh())
# freeze_time will pretend 10 seconds have passed!
with freeze_time(lambda: datetime.utcnow() + timedelta(seconds=10)):
# with max age and last refreshed date KO
self.assertTrue(ref._should_refresh())
示例2: test_get
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_get(self, s3_client):
# given
data = b"#000000"
frozen_time = datetime.datetime(
2016, 10, 23, 10, 30, tzinfo=datetime.timezone.utc
)
with freezegun.freeze_time(frozen_time):
s3_client.boto.put_object(
Bucket=s3_client.bucket,
Key=os.path.join(s3_client.prefix, "black.color"),
Body=data,
)
# when
output_object = s3_client.get("black.color")
# then
assert output_object.fp.read() == data
assert output_object.total_size == len(data)
assert output_object.timestamp == to_timestamp(frozen_time)
示例3: test_put_get
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_put_get(self, s3_client):
# given
data = b"woooooooooshhh"
input_object = SyncObject(io.BytesIO(data), len(data), 4000)
frozen_time = datetime.datetime(
2016, 10, 23, 10, 30, tzinfo=datetime.timezone.utc
)
# when
with freezegun.freeze_time(frozen_time):
s3_client.put("something/woosh.gif", input_object)
# then
output_object = s3_client.get("something/woosh.gif")
assert output_object.fp.read() == data
assert output_object.timestamp == to_timestamp(frozen_time)
示例4: freezer_fixture
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
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()
示例5: test_enable_guest_mode_allowed
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_enable_guest_mode_allowed(self, mock_defer):
now = datetime.datetime(year=2017, month=1, day=1)
config_model.Config.set('allow_guest_mode', True)
self.enroll_test_device(loanertest.TEST_DIR_DEVICE_DEFAULT)
with freezegun.freeze_time(now):
self.test_device.assigned_user = loanertest.USER_EMAIL
self.test_device.put()
self.test_device.enable_guest_mode(loanertest.USER_EMAIL)
self.assertEqual(
device_model.constants.ORG_UNIT_DICT['GUEST'],
self.test_device.current_ou)
self.assertEqual(now, self.test_device.ou_changed_date)
config_model.Config.set(
'guest_mode_timeout_in_hours', 12)
countdown = datetime.timedelta(
hours=config_model.Config.get(
'guest_mode_timeout_in_hours')).total_seconds()
mock_defer.assert_called_once_with(
self.test_device._disable_guest_mode, loanertest.USER_EMAIL,
_countdown=countdown)
示例6: test_get
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_get(
self, mock_config, mock_urlfetch, mock_app_identity, mock_logging):
test_destination_url = cloud_datastore_export._DESTINATION_URL
test_bucket_name = 'gcp_bucket_name'
mock_config.side_effect = [test_bucket_name, True]
expected_url = (
cloud_datastore_export._DATASTORE_API_URL % self.test_application_id)
mock_urlfetch.return_value.status_code = httplib.OK
now = datetime.datetime(
year=2017, month=1, day=1, hour=1, minute=1, second=15)
with freezegun.freeze_time(now):
self.testapp.get(self._CRON_URL)
mock_urlfetch.assert_called_once_with(
url=expected_url,
payload=json.dumps({
'project_id': self.test_application_id,
'output_url_prefix': test_destination_url.format(
test_bucket_name, now.strftime('%Y_%m_%d-%H%M%S'))
}),
method=urlfetch.POST,
deadline=60,
headers={
'Content-Type': 'application/json',
'Authorization': 'Bearer mock_token'})
self.assertEqual(mock_logging.call_count, 3)
示例7: test_configuration
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_configuration(value, user):
fakenow = datetime.now(tz=timezone.utc)
assert Configuration.objects.count() == 0
with freezegun.freeze_time(fakenow):
Configuration(
namespace='tests', key='setting1', value=value, actor=user).save()
assert Configuration.objects.count() == 1
configuration = Configuration.objects.first()
assert configuration.namespace == 'tests'
assert configuration.key == 'setting1'
assert configuration.value == value
assert configuration.actor == user
assert configuration.date == fakenow
assert str(configuration) == 'tests.setting1=%r' % value
示例8: make_activity_in_group
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def make_activity_in_group(self, group):
place = PlaceFactory(group=group)
new_users = [VerifiedUserFactory() for _ in range(self.new_user_count)]
user = new_users[0]
a_few_days_ago = timezone.now() - relativedelta(days=4)
with freeze_time(a_few_days_ago, tick=True):
[group.add_member(u) for u in new_users]
# a couple of messages
[group.conversation.messages.create(author=user, content='hello') for _ in range(self.message_count)]
# missed activities
[ActivityFactory(place=place) for _ in range(self.activities_missed_count)]
# fullfilled activities
activities = [
ActivityFactory(place=place, max_participants=1, participants=[user])
for _ in range(self.activities_done_count)
]
# activity feedback
[FeedbackFactory(about=activity, given_by=user) for activity in activities[:self.feedback_count]]
示例9: test_refund_transaction
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_refund_transaction(_, alice_wallet, signed_transaction):
btc_network = BitcoinTestNet()
transaction_details = signed_transaction.show_details()
contract = btc_network.audit_contract(
transaction_details['contract'],
transaction_details['contract_transaction']
)
with freeze_time(transaction_details['locktime']):
refund_transaction = contract.refund(alice_wallet)
refund_transaction.fee_per_kb = 0.002
refund_transaction.add_fee_and_sign()
assert refund_transaction.recipient_address == alice_wallet.address
assert refund_transaction.value == signed_transaction.value
示例10: test_cookie_store_save_expires
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_cookie_store_save_expires(self):
with freezegun.freeze_time(datetime.datetime(2018, 1, 1)):
session = Mock()
session.http.cookies = [
requests.cookies.create_cookie("test-name", "test-value", domain="test.se", expires=time.time() + 3600,
rest={'HttpOnly': None})
]
Plugin.bind(session, 'tests.test_plugin')
Plugin.cache = Mock()
Plugin.cache.get_all.return_value = {}
plugin = Plugin("http://test.se")
plugin.save_cookies(default_expires=60)
Plugin.cache.set.assert_called_with("__cookie:test-name:test.se:80:/",
self._create_cookie_dict("test-name", "test-value", 1514768400),
3600)
示例11: test_segments_dynamic_number
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_segments_dynamic_number(self):
with freeze_time(FakeDatetime(2018, 5, 22, 13, 37, 0, tzinfo=utc)):
with xml("dash/test_4.mpd") as mpd_xml:
mpd = MPD(mpd_xml, base_url="http://test.se/", url="http://test.se/manifest.mpd")
segments = mpd.periods[0].adaptationSets[0].representations[0].segments()
init_segment = next(segments)
self.assertEqual(init_segment.url, "http://test.se/hd-5-init.mp4")
video_segments = []
for _ in range(3):
seg = next(segments)
video_segments.append((seg.url,
seg.available_at))
self.assertSequenceEqual(video_segments,
[('http://test.se/hd-5_000311235.mp4',
datetime.datetime(2018, 5, 22, 13, 37, 0, tzinfo=utc)),
('http://test.se/hd-5_000311236.mp4',
datetime.datetime(2018, 5, 22, 13, 37, 5, tzinfo=utc)),
('http://test.se/hd-5_000311237.mp4',
datetime.datetime(2018, 5, 22, 13, 37, 10, tzinfo=utc))
])
示例12: test_symlink_latest_log_directory_exists
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_symlink_latest_log_directory_exists(self):
handler = FileProcessorHandler(base_log_folder=self.base_log_folder,
filename_template=self.filename)
handler.dag_dir = self.dag_dir
date1 = (timezone.utcnow() + timedelta(days=1)).strftime("%Y-%m-%d")
path1 = os.path.join(self.base_log_folder, date1, "log1")
if os.path.exists(path1):
os.remove(path1)
link = os.path.join(self.base_log_folder, "latest")
if os.path.exists(link):
os.remove(link)
os.makedirs(link)
with freeze_time(date1):
handler.set_context(filename=os.path.join(self.dag_dir, "log1"))
示例13: test_verify_endpoint_with_error
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_verify_endpoint_with_error(
self, app_with_sync_methods, authenticated_response
):
sanic_app, sanicjwt = app_with_sync_methods
access_token = authenticated_response.json.get(
sanicjwt.config.access_token_name(), None
)
with freeze_time(datetime.utcnow() + timedelta(seconds=(60 * 5 * 60))):
_, response = sanic_app.test_client.get(
"/auth/verify",
headers={"Authorization": "Bearer {}".format(access_token)},
)
assert response.status == 401
assert response.json.get("exception") == "InvalidToken"
assert "Signature has expired." in response.json.get("reasons")
示例14: test_get_weekly_user_transactions
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_get_weekly_user_transactions(self):
"""
Get weekly user transactions
"""
initial_time = timezone.now() - timedelta(days=8)
with freeze_time(initial_time) as frozen_time:
user = UserFactory()
events = EventFactory.create_batch(3)
TransactionFactory(user=user, event=events[0])
frozen_time.tick(delta=timedelta(days=3))
transaction2 = TransactionFactory(user=user, event=events[1])
frozen_time.tick(delta=timedelta(days=3))
transaction3 = TransactionFactory(user=user, event=events[2])
self.assertEqual(
[transaction3, transaction2],
list(Transaction.objects.get_weekly_user_transactions(user))
)
示例15: test_get_monthly_user_transactions
# 需要导入模块: import freezegun [as 别名]
# 或者: from freezegun import freeze_time [as 别名]
def test_get_monthly_user_transactions(self):
"""
Get monthly user transactions
"""
initial_time = timezone.now() - timedelta(days=32)
with freeze_time(initial_time) as frozen_time:
user = UserFactory()
events = EventFactory.create_batch(3)
TransactionFactory(user=user, event=events[0])
frozen_time.tick(delta=timedelta(days=3))
transaction2 = TransactionFactory(user=user, event=events[1])
frozen_time.tick(delta=timedelta(days=3))
transaction3 = TransactionFactory(user=user, event=events[2])
self.assertEqual(
[transaction3, transaction2],
list(Transaction.objects.get_monthly_user_transactions(user))
)