Ejemplo n.º 1
0
    def test_rfs_update(self):
        fieldset_a = rfs(('a', 'b', 'b__c', 'b__g', ('d', ('e__f',))))
        fieldset_b = rfs(('a__i', 'l'))

        fieldset_a.update(fieldset_b)
        assert_equal(str(fieldset_a), 'a(i),b(c,g),d(e(f)),l')
        assert_equal(str(fieldset_b), 'a(i),l')
Ejemplo n.º 2
0
    def test_rfs_add_list(self):
        fieldset_a = rfs(('a', 'b', 'b__c', 'b__g', ('d', ('e__f',))))
        fieldset_b = ('a__i', 'l')

        fieldset_c = fieldset_a + fieldset_b
        assert_equal(str(fieldset_a), 'a,b(c,g),d(e(f))')
        assert_equal(str(fieldset_c), 'a(i),b(c,g),d(e(f)),l')
Ejemplo n.º 3
0
 def test_processing_sms_is_timeouted(self):
     sms1 = OutputSMSFactory(state=ATS_STATES.PROCESSING, changed_at=timezone.now())
     call_command('clean_processing_sms', stdout=StringIO(), stderr=StringIO())
     assert_equal(OutputSMS.objects.get(pk=sms1.pk).state, ATS_STATES.PROCESSING)
     sms2 = OutputSMSFactory(state=ATS_STATES.PROCESSING, changed_at=timezone.now() - timedelta(seconds=11))
     call_command('clean_processing_sms', stdout=StringIO(), stderr=StringIO())
     assert_equal(OutputSMS.objects.get(pk=sms2.pk).state, ATS_STATES.TIMEOUT)
Ejemplo n.º 4
0
 def test_change_and_save_with_update_only_changed_fields_should_change_only_defined_fields(self):
     obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2)
     DiffModel.objects.filter(pk=obj.pk).update(name='test2')
     obj.change_and_save(number=3, update_only_changed_fields=True)
     obj.refresh_from_db()
     assert_equal(obj.name, 'test2')
     assert_equal(obj.number, 3)
Ejemplo n.º 5
0
 def test_smart_model_pre_save(self):
     obj = TestPreProxySmartModel.objects.create()
     assert_equal(obj.name, 'test pre save')
     obj.name = 10 * 'a'
     obj.save()
     assert_equal(obj.name, 'test pre save')
     assert_true(TestPreProxySmartModel.objects.filter(name='test pre save').exists())
Ejemplo n.º 6
0
 def test_get_domain_choices(self):
     choices = get_domain_choices()
     assert_equal(len(choices), 2)
     assert_equal(choices[0][1], 'backend')
     assert_equal(choices[1][1], 'frontend')
     assert_equal(choices[0][0], 1)
     assert_equal(choices[1][0], 2)
Ejemplo n.º 7
0
 def test_num_enum(self):
     enum = NumEnum(
         'A', 'B'
     )
     assert_equal(enum.A, 1)
     assert_equal(enum.B, 2)
     with assert_raises(AttributeError):
         enum.C
Ejemplo n.º 8
0
 def test_output_logged_requests_with_atomic_block_should_not_be_logged_if_exception_is_raised(self):
     responses.add(responses.GET, 'http://test.cz', body='test')
     with assert_raises(TestException):
         with transaction.atomic():
             requests.get('http://test.cz')
             assert_equal(OutputLoggedRequest.objects.count(), 1)
             raise TestException
     assert_equal(OutputLoggedRequest.objects.count(), 0)
Ejemplo n.º 9
0
 def test_smart_model_clean_pre_save(self):
     assert_raises(PersistenceException, TestProxySmartModel.objects.create, name=10 * 'a')
     obj = TestProxySmartModel.objects.create(name=9 * 'a')
     obj.name = 11 * 'a'
     assert_raises(PersistenceException, obj.save)
     assert_equal(len(TestProxySmartModel.objects.get(pk=obj.pk).name), 9)
     obj.save(is_cleaned_pre_save=False)
     assert_equal(len(TestProxySmartModel.objects.get(pk=obj.pk).name), 11)
Ejemplo n.º 10
0
 def test_enum(self):
     enum = Enum(
         'A', 'B'
     )
     assert_equal(enum.A, 'A')
     assert_equal(enum.B, 'B')
     with assert_raises(AttributeError):
         enum.C  # pylint: disable=W0104
Ejemplo n.º 11
0
    def test_sms_template_for_unavailable_service_should_create_message_with_state_local_to_send(self):
        def raise_exception(request):
            raise requests.exceptions.HTTPError()

        responses.add_callback(responses.POST, settings.ATS_URL, content_type='text/xml', callback=raise_exception)
        assert_raises(SMSSendingError, send_template, '+420777111222', slug='test',
                      context={'variable': 'context works'}, pk=245)
        assert_equal(OutputSMS.objects.get(pk=245).state, ATS_STATES.LOCAL_TO_SEND)
