def test_requests_exception_should_be_caught_and_raised(self):
        responses.add(responses.POST, settings.ATS_URL, content_type='text/xml',
                      body=self.ATS_SMS_REQUEST_RESPONSE_SENT.format(*self.ATS_INVALID_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)

        assert_raises(SMSValidationError, send_and_update_sms_states, sms1, sms2)
Esempio n. 2
0
    def test_smart_model_get_locked_instance(self):
        not_saved_obj = TestSmartModel()

        assert_raises(OperationalError, not_saved_obj.get_locked_instance)

        obj = TestSmartModel.objects.create(name='1')
        assert_equal(obj, obj.get_locked_instance())
Esempio n. 3
0
    def test_smart_model_clean_atomic_post_delete(self):
        class AtomicPostDeleteTestProxySmartModel(TestProxySmartModel):
            class Meta:
                proxy = True
                verbose_name = 'testmodel'
                verbose_name_plural = 'testmodels'

            class SmartMeta:
                is_cleaned_pre_save = False
                is_cleaned_post_delete = True
                is_delete_atomic = True

        obj = AtomicPostDeleteTestProxySmartModel.objects.create(name=10 * 'a')
        obj_pk = obj.pk
        assert_raises(PersistenceException, obj.delete)
        assert_true(
            AtomicPostDeleteTestProxySmartModel.objects.filter(
                pk=obj_pk).exists())

        obj = AtomicPostDeleteTestProxySmartModel.objects.create(name=10 * 'a')
        obj_pk = obj.pk
        obj.delete(is_cleaned_post_delete=False)
        assert_false(
            AtomicPostDeleteTestProxySmartModel.objects.filter(
                pk=obj_pk).exists())
Esempio n. 4
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')
Esempio n. 5
0
    def test_smart_model_clean_atomic_post_save(self):
        class AtomicPostSaveTestProxySmartModel(TestProxySmartModel):
            class Meta:
                proxy = True
                verbose_name = 'testmodel'
                verbose_name_plural = 'testmodels'

            class SmartMeta:
                is_cleaned_pre_save = False
                is_cleaned_post_save = True
                is_save_atomic = True

        assert_false(
            AtomicPostSaveTestProxySmartModel.objects.filter(name=10 *
                                                             'a').exists())
        assert_raises(PersistenceException,
                      AtomicPostSaveTestProxySmartModel.objects.create,
                      name=10 * 'a')
        assert_false(
            AtomicPostSaveTestProxySmartModel.objects.filter(name=10 *
                                                             'a').exists())
        obj = AtomicPostSaveTestProxySmartModel.objects.create(name=9 * 'a')
        obj.name = 11 * 'a'
        assert_raises(PersistenceException, obj.save)
        assert_equal(
            len(AtomicPostSaveTestProxySmartModel.objects.get(pk=obj.pk).name),
            9)
        obj.name = 12 * 'a'
        obj.save(is_cleaned_post_save=False)
        assert_equal(
            len(AtomicPostSaveTestProxySmartModel.objects.get(pk=obj.pk).name),
            12)
Esempio n. 6
0
    def test_restricted_file_field_should_raise_validation_error_for_invalid_files(
            self):
        field = RestrictedFileField(allowed_content_types=('image/jpeg',
                                                           'application/pdf'),
                                    max_upload_size=1)

        # Invalid file type
        with open(
                os.path.join(settings.PROJECT_DIR, 'data',
                             'all_fields_filled.csv'), 'rb') as f:
            with assert_raises(ValidationError):
                field.clean(
                    SimpleUploadedFile('all_fields_filled.pdf', f.read()))

        # Invalid size
        with open(os.path.join(settings.PROJECT_DIR, 'data', 'test.jpg'),
                  'rb') as f:
            with assert_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.jpg', f.read()))

        # Invalid file suffix
        with open(os.path.join(settings.PROJECT_DIR, 'data', 'test.pdf'),
                  'rb') as f:
            with assert_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.csv', f.read()))

        # Valid file
        with open(os.path.join(settings.PROJECT_DIR, 'data', 'test.pdf'),
                  'rb') as f:
            with assert_not_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.pdf', f.read()))
Esempio n. 7
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_SMS_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)
Esempio n. 8
0
    def test_requests_exception_should_be_caught_and_raised(self):
        responses.add(responses.POST, settings.ATS_SMS_URL, content_type='text/xml', status=200,
                      body=self.ATS_SMS_REQUEST_RESPONSE_SENT.format(prefix=settings.ATS_SMS_UNIQ_PREFIX,
                                                                     **self.ATS_INVALID_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)

        assert_raises(SMSValidationError, send_and_update_sms_states, sms1, sms2)
Esempio 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)
Esempio n. 10
0
 def test_enum_key_should_have_right_format(self):
     with assert_raises(ValueError):
         Enum(1, 2)
     with assert_raises(ValueError):
         Enum('1A', 'B')
     with assert_raises(ValueError):
         Enum('A-B', 'B')
     Enum('A_B_3', 'B')
