Example #1
0
    def test_reached_steps_are_discared(self):
        """ No yesterday stats, then workers must start at first step """
        worker_01 = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings=self.default_settings)
        worker_02 = Worker.objects.create(
            name='worker_02', ip='10.0.0.2',
            policies_settings=self.default_settings)

        with fake_time('2015-12-09 12:00:00'):
            self.create_mails(worker_01, 5)
            self.create_mails(worker_02, 5)

        with fake_time('2015-12-10 12:00:00'):
            self.create_mails(worker_01, 11)
            self.create_mails(worker_02, 11)

        with fake_time('2015-12-10 18:30:30'):
            mail_metadata = Mail.objects.create(identifier="test_one")
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = warm_up.Policy(
                mail_metadata.identifier,
                {'To': '*****@*****.**'}, MailStatus).apply(workers)

            self.assertEqual(len(worker_ranking), 0)
            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)
            self.assertIsNone(best_worker)
Example #2
0
    def test_max_step_tolerance(self):
        worker = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings={
                'warm_up': {
                    'ip_warm_up': {
                        'matrix': [5, 10, 30, 50, 100], 'goal': 50,
                        'step_tolerance': 10, 'max_tolerance': 0,
                        'enabled': True}}})

        with fake_time('2015-12-09 12:00:00'):
            self.create_mails(worker, 5)

        with fake_time('2015-12-10 12:00:00'):
            self.create_mails(worker, 10)

        with fake_time('2015-12-11 12:00:00'):
            self.create_mails(worker, 30)

        with fake_time('2015-12-11 18:30:30'):
            mail_metadata = Mail.objects.create(identifier="test_one")
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = warm_up.Policy(
                mail_metadata.identifier, {'To': '*****@*****.**'},
                MailStatus).apply(workers)

        best_worker, next_available, *_ = policies.mx.Last().apply(
            worker_ranking)
        self.assertIsNone(best_worker)
        self.assertIsNone(next_available)
Example #3
0
    def test_simple_priority(self):
        """ Simple priority between two workers """
        worker_01 = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings=self.default_settings)
        worker_02 = Worker.objects.create(
            name='worker_02', ip='10.0.0.2',
            policies_settings=self.default_settings)

        with fake_time('2015-12-09 12:00:00'):
            self.create_mails(worker_01, 5)
            self.create_mails(worker_02, 5)

        with fake_time('2015-12-10 12:00:00'):
            self.create_mails(worker_01, 10)
            self.create_mails(worker_02, 9)

        with fake_time('2015-12-11 12:00:00'):
            self.create_mails(worker_01, 2)

        with fake_time('2015-12-11 18:30:30'):
            mail_metadata = Mail.objects.create(identifier="test-du-jambon")
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = warm_up.Policy(
                mail_metadata.identifier,
                {'To': '*****@*****.**'}, MailStatus).apply(workers)

            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)
            self.assertEqual(best_worker.name, worker_02.name)
            self.assertEqual(best_worker.ip, worker_02.ip)
Example #4
0
    def test_pool_no_match(self):
        worker_01 = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings={
                'pool': {'X_POOL_HEADER': 'X-MAILSEND-Pool', 'pools': [
                    'jambon']}})
        Worker.objects.create(
            name='worker_02', ip='10.0.0.2',
            policies_settings={
                'pool': {'X_POOL_HEADER': 'X-MAILSEND-Pool', 'pools': [
                    'jambon']}})
        mail_metadata_01 = Mail.objects.create(identifier='0001')

        with fake_time('2015-12-10 12:00:00'):
            MailStatus.objects.create(
                destination_domain='example.com',
                mail=mail_metadata_01, source_ip=worker_01.ip)

        with fake_time('2015-12-10 12:00:05'):
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = pool.Policy(
                mail_metadata_01.identifier,
                {'To': '*****@*****.**'},
                MailStatus).apply(workers)

            self.assertEqual(len(worker_ranking), 0)

            best_worker, next_available, score, *_ = policies.mx.Last().apply(
                worker_ranking)

            self.assertIsNone(best_worker)