Ejemplo n.º 12
0
    def test_user_may_edit_itself(self):
        user = self.logged_user.user
        resp = self.get('%s%s/' % (self.USER_UI_URL, user.pk))
        assert_http_ok(resp)

        CHANGED_USERNAME = '******'
        self.post('%s%s/' % (self.USER_UI_URL, user.pk), data={'edit-is-user-username': CHANGED_USERNAME})
        assert_http_ok(resp)
        assert_equal(User.objects.get(pk=user.pk).username, CHANGED_USERNAME)
Ejemplo n.º 13
0
 def test_json_request_should_be_truncated_with_another_method(self):
     self.c.post('/admin/login/', data=json.dumps({'a': 50 * 'a', 'b': 50 * 'b'}),
                 content_type='application/json')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(
         json.loads(input_logged_request.request_body),
         json.loads('{"a": "aaaaaaa...", "b": "bbbbbbb..."}')
     )
     assert_false(input_logged_request.request_body.endswith('...'))
Ejemplo n.º 14
0
 def test_return_json_snippet_content_without_snippet(self):
     resp = self.get(self.JSON_SNIPPET_URL)
     assert_equal(
         force_text(resp.content),
         '<div class="snippet snippet-1" data-snippet="test-snippet-1" data-snippet-type="replace">'
         'test-snippet-1-content</div><div class="snippet snippet-2" data-snippet="test-snippet-2" '
         'data-snippet-type="replace">test-snippet-2-content</div>'
     )
     assert_equal(resp['content-type'], 'text/html; charset=utf-8')
Ejemplo n.º 15
0
 def test_ats_invalid_request_should_return_24_code(self):
     sms_count = InputSMS.objects.count()
     response = self.post(self.API_URL, self.ATS_SMS_POST_PAYLOAD.format(self.INVALID_MESSAGES))
     self.assert_http_ok(response)  # ATS requires to return 200 in every situation
     assert_equal(sms_count + 1, InputSMS.objects.count())
     assert_equal(response.content.replace('\n', ' ').replace('\r', ''),
                  '<?xml version="1.0" encoding="UTF-8" ?> <status> <code uniq="">24</code> '
                  '<code uniq="invalid">24</code> <code uniq="4">24</code> '
                  '<code uniq="5">23</code> </status>')
Ejemplo n.º 16
0
    def test_translation_activate_block(self):

        @translation_activate_block(language='en')
        def en_block():
            assert_equal(get_language(), 'en')

        assert_equal(get_language(), 'cs')
        en_block()
        assert_equal(get_language(), 'cs')
Ejemplo n.º 17
0
 def test_subchoices_field_value_should_be_empty(self):
     self.inst.state = 4  # setting an invalid value
     try:
         TestFieldsModel._meta.get_field('state_reason').validate(  # pylint: disable=W0212
             TestFieldsModel.STATE_REASON.SUB_NOT_OK_2, self.inst)  # pylint: disable=W0212
         assert_true(False, 'Field validation should raise an error')
     except ValidationError as ex:
         assert_equal(['Value must be empty'], ex.messages)
     assert_is_none(TestFieldsModel._meta.get_field('state_reason').clean(  # pylint: disable=W0212
         TestFieldsModel.STATE_REASON.SUB_NOT_OK_2, self.inst))  # pylint: disable=W0212
Ejemplo n.º 18
0
 def test_decimal_field(self):
     change_and_save(self.inst, decimal=3)
     assert_equal(self.inst.decimal, 3)
     assert_raises(PersistenceException, change_and_save, self.inst, decimal='2.99')
     assert_raises(PersistenceException, change_and_save, self.inst, decimal='10.00001')
     try:
         change_and_save(self.inst, decimal='11.1')
         assert_true(False, 'Previous `change_and_save` suppose to raise an exception')
     except PersistenceException as ex:
         assert_true('decimal: ' in str(ex), 'Exception message was supposed to contain a field name.')
Ejemplo n.º 19
0
    def test_sms_template_should_be_immediately_send(self):
        responses.add(responses.POST, settings.ATS_URL, content_type='text/xml',
                      body=self.ATS_SINGLE_SMS_REQUEST_RESPONSE_SENT.format(245), status=200)
        sms1 = send_template('+420777111222', slug='test', context={'variable': 'context works'}, pk=245)

        sms1 = OutputSMS.objects.get(pk=sms1.pk)

        assert_equal(sms1.state, ATS_STATES.OK)
        assert_true('context works' in sms1.content)
        assert_is_not_none(sms1.sent_at)
Ejemplo n.º 20
0
 def test_decimal_field_should_return_correct_widget_attrs(self):
     kwargs = {
         'step': 0.5,
         'min': 1.0,
         'max': 10.0,
     }
     field = DecimalField(**kwargs)
     widget_attrs = field.widget_attrs(TextInput())
     assert_true(len(widget_attrs.keys()) > 0)
     for attr, value in kwargs.items():
         assert_equal(value, widget_attrs[attr])