Esempio 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)
Esempio n. 12
0
 def test_input_logged_request_should_have_right_status(self, user):
     assert_http_ok(self.post('/admin/login/', data={'username': '******', 'password': '******'}))
     assert_equal(InputLoggedRequest.objects.first().status, InputLoggedRequest.INFO)
     assert_http_redirect(self.post('/admin/login/', data={'username': '******', 'password': '******'}))
     assert_equal(InputLoggedRequest.objects.first().status, InputLoggedRequest.INFO)
     assert_raises(Exception, self.get, '/proxy/')
     assert_equal(InputLoggedRequest.objects.first().status, InputLoggedRequest.ERROR)
     assert_http_not_found(self.get('/404/'))
     assert_equal(InputLoggedRequest.objects.first().status, InputLoggedRequest.WARNING)
Esempio n. 13
0
    def test_irreversible_deanonymization(self):
        contact_form: ContactForm = ContactForm(email=CUSTOMER__EMAIL,
                                                full_name=CUSTOMER__LAST_NAME)
        contact_form.save()
        contact_form._anonymize_obj(fields=('__ALL__', ))

        assert_raises(ModelAnonymizer.IrreversibleAnonymizerException,
                      contact_form._deanonymize_obj,
                      fields=('__ALL__', ))
Esempio n. 14
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)
Esempio n. 15
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.')
    def test_parsing_response_should_raise_exception_if_uniq_does_not_exist(self):
        def raise_exception(request):
            raise requests.exceptions.HTTPError()

        responses.add_callback(responses.POST, settings.ATS_URL, content_type='text/xml', callback=raise_exception)

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

        assert_raises(SMSSendingError, send_and_update_sms_states, sms1, sms2)
Esempio n. 17
0
    def test_parsing_response_should_raise_exception_if_uniq_does_not_exist(self):
        def raise_exception(request):
            raise requests.exceptions.HTTPError()

        responses.add_callback(responses.POST, settings.ATS_SMS_URL, content_type='text/xml', callback=raise_exception)

        sms1 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ['uniq1'], **self.ATS_OUTPUT_SMS1)
        sms2 = OutputSMSFactory(pk=self.ATS_TEST_UNIQ['uniq2'], **self.ATS_OUTPUT_SMS2)

        assert_raises(SMSSendingError, send_and_update_sms_states, sms1, sms2)
Esempio n. 18
0
    def test_subchoices_field(self):
        change_and_save(self.inst, state_reason=TestFieldsModel.STATE_REASON.SUB_OK_2)
        assert_equal(self.inst.state_reason, TestFieldsModel.STATE_REASON.SUB_OK_2)
        assert_raises(PersistenceException, change_and_save, self.inst,
                      state_reason=TestFieldsModel.STATE_REASON.SUB_NOT_OK_1)

        # Change state and substate should work
        change_and_save(self.inst, state=TestFieldsModel.STATE.NOT_OK,
                        state_reason=TestFieldsModel.STATE_REASON.SUB_NOT_OK_2)
        assert_equal(self.inst.state, TestFieldsModel.STATE.NOT_OK)
        assert_equal(self.inst.state_reason, TestFieldsModel.STATE_REASON.SUB_NOT_OK_2)
