Example #1
0
def test_message_encryptor_with_expires_in():
    me = MessageEncryptor(__name__)
    with time_machine.travel(0):
        crypted = me.encrypt_and_sign('secret message', expires_in=10)
    with time_machine.travel(11):
        with pytest.raises(ExpiredError):
            me.decrypt_and_verify(crypted)
def test_sssion_expiration_2(client):
    with time_machine.travel(0):
        client.get('/setitem?q=42')
    with time_machine.travel(EXPIRES_IN - 1):
        assert client.get('/show').json() == {'q': 42}
    with time_machine.travel(EXPIRES_IN + 1):
        assert client.get('/show').json() == {'q': 42}  # ↑のアクセスで寿命が延びる
Example #3
0
    def test_small_timetable(self):
        with time_machine.travel('2017-06-07'):
            response = self.client.get('/services/165')
        timetable = response.context_data['timetable']
        self.assertEqual(str(timetable.groupings[0]), 'Outbound')
        self.assertEqual(str(timetable.groupings[1]), 'Inbound')
        # self.assertEqual(str(timetable.groupings[0]), 'Merrion - Citywest')
        # self.assertEqual(str(timetable.groupings[1]), 'Citywest - Ballsbridge')
        self.assertEqual(str(timetable.groupings[0].rows[0].times), '[07:45]')
        self.assertEqual(str(timetable.groupings[0].rows[4].times), '[07:52]')
        self.assertEqual(str(timetable.groupings[0].rows[6].times), '[08:01]')
        self.assertEqual(str(timetable.groupings[1].rows[0].times), '[17:20]')
        self.assertEqual(str(timetable.groupings[1].rows[6].times), '[17:45]')
        self.assertEqual(str(timetable.groupings[1].rows[-1].times), '[18:25]')
        self.assertEqual(len(timetable.groupings[0].rows), 18)
        self.assertEqual(len(timetable.groupings[1].rows), 14)

        self.assertContains(
            response,
            '<a href="https://www.transportforireland.ie/transitData/PT_Data.html">Transport for Ireland</a>'
        )

        for day in (
            datetime.date(2017, 6, 11),
            datetime.date(2017, 12, 25),
            datetime.date(2015, 12, 3),
            datetime.date(2020, 12, 3)
        ):
            with time_machine.travel(day):
                with self.assertNumQueries(11):
                    response = self.client.get(f'/services/165?date={day}')
                timetable = response.context_data['timetable']
                self.assertEqual(day, timetable.date)
                self.assertEqual(timetable.groupings, [])
Example #4
0
 def test_adding_a_source_updates_childrens_last_updated(self):
     PlaylistRelation.objects.create(inheriting_list=self.list_b, super_list=self.list_a)
     update_time = datetime.datetime.fromisoformat("2022-03-28T21:59:34+00:00")
     time_machine.travel(update_time, tick=False).start()
     PlaylistEntry.objects.create(playlist=self.list_a, number=2, source=Source.objects.create())
     self.list_b.refresh_from_db()
     self.assertEqual(self.list_b.last_updated.astimezone(UTC), update_time.astimezone(UTC))
    def test_that_the_current_date_is_put_in_every_row(self):
        """ Tests that the current date will be present in every room-row """
        site_preferences.bookings_per_room_in_study_room_booking_display_export = 1
        token = self.superuser_token

        self.create_study_room(token,
                               name='First Room',
                               room_id=101,
                               display_design=self.default_design)
        self.create_study_room(token,
                               name='Second Room',
                               room_id=202,
                               display_design=self.default_design)

        with time_machine.travel('2333-09-12 18:00'):
            response = self.rest_get_study_room_display_export()
            self.assert_response_status(response, status.HTTP_200_OK)
            rows = self.get_csv_without_first_row(response)
            self.assertEquals(
                '101;First Room;;;;;;;12.09.2333;Default' + LINE_BREAK +
                '202;Second Room;;;;;;;12.09.2333;Default', rows)

        cache.clear()
        with time_machine.travel('2020-12-02 13:00'):
            response = self.rest_get_study_room_display_export()
            self.assert_response_status(response, status.HTTP_200_OK)
            rows = self.get_csv_without_first_row(response)
            self.assertEquals(
                '101;First Room;;;;;;;02.12.2020;Default' + LINE_BREAK +
                '202;Second Room;;;;;;;02.12.2020;Default', rows)