Ejemplo n.º 21
0
    def test_get_object_or_404(self):
        obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1)
        ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2)
        ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3)

        assert_equal(get_object_or_404(ShortcutsModel, name='test1'), obj)
        assert_raises(Http404, get_object_or_404, ShortcutsModel, name='test3')
        assert_raises(Http404, get_object_or_404, ShortcutsModel, number='test3')
        assert_raises(Http404, get_object_or_404, ShortcutsModel, datetime='test3')

        assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2')
        assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2')
Ejemplo n.º 22
0
 def test_smart_model_post_save(self):
     assert_raises(PersistenceException, TestPostProxySmartModel.objects.create)
     obj = TestPostProxySmartModel.objects.create(name=10 * 'a')
     assert_equal(obj.name, 'test post save')
     assert_false(TestPreProxySmartModel.objects.filter(name='test post save').exists())
     assert_true(TestPreProxySmartModel.objects.filter(name=10 * 'a').exists())
     obj.save()
     assert_true(TestPreProxySmartModel.objects.filter(name='test post save').exists())
     obj.name = 10 * 'a'
     obj.save()
     assert_equal(obj.name, 'test post save')
     assert_false(TestPreProxySmartModel.objects.filter(name='test post save').exists())
Ejemplo n.º 23
0
    def test_records_should_be_imported_from_csv(self):
        assert_equal(CSVRecord.objects.count(), 0)
        BulkCSVRecordImporter().import_csv()

        assert_equal(CSVRecord.objects.count(), 7)
        assert_equal(CSVRecord.objects.last().name, 'Geordi LaForge')  # Ensure correct value is stored
        assert_equal(CSVRecord.objects.last().number, 888)  # Ensure clean methods work
Ejemplo n.º 24
0
 def test_serialization(self):
     for i in range(10):
         User.objects.create(is_superuser=True, email='test{}@test.cz'.format(i))
     assert_true(isinstance(json.loads((serialize(User.objects.all()))), list))
     assert_true(isinstance(json.loads((serialize(User.objects.first()))), dict))
     assert_equal(
         set(json.loads((serialize(User.objects.first()))).keys()),
         {'_obj_name', 'id', 'created_at', 'contract', 'email'}
     )
     assert_equal(
         set(json.loads((serialize(User.objects.first(), ('id',)))).keys()),
         {'id'}
     )
     xml.dom.minidom.parseString(serialize(User.objects.first(), converter_name='xml'))
Ejemplo n.º 25
0
 def test_enum_should_contain_only_defined_values(self):
     enum = Enum(
         'A', 'B'
     )
     assert_equal(enum.A, 'A')
     assert_equal(enum.B, 'B')
     assert_equal(list(enum), ['A', 'B'])
     assert_equal(enum.all, ('A', 'B'))
     assert_equal(enum.get_name('A'), 'A')
     with assert_raises(AttributeError):
         enum.C  # pylint: disable=W0104
     assert_is_none(enum.get_name('C'))
     assert_in('A', enum)
     assert_in(enum.A, enum)
     assert_not_in('C', enum)
Ejemplo n.º 26
0
 def test_enum_with_distinct_key_and_value_should_contain_only_defined_values(self):
     enum = Enum(
         ('A', 'c'), ('B', 'd')
     )
     assert_equal(enum.A, 'c')
     assert_equal(enum.B, 'd')
     assert_equal(list(enum), ['c', 'd'])
     assert_equal(enum.all, ('c', 'd'))
     assert_equal(enum.get_name('c'), 'A')
     with assert_raises(AttributeError):
         enum.C  # pylint: disable=W0104
     assert_is_none(enum.get_name('f'))
     assert_in('c', enum)
     assert_in(enum.A, enum)
     assert_not_in('A', enum)
Ejemplo n.º 27
0
 def test_auto_gemerated_num_enum_should_contain_only_defined_values(self):
     enum = NumEnum(
         'A', 'B'
     )
     assert_equal(enum.A, 1)
     assert_equal(enum.B, 2)
     assert_equal(list(enum), [1, 2])
     assert_equal(enum.all, (1, 2))
     assert_equal(enum.get_name(1), 'A')
     with assert_raises(AttributeError):
         enum.C  # pylint: disable=W0104
     assert_is_none(enum.get_name(3))
     assert_in(1, enum)
     assert_in(enum.A, enum)
     assert_not_in('A', enum)
Ejemplo n.º 28
0
 def test_num_enum_with_defined_ids_should_return_valid_values(self):
     enum = NumEnum(
         ('A', 4), ('B', 2), 'C'
     )
     assert_equal(enum.A, 4)
     assert_equal(enum.B, 2)
     assert_equal(enum.C, 3)
     assert_equal(list(enum), [4, 2, 3])
Ejemplo n.º 29
0
 def test_output_logged_request_should_be_related_with_object(self, user):
     assert_http_redirect(self.post('/admin/login/', data={'username': '******', 'password': '******'}))
     responses.add(responses.GET, 'http://test.cz', body='test')
     assert_equal(self.get('/proxy/?url=http://test.cz').content, b'test')
     assert_equal(InputLoggedRequest.objects.count(), 2)
     assert_equal(OutputLoggedRequest.objects.count(), 1)
     output_logged_request = OutputLoggedRequest.objects.get()
     assert_equal(output_logged_request.related_objects.get().content_object, user)