Esempio n. 19
0
 def test_choices_num_enum_should_return_right_values_and_choices(self):
     choices_num = ChoicesNumEnum(
         ('A', 'label a'),
         ('B', 'label b'),
     )
     assert_equal(choices_num.A, 1)
     assert_equal(choices_num.B, 2)
     assert_equal(list(choices_num.choices), [(1, 'label a'), (2, 'label b')])
     assert_equal(tuple(choices_num.all), (1, 2))
     assert_equal(choices_num.get_label(1), 'label a')
     assert_equal(choices_num.get_label(2), 'label b')
     assert_raises(AttributeError, choices_num.get_label, 3)
Esempio n. 20
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')
Esempio n. 21
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())
Esempio n. 22
0
    def test_chamber_atomic_should_ignore_errors(self):
        with assert_raises(RuntimeError):
            with smart_atomic():
                TestSmartModel.objects.create(name='test')
                raise RuntimeError
        assert_false(TestSmartModel.objects.exists())

        with assert_raises(RuntimeError):
            with smart_atomic(ignore_errors=(RuntimeError, )):
                TestSmartModel.objects.create(name='test')
                raise RuntimeError
        assert_true(TestSmartModel.objects.exists())
Esempio n. 23
0
 def test_choices_num_enum(self):
     choices_num = ChoicesNumEnum(
         ('A', 'a'),
         ('B', 'b'),
     )
     assert_equal(choices_num.A, 1)
     assert_equal(choices_num.B, 2)
     assert_equal(list(choices_num.choices), [(1, 'a'), (2, 'b')])
     assert_equal(tuple(choices_num.all), (1, 2))
     assert_equal(choices_num.get_label(1), 'a')
     assert_equal(choices_num.get_label(2), 'b')
     assert_raises(AttributeError, choices_num.get_label, 3)
Esempio n. 24
0
 def test_choices_num_enum_should_return_right_values_and_choices(self):
     choices_num = ChoicesNumEnum(
         ('A', 'label a'),
         ('B', 'label b'),
     )
     assert_equal(choices_num.A, 1)
     assert_equal(choices_num.B, 2)
     assert_equal(list(choices_num.choices), [(1, 'label a'),
                                              (2, 'label b')])
     assert_equal(tuple(choices_num.all), (1, 2))
     assert_equal(choices_num.get_label(1), 'label a')
     assert_equal(choices_num.get_label(2), 'label b')
     assert_raises(AttributeError, choices_num.get_label, 3)
Esempio n. 25
0
    def test_file_field_content_type(self):
        # These files can be saved because it has supported type
        for filename in ('all_fields_filled.csv', 'test.pdf'):
            with open('data/{}'.format(filename), 'rb') as f:
                assert_false(self.inst.file)
                self.inst.file.save(filename, File(f))
                assert_true(self.inst.file)
                change_and_save(self.inst, file=None)

        # Image file is not supported
        with open('data/test2.jpg', 'rb') as f:
            assert_false(self.inst.file)
            assert_raises(PersistenceException, self.inst.file.save, 'image.jpeg', File(f))
Esempio n. 26
0
    def test_queryset_get_should_return_item_or_error(self):
        instances = self.create_test_dynamo_model_instances(string='test')
        qs = TestDynamoModel.objects_string_number.set_hash_key('test')
        with assert_raises(MultipleObjectsReturned):
            qs.get()

        with assert_raises(ObjectDoesNotExist):
            qs.filter(number=10).get()

        with assert_raises(ObjectDoesNotExist):
            qs.get(number=10)

        assert_equal(qs.get(number=9), instances[-1])
Esempio n. 27
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)
Esempio n. 28
0
    def test_file_field_content_type(self):
        # These files can be saved because it has supported type
        for filename in ('all_fields_filled.csv', 'test.pdf'):
            with open('data/{}'.format(filename), 'rb') as f:
                assert_false(self.inst.file)
                self.inst.file.save(filename, File(f))
                assert_true(self.inst.file)
                change_and_save(self.inst, file=None)

        # Image file is not supported
        with open('data/test2.jpg', 'rb') as f:
            assert_false(self.inst.file)
            assert_raises(PersistenceException, self.inst.file.save,
                          'image.jpeg', File(f))
