def test_only_superuser_may_add_user(self):
        USERNAME = '******'

        resp = self.post('%sadd/' % self.USER_UI_URL, data={'add-is-user-username': USERNAME,
                                                            'add-is-user-password': '******'})
        assert_http_forbidden(resp)
        assert_false(User.objects.filter(username=USERNAME).exists())
示例#2
0
    def test_only_superuser_may_add_user(self):
        USERNAME = '******'

        resp = self.post('%sadd/' % self.USER_UI_URL, data={'add-is-user-username': USERNAME,
                                                            'add-is-user-password': '******'})
        assert_http_forbidden(resp)
        assert_false(User.objects.filter(username=USERNAME).exists())
示例#3
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)
示例#4
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())
示例#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)
 def test_superuser_should_update_is_superuser(self):
     user = self.logged_user.user
     resp = self.put('%s%s/' % (self.USER_API_URL, user.pk),
                     data={'is_superuser': False})
     assert_valid_JSON_response(resp)
     user.refresh_from_db()
     assert_false(user.is_superuser)
示例#7
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'
示例#8
0
    def test_user_should_be_authorized_with_two_factor_authentication(
            self, user):
        login_resp = self.post(self.UI_TWO_FACTOR_LOGIN_URL, {
            'username': '******',
            'password': '******'
        })

        assert_http_redirect(login_resp)
        resp_location = login_resp['Location']
        assert_equal(resp_location[:resp_location.find('?')],
                     settings.TWO_FACTOR_REDIRECT_URL)
        assert_false(login_resp.wsgi_request.user.is_authenticated)

        token = login_resp.wsgi_request.token
        assert_true(token.two_factor_code is not None)
        assert_false(token.is_authenticated)
        # the code value needs to be overwritted, so that its value could be used for next request
        token.two_factor_code = make_password('12345',
                                              salt=Token.TWO_FACTOR_CODE_SALT)
        token.save()

        code_check_resp = self.post(self.UI_CODE_CHECK_LOGIN_URL,
                                    {'code': '12345'})

        assert_http_redirect(code_check_resp)
        assert_equal(code_check_resp['location'], '/accounts/profile/')
        assert_true(code_check_resp.wsgi_request.token.is_authenticated)
        assert_true(code_check_resp.wsgi_request.user.is_authenticated)
        assert_equal(code_check_resp.wsgi_request.user, user)
示例#9
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'
示例#10
0
    def test_smart_model_initial_values_should_be_deferred_for_partly_loaded_instance(
            self):
        obj = DiffModel.objects.only('name').get(pk=DiffModel.objects.create(
            name='test', datetime=timezone.now(), number=2).pk)

        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)
        assert_false(obj.is_adding)
        assert_true(obj.is_changing)
        assert_true(
            all(v is Deferred for k, v in obj.initial_values.items()
                if k not in {'id', 'name'}))
        assert_true(
            all(not bool(v) for k, v in obj.initial_values.items()
                if k not in {'id', 'name'}))

        assert_equal(obj.number, 2)
        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)
        assert_equal(obj.initial_values['number'], 2)

        obj.datetime = timezone.now()
        assert_equal(obj.initial_values['datetime'], Deferred)
        assert_true(obj.changed_fields)
        assert_equal(obj.changed_fields.keys(), {'datetime'})
        assert_equal(str(Deferred), 'deferred')
示例#11
0
 def test_key_generator_values_should_be_able_to_change(self, user):
     token = VerificationToken.objects.deactivate_and_create(
         user, key_generator_kwargs={
             'length': 100,
             'allowed_chars': 'abc'
         })
     assert_equal(len(token.key), 100)
     assert_false(set(token.key) - set('abc'))
示例#12
0
 def test_request_body_truncation_should_be_turned_off(self):
     self.post('/admin/login/',
               data={
                   'username': 2000 * 'a',
                   'password': 2000 * 'b'
               })
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.request_body), 4183)
     assert_false(input_logged_request.request_body.endswith('...'))
示例#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('...'))
示例#14
0
 def test_response_body_truncation_should_be_turned_off(self):
     resp = self.post('/admin/login/',
                      data={
                          'username': 20 * 'a',
                          'password': 20 * 'b'
                      })
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(input_logged_request.response_body, str(resp.content))
     assert_false(input_logged_request.response_body.endswith('...'))
示例#15
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())
 def test_verification_token_should_be_created_and_old_one_should_be_deactivated(self, user):
     token1 = VerificationToken.objects.deactivate_and_create(user)
     assert_true(token1.is_valid)
     assert_true(token1.is_active)
     token2 = VerificationToken.objects.deactivate_and_create(user)
     assert_true(token2.is_valid)
     assert_true(token2.is_active)
     token1.refresh_from_db()
     assert_false(token1.is_valid)
     assert_false(token1.is_active)