Ejemplo n.º 30
0
 def test_bulk_change_and_save(self):
     obj1 = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1)
     obj2 = ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2)
     bulk_change_and_save([obj1, obj2], name='modified')
     assert_equal(obj1.name, 'modified')
     assert_equal(obj2.name, 'modified')
     assert_equal(ShortcutsModel.objects.first().name, 'modified')  # instance is changed but NOT saved to DB
     assert_equal(ShortcutsModel.objects.last().name, 'modified')  # instance is changed but NOT saved to DB
Ejemplo n.º 31
0
 def test_decimal_field(self):
     change_and_save(self.inst, decimal=3)
     assert_equal(self.inst.decimal, 3)
     assert_raises(PersistenceException,
                   change_and_save,
                   self.inst,
                   decimal='2.99')
     assert_raises(PersistenceException,
                   change_and_save,
                   self.inst,
                   decimal='10.00001')
     try:
         change_and_save(self.inst, decimal='11.1')
         assert_true(
             False,
             'Previous `change_and_save` suppose to raise an exception')
     except PersistenceException as ex:
         assert_true(
             'decimal: ' in str(ex),
             'Exception message was supposed to contain a field name.')
Ejemplo n.º 32
0
    def test_on_success_inheritance(self):
        numbers_list = []

        with transaction_signals():
            with transaction_signals():
                on_success(lambda: add_number(numbers_list, 0))

                assert_equal(len(numbers_list), 0)
            assert_equal(len(numbers_list), 0)
            try:
                with transaction_signals():
                    on_success(lambda: add_number(numbers_list, 1))

                    assert_equal(len(numbers_list), 0)
                    raise Exception()
            except Exception:
                pass
            on_success(lambda: add_number(numbers_list, 2))
            assert_equal(len(numbers_list), 0)

        assert_equal(numbers_list, [0, 2])
Ejemplo n.º 33
0
    def test_file_field(self):
        customer = Customer(**CUSTOMER__KWARGS)
        customer.save()

        avatar = Avatar()
        avatar.customer = customer
        avatar.image.save('test_file_secret_data',
                          ContentFile('Super secret data'),
                          save=False)
        avatar.save()

        avatar_2: Avatar = Avatar.objects.last()
        assert_equal(avatar_2.image.read(), b'Super secret data')
        avatar_2._anonymize_obj(base_encryption_key='LoremIpsumDolorSitAmet')

        avatar_3: Avatar = Avatar.objects.last()
        assert_not_equal(avatar_3.image.read(), b'Super secret data')

        # Cleanup
        avatar_3.image.delete()
        avatar_3.delete()
Ejemplo n.º 34
0
    def test_file_field_real_file(self):
        anonymizer = anonymizer_register[Avatar]
        anonymizer.image.replacement_file = 'test_file'
        customer = Customer(**CUSTOMER__KWARGS)
        customer.save()

        avatar = Avatar()
        avatar.customer = customer
        avatar.image.save('test_file_real', ContentFile('Super secret data'))

        avatar_2: Avatar = Avatar.objects.last()
        assert_equal(avatar_2.image.read(), b'Super secret data')
        avatar_2._anonymize_obj(base_encryption_key='LoremIpsumDolorSitAmet')

        avatar_3: Avatar = Avatar.objects.last()
        assert_not_equal(avatar_3.image.read(), b'Super secret data')

        anonymizer.image.replacement_file = None
        # Cleanup
        avatar_3.image.delete()
        avatar_3.delete()
Ejemplo n.º 35
0
 def test_clean_tokens_remove_only_old_tokens(self, user):
     expired_tokens = [
         Token.objects.create(user=user, ip='127.0.0.1') for _ in range(10)
     ]
     not_expired_tokens = [
         Token.objects.create(user=user, ip='127.0.0.1')
         for _ in range(settings.COUNT_USER_PRESERVED_TOKENS - 5)
     ]
     Token.objects.filter(
         pk__in=[token.pk for token in expired_tokens]).update(
             last_access=timezone.now() -
             timedelta(seconds=settings.MAX_TOKEN_AGE))
     call_command('clean_tokens', stdout=StringIO(), stderr=StringIO())
     assert_equal(
         Token.objects.filter(
             pk__in=[token.pk for token in not_expired_tokens]).count(),
         settings.COUNT_USER_PRESERVED_TOKENS - 5)
     assert_equal(
         Token.objects.filter(pk__in=[token.pk
                                      for token in expired_tokens]).count(),
         5)
    def test_should_correctly_handle_unknown_ats_state(self):
        responses.add(responses.POST,
                      settings.ATS_URL,
                      content_type='text/xml',
                      body=self.ATS_UNKNOW_STATE_RESPONSE,
                      status=200)
        sms1 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[0],
                                **self.ATS_OUTPUT_SMS1)
        sms2 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[1],
                                **self.ATS_OUTPUT_SMS2)

        response = send_ats_requests(sms1, sms2)
        with open('./var/log/ats_sms.log') as ats_log:
            log_lines_count = sum(1 for _ in ats_log)
            response_codes = parse_response_codes(response.text)
            ats_log.seek(0)
            log_lines = ats_log.readlines()

            assert_equal(log_lines_count + 1, len(log_lines))
            assert_true('999' in log_lines[-1])
            assert_false(response_codes)