def test_sssion_expiration_3(client):
    with time_machine.travel(0):
        client.get('/setitem?q=42')
    with time_machine.travel(EXPIRES_IN - 1):
        assert client.get('/peek').json() == {'q': 42}
    with time_machine.travel(EXPIRES_IN + 1):
        assert client.get('/peek').json() == {}
    def test_projected_invoices(self):
        """Functionality around projected invoices and reminder mails"""
        obj = factories.ProjectedInvoiceFactory.create(
            gross_margin=Decimal(1000))
        pi = projected_invoices()

        self.assertEqual(pi["monthly_overall"][(2021, 11)], Decimal(1000))
        self.assertEqual(
            pi["projects"],
            [{
                "delta": Decimal("1000.00"),
                "gross_margin": Decimal("0.00"),
                "invoiced": [],
                "monthly": {
                    (2021, 11): Decimal("1000.00")
                },
                "project": obj.project,
                "projected": [obj],
                "projected_total": Decimal("1000.00"),
            }],
        )

        send_unsent_projected_invoices_reminders()
        self.assertEqual(len(mail.outbox), 0)

        with travel("2021-12-01"):
            send_unsent_projected_invoices_reminders()
        self.assertEqual(len(mail.outbox), 0)

        with travel("2021-11-28"):
            send_unsent_projected_invoices_reminders()
        self.assertEqual(len(mail.outbox), 1)
Example #8
0
async def _(graphql_client=graphql_client, db=db, user_factory=user_factory):
    user = await user_factory(email="*****@*****.**", password="******")

    with time_machine.travel("2020-10-10 15:00:00", tick=False):
        token = user.create_reset_password_token()

    query = """
    mutation($input: ResetPasswordInput!) {
        resetPassword(input: $input) {
            __typename

            ... on ResetPasswordTokenExpired {
                message
            }
        }
    }
    """

    with time_machine.travel("2020-10-13 15:00:00", tick=False):
        response = await graphql_client.query(
            query,
            variables={"input": {"token": token, "newPassword": "******"}},
        )

    assert not response.errors
    assert response.data["resetPassword"]["__typename"] == "ResetPasswordTokenExpired"
    query = select(User).where(User.email == "*****@*****.**")
    raw_query_user: User = (await db.execute(query)).scalar()
    assert raw_query_user.check_password("hello")
Example #9
0
 def test_adding_a_parent_updates_last_updated(self):
     update_time = datetime.datetime.fromisoformat("2022-03-28T21:59:34+00:00")
     time_machine.travel(update_time, tick=False).start()
     PlaylistRelation.objects.create(inheriting_list=self.list_b, super_list=self.list_a)
     self.list_a.refresh_from_db()
     self.assertEqual(self.list_a.last_updated.astimezone(UTC), self.base_time.astimezone(UTC))
     self.list_b.refresh_from_db()
     self.assertEqual(self.list_b.last_updated.astimezone(UTC), update_time.astimezone(UTC))
Example #10
0
def test_not_nestable():
    with time_machine.travel(0.0):
        with pytest.raises(RuntimeError) as excinfo:
            with time_machine.travel(1.0):
                pass

    assert excinfo.value.args == (
        "Cannot time travel whilst already travelling.", )