示例#17
0
 def test_user_should_log_and_logout_to_the_administration(self, user):
     assert_http_redirect(self.get(self.INDEX_URL))
     resp = self.post(self.LOGIN_URL, {'username': '******', 'password': '******'})
     assert_http_redirect(resp)
     assert_http_ok(self.get(self.INDEX_URL))
     assert_in('Authorization', self.c.cookies)
     assert_false(Token.objects.last().allowed_header)
     assert_true(Token.objects.last().allowed_cookie)
     assert_http_ok(self.get(self.LOGOUT_URL))
     assert_http_redirect(self.get(self.INDEX_URL))
示例#18
0
 def test_user_should_be_authorized_via_cookie(self, user):
     assert_http_redirect(self.get(self.INDEX_URL))
     resp = self.post(self.UI_LOGIN_URL, {
         'username': '******',
         'password': '******'
     })
     assert_http_redirect(resp)
     assert_http_ok(self.get(self.INDEX_URL))
     assert_in('Authorization', self.c.cookies)
     assert_false(Token.objects.last().allowed_header)
     assert_true(Token.objects.last().allowed_cookie)
示例#19
0
    def test_comparator(self):
        obj1 = ComparableModel.objects.create(name='test')
        obj2 = ComparableModel.objects.create(name='test')
        obj3 = ComparableModel.objects.create(name='test2')
        comparator = NameComparator()

        assert_true(obj1.equals(obj2, comparator))
        assert_true(obj2.equals(obj1, comparator))

        assert_false(obj1.equals(obj3, comparator))
        assert_false(obj3.equals(obj1, comparator))
示例#20
0
    def test_comparator(self):
        obj1 = ComparableModel.objects.create(name='test')
        obj2 = ComparableModel.objects.create(name='test')
        obj3 = ComparableModel.objects.create(name='test2')
        comparator = NameComparator()

        assert_true(obj1.equals(obj2, comparator))
        assert_true(obj2.equals(obj1, comparator))

        assert_false(obj1.equals(obj3, comparator))
        assert_false(obj3.equals(obj1, comparator))
示例#21
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('...'))
示例#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())
示例#23
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())
示例#24
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))
示例#25
0
    def test_smat_atomic_should_be_to_use_as_a_decorator(self):
        @smart_atomic
        def change_object_and_raise_exception():
            CSVRecord.objects.create(
                name='test',
                number=1
            )
            raise RuntimeError('test')

        with assert_raises(RuntimeError):
            change_object_and_raise_exception()

        assert_false(CSVRecord.objects.exists())
示例#26
0
    def test_permissions_should_be_joined_with_operators(self):
        obj_is_none = ObjIsNonePermission()
        obj_is_not_none = ObjIsNotNonePermission()
        obj_is_string = ObjIsStringPermission()

        assert_true((obj_is_none | obj_is_not_none).has_permission(
            'test', None, None, None))
        assert_true((obj_is_none | obj_is_not_none).has_permission(
            'test', None, None, ''))
        assert_false((obj_is_none & obj_is_not_none).has_permission(
            'test', None, None, None))
        assert_false((obj_is_none & obj_is_not_none).has_permission(
            'test', None, None, ''))
        assert_true(
            ((obj_is_none | obj_is_string) & obj_is_not_none).has_permission(
                'test', None, None, ''))
        assert_true(
            ((obj_is_none & obj_is_string) | obj_is_not_none).has_permission(
                'test', None, None, ''))
        assert_false(
            (obj_is_not_none | (obj_is_none & obj_is_string)).has_permission(
                'test', None, None, None))
        assert_true((~obj_is_none).has_permission('test', None, None, ''))
        assert_false((~obj_is_not_none).has_permission('test', None, None, ''))
        assert_true((obj_is_none & ~obj_is_not_none).has_permission(
            'test', None, None, None))
示例#27
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))
示例#28
0
    def test_permissions_should_be_synchronized(self):
        assert_false(Perm.objects.exists())
        call_command('sync_permissions', stdout=StringIO())
        assert_equal(Perm.objects.count(), 12)

        model_names = {'user', 'issue', 'group'}
        perm_names = {'create', 'read', 'update', 'delete'}

        for model_name in model_names:
            for perm_name in perm_names:
                assert_equal(
                    Perm.objects.filter(type=PERM_TYPE_CORE,
                                        codename='{}__{}'.format(
                                            model_name, perm_name)).count(), 1)
示例#29
0
 def test_valid_verification_token_with_same_slug_should_exists(self, user):
     token = VerificationToken.objects.deactivate_and_create(user, slug='a')
     assert_true(
         VerificationToken.objects.exists_valid(user,
                                                slug='a',
                                                key=token.key))
     assert_false(
         VerificationToken.objects.exists_valid(user,
                                                slug='b',
                                                key=token.key))
     assert_false(
         VerificationToken.objects.exists_valid(user,
                                                slug='a',
                                                key='invalid key'))
示例#30
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": "%s%s", "b": "%s%s"}' %
                    ((9 + TRUNCATION_DIFF) * 'a', TRUNCATION_CHAR,
                     (9 + TRUNCATION_DIFF) * 'b', TRUNCATION_CHAR)))
     assert_false(
         input_logged_request.request_body.endswith(TRUNCATION_CHAR))