Esempio n. 29
0
    def test_image_field_max_upload_size(self):
        # File is can be stored
        with open('data/test2.jpg', 'rb') as f:
            assert_false(self.inst.image)
            self.inst.image.save('test2.jpg', File(f))
            assert_true(self.inst.image)
            change_and_save(self.inst, image=None)

        # File is too large to store
        with open('data/test.jpg', 'rb') as f:
            assert_false(self.inst.image)
            assert_raises(PersistenceException, self.inst.image.save, 'image.jpeg', File(f))

        # File has a wrong extension
        with open('data/test2.jpg', 'rb') as f:
            assert_raises(PersistenceException, self.inst.image.save, 'image.html', File(f))
Esempio n. 30
0
    def test_new_domain_port(self):
        assert_equal(Domain('testA', 'http', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser').port, 80)
        assert_equal(Domain('testB', 'https', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser').port, 443)
        assert_equal(Domain('testC', 'http', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser', 443).port, 443)
        assert_equal(Domain('testD', 'https', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser', 80).port, 80)
        assert_raises(ImproperlyConfigured, Domain, 'testF', 'hbbs', 'localhost', 'dj.backend_urls',
                      'test_chamber.BackendUser')

        assert_equal(Domain('testA', 'http', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser').url,
                     'http://localhost')
        assert_equal(Domain('testB', 'https', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser').url,
                     'https://localhost')
        assert_equal(Domain('testC', 'http', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser', 443).url,
                     'http://localhost:443')
        assert_equal(Domain('testD', 'https', 'localhost', 'dj.backend_urls', 'test_chamber.BackendUser', 80).url,
                     'https://localhost:80')
Esempio n. 31
0
    def test_input_request_to_error_page_should_be_logged(self):
        expected_input_request_started_data = {
            'request_headers': {'Cookie': '[Filtered]'},
            'request_body': '',
            'user_id': None,
            'method': 'GET',
            'host': 'testserver',
            'path': '/error/',
            'queries': {},
            'is_secure': False,
            'ip': '127.0.0.1',
            'start': all_eq_obj,
            'view_slug': 'apps.test_security.views.error_view',
        }
        expected_input_request_error_data = {
            **expected_input_request_started_data,
            'error_message': all_eq_obj,
        }
        expected_input_request_finished_data = {
            **expected_input_request_error_data,
            'stop': all_eq_obj,
            'response_code': 500,
            'response_headers': all_eq_obj,
            'response_body': all_eq_obj,
        }

        with capture_security_logs() as logged_data:
            with assert_raises(RuntimeError):
                assert_http_ok(self.get('/error/'))
            assert_length_equal(logged_data.input_request_started, 1)
            assert_length_equal(logged_data.input_request_finished, 1)
            assert_length_equal(logged_data.input_request_error, 1)
            assert_equal_log_data(logged_data.input_request_started[0], expected_input_request_started_data)
            assert_equal_log_data(logged_data.input_request_finished[0], expected_input_request_finished_data)
            assert_equal_log_data(logged_data.input_request_error[0], expected_input_request_error_data)
Esempio n. 32
0
 def test_unique_task_shoud_have_set_stale_limit(self):
     with assert_raises(CeleryError):
         unique_task.delay()
     with override_settings(
             DJANGO_CELERY_EXTENSIONS_DEFAULT_TASK_STALE_TIME_LIMIT=10):
         with assert_not_raises(CeleryError):
             unique_task.delay()
Esempio n. 33
0
 def test_enum_key_should_have_right_format(self):
     with assert_raises(ValueError):
         Enum(
             1, 2
         )
     with assert_raises(ValueError):
         Enum(
             '1A', 'B'
         )
     with assert_raises(ValueError):
         Enum(
             'A-B', 'B'
         )
     Enum(
         'A_B_3', 'B'
     )
Esempio n. 34
0
    def test_pre_commit_should_call_one_time_callable_only_once_for_not_failed_blocks(
            self):
        numbers_list = []

        class AddNumberOneTimePreCommitCallable(UniquePreCommitCallable):
            def handle(self):
                for kwargs in self.kwargs_list:
                    self.kwargs_list[-1]['numbers_list'].append(
                        kwargs['number'])

        with transaction.atomic():
            pre_commit(
                AddNumberOneTimePreCommitCallable(numbers_list=numbers_list,
                                                  number=1))
            with assert_raises(RuntimeError):
                with transaction.atomic():
                    pre_commit(
                        AddNumberOneTimePreCommitCallable(
                            numbers_list=numbers_list, number=2))

                    assert_equal(len(numbers_list), 0)
                    raise RuntimeError
            with transaction.atomic():
                pre_commit(
                    AddNumberOneTimePreCommitCallable(
                        numbers_list=numbers_list, number=3))

                assert_equal(len(numbers_list), 0)
            assert_equal(len(numbers_list), 0)

        assert_equal(numbers_list, [1])
Esempio n. 35
0
    def test_celery_health_check_command_raises_error_if_queue_exceeds_max_tasks_count_limit(
            self, task_log):
        max_tasks_count = 0

        with assert_raises(CommandError):
            call_command('celery_health_check',
                         max_tasks_count=max_tasks_count)
Esempio n. 36
0
    def test_celery_health_check_command_does_raise_error_if_queue_is_not_within_max_created_at_diff_limit(
            self, task_log):
        max_created_at_diff = 1

        with assert_raises(CommandError):
            call_command('celery_health_check',
                         max_created_at_diff=max_created_at_diff)
Esempio n. 37
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
Esempio n. 38
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
Esempio n. 39
0
    def test_subchoices_field(self):
        change_and_save(self.inst,
                        state_reason=TestFieldsModel.STATE_REASON.SUB_OK_2)
        assert_equal(self.inst.state_reason,
                     TestFieldsModel.STATE_REASON.SUB_OK_2)
        assert_raises(PersistenceException,
                      change_and_save,
                      self.inst,
                      state_reason=TestFieldsModel.STATE_REASON.SUB_NOT_OK_1)

        # Change state and substate should work
        change_and_save(self.inst,
                        state=TestFieldsModel.STATE.NOT_OK,
                        state_reason=TestFieldsModel.STATE_REASON.SUB_NOT_OK_2)
        assert_equal(self.inst.state, TestFieldsModel.STATE.NOT_OK)
        assert_equal(self.inst.state_reason,
                     TestFieldsModel.STATE_REASON.SUB_NOT_OK_2)
Esempio n. 40
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)
Esempio n. 41
0
    def test_image_field_max_upload_size(self):
        # File is can be stored
        with open('data/test2.jpg', 'rb') as f:
            assert_false(self.inst.image)
            self.inst.image.save('test2.jpg', File(f))
            assert_true(self.inst.image)
            change_and_save(self.inst, image=None)

        # File is too large to store
        with open('data/test.jpg', 'rb') as f:
            assert_false(self.inst.image)
            assert_raises(PersistenceException, self.inst.image.save,
                          'image.jpeg', File(f))

        # File has a wrong extension
        with open('data/test2.jpg', 'rb') as f:
            assert_raises(PersistenceException, self.inst.image.save,
                          'image.html', File(f))
Esempio n. 42
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)
Esempio n. 43
0
    def test_smart_atomic_should_be_to_use_as_a_context_manager(self):
        with assert_raises(RuntimeError):
            with smart_atomic():
                CSVRecord.objects.create(
                    name='test',
                    number=1
                )
                raise RuntimeError('test')

        assert_false(CSVRecord.objects.exists())
Esempio n. 44
0
    def test_reverse(self):
        assert_equal(reverse('current-datetime'), '/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID), '/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID), '/current_time_frontend/')

        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID, add_domain=True),
                     'http://localhost:8000/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID, add_domain=True),
                     'https://localhost/current_time_frontend/')

        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID, add_domain=True,
                             urlconf='dj.frontend_urls'),
                     'http://localhost:8000/current_time_frontend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID, add_domain=True,
                             urlconf='dj.backend_urls'),
                     'https://localhost/current_time_backend/')

        assert_equal(reverse('current-datetime', qs_kwargs={'a': 1}), '/current_time_backend/?a=1')

        assert_raises(ImproperlyConfigured, reverse, 'current-datetime', site_id=3)
Esempio n. 45
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())
Esempio n. 46
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.')
Esempio n. 47
0
    def test_pre_commit_should_not_be_called_for_rollback(self):
        numbers_list = []

        with assert_raises(RuntimeError):
            with transaction.atomic():
                on_commit(lambda: add_number(numbers_list, 2))
                pre_commit(lambda: add_number(numbers_list, 1))
                assert_equal(len(numbers_list), 0)
                raise RuntimeError

        assert_equal(numbers_list, [])
Esempio n. 48
0
    def test_smart_model_clean_post_delete(self):
        class PostDeleteTestProxySmartModel(TestProxySmartModel):
            class Meta:
                proxy = True
                verbose_name = 'testmodel'
                verbose_name_plural = 'testmodels'

            class SmartMeta:
                is_cleaned_pre_save = False
                is_cleaned_post_delete = True

        obj = PostDeleteTestProxySmartModel.objects.create(name=10 * 'a')
        obj_pk = obj.pk
        assert_raises(PersistenceException, obj.delete)
        assert_false(PostDeleteTestProxySmartModel.objects.filter(pk=obj_pk).exists())

        obj = PostDeleteTestProxySmartModel.objects.create(name=10 * 'a')
        obj_pk = obj.pk
        obj.delete(is_cleaned_post_delete=False)
        assert_false(PostDeleteTestProxySmartModel.objects.filter(pk=obj_pk).exists())
Esempio n. 49
0
    def test_reverse(self):
        assert_equal(reverse('current-datetime'), '/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID), '/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID), '/current_time_frontend/')

        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID, add_domain=True),
                     'http://localhost:8000/current_time_backend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID, add_domain=True),
                     'https://localhost/current_time_frontend/')

        assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID, add_domain=True,
                             urlconf='dj.frontend_urls'),
                     'http://localhost:8000/current_time_frontend/')
        assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID, add_domain=True,
                             urlconf='dj.backend_urls'),
                     'https://localhost/current_time_backend/')

        assert_equal(reverse('current-datetime', qs_kwargs={'a': 1}), '/current_time_backend/?a=1')

        assert_raises(ImproperlyConfigured, reverse, 'current-datetime', site_id=3)