Ejemplo n.º 37
0
    def test_verification_token_should_be_found_by_model_class_or_instance(
            self, user):
        # 2 users of the same content type with tokens created
        user2 = User.objects._create_user('user2', '*****@*****.**', 'test2')
        token = VerificationToken.objects.deactivate_and_create(user)
        VerificationToken.objects.deactivate_and_create(
            user2, deactivate_old_tokens=False)

        # another content type object with token created
        group = Group.objects.create(name='authorized_group')
        token_from_group = VerificationToken.objects.deactivate_and_create(
            group, deactivate_old_tokens=False)

        tokens_by_class = VerificationToken.objects.filter_active_tokens(User)
        assert_equal(tokens_by_class.count(), 2)

        tokens_by_object = VerificationToken.objects.filter_active_tokens(user)
        assert_equal(tokens_by_object.count(), 1)
        assert_token_is_same_active_and_valid(tokens_by_object.first(), token)

        tokens_by_object = VerificationToken.objects.filter_active_tokens(
            Group)
        assert_equal(tokens_by_object.count(), 1)
        assert_token_is_same_active_and_valid(tokens_by_object.first(),
                                              token_from_group)
Ejemplo n.º 38
0
 def test_output_logged_request_should_be_related_with_object(self, user):
     with capture_security_logs() as logged_data:
         assert_http_redirect(self.post('/admin/login/', data={'username': '******', 'password': '******'}))
         responses.add(responses.GET, 'http://localhost', body='test')
         assert_equal(self.get('/proxy/?url=http://localhost').content, b'test')
         assert_equal(len(logged_data.output_request[0].related_objects), 1)
         assert_equal(list(logged_data.output_request[0].related_objects)[0], get_object_triple(user))
Ejemplo n.º 39
0
 def test_input_logged_request_should_have_set_data(self, user):
     with capture_security_logs() as logged_data:
         assert_http_redirect(self.post('/admin/login/', data={'username': '******', 'password': '******'}))
         assert_http_ok(self.get('/home/'))
         assert_equal(len(logged_data.input_request[1].related_objects), 1)
         assert_equal(list(logged_data.input_request[1].related_objects)[0], get_object_triple(user))
         assert_equal(logged_data.input_request_finished[1].slug, 'user-home')
Ejemplo n.º 40
0
 def create_and_upldate_test_on_dispatcher_model():
     model = TestDispatchersModel.objects.create()
     assert_equal(TestOnDispatchModel.objects.count(), 0)
     model.change_and_save(state=2)
     assert_equal(TestOnDispatchModel.objects.count(), 0)
     model.change_and_save(state=1)
     assert_equal(TestOnDispatchModel.objects.count(), 0)
Ejemplo n.º 41
0
 def test_more_test_on_dispatch_instances_should_be_created_if_transaction_signals_is_not_activated(self):
     model = TestDispatchersModel.objects.create()
     assert_equal(TestOnDispatchModel.objects.count(), 1)
     model.change_and_save(state=2)
     assert_equal(TestOnDispatchModel.objects.count(), 2)
     model.change_and_save(state=1)
     assert_equal(TestOnDispatchModel.objects.count(), 3)
Ejemplo n.º 42
0
 def test_celery_task_should_have_rightly_set_expires_time_if_stale_time_limit_is_set_in_task_call(
         self):
     sum_task.apply_async(args=(5, 8), stale_time_limit=100)
     celery_task_log = CeleryTaskLog.objects.get()
     assert_equal(celery_task_log.estimated_time_of_first_arrival, now())
     assert_equal(celery_task_log.stale, now() + timedelta(seconds=100))
     assert_equal(celery_task_log.expires, now() + timedelta(seconds=90))
Ejemplo n.º 43
0
 def test_bulk_change_and_save(self):
     obj1 = ShortcutsModel.objects.create(name='test1',
                                          datetime=timezone.now(),
                                          number=1)
     obj2 = ShortcutsModel.objects.create(name='test2',
                                          datetime=timezone.now(),
                                          number=2)
     bulk_change_and_save([obj1, obj2], name='modified')
     assert_equal(obj1.name, 'modified')
     assert_equal(obj2.name, 'modified')
     assert_equal(ShortcutsModel.objects.first().name,
                  'modified')  # instance is changed but NOT saved to DB
     assert_equal(ShortcutsModel.objects.last().name,
                  'modified')  # instance is changed but NOT saved to DB