Example #11
0
 def setUp(self):
     self.base_time = datetime.datetime.fromisoformat("2022-03-27T20:59:34.000+00:00")
     time_machine.travel(self.base_time, tick=False).start()
     self.list_a = Playlist.objects.create(name="listA")
     self.entry_a = PlaylistEntry.objects.create(playlist=self.list_a, number=1, source=Source.objects.create()).source
     self.list_b = Playlist.objects.create(name="listB")
     self.entry_b = PlaylistEntry.objects.create(playlist=self.list_b, number=2, source=Source.objects.create()).source
     self.list_c = Playlist.objects.create(name="listC")
     self.entry_c = PlaylistEntry.objects.create(playlist=self.list_c, number=3, source=Source.objects.create()).source
Example #12
0
 def setUp(self):
     self.base_time = datetime.datetime.fromisoformat(
         "2022-03-27T20:59:34.000+00:00")
     time_machine.travel(self.base_time, tick=False).start()
     self.playlist = Playlist.objects.create(name="listA")
     self.source = Source.objects.create(
         file=SimpleUploadedFile("test_file_original.png", b"an_image"))
     self.pl_entry = PlaylistEntry.objects.create(playlist=self.playlist,
                                                  number=1,
                                                  source=self.source)
Example #13
0
    def test_send_accounting_files(self):
        """Accounting files are automatically sent on the first day of the year"""
        factories.UserFactory.create(is_admin=True)
        factories.ProjectFactory.create()

        with travel("2019-12-26 12:00"):
            send_accounting_files()
            self.assertEqual(len(mail.outbox), 0)

        with travel("2020-01-01 12:00"):
            send_accounting_files()
            self.assertEqual(len(mail.outbox), 1)
def test_time_time_ns():
    with time_machine.travel(EPOCH + 150.0):
        first = time.time_ns()
        assert first == int((EPOCH + 150.0) * NANOSECONDS_PER_SECOND)
        second = time.time_ns()
        assert first < second < int((EPOCH + 151.0) * NANOSECONDS_PER_SECOND)
    assert time.time_ns() >= int(LIBRARY_EPOCH * NANOSECONDS_PER_SECOND)
Example #15
0
def test_ttl_cache():

    with time_machine.travel("2021-09-01 05:00:00 +00:00") as t:

        cache = PeriodicCache(5, ttl=60)
        cache1h = PeriodicCache(5, ttl=3600)

        assert cache.timer() == 1630472400.0
        cache['a'] = 1235
        cache1h['a'] = 555123
        assert 'a' in cache
        assert 'a' in cache1h

        t.move_to("2021-09-01 05:00:59 +00:00")
        assert 'a' in cache
        assert 'a' in cache1h

        # Cache expired
        t.move_to("2021-09-01 05:01:00 +00:00")
        assert 'a' not in cache
        assert 'a' in cache1h

        t.move_to("2021-09-01 05:59:59 +00:00")
        assert 'a' not in cache
        assert 'a' in cache1h

        t.move_to("2021-09-01 06:00:00 +00:00")
        assert 'a' not in cache
        assert 'a' not in cache1h
def test_shift_wrong_delta():
    with time_machine.travel(EPOCH, tick=False) as traveller:
        with pytest.raises(TypeError) as excinfo:
            traveller.shift(delta="1.1")

    assert excinfo.value.args == (
        "Unsupported type for delta argument: '1.1'", )
def test_destination_datetime_tzinfo_zoneinfo_nested():
    orig_tzname = time.tzname

    dest = LIBRARY_EPOCH_DATETIME.replace(
        tzinfo=ZoneInfo("Africa/Addis_Ababa"))
    with time_machine.travel(dest):
        assert time.tzname == ("EAT", "EAT")

        dest2 = LIBRARY_EPOCH_DATETIME.replace(
            tzinfo=ZoneInfo("Pacific/Auckland"))
        with time_machine.travel(dest2):
            assert time.tzname == ("NZST", "NZDT")

        assert time.tzname == ("EAT", "EAT")

    assert time.tzname == orig_tzname