Example #5
0
    def test_greylisting_not_delayed(self):
        worker_01 = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings={'greylist': {}})
        Worker.objects.create(
            name='worker_02', ip='10.0.0.2',
            policies_settings={'greylist': {}})

        mail_metadata_01 = Mail.objects.create(identifier='0001')
        with fake_time('2015-12-10 12:00:00'):
            MailStatus.objects.create(
                destination_domain='example.com',
                mail=mail_metadata_01, source_ip=worker_01.ip)
            MailStatus.objects.create(
                destination_domain='example.com',
                mail=mail_metadata_01,
                status=MailStatus.SENDING,
                source_ip=worker_01.ip)
            MailStatus.objects.create(
                destination_domain='example.com', mail=mail_metadata_01,
                status=MailStatus.DELIVERED, source_ip=worker_01.ip)

        with fake_time('2015-12-10 12:05:00'):
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = greylist.Policy(
                mail_metadata_01.identifier, {'To': '*****@*****.**'},
                MailStatus, reply_code='4.2.0',
                reply_message='GreylisTeDd').apply(workers)

            self.assertEqual(worker_ranking[0]['score'], 0.0)
            self.assertEqual(worker_ranking[1]['score'], 0.0)
            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)
Example #6
0
def test_fruit_list_difference(client, truncate_table, new_fruit_list):
    truncate_table(Fruit)
    old = (date.today() - timedelta(days=6)).strftime("%Y-%m-%d")
    new = (date.today() - timedelta(days=3)).strftime("%Y-%m-%d")

    with fake_time(old):
        f1, *_ = new_fruit_list(4)

    with fake_time(new):
        f2, f3 = new_fruit_list(2)
        f2.deleted = True
        f2.save()
        f1.save()

    response = client.get(reverse("api:fruit-diff", args=[new]))

    assert response.status_code == status.HTTP_200_OK
    assert Fruit.objects.count() == 6

    diff = response.json()
    scenarios = (
        ("created", f3),
        ("deleted", f2),
        ("updated", f1),
    )
    for state, instance in scenarios:
        assert len(diff[state]) == 1
        assert diff[state][0]["id"] == instance.id
Example #7
0
def test_users_list_top_users_last_month(client, truncate_table, new_user,
                                         new_fruit_list):
    truncate_table(FruitUser)

    user4 = new_user(username="******")
    user3 = new_user(username="******")
    user2 = new_user(username="******")
    user1 = new_user(username="******")

    month_ago = (date.today() -
                 timedelta(days=365 / 12 + 1)).strftime("%Y-%m-%d")
    now = date.today().strftime("%Y-%m-%d")

    with fake_time(month_ago):
        new_fruit_list(3, user=user1)

    with fake_time(now):
        new_fruit_list(1, user=user4)
        new_fruit_list(2, user=user3)
        new_fruit_list(2, user=user2)

    response = client.get(reverse("api:users-list-top-last-month"))

    assert response.status_code == status.HTTP_200_OK
    assert response.json() == list(
        map(partial(top_user_to_data, response=response),
            (user2, user3, user4)))
Example #8
0
def test_datetime_lastupdate_datetime(sheraf_database):
    sheraf_database.reset()

    class Model(tests.UUIDAutoModel):
        pass

    with libfaketime.fake_time("2014-08-04 02:00:00") as fk:
        with sheraf.connection(commit=True) as conn:
            m = Model.create()
            fk.tick()
            assert m.last_update_datetime() is None
            conn.transaction_manager.commit()
            assert datetime.datetime(2014, 8, 4, 2, 0,
                                     1) == m.last_update_datetime()

    with sheraf.connection():
        m = Model.read(m.id)
        assert datetime.datetime(2014, 8, 4, 2, 0,
                                 1) == m.last_update_datetime()

    with libfaketime.fake_time("2014-08-04 08:00:00") as fk:
        with sheraf.connection(commit=True) as conn:
            m = Model.read(m.id)
            m.save()
            fk.tick()
            assert datetime.datetime(2014, 8, 4, 2, 0,
                                     1) == m.last_update_datetime()
            conn.transaction_manager.commit()
            assert datetime.datetime(2014, 8, 4, 8, 0,
                                     1) == m.last_update_datetime()
Example #9
0
    def test_default_timer(self):
        with fake_time('2016'):
            res = self.send_message('start')
            self.assertEqual(res, '2016')

        with fake_time('2017'):
            res = self.send_message('stop')
            self.assertEqual(res, '365')