Ejemplo n.º 44
0
    def test_model_diff(self):
        obj = DiffModel.objects.create(name='test',
                                       datetime=timezone.now(),
                                       number=2)
        assert_false(obj.has_changed)
        obj.name = 'test2'
        assert_true(obj.has_changed)
        assert_equal(set(obj.changed_fields.keys()), {'name'})
        assert_equal((obj.changed_fields['name'].initial,
                      obj.changed_fields['name'].current), ('test', 'test2'))

        obj.name = 'test'
        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)

        obj.name = 'test2'
        obj.number = 3
        obj.datetime = obj.datetime + timedelta(days=2)
        assert_true(obj.has_changed)
        assert_equal(set(obj.changed_fields.keys()),
                     {'name', 'number', 'datetime'})

        obj.save()
        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)
Ejemplo n.º 45
0
 def test_apply_task_with_related_objects_should_be_stored(self, user):
     sum_task.apply_async(args=(5, 8), related_objects=[user])
     assert_equal(CeleryTaskLog.objects.count(), 1)
     assert_equal(CeleryTaskLog.objects.get().state,
                  CeleryTaskLogState.SUCCEEDED)
     assert_equal(CeleryTaskLog.objects.get().related_objects.get().object,
                  user)
Ejemplo n.º 46
0
    def test_expirement_legal_reason_related(self):
        related_email: Email = Email(customer=self.customer,
                                     email=CUSTOMER__EMAIL)
        related_email.save()

        related_email2: Email = Email(customer=self.customer,
                                      email=CUSTOMER__EMAIL2)
        related_email2.save()

        related_email3: Email = Email(customer=self.customer,
                                      email=CUSTOMER__EMAIL3)
        related_email3.save()

        legal = LegalReason.objects.create_consent(EMAIL_SLUG, self.customer)
        legal.expire()

        anon_customer = Customer.objects.get(pk=self.customer.pk)

        assert_equal(anon_customer.primary_email_address, CUSTOMER__EMAIL)
        self.assertAnonymizedDataNotExists(anon_customer,
                                           "primary_email_address")

        # make sure only data we want were anonymized
        assert_equal(anon_customer.first_name, CUSTOMER__FIRST_NAME)
        self.assertAnonymizedDataNotExists(anon_customer, "first_name")

        anon_related_email: Email = Email.objects.get(pk=related_email.pk)

        assert_not_equal(anon_related_email.email, CUSTOMER__EMAIL)
        self.assertAnonymizedDataExists(anon_related_email, "email")

        anon_related_email2: Email = Email.objects.get(pk=related_email2.pk)

        assert_not_equal(anon_related_email2.email, CUSTOMER__EMAIL2)
        self.assertAnonymizedDataExists(anon_related_email2, "email")

        anon_related_email3: Email = Email.objects.get(pk=related_email3.pk)

        assert_not_equal(anon_related_email3.email, CUSTOMER__EMAIL3)
        self.assertAnonymizedDataExists(anon_related_email3, "email")
Ejemplo n.º 47
0
    def test_sequence_choices_num_enum(self):
        # Only the first state is valid when field is null because it is the initial state
        assert_is_none(self.inst.state_graph)
        assert_raises(PersistenceException,
                      change_and_save,
                      self.inst,
                      state_graph=TestFieldsModel.GRAPH.SECOND)
        assert_raises(PersistenceException,
                      change_and_save,
                      self.inst,
                      state_graph=TestFieldsModel.GRAPH.THIRD)
        change_and_save(self.inst, state_graph=TestFieldsModel.GRAPH.FIRST)
        assert_equal(self.inst.state_graph, TestFieldsModel.GRAPH.FIRST)

        # Than one can switch only to second state
        assert_raises(PersistenceException,
                      change_and_save,
                      self.inst,
                      state_graph=TestFieldsModel.GRAPH.THIRD)
        change_and_save(self.inst, state_graph=TestFieldsModel.GRAPH.SECOND)
        assert_equal(self.inst.state_graph, TestFieldsModel.GRAPH.SECOND)

        # We cannot go back to first but we can go to the third state
        assert_raises(PersistenceException,
                      change_and_save,
                      self.inst,
                      state_graph=TestFieldsModel.GRAPH.FIRST)
        change_and_save(self.inst, state_graph=TestFieldsModel.GRAPH.THIRD)
        assert_equal(self.inst.state_graph, TestFieldsModel.GRAPH.THIRD)