Example #18
0
async def _():
    user = User(
        id=1,
        username="******",
        password="******",
        email="*****@*****.**",
        fullname="Marco Acierno",
        name="Marco",
        gender="",
        date_birth=None,
        open_to_newsletter=False,
        open_to_recruiting=False,
        country="",
        date_joined=datetime(2020, 1, 1),
        is_staff=False,
        is_superuser=False,
        is_active=True,
    )
    repository = FakeUsersRepository(users=[user])

    with time_machine.travel("2020-10-10 10:10:00Z", tick=False):
        logged_user = await login(
            LoginInputModel(email="*****@*****.**", password="******"),
            users_repository=repository,
        )

    assert logged_user.id == user.id
    assert logged_user.last_login == datetime(
        2020, 10, 10, 10, 10, 00, tzinfo=timezone.utc
    )
async def _(db=db):
    subscription = await SubscriptionFactory(user_id=1)
    await StripeCustomerFactory(user_id=1,
                                stripe_customer_id="cus_customer_id")

    with time_machine.travel("2021-10-10 12:00:00", tick=False):
        await handle_invoice_paid(
            util.convert_to_stripe_object({
                **RAW_INVOICE_PAID_PAYLOAD,
                "data": {
                    **RAW_INVOICE_PAID_PAYLOAD["data"],
                    "object": {
                        **RAW_INVOICE_PAID_PAYLOAD["data"]["object"],
                        "lines": {
                            "data": [{
                                **RAW_INVOICE_PAID_PAYLOAD["data"]["object"]["lines"]["data"][0],
                                "period": {
                                    "end":
                                    1607979272,  # Mon Dec 14 2020 20:54:32 GMT+0000
                                    "start":
                                    1576356872,  # Sat Dec 14 2019 20:54:32 GMT+0000
                                },
                            }],
                        },
                    },
                },
            }))

    subscription = await Subscription.objects.select_related(
        ["payments", "payments__stripesubscriptionpayments"]).get(user_id=1)
    assert subscription.status == SubscriptionStatus.PENDING
    assert len(subscription.payments) == 1
Example #20
0
def test_datetime_utcnow():
    with time_machine.travel(EPOCH):
        now = dt.datetime.utcnow()
        assert now.year == 1970
        assert now.month == 1
        assert now.day == 1
    assert dt.datetime.utcnow() >= LIBRARY_EPOCH_DATETIME
Example #21
0
def test_traveller_object():
    traveller = time_machine.travel(EPOCH + 10.0)
    assert time.time() >= LIBRARY_EPOCH
    traveller.start()
    assert EPOCH + 10.0 < time.time() < EPOCH + 11.0
    traveller.stop()
    assert time.time() >= LIBRARY_EPOCH
def test_time_time():
    with time_machine.travel(EPOCH):
        first = time.time()
        assert first == EPOCH
        second = time.time()
        assert first < second < EPOCH + 1.0
    assert time.time() >= LIBRARY_EPOCH
Example #23
0
def test_datetime_now_arg():
    with time_machine.travel(EPOCH):
        now = dt.datetime.now(tz=dt.timezone.utc)
        assert now.year == 1970
        assert now.month == 1
        assert now.day == 1
    assert dt.datetime.now(dt.timezone.utc) >= LIBRARY_EPOCH_DATETIME
Example #24
0
    def test_run_ok(self):
        send_mock = Mock()
        api_mock = Mock()
        api_mock.messages.send = send_mock

        events = []
        for input_text in self.INPUTS:
            event = deepcopy(self.RAW_EVENT)
            event['object']['message']['text'] = input_text
            events.append(VkBotMessageEvent(event))

        long_poller_mock = Mock()
        long_poller_mock.listen = Mock(return_value=events)

        time_now = time_machine.travel(
            datetime.datetime(year=2020, month=5, day=25))
        time_now.start()

        with patch('avia_ticket_bot.vk_api.bot_longpoll.VkBotLongPoll',
                   return_value=long_poller_mock):
            bot = ChatBot('', '')
            bot.api = api_mock
            bot.send_image = Mock()
            bot.run()

        time_now.stop()

        assert send_mock.call_count == len(self.INPUTS)

        real_outputs = []
        for call in send_mock.call_args_list:
            args, kwargs = call
            real_outputs.append(kwargs['message'])
        assert real_outputs == self.EXPECTED_OUTPUTS
