當前位置: 首頁>>代碼示例>>Python>>正文


Python freezegun.freeze_time方法代碼示例

本文整理匯總了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()) 
開發者ID:alexcasalboni,項目名稱:ssm-cache-python,代碼行數:21,代碼來源:cache_test.py

示例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) 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:22,代碼來源:test_s3.py

示例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) 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:18,代碼來源:test_s3.py

示例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() 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:26,代碼來源:pytest_freezegun.py

示例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) 
開發者ID:google,項目名稱:loaner,代碼行數:23,代碼來源:device_model_test.py

示例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) 
開發者ID:google,項目名稱:loaner,代碼行數:27,代碼來源:cloud_datastore_export_test.py

示例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 
開發者ID:ideascube,項目名稱:ideascube,代碼行數:19,代碼來源:test_models.py

示例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]] 
開發者ID:yunity,項目名稱:karrot-backend,代碼行數:25,代碼來源:test_tasks.py

示例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 
開發者ID:Lamden,項目名稱:clove,代碼行數:19,代碼來源:test_bitcoin_transfer.py

示例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) 
開發者ID:streamlink,項目名稱:streamlink,代碼行數:20,代碼來源:test_plugin.py

示例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))
                                          ]) 
開發者ID:streamlink,項目名稱:streamlink,代碼行數:25,代碼來源:test_dash_parser.py

示例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")) 
開發者ID:apache,項目名稱:airflow,代碼行數:20,代碼來源:test_file_processor_handler.py

示例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") 
開發者ID:ahopkins,項目名稱:sanic-jwt,代碼行數:19,代碼來源:test_endpoints_sync_methods.py

示例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))
        ) 
開發者ID:KlubJagiellonski,項目名稱:Politikon,代碼行數:22,代碼來源:tests.py

示例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))
        ) 
開發者ID:KlubJagiellonski,項目名稱:Politikon,代碼行數:22,代碼來源:tests.py


注:本文中的freezegun.freeze_time方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。