示例#31
0
 def test_user_should_not_be_authorized_via_http_header_if_headers_are_turned_off(
         self, user):
     resp = self.post(self.API_LOGIN_URL, {
         'username': '******',
         'password': '******'
     })
     assert_http_ok(resp)
     assert_in('token', resp.json())
     assert_http_redirect(
         self.get(self.INDEX_URL,
                  headers={
                      'HTTP_AUTHORIZATION':
                      'Bearer {}'.format(resp.json()['token'])
                  }))
     assert_false(self.client.cookies)
    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)
示例#33
0
    def test_should_correctly_handle_unknown_ats_state(self):
        responses.add(responses.POST, settings.ATS_SMS_URL, content_type='text/xml',
                      body=self.ATS_UNKNOW_STATE_RESPONSE, status=200)
        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)
        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)
示例#34
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))
示例#35
0
 def test_stale_waiting_celery_task_should_be_set_as_failed_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))
     test_call_command('set_celery_task_log_state')
     assert_equal(celery_task_log.refresh_from_db().state,
                  CeleryTaskLogState.EXPIRED)
     assert_false(CeleryTaskLog.objects.filter_processing().exists())
示例#36
0
 def test_user_should_be_authorized_via_http_header(self, user):
     assert_http_redirect(self.get(self.INDEX_URL))
     resp = self.post(self.API_LOGIN_URL, {
         'username': '******',
         'password': '******'
     })
     assert_http_ok(resp)
     assert_in('token', resp.json())
     assert_http_ok(
         self.get(self.INDEX_URL,
                  headers={
                      'HTTP_AUTHORIZATION':
                      'Bearer {}'.format(resp.json()['token'])
                  }))
     assert_not_in('Authorization', self.c.cookies)
     assert_true(Token.objects.last().allowed_header)
     assert_false(Token.objects.last().allowed_cookie)
示例#37
0
 def test_user_should_be_authorized_from_token_and_uuid(self, user):
     device_token = DeviceKey.objects.create_token(uuid=UUID, user=user)
     resp = self.post(self.API_MOBILE_LOGIN_URL, {
         'uuid': UUID,
         'login_device_token': device_token
     })
     assert_http_ok(resp)
     assert_in('token', resp.json())
     assert_http_ok(
         self.get(INDEX_URL,
                  headers={
                      'HTTP_AUTHORIZATION':
                      'Bearer {}'.format(resp.json()['token'])
                  }))
     assert_not_in('Authorization', self.c.cookies)
     assert_true(Token.objects.last().allowed_header)
     assert_false(Token.objects.last().allowed_cookie)
示例#38
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))
示例#39
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())
示例#40
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)
示例#41
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)
示例#42
0
 def test_rfs_bool(self):
     assert_true(rfs(('a', 'b', 'b__c', 'b__g', ('d', ('e__f',)))))
     assert_false(rfs())
     assert_false(rfs(()))
     assert_false(rfs({}))
示例#43
0
    def test_smart_model_initial_values_should_be_unknown_for_not_saved_instance(self):
        obj = DiffModel(name='test', datetime=timezone.now(), number=2)
        assert_true(obj.has_changed)
        assert_true(obj.changed_fields)
        assert_equal(set(obj.changed_fields.keys()), {'created_at', 'changed_at', 'id', 'datetime', 'name', 'number'})
        assert_true(obj.is_adding)
        assert_false(obj.is_changing)
        assert_true(all(v is Unknown for v in obj.initial_values.values()))
        assert_true(all(not bool(v) for v in obj.initial_values.values()))

        obj.save()
        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)
        assert_false(obj.is_adding)
        assert_true(obj.is_changing)
        assert_true(all(v is not Unknown for v in obj.initial_values.values()))

        obj = DiffModel.objects.get(pk=obj.pk)
        assert_false(obj.has_changed)
        assert_false(obj.changed_fields)
        assert_false(obj.is_adding)
        assert_true(obj.is_changing)
        assert_true(all(v is not Unknown for v in obj.initial_values.values()))
示例#44
0
 def test_allowed_content_type_should_be_turned_off(self):
     self.get('/')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_false(input_logged_request.response_body)
示例#45
0
 def test_decorated_view_with_hide_request_body_should_not_log_request_body(self):
     self.post('/hide-request-body/', data={'a': 20 * 'a', 'b': 20 * 'b'})
     input_logged_request = InputLoggedRequest.objects.get()
     assert_false(input_logged_request.request_body)
示例#46
0
 def test_request_body_truncation_should_be_turned_off(self):
     self.post('/admin/login/', data={'username': 2000 * 'a', 'password': 2000 * 'b'})
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.request_body), 4183)
     assert_false(input_logged_request.request_body.endswith('...'))
示例#47
0
 def test_response_body_truncation_should_be_turned_off(self):
     resp = self.post('/admin/login/', data={'username': 20 * 'a', 'password': 20 * 'b'})
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(input_logged_request.response_body, str(resp.content))
     assert_false(input_logged_request.response_body.endswith('...'))