Esempio n. 50
0
    def test_smart_model_clean_post_save(self):
        class PostSaveTestProxySmartModel(TestProxySmartModel):
            class Meta:
                proxy = True
                verbose_name = 'testmodel'
                verbose_name_plural = 'testmodels'

            class SmartMeta:
                is_cleaned_pre_save = False
                is_cleaned_post_save = True

        assert_false(PostSaveTestProxySmartModel.objects.filter(name=10 * 'a').exists())
        assert_raises(PersistenceException, PostSaveTestProxySmartModel.objects.create, name=10 * 'a')
        assert_true(PostSaveTestProxySmartModel.objects.filter(name=10 * 'a').exists())
        obj = PostSaveTestProxySmartModel.objects.create(name=9 * 'a')
        obj.name = 11 * 'a'
        assert_raises(PersistenceException, obj.save)
        assert_equal(len(PostSaveTestProxySmartModel.objects.get(pk=obj.pk).name), 11)
        obj.name = 12 * 'a'
        obj.save(is_cleaned_post_save=False)
        assert_equal(len(PostSaveTestProxySmartModel.objects.get(pk=obj.pk).name), 12)
Esempio n. 51
0
    def test_smart_model_changed_fields(self):
        obj = TestProxySmartModel.objects.create(name='a')
        changed_fields = DynamicChangedFields(obj)
        assert_equal(len(changed_fields), 0)
        obj.name = 'b'
        assert_equal(len(changed_fields), 1)
        assert_equal(changed_fields['name'].initial, 'a')
        assert_equal(changed_fields['name'].current, 'b')
        static_changed_fields = changed_fields.get_static_changes()
        obj.save()

        # Initial values is not changed
        assert_equal(len(changed_fields), 2)
        assert_equal(len(static_changed_fields), 1)
        assert_equal(set(changed_fields.keys()), {'name', 'changed_at'})
        assert_equal(set(static_changed_fields.keys()), {'name'})
        assert_equal(changed_fields['name'].initial, 'a')
        assert_equal(changed_fields['name'].current, 'b')

        assert_true(changed_fields.has_any_key('name', 'crated_at'))
        assert_false(changed_fields.has_any_key('invalid', 'crated_at'))

        assert_raises(AttributeError, changed_fields.__delitem__, 'name')
        assert_raises(AttributeError, changed_fields.clear)
        assert_raises(AttributeError, changed_fields.pop, 'name')

        obj.name = 'b'