Example #10
0
    def test_named_timer(self):
        with fake_time('2016'):
            res = self.send_message('start --name=mytimer')
            self.assertEqual(res, '2016')

        with fake_time('2017'):
            res = self.send_message('stop --name=mytimer')
            self.assertEqual(res, '365')
Example #11
0
    def test_by_source_ip_disabled(self):
        worker = Worker.objects.create(
            name='worker_01', ip='10.0.0.1', policies_settings={
                'warm_up': {
                    'domain_warm_up': {
                        'matrix': [5, 10, 30, 50, 100], 'goal': 50,
                        'step_tolerance': 0, 'max_tolerance': 0},
                    'ip_warm_up': {
                        'matrix': [5, 10, 30, 50, 100], 'goal': 50,
                        'step_tolerance': 0, 'max_tolerance': 0,
                        'enabled': False}}})

        with fake_time('2015-12-09 12:00:00'):
            self.create_mails(worker, 5)

        with fake_time('2015-12-10 12:00:30'):
            mail = Mail.objects.create(identifier="1")
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = warm_up.Policy(
                mail.identifier, {'To': '*****@*****.**'},
                MailStatus).apply(workers)
            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)
            self.assertEqual(best_worker.name, worker.name)
            self.assertEqual(best_worker.ip, worker.ip)

        with fake_time('2015-12-10 12:05:00'):
            self.create_mails(worker, 10, 'example.com', {
                'example.com': ('example.com')})
            MAILSEND_SETTINGS = copy.deepcopy(settings.MAILSEND)
            MAILSEND_SETTINGS['WORKER_POLICIES'] = [
                'munch_mailsend.policies.mx.warm_up.Apply']
            MAILSEND_SETTINGS['WARM_UP_DOMAINS'] = {
                'example.com': ('example.com')}
            with override_settings(MAILSEND=MAILSEND_SETTINGS):
                mail = Mail.objects.create(identifier="2")
                workers = policies.mx.First().apply({'To': '*****@*****.**'})
                worker_ranking = warm_up.Policy(
                    mail.identifier, {'To': '*****@*****.**'},
                    MailStatus).apply(workers)
                best_worker, next_available, *_ = policies.mx.Last().apply(
                    worker_ranking)
                self.assertIsNone(best_worker)

                mail = Mail.objects.create(identifier="3")
                workers = policies.mx.First().apply(
                    {'To': '*****@*****.**'})
                worker_ranking = warm_up.Policy(
                    mail.identifier, {'To': '*****@*****.**'},
                    MailStatus).apply(workers)
                best_worker, next_available, *_ = policies.mx.Last().apply(
                    worker_ranking)
                self.assertEqual(best_worker.name, worker.name)
                self.assertEqual(best_worker.ip, worker.ip)
    def test_nested_fake_time(self):
        self._assert_time_not_faked()

        with fake_time('1/1/2000'):
            self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1))

            with fake_time('1/1/2001'):
                self.assertEqual(datetime.datetime.now(), datetime.datetime(2001, 1, 1))

            self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1))

        self._assert_time_not_faked()
Example #13
0
    def test_nested_fake_time(self):
        self._assert_time_not_faked()

        with fake_time('1/1/2000'):
            assert datetime.datetime(2000, 1, 1) == datetime.datetime.now()

            with fake_time('1/1/2001'):
                assert datetime.datetime(2001, 1, 1) == datetime.datetime.now()

            assert datetime.datetime(2000, 1, 1) == datetime.datetime.now()

        self._assert_time_not_faked()
Example #14
0
    def test_fake_time_parses_easy_strings_with_timezones(self):
        with fake_time('2000-01-01 10:00:05', tz_offset=3):
            assert datetime.datetime(2000, 1, 1, 13, 0,
                                     5) == datetime.datetime.now()
            assert datetime.datetime(2000, 1, 1, 10, 0,
                                     5) == datetime.datetime.utcnow()

        with fake_time('2000-01-01 10:00:05', tz_offset=-3):
            assert datetime.datetime(2000, 1, 1, 7, 0,
                                     5) == datetime.datetime.now()
            assert datetime.datetime(2000, 1, 1, 10, 0,
                                     5) == datetime.datetime.utcnow()
    def test_nested_fake_time(self):
        self._assert_time_not_faked()

        with fake_time('1/1/2000'):
            self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1))

            with fake_time('1/1/2001'):
                self.assertEqual(datetime.datetime.now(), datetime.datetime(2001, 1, 1))

            self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1))

        self._assert_time_not_faked()