Example #25
0
def test_date_today():
    with time_machine.travel(EPOCH):
        today = dt.date.today()
        assert today.year == 1970
        assert today.month == 1
        assert today.day == 1
    assert dt.datetime.today() >= LIBRARY_EPOCH_DATETIME
def test_destination_datetime_tzinfo_zoneinfo():
    orig_timezone = time.timezone
    orig_altzone = time.altzone
    orig_tzname = time.tzname
    orig_daylight = time.daylight

    dest = LIBRARY_EPOCH_DATETIME.replace(
        tzinfo=ZoneInfo("Africa/Addis_Ababa"))
    with time_machine.travel(dest):
        assert time.timezone == -3 * 3600
        assert time.altzone == -3 * 3600
        assert time.tzname == ("EAT", "EAT")
        assert time.daylight == 0

        assert time.localtime() == time.struct_time((
            2020,
            4,
            29,
            0,
            0,
            0,
            2,
            120,
            0,
        ))

    assert time.timezone == orig_timezone
    assert time.altzone == orig_altzone
    assert time.tzname == orig_tzname
    assert time.daylight == orig_daylight
Example #27
0
async def _():
    repository = FakeUsersRepository(users=[])

    with time_machine.travel("2020-10-10 10:10:00Z", tick=False):
        user = await social_login(
            SocialLoginInput(
                email="*****@*****.**",
                social_account=SocialAccount(
                    social_id="1",
                    fullname="Test Account",
                    first_name="Test",
                    last_name="Account",
                ),
            ),
            users_repository=repository,
        )

    assert user
    assert user.id is not None
    assert user.date_joined == datetime(2020,
                                        10,
                                        10,
                                        10,
                                        10,
                                        0,
                                        tzinfo=timezone.utc)
    assert not user.has_usable_password()
    assert user.fullname == "Test Account"
    assert user.name == "Test"
    assert user.email == "*****@*****.**"
Example #28
0
async def _():
    user = User(
        id=10,
        email="*****@*****.**",
        date_joined=datetime.now(timezone.utc),
        password="******",
        is_active=True,
        jwt_auth_id=1,
    )

    with time_machine.travel("2021-10-10 15:00:00Z", tick=False):
        token = jwt.encode(
            {
                "user_id": 10,
                "exp": datetime.now(timezone.utc) + timedelta(minutes=30),
                "iat": datetime.now(timezone.utc),
                "iss": "users",
                "aud": "users/not-reset-password",
            },
            str(SECRET_KEY),
        )

    with raises(ResetPasswordTokenInvalidError):
        await reset_password(
            ResetPasswordInput(token=token, new_password="******"),
            repository=FakeUsersRepository([user]),
        )
Example #29
0
async def _(graphql_client=graphql_client, db=db, user_factory=user_factory):
    user = await user_factory(id=1, email="*****@*****.**")

    with time_machine.travel("1500-10-10 10:10:10", tick=False):
        graphql_client.force_login(user)

    query = """{
        me {
            id
            email
        }
    }"""

    with time_machine.travel("2021-01-10 10:10:10", tick=False):
        response = await graphql_client.query(query)

    assert response.errors[0]["message"] == "Invalid auth credentials"
Example #30
0
def test_time_gmtime_no_args():
    with time_machine.travel(EPOCH):
        local_time = time.gmtime()
        assert local_time.tm_year == 1970
        assert local_time.tm_mon == 1
        assert local_time.tm_mday == 1
    now_time = time.gmtime()
    assert now_time.tm_year >= 2020