Python freezegun.freeze_time() Examples
The following are 30
code examples of freezegun.freeze_time().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
freezegun
, or try the search function
.
Example #1
Source File: cache_test.py From ssm-cache-python with MIT License | 6 votes |
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())
Example #2
Source File: test_models.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
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
Example #3
Source File: test_plugin.py From streamlink with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #4
Source File: test_dash_parser.py From streamlink with BSD 2-Clause "Simplified" License | 6 votes |
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)) ])
Example #5
Source File: cloud_datastore_export_test.py From loaner with Apache License 2.0 | 6 votes |
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)
Example #6
Source File: test_file_processor_handler.py From airflow with Apache License 2.0 | 6 votes |
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"))
Example #7
Source File: device_model_test.py From loaner with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: test_bitcoin_transfer.py From clove with GNU General Public License v3.0 | 6 votes |
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
Example #9
Source File: test_tasks.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
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]]
Example #10
Source File: test_endpoints_sync_methods.py From sanic-jwt with MIT License | 6 votes |
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")
Example #11
Source File: pytest_freezegun.py From pytest-freezegun with MIT License | 6 votes |
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()
Example #12
Source File: test_s3.py From S4 with GNU General Public License v3.0 | 6 votes |
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)
Example #13
Source File: test_s3.py From S4 with GNU General Public License v3.0 | 6 votes |
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)
Example #14
Source File: test_thing.py From flask-saml2 with MIT License | 6 votes |
def test_just_right(self): now = utcnow() self.login(self.user) with freezegun.freeze_time(now) as frozen: authn_request = self._make_authn_request() # step forwards a bit for transmission time frozen.tick(delta=datetime.timedelta(seconds=30)) authn_response = self._process_authn_request(authn_request) # step forwards a bit for transmission times frozen.tick(delta=datetime.timedelta(seconds=30)) auth_data = self._process_authn_response(authn_response) assert auth_data.nameid == self.user.email
Example #15
Source File: tests.py From Politikon with GNU General Public License v2.0 | 6 votes |
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)) )
Example #16
Source File: tests.py From Politikon with GNU General Public License v2.0 | 6 votes |
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)) )
Example #17
Source File: test_thing.py From flask-saml2 with MIT License | 6 votes |
def test_too_late(self): now = utcnow() self.login(self.user) with freezegun.freeze_time(now) as frozen: authn_request = self._make_authn_request() # step forwards a bit for transmission time frozen.tick(delta=datetime.timedelta(seconds=30)) authn_response = self._process_authn_request(authn_request) # step backwards a bunch frozen.tick(delta=datetime.timedelta(minutes=25)) with pytest.raises(CannotHandleAssertion, match='NotOnOrAfter'): self._process_authn_response(authn_response)
Example #18
Source File: test_thing.py From flask-saml2 with MIT License | 6 votes |
def test_too_early(self): now = utcnow() self.login(self.user) with freezegun.freeze_time(now) as frozen: authn_request = self._make_authn_request() # step forwards a bit for transmission time frozen.tick(delta=datetime.timedelta(seconds=30)) authn_response = self._process_authn_request(authn_request) # step backwards a bunch frozen.tick(delta=datetime.timedelta(minutes=-5)) with pytest.raises(CannotHandleAssertion, match='NotBefore'): self._process_authn_response(authn_response)
Example #19
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def fast_forward_to_voting_expiration(self, voting): time_when_voting_expires = voting.expires_at + relativedelta(hours=1) return freeze_time(time_when_voting_expires, tick=True)
Example #20
Source File: test_complete_authentication.py From sanic-jwt with MIT License | 5 votes |
def test_refresh_token_with_expired_access_token(app_full_auth_cls): app, sanicjwt = app_full_auth_cls _, response = app.test_client.post( "/auth", json={"username": "user1", "password": "abcxyz"} ) assert response.status == 200 assert sanicjwt.config.access_token_name() in response.json assert sanicjwt.config.refresh_token_name() in response.json access_token = response.json.get(sanicjwt.config.access_token_name(), None) refresh_token = response.json.get( sanicjwt.config.refresh_token_name(), None ) assert access_token is not None assert refresh_token is not None with freeze_time(datetime.utcnow() + timedelta(seconds=(60 * 5 * 60))): _, response = app.test_client.post( "/auth/refresh", headers={"Authorization": "Bearer {}".format(access_token)}, json={sanicjwt.config.refresh_token_name(): refresh_token}, ) new_access_token = response.json.get( sanicjwt.config.access_token_name(), None ) assert response.status == 200 assert new_access_token is not None assert ( response.json.get(sanicjwt.config.refresh_token_name(), None) is None ) # there is no new refresh token assert sanicjwt.config.refresh_token_name() not in response.json
Example #21
Source File: factories.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def fast_forward_just_before_voting_expiration(voting): time_when_voting_expires = voting.expires_at - relativedelta(hours=1) return freeze_time(time_when_voting_expires, tick=True)
Example #22
Source File: crontab_test.py From tornado-crontab with MIT License | 5 votes |
def setUp(self): unittest.TestCase.setUp(self) self._freezer = freeze_time(self.BEGIN_TIME) self._freezer.start() self.io_loop = FakeTimeIOLoop(self._freezer) self.calls = []
Example #23
Source File: test_transaction_serializer.py From loopchain with Apache License 2.0 | 5 votes |
def test_orig_tx_equals_deserialized_tx(self, tx_builder_factory: TxBuilderFactory): with freeze_time(): # TODO: origin data contains signature, so it affects tx_hash of deserialized tx. tx: genesis.Transaction = tx_builder_factory(self.tx_version)\ .build(is_signing=False) ts: genesis.TransactionSerializer = TransactionSerializer.new(version=tx.version, type_=tx.type(), versioner=tx_versioner) tx_restored = ts.from_(tx.raw_data) assert tx == tx_restored
Example #24
Source File: test_bitcoin_transfer.py From clove with GNU General Public License v3.0 | 5 votes |
def test_refund_zero_balance(_, btc_testnet_contract, bob_wallet): with freeze_time(btc_testnet_contract.locktime + timedelta(days=5)): with pytest.raises(ValueError) as e: btc_testnet_contract.refund(bob_wallet) assert str(e.value) == 'Balance of this contract is 0.'
Example #25
Source File: test_bitcoin_transfer.py From clove with GNU General Public License v3.0 | 5 votes |
def test_refund_not_expired_contract(_, 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'] - timedelta(seconds=1)): locktime_string = transaction_details['locktime'].strftime('%Y-%m-%d %H:%M:%S') with raises( RuntimeError, match=f"This contract is still valid! It can't be refunded until {locktime_string}." ): contract.refund(alice_wallet)
Example #26
Source File: test_tasks.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_mark_issue_conversation_as_closed(self): long_time_ago = timezone.now() - relativedelta(days=30) # not cancelled -> should stay open issue = IssueFactory() conversation = issue.conversation conversation.messages.create(content='hello', author=issue.created_by, created_at=long_time_ago) # cancelled but recently commented on -> should stay open with freeze_time(long_time_ago, tick=True): issue_ended_recently = IssueFactory() issue_ended_recently.cancel() conversation_ended_recently = issue_ended_recently.conversation conversation_ended_recently.messages.create( content='hello', author=issue_ended_recently.created_by, created_at=timezone.now() ) # cancelled and not commented on -> should be closed with freeze_time(long_time_ago, tick=True): issue_ended = IssueFactory() issue_ended.cancel() conversation_ended = issue_ended.conversation conversation_ended.messages.create(content='hello', author=issue_ended.created_by, created_at=long_time_ago) conversations = Conversation.objects.filter(target_type__model='issue') self.assertEqual(conversations.count(), 3) self.assertEqual(conversations.filter(is_closed=False).count(), 3) mark_conversations_as_closed() self.assertEqual(conversations.filter(is_closed=False).count(), 2) self.assertEqual(conversations.filter(is_closed=True).first(), conversation_ended)
Example #27
Source File: test_tasks.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def group_timezone_at(group, **kwargs): with timezone.override(group.timezone): datetime = timezone.localtime(timezone=group.timezone).replace(**kwargs) with freeze_time(datetime, tick=True): yield
Example #28
Source File: test_models.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_delete(self): now = timezone.now() two_weeks_ago = now - relativedelta(weeks=2) with freeze_time(two_weeks_ago, tick=True): series = ActivitySeriesFactory(place=self.place, start_date=two_weeks_ago) activities = series.activities.all() past_date_count = activities.filter(date__startswith__lt=now).count() self.assertGreater(activities.count(), 2) series.delete() upcoming_activities = Activity.objects.filter(date__startswith__gte=now, is_disabled=False) self.assertEqual(upcoming_activities.count(), 0, upcoming_activities) self.assertEqual(Activity.objects.filter(date__startswith__lt=now).count(), past_date_count)
Example #29
Source File: test_models.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_daylight_saving_time_to_winter(self): start_date = self.place.group.timezone.localize(datetime.now().replace(2016, 10, 22, 15, 0, 0, 0)) before_dst_switch = timezone.now().replace(2016, 10, 22, 4, 40, 13) with freeze_time(before_dst_switch, tick=True): series = ActivitySeriesFactory(place=self.place, start_date=start_date) expected_dates = [] for month, day in [(10, 22), (10, 29), (11, 5), (11, 12)]: expected_dates.append(self.place.group.timezone.localize(datetime(2016, month, day, 15, 0))) for actual_date, expected_date in zip(Activity.objects.filter(series=series), expected_dates): self.assertEqual(actual_date.date.start, expected_date)
Example #30
Source File: test_models.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_daylight_saving_time_to_summer(self): start_date = self.place.group.timezone.localize(datetime.now().replace(2017, 3, 18, 15, 0, 0, 0)) before_dst_switch = timezone.now().replace(2017, 3, 18, 4, 40, 13) with freeze_time(before_dst_switch, tick=True): series = ActivitySeriesFactory(place=self.place, start_date=start_date) expected_dates = [] for month, day in [(3, 18), (3, 25), (4, 1), (4, 8)]: expected_dates.append(self.place.group.timezone.localize(datetime(2017, month, day, 15, 0))) for actual_date, expected_date in zip(Activity.objects.filter(series=series), expected_dates): self.assertEqual(actual_date.date.start, expected_date)