Ejemplo n.º 48
0
 def test_output_logged_request_should_be_related_with_object(self, user):
     assert_http_redirect(
         self.post('/admin/login/',
                   data={
                       'username': '******',
                       'password': '******'
                   }))
     responses.add(responses.GET, 'http://test.cz', body='test')
     assert_equal(self.get('/proxy/?url=http://test.cz').content, b'test')
     assert_equal(InputLoggedRequest.objects.count(), 2)
     assert_equal(OutputLoggedRequest.objects.count(), 1)
     output_logged_request = OutputLoggedRequest.objects.get()
     assert_equal(
         output_logged_request.related_objects.get().content_object, user)
    def test_command_should_check_delivery_status(self):
        responses.add(
            responses.POST,
            settings.ATS_URL,
            content_type='text/xml',
            body=self.ATS_SMS_DELIVERY_RESPONSE.format(*self.ATS_TEST_UNIQ),
            status=200)

        sms2 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[1],
                                sent_at=timezone.now(),
                                state=ATS_STATES.OK,
                                **self.ATS_OUTPUT_SMS2)
        sms1 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[0],
                                sent_at=timezone.now(),
                                state=ATS_STATES.OK,
                                **self.ATS_OUTPUT_SMS1)

        CheckDeliveryCommand().handle()

        sms1 = OutputSMS.objects.get(pk=sms1.pk)
        sms2 = OutputSMS.objects.get(pk=sms2.pk)

        assert_equal(
            strip_all(responses.calls[0].request.body),
            strip_all(
                self.ATS_SMS_DELIVERY_REQUEST.format(
                    first_id=self.ATS_TEST_UNIQ[0],
                    second_id=self.ATS_TEST_UNIQ[1])))
        assert_equal(sms1.state, ATS_STATES.SENT)
        assert_equal(sms2.state, ATS_STATES.DELIVERED)
Ejemplo n.º 50
0
 def test_error_command_should_be_logged_in_elasticsearch_backend(self, user):
     with capture_security_logs() as logged_data:
         with log_with_data(related_objects=[user]):
             with assert_raises(RuntimeError):
                 test_call_command('test_error_command')
             elasticsearch_command_log = ElasticsearchCommandLog.get(
                 id=logged_data.command[0].id
             )
             assert_equal_model_fields(
                 elasticsearch_command_log,
                 name='test_error_command',
                 input='',
                 is_executed_from_command_line=False,
                 time=(elasticsearch_command_log.stop - elasticsearch_command_log.start).total_seconds(),
                 state=CommandState.FAILED,
                 output=None,
             )
             assert_is_not_none(elasticsearch_command_log.error_message)
             assert_equal(
                 [rel_obj for rel_obj in elasticsearch_command_log.related_objects],
                 ['default|3|{}'.format(user.id)]
             )
Ejemplo n.º 51
0
    def test_serialization(self):
        for i in range(10):
            User.objects.create(is_superuser=True,
                                email='test{}@test.cz'.format(i))
        assert_true(
            isinstance(json.loads((serialize(User.objects.all()))), list))
        assert_true(
            isinstance(json.loads((serialize(User.objects.first()))), dict))

        assert_equal(
            set(json.loads((serialize(User.objects.first()))).keys()), {
                'id', 'created_at', '_obj_name', 'email', 'contract',
                'solving_issue', 'first_name', 'last_name',
                'manual_created_date'
            })
        assert_equal(
            set(
                json.loads((serialize(User.objects.first(),
                                      ('id', )))).keys()), {'id'})

        xml.dom.minidom.parseString(
            serialize(User.objects.first(), converter_name='xml'))
    def test_command_should_send_and_update_sms(self):
        responses.add(responses.POST,
                      settings.ATS_URL,
                      content_type='text/xml',
                      body=self.ATS_SMS_REQUEST_RESPONSE_SENT.format(
                          *self.ATS_TEST_UNIQ),
                      status=200)

        sms1 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[0],
                                **self.ATS_OUTPUT_SMS1)
        sms2 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ[1],
                                **self.ATS_OUTPUT_SMS2)

        SendCommand().handle()

        sms1 = OutputSMS.objects.get(pk=sms1.pk)
        sms2 = OutputSMS.objects.get(pk=sms2.pk)

        assert_equal(sms1.state, ATS_STATES.OK)
        assert_is_not_none(sms1.sent_at)
        assert_equal(sms2.state, ATS_STATES.LOCAL_UNKNOWN_ATS_STATE)
        assert_is_not_none(sms2.sent_at)
Ejemplo n.º 53
0
    def test_should_send_ats_request_and_parse_response_codes(self, prefix):
        responses.add(responses.POST, settings.ATS_SMS_URL, content_type='text/xml', status=200,
                      body=self.ATS_SMS_REQUEST_RESPONSE_SENT.format(prefix=prefix, **self.ATS_TEST_UNIQ))
        sms1 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ['uniq1'], **self.ATS_OUTPUT_SMS1)
        sms2 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ['uniq2'], **self.ATS_OUTPUT_SMS2)

        response = send_ats_requests(sms1, sms2)

        assert_equal(response.request.url, 'http://fik.atspraha.cz/gwfcgi/XMLServerWrapper.fcgi')
        assert_equal(response.request.headers['content-type'], 'text/xml')

        response_codes = parse_response_codes(response.text)

        assert_equal(response_codes[self.ATS_TEST_UNIQ['uniq1']], 0)
        assert_equal(response_codes[self.ATS_TEST_UNIQ['uniq2']], 123456)
Ejemplo n.º 54
0
 def test_celery_task_should_have_rightly_set_expires_time_according_to_default_task_stale_limit_value(
         self):
     error_task.apply_async()
     celery_task_log = CeleryTaskLog.objects.get()
     assert_equal(celery_task_log.estimated_time_of_first_arrival, now())
     assert_equal(celery_task_log.stale, now() + timedelta(seconds=60 * 60))
     assert_equal(celery_task_log.expires,
                  now() + timedelta(seconds=60 * 60 - 10))