Esempio n. 52
0
    def test_smart_model_changed_fields(self):
        obj = TestProxySmartModel.objects.create(name='a')
        changed_fields = DynamicChangedFields(obj)
        assert_equal(len(changed_fields), 0)
        obj.name = 'b'
        assert_equal(len(changed_fields), 1)
        assert_equal(changed_fields['name'].initial, 'a')
        assert_equal(changed_fields['name'].current, 'b')
        static_changed_fields = changed_fields.get_static_changes()
        obj.save()

        # Initial values is not changed
        assert_equal(len(changed_fields), 2)
        assert_equal(len(static_changed_fields), 1)
        assert_equal(set(changed_fields.keys()), {'name', 'changed_at'})
        assert_equal(set(static_changed_fields.keys()), {'name'})
        assert_equal(changed_fields['name'].initial, 'a')
        assert_equal(changed_fields['name'].current, 'b')

        assert_true(changed_fields.has_any_key('name', 'crated_at'))
        assert_false(changed_fields.has_any_key('invalid', 'crated_at'))

        assert_raises(AttributeError, changed_fields.__delitem__, 'name')
        assert_raises(AttributeError, changed_fields.clear)
        assert_raises(AttributeError, changed_fields.pop, 'name')

        obj.name = 'b'
Esempio n. 53
0
    def test_restricted_file_field_should_raise_validation_error_for_invalid_files(self):
        field = RestrictedFileField(allowed_content_types=('image/jpeg', 'application/pdf'), max_upload_size=1)

        # Invalid file type
        with open('data/all_fields_filled.csv', 'rb') as f:
            with assert_raises(ValidationError):
                field.clean(SimpleUploadedFile('all_fields_filled.pdf', f.read()))

        # Invalid size
        with open('data/test.jpg', 'rb') as f:
            with assert_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.jpg', f.read()))

        # Invalid file suffix
        with open('data/test.pdf', 'rb') as f:
            with assert_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.csv', f.read()))

        # Valid file
        with open('data/test.pdf', 'rb') as f:
            with assert_not_raises(ValidationError):
                field.clean(SimpleUploadedFile('test.pdf', f.read()))
Esempio n. 54
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)
Esempio n. 55
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)
Esempio n. 56
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)
Esempio n. 57
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)
Esempio n. 58
0
 def test_should_validate_positive_price_field(self):
     assert_raises(PersistenceException, change_and_save, self.inst, total_price=-100)
Esempio n. 59
0
 def test_get_domain(self):
     assert_equal(get_domain(settings.BACKEND_SITE_ID).name, 'backend')
     assert_equal(get_domain(settings.FRONTEND_SITE_ID).name, 'frontend')
     assert_raises(ImproperlyConfigured, get_domain, 3)
Esempio n. 60
0
    def test_should_raise_exception_due_calling_default_comparator(self):
        obj1 = ComparableModel.objects.create(name='test')
        obj2 = ComparableModel.objects.create(name='test')

        assert_raises(NotImplementedError, obj1.equals, obj2, Comparator())