Example #16
0
    def test_reaction_time(self):
        with fake_time('2016-10-10 08:00:00'):
            message = MessageFactory(status='message_ok', author=self.user)
            mail = MailFactory(message=message)
            MailStatusFactory(mail=mail)
            MailStatusFactory(mail=mail, status=MailStatus.SENDING)
            MailStatusFactory(mail=mail, status=MailStatus.DELIVERED)
        with fake_time('2016-10-10 08:00:15'):
            self.client.get('/t/open/{}'.format(mail.identifier))
            records = TrackRecord.objects.filter(identifier=mail.identifier,
                                                 kind='read')

        self.assertEqual(records.first().properties['reaction_time'], '15')
    def test_nested_faketime_returns_uuid1_library_state(self):
        uuid_generate_time = "My System Level UUID1 Generator"
        uuid._uuid_generate_time = uuid_generate_time

        with fake_time(datetime.datetime.now()):
            self.assertIsNone(uuid._uuid_generate_time)

            with fake_time(datetime.datetime.now()):
                self.assertIsNone(uuid._uuid_generate_time)

            self.assertIsNone(uuid._uuid_generate_time)

        self.assertEqual(uuid._uuid_generate_time, uuid_generate_time)
Example #18
0
    def test_nested_faketime_returns_uuid1_library_state(self):
        uuid_generate_time = "My System Level UUID1 Generator"
        uuid._uuid_generate_time = uuid_generate_time

        with fake_time(datetime.datetime.now()):
            assert uuid._uuid_generate_time is None

            with fake_time(datetime.datetime.now()):
                assert uuid._uuid_generate_time is None

            assert uuid._uuid_generate_time is None

        assert uuid_generate_time == uuid._uuid_generate_time
Example #19
0
    def test_bounce_backend(self):
        q = ContactQueue(author=self.user)
        q.save()

        qa = ContactQueuePolicyAttribution(
            contact_queue=q,
            policy=ContactListPolicy.objects.get(name='BounceCheck'))
        qa.save()

        contact = CollectedContact(contact_queue=q,
                                   address='nope@nope',
                                   subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()
        self.assertEqual(1, len(mail.outbox))

        bounce_address = mail.outbox.pop().message().get('Return-Path')

        # sending bounce task
        tasks.handle_bounce(
            {k: v.format(bounce=bounce_address)
             for k, v in bounce.items()})

        contact.refresh_from_db()
        self.assertEqual(CollectedContact.BOUNCED, contact.status)

        contact = CollectedContact(contact_queue=q,
                                   address='*****@*****.**',
                                   subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()

        with fake_time(timezone.now() + timedelta(hours=5)):
            tasks.handle_bounce_expirations()

        contact.refresh_from_db()
        self.assertEqual(CollectedContact.OK, contact.status)

        contact = CollectedContact(contact_queue=q,
                                   address='*****@*****.**',
                                   subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()

        with fake_time(timezone.now() + timedelta(minutes=5)):
            tasks.handle_bounce_expirations()

        contact.refresh_from_db()
        self.assertEqual(
            CollectedContact.PENDING, contact.status,
            'Bounce-check hasn’t expired yet, so the contact should not be OK')
Example #20
0
    def test_interval_between_sending(self):
        worker = Worker.objects.create(name='worker',
                                       ip='10.0.0.1',
                                       policies_settings=self.default_settings)

        with fake_time('2015-12-10 12:00:00'):
            mail_01 = Mail.objects.create(identifier='0001')
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_01,
                                      source_ip=worker.ip)
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_01,
                                      status=MailStatus.SENDING,
                                      source_ip=worker.ip)

        with fake_time('2015-12-10 12:05:00'):
            mail_02 = Mail.objects.create(identifier='0002')
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_02,
                                      source_ip=worker.ip)
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_02,
                                      status=MailStatus.SENDING,
                                      source_ip=worker.ip)

        with fake_time('2015-12-10 12:01:00'):
            mail_03 = Mail.objects.create(identifier='0003')
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_03,
                                      source_ip=worker.ip)
            MailStatus.objects.create(destination_domain='example.com',
                                      mail=mail_03,
                                      status=MailStatus.SENDING,
                                      source_ip=worker.ip)

            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = rate_limit.Policy(mail_03.identifier, {
                'To': '*****@*****.**'
            }, MailStatus).apply(workers)

            self.assertEqual(len(worker_ranking), 1)

            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)

            self.assertEqual(best_worker.name, worker.name)
            self.assertEqual(next_available,
                             datetime.now(pytz.UTC) + timedelta(minutes=1))