Ejemplo n.º 55
0
    def test_rfs_add(self):
        fieldset_a = rfs(('a', 'b', 'b__c', 'b__g', ('d', ('e__f', ))))
        fieldset_b = rfs(('a__i', 'l'))

        fieldset_c = fieldset_a + fieldset_b
        assert_equal(str(fieldset_a), 'a,b(c,g),d(e(f))')
        assert_equal(str(fieldset_b), 'a(i),l')
        assert_equal(str(fieldset_c), 'a(i),b(c,g),d(e(f)),l')
Ejemplo n.º 56
0
 def test_command_should_be_logged_in_elasticsearch_backend(self, user):
      with capture_security_logs() as logged_data:
         with log_with_data(related_objects=[user]):
             test_call_command('test_command', verbosity=0)
             elasticsearch_command_log = ElasticsearchCommandLog.get(
                 id=logged_data.command[0].id
             )
             assert_equal_model_fields(
                 elasticsearch_command_log,
                 name='test_command',
                 input='verbosity=0',
                 is_executed_from_command_line=False,
                 time=(elasticsearch_command_log.stop - elasticsearch_command_log.start).total_seconds(),
                 state=CommandState.SUCCEEDED,
                 error_message=None,
             )
             assert_is_not_none(elasticsearch_command_log.output)
             assert_equal(
                 [rel_obj for rel_obj in elasticsearch_command_log.related_objects],
                 ['default|3|{}'.format(user.id)]
             )
             ElasticsearchCommandLog._index.refresh()
             assert_equal(get_logs_related_with_object(LoggerName.COMMAND, user), [elasticsearch_command_log])
Ejemplo n.º 57
0
    def test_stale_succeded_celery_task_should_not_be_set_as_succeeded_with_command(
            self):
        sum_task.apply_async(args=(5, 8))
        celery_task_log = CeleryTaskLog.objects.create(
            celery_task_id='random id',
            name='error_task',
            queue_name='default',
            input='',
            task_args=[],
            task_kwargs={},
            estimated_time_of_first_arrival=now() - timedelta(minutes=5),
            expires=now() - timedelta(minutes=4),
            stale=now() - timedelta(minutes=3))
        CeleryTaskRunLog.objects.create(celery_task_id='random id',
                                        name='error_task',
                                        state=CeleryTaskRunLogState.SUCCEEDED,
                                        task_args=[],
                                        task_kwargs={},
                                        retries=0)

        test_call_command('set_celery_task_log_state')
        assert_equal(celery_task_log.refresh_from_db().state,
                     CeleryTaskLogState.SUCCEEDED)
Ejemplo n.º 58
0
    def test_state_dispatcher(self):
        m = TestDispatchersModel.objects.create()

        # Moving TestDispatcher model to SECOND state should create new TestSmartModel instance
        assert_equal(TestSmartModel.objects.count(), 0)
        change_and_save(m, state=TestDispatchersModel.STATE.SECOND)
        assert_equal(TestSmartModel.objects.count(), 1)

        # But subsequent saves should not create more instances
        change_and_save(m, state=TestDispatchersModel.STATE.SECOND)
        assert_equal(TestSmartModel.objects.count(), 1)

        # Moving back and forth between the states creates another instance
        change_and_save(m, state=TestDispatchersModel.STATE.FIRST)
        change_and_save(m, state=TestDispatchersModel.STATE.SECOND)
        assert_equal(TestSmartModel.objects.count(), 2)
Ejemplo n.º 59
0
 def test_smart_queryset_fast_distinct(self):
     t = TestSmartModel.objects.create(name='name')
     RelatedSmartModel.objects.create(test_smart_model=t)
     RelatedSmartModel.objects.create(test_smart_model=t)
     qs = TestSmartModel.objects.filter(
         test_smart_models__test_smart_model=t)
     assert_equal(qs.count(), 2)
     assert_equal(tuple(qs.values_list('pk', flat=True)), (t.pk, t.pk))
     assert_equal(qs.fast_distinct().count(), 1)
Ejemplo n.º 60
0
    def test_get_object_or_none(self):
        obj = ShortcutsModel.objects.create(name='test1',
                                            datetime=timezone.now(),
                                            number=1)
        ShortcutsModel.objects.create(name='test2',
                                      datetime=timezone.now(),
                                      number=2)
        ShortcutsModel.objects.create(name='test2',
                                      datetime=timezone.now(),
                                      number=3)

        assert_equal(get_object_or_none(ShortcutsModel, name='test1'), obj)
        assert_is_none(get_object_or_none(ShortcutsModel, name='test3'))
        assert_is_none(get_object_or_none(ShortcutsModel, number='test3'))
        assert_is_none(get_object_or_none(ShortcutsModel, datetime='test3'))

        assert_raises(FieldError,
                      get_object_or_none,
                      ShortcutsModel,
                      non_field='test2')
        assert_raises(MultipleObjectsReturned,
                      get_object_or_none,
                      ShortcutsModel,
                      name='test2')