Example #21
0
 def setUp(self):
     bot_users = Group.objects.get(name="Bot user")
     self.user1 = User.objects.create_user("User1", "*****@*****.**",
                                           "x")
     self.user2 = User.objects.create_user("User2", "*****@*****.**",
                                           "x")
     bot_users.user_set.add(self.user1)
     bot_users.user_set.add(self.user2)
     Favourites.objects.create(name="user2 favourites", owner=self.user2)
     path = os.path.join(settings.TEST_DATA, "nerd.ogg")
     with open(path, "rb") as audio:
         size = os.path.getsize(path)
         file = InMemoryUploadedFile(audio, "sound_effect", audio.name,
                                     None, size, None)
         now = timezone.now()
         self.created_at_drf = serializers.DateTimeField(
         ).to_representation(now)
         with libfaketime.fake_time(now):
             self.se1 = SoundEffect.objects.create(name="sound_effect_1",
                                                   sound_effect=file,
                                                   created_by=self.user1)
             self.se2 = SoundEffect.objects.create(name="sound_effect_2",
                                                   sound_effect=file,
                                                   created_by=self.user1)
             self.se3 = SoundEffect.objects.create(name="sound_effect_3",
                                                   sound_effect=file,
                                                   created_by=self.user1)
Example #22
0
    def test_mail_msg_ok(self):
        with fake_time('Fri,  5 Aug 2014 23:35:52 +0700 (WIT)'):
            handle_dsn(
                'To: return-{}@test.munch.example.com'.format(
                    self.mail_1.identifier), {
                        'Final-Recipient': self.mail_1.recipient,
                        'Diagnostic-Code': 'Delivered',
                        'Status': '2.0.0',
                        'Arrival-Date': 'Fri,  5 Aug 2014 23:35:50 +0700 (WIT)'
                    })
        self.mail_1 = Mail.objects.get(pk=self.mail_1.pk)
        self.assertEqual(self.mail_1.curstatus, MailStatus.DELIVERED)

        last_status = self.mail_1.statuses.last()
        self.assertEqual(last_status.status, MailStatus.DELIVERED)
        self.assertEqual(
            last_status.creation_date,
            datetime(2014,
                     8,
                     5,
                     21,
                     35,
                     52,
                     tzinfo=last_status.creation_date.tzinfo))
        self.assertEqual(last_status.mail, self.mail_1)
        self.assertEqual(last_status.raw_msg, 'Delivered')
        self.assertEqual(last_status.status_code, '2.0.0')
Example #23
0
 def test_fake_time_tick(self):
     with fake_time('2000-01-01 10:00:05') as fake:
         assert datetime.datetime(2000, 1, 1, 10, 0,
                                  5) == datetime.datetime.now()
         fake.tick(delta=datetime.timedelta(hours=1))
         assert datetime.datetime(2000, 1, 1, 11, 0,
                                  5) == datetime.datetime.now()
Example #24
0
 def test_median(self):
     with fake_time('2016-10-10 08:00:00'):
         mail_1 = MailFactory(message=self.message)
         mail_2 = MailFactory(message=self.message)
         MailStatusFactory(mail=mail_1)
         MailStatusFactory(mail=mail_2)
     with fake_time('2016-10-10 08:00:05'):
         MailStatusFactory(mail=mail_1, status='sending')
         MailStatusFactory(mail=mail_2, status='sending')
     with fake_time('2016-10-10 08:00:30'):
         MailStatusFactory(mail=mail_1, status='delivered')
     with fake_time('2016-10-10 08:01:00'):
         MailStatusFactory(mail=mail_2, status='delivered')
     median = Mail.objects.filter(
         pk__in=[mail_1.pk, mail_2.pk]).median('delivery_duration')
     self.assertEqual(median, datetime.timedelta(seconds=45))
Example #25
0
    def test_update_cached_fields(self):
        with fake_time('2016-10-10 08:00:00'):
            mail = MailFactory(recipient=faker.email(), message=self.message)
            now = timezone.now()
            d = now
            for status in [
                    MailStatus.QUEUED, MailStatus.SENDING, MailStatus.DROPPED
            ]:
                MailStatusFactory(mail=mail,
                                  status=status,
                                  creation_date=d,
                                  raw_msg='test1')
                d = now + datetime.timedelta(minutes=5)

        Mail.objects.update(latest_status_date=None,
                            first_status_date=None,
                            delivery_duration=None,
                            curstatus=MailStatus.SENDING)
        Mail.objects.filter(message=self.message).update_cached_fields()

        mail = Mail.objects.get(pk=mail.pk)
        self.assertEqual(mail.delivery_duration.total_seconds(), 300)
        self.assertEqual(mail.latest_status_date,
                         now + datetime.timedelta(minutes=5))
        self.assertEqual(mail.first_status_date, now)
        self.assertEqual(mail.curstatus, MailStatus.DROPPED)
        self.assertEqual(mail.had_delay, True)
Example #26
0
    def test_ignore_old_dkim_status_change_when_bad(self):
        """
        'run_domains_validation' task must ignore
        domains that failed since more than 2 days.
        In order to prevent checking a badly configured
        domain during a long time.
        """
        mock_queries = {
            'test._domainkey.bad.sandbox.munch.example.com': {
                'TXT': DNSResultMock(settings.DOMAINS['DKIM_KEY_CONTENT'])
            }
        }
        resolver = mock_resolver(mock_queries)

        # Must be OK with "resolver"
        with fake_time('2099-10-12 08:00:00'):
            with patch('dns.resolver.query', resolver):
                run_domains_validation([DomainCheckField.BADLY_CONFIGURED])

        self.assertEqual(
            SendingDomain.objects.get(
                name='bad.sandbox.munch.example.com').dkim_status,
            DomainCheckField.BADLY_CONFIGURED)
        self.assertEqual(
            SendingDomain.objects.get(
                name='bad.sandbox.munch.example.com').dkim_status_date,
            datetime(year=2099, month=10, day=10,
                     hour=4).replace(tzinfo=pytz.UTC))
Example #27
0
    def test_double_opt_in_backend(self):
        contact_list = ContactList(author=self.user)
        contact_list.save()

        cl_queue_policy = ContactListPolicyAttribution(
            contact_list=contact_list,
            policy=ContactListPolicy.objects.get(name='DoubleOptIn'))
        cl_queue_policy.save()

        contact = Contact(contact_list=contact_list,
                          address='nope@nope',
                          subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()
        self.assertEqual(1, len(mail.outbox))
        confirmation_msg = mail.outbox.pop().body
        url = URL_REGEX.search(confirmation_msg).group().replace(
            settings.APPLICATION_URL, '')
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)

        contact.refresh_from_db()
        self.assertEqual(Contact.OK, contact.status)

        contact = Contact(contact_list=contact_list,
                          address='nope2@nope',
                          subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()

        with fake_time(timezone.now() + timedelta(days=8)):
            tasks.handle_opt_ins_expirations()

        contact.refresh_from_db()
        self.assertEqual(Contact.EXPIRED, contact.status)

        contact = Contact(contact_list=contact_list,
                          address='nope3@nope',
                          subscription_ip='127.0.0.1')
        contact.save()
        contact.apply_policies()

        with fake_time(timezone.now() + timedelta(days=2)):
            tasks.handle_opt_ins_expirations()

        contact.refresh_from_db()
        self.assertEqual(Contact.PENDING, contact.status)
Example #28
0
    def test_by_domains_list(self):
        worker = Worker.objects.create(
            name='worker_01', ip='10.0.0.1',
            policies_settings={
                'warm_up': {
                    'domain_warm_up': {
                        'matrix': [5, 10, 30, 50, 100], 'goal': 50,
                        'step_tolerance': 0, 'max_tolerance': 0},
                    'ip_warm_up': {
                        'matrix': [5, 10, 30, 50, 100], 'goal': 50,
                        'step_tolerance': 0, 'max_tolerance': 0,
                        'enabled': False}
                }
            })

        with fake_time('2015-12-10 12:00:00'):
            MAILSEND_SETTINGS = copy.deepcopy(settings.MAILSEND)
            MAILSEND_SETTINGS['WARM_UP_DOMAINS'] = {
                'jambon': ('jambon.com', 'jambon.fr'),
                'gmail': ('gmail.com', 'gmail.fr')}
            with override_settings(MAILSEND=MAILSEND_SETTINGS):
                self.create_mails(worker, 5, destination_domain="gmail.com")

        with fake_time('2015-12-10 12:00:30'):
            MAILSEND_SETTINGS = copy.deepcopy(settings.MAILSEND)
            MAILSEND_SETTINGS['WARM_UP_DOMAINS'] = {
                'jambon': ('jambon.com', 'jambon.fr'),
                'gmail': ('gmail.com', 'gmail.fr')}
            with override_settings(MAILSEND=MAILSEND_SETTINGS):
                mail_metadata = Mail.objects.create(identifier="1")
                workers = policies.mx.First().apply({'To': '*****@*****.**'})
                worker_ranking = warm_up.Policy(
                    mail_metadata.identifier, {'To': '*****@*****.**'},
                    MailStatus).apply(workers)
                best_worker, *_ = policies.mx.Last().apply(
                    worker_ranking)
                self.assertIsNone(best_worker)

        with fake_time('2015-12-10 12:00:30'):
            mail_metadata = Mail.objects.create(identifier="2")
            workers = policies.mx.First().apply({'To': '*****@*****.**'})
            worker_ranking = warm_up.Policy(
                mail_metadata.identifier, {'To': '*****@*****.**'},
                MailStatus).apply(workers)
            best_worker, next_available, *_ = policies.mx.Last().apply(
                worker_ranking)
            self.assertEqual(best_worker.name, worker.name)
Example #29
0
def test_generated_tz_is_valid(offset):
    """https://github.com/simon-weber/python-libfaketime/issues/46"""
    now = datetime.datetime.now()

    with fake_time(now, tz_offset=offset):
        fake_tz = os.environ['TZ']
        timezone(
            fake_tz)  # should not raise pytzdata.exceptions.TimezoneNotFound
def clock_set_forward_by(**kwargs):
    delta = timedelta(**kwargs)

    if delta < timedelta(0):
        raise Exception(f"Can't set clock backwards ({delta=})")

    with libfaketime.fake_time(datetime.now() + delta):
        yield
Example #31
0
def test_dateutil_tz_is_valid():
    test_dt = datetime.datetime(2017, 1, 2, 15, 2)
    dateutil_tzinfo = dateutil.tz.gettz('UTC')
    dt_dateutil_tzinfo = test_dt.replace(tzinfo=dateutil_tzinfo)

    # Should be compatible with a dateutil tzinfo object, not just pytz
    with fake_time(dt_dateutil_tzinfo):
        assert datetime.datetime.now(tz=dateutil_tzinfo) == dt_dateutil_tzinfo
def test_purge(SETTINGS):
    SETTINGS.CACHE_LIFE = 10
    SETTINGS.REPOSITORIES = 'owner/repository1 owner/repository2'

    from jenkins_epo.cache import MemoryCache

    cache = MemoryCache()
    with fake_time('2012-12-21 00:00:00 UTC') as time:
        cache.set('key', 'data')
        cache.purge()
        data = cache.get('key')
        assert 'data' == data

        time.tick(timedelta(seconds=1800))
        cache.purge()
        with pytest.raises(KeyError):
            cache.get('key')
Example #33
0
 def test_fake_time_tick(self):
     with fake_time('2000-01-01 10:00:05') as fake:
         self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1, 10, 0, 5))
         fake.tick(delta=datetime.timedelta(hours=1))
         self.assertEqual(datetime.datetime.now(), datetime.datetime(2000, 1, 1, 11, 0, 5))