コード例 #1
0
    def test_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_redirect(resp)
        assert_true(User.objects.filter(username=USERNAME).exists())
コード例 #2
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
    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)
コード例 #3
0
    def test_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_redirect(resp)
        assert_true(User.objects.filter(username=USERNAME).exists())
コード例 #4
0
    def test_local_and_related(self):
        fields = Fields(BASIC_FIELDS, Customer)

        assert_list_equal(fields.local_fields, ['primary_email_address'])
        assert_true('emails' in fields.related_fields)
        assert_list_equal(fields.related_fields['emails'].local_fields,
                          ['email'])
コード例 #5
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
    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)
コード例 #6
0
ファイル: fields.py プロジェクト: zzuzzy/django-chamber
 def test_should_check_price_form_field(self):
     field = TestFieldsModel._meta.get_field('price')  # pylint: disable=W0212
     assert_equal(ugettext_lazy('EUR'), field.currency)
     form_field = field.formfield()
     assert_true(isinstance(form_field.widget,
                            form_fields.PriceNumberInput))
     assert_equal(field.currency, form_field.widget.placeholder)
コード例 #7
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
    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())
コード例 #8
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
    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'
コード例 #9
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
 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())
コード例 #10
0
ファイル: __init__.py プロジェクト: druids/django-chamber
    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'
コード例 #11
0
 def test_verification_token_does_not_expire_without_expiration_value(
         self, user):
     token = VerificationToken.objects.deactivate_and_create(
         user, expiration_in_minutes=None)
     with freeze_time(timezone.now() + timedelta(days=30 * 365), tick=True):
         assert_true(token.is_valid)
         assert_true(token.is_active)
コード例 #12
0
 def test_json_request_should_not_be_truncated_with_another_method(self):
     self.c.post('/admin/login/',
                 data=json.dumps({'a': 50 * 'a'}),
                 content_type='application/json')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(input_logged_request.request_body,
                  '{"a": "' + 40 * 'a' + '...')
     assert_true(input_logged_request.request_body.endswith('...'))
コード例 #13
0
 def assert_text(self, selector, text):
     # Standard element.text has problem with html inside element
     html = self.css(selector).get_attribute("innerHTML")
     texts = selector, text, html
     assert_true(
         text in html,
         "Text does not match.\nSelector: %s\nExpected: %s\nActual: %s\n" %
         texts)
コード例 #14
0
ファイル: fields.py プロジェクト: zzuzzy/django-chamber
 def test_should_assert_form_field(self, field_name, currency,
                                   kwargs_to_remove):
     field = TestFieldsModel._meta.get_field(field_name)  # pylint: disable=W0212
     assert_equal(currency, field.currency)
     form_field = field.formfield()
     assert_true(isinstance(form_field.widget,
                            form_fields.PriceNumberInput))
     assert_equal(field.currency, form_field.widget.placeholder)
コード例 #15
0
ファイル: crawler.py プロジェクト: zamazaljiri/django-is-core
 def post_response(url, referer, resp, exception):
     tested_urls.append(url)
     assert_true(exception is None, msg='Received exception %s, url %s' % (force_text(exception), url))
     if resp.status_code != 200:
         failed_urls.append(url)
         self.logger.warning('Response code for url %s from referer %s should be 200 but code is %s, user %s' %
                             (url, referer, resp.status_code, self.logged_user.user))
     assert_not_equal(resp.status_code, 500, msg='Response code for url %s from referer %s is 500, user %s' %
                      (url, referer, self.logged_user.user))
コード例 #16
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
 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())
コード例 #17
0
    def test_user_with_permission_may_add_user(self):
        self.logged_user.user.perms.add_perm('core.issue_tracker.UserIsCore.create')

        USERNAME = '******'

        resp = self.post('%sadd/' % self.USER_UI_URL, data={'add-is-user-username': USERNAME,
                                                            'add-is-user-password': '******'})
        assert_http_redirect(resp)
        assert_true(User.objects.filter(username=USERNAME).exists())
コード例 #18
0
 def test_response_body_should_be_truncated(self):
     self.post('/admin/login/',
               data={
                   'username': 20 * 'a',
                   'password': 20 * 'b'
               })
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.response_body), 10)
     assert_true(input_logged_request.response_body.endswith('...'))
コード例 #19
0
    def test_create_legal_reson_from_slug(self):
        LegalReason.objects.create_consent(FIRST_AND_LAST_NAME_SLUG,
                                           self.customer).save()

        assert_true(
            LegalReason.objects.filter(
                purpose_slug=FIRST_AND_LAST_NAME_SLUG,
                source_object_id=self.customer.pk,
                source_object_content_type=ContentType.objects.get_for_model(
                    Customer)).exists())
コード例 #20
0
    def test_sms_template_should_be_immediately_send(self):
        responses.add(responses.POST, settings.ATS_SMS_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)
コード例 #21
0
ファイル: fields.py プロジェクト: druids/django-chamber
 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.')
コード例 #22
0
ファイル: fields.py プロジェクト: druids/django-chamber
 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
コード例 #23
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))
コード例 #24
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)
コード例 #25
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
    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))
コード例 #26
0
ファイル: fields.py プロジェクト: zzuzzy/django-chamber
 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
コード例 #27
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])
コード例 #28
0
 def test_json_request_should_be_truncated_with_another_method_and_standard_method_too(
         self):
     self.c.post('/admin/login/',
                 data=json.dumps({
                     50 * 'a': 50 * 'a',
                     50 * 'b': 50 * 'b'
                 }),
                 content_type='application/json')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.request_body), 100)
     assert_true(input_logged_request.request_body.endswith('...'))
コード例 #29
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)
コード例 #30
0
ファイル: fields.py プロジェクト: druids/django-chamber
 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])
コード例 #31
0
ファイル: __init__.py プロジェクト: Formulka/django-chamber
    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))
コード例 #32
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
 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())
コード例 #33
0
    def test_permissions_set_should_return_permissions_according_to_name(self):
        permission = PermissionsSet(
            none=ObjIsNonePermission(),
            not_none=ObjIsNotNonePermission(),
            string=ObjIsStringPermission(),
        )

        assert_true(permission.has_permission('none', None, None, None))
        assert_false(permission.has_permission('none', None, None, ''))
        assert_false(permission.has_permission('invalid', None, None, None))
        assert_false(permission.has_permission('not_none', None, None, None))
        assert_true(permission.has_permission('string', None, None, ''))
コード例 #34
0
    def test_multilevel_related(self):
        fields = Fields(MULTILEVEL_FIELDS, Customer)

        assert_list_equal(fields.local_fields, [])
        assert_true('accounts' in fields.related_fields)
        assert_list_equal(fields.related_fields['accounts'].local_fields,
                          ['number', 'owner'])
        assert_true(
            'payments' in fields.related_fields['accounts'].related_fields)
        assert_list_equal(
            fields.related_fields['accounts'].related_fields['payments'].
            local_fields, ['value', 'date'])
コード例 #35
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())
コード例 #36
0
ファイル: fields.py プロジェクト: druids/django-chamber
    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))
コード例 #37
0
    def test_is_reverse_many_to_one(self):
        assert_false(is_reverse_many_to_one(Issue, 'watched_by'))
        assert_false(is_reverse_many_to_one(Issue, 'created_by'))
        assert_false(is_reverse_many_to_one(Issue, 'solver'))
        assert_false(is_reverse_many_to_one(Issue, 'leader'))
        assert_false(is_reverse_many_to_one(Issue, 'name'))
        assert_false(is_reverse_many_to_one(Issue, 'created_at'))
        assert_false(is_reverse_many_to_one(Issue, 'invalid'))

        assert_false(is_reverse_many_to_one(User, 'watched_issues'))
        assert_true(is_reverse_many_to_one(User, 'created_issues'))
        assert_false(is_reverse_many_to_one(User, 'solving_issue'))
        assert_false(is_reverse_many_to_one(User, 'leading_issue'))
コード例 #38
0
ファイル: serializer.py プロジェクト: asgeirrr/django-pyston
 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'))
コード例 #39
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'))
コード例 #40
0
ファイル: __init__.py プロジェクト: druids/django-chamber
    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')
コード例 #41
0
ファイル: fields.py プロジェクト: zzuzzy/django-chamber
    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))
コード例 #42
0
ファイル: __init__.py プロジェクト: jsilhan/django-security
    def test_every_output_request_has_data_for_stdout_logging(self, func):
        requests.get('http://test.cz')

        assert_true(func.called)
        func_args = func.call_args.args[0] if sys.version_info >= (
            3, 8) else func.call_args_list[0][0][0]  # data
        assert_in('request_timestamp', func_args)
        assert_in('response_timestamp', func_args)
        assert_in('response_time', func_args)
        assert_in('response_code', func_args)
        assert_in('host', func_args)
        assert_in('path', func_args)
        assert_in('method', func_args)
        assert_in('slug', func_args)
コード例 #43
0
ファイル: fields.py プロジェクト: druids/django-chamber
    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))
コード例 #44
0
    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)
コード例 #45
0
ファイル: crawler.py プロジェクト: studyjan/django-is-core
 def post_response(url, referer, resp, exception):
     tested_urls.append(url)
     gt.assert_true(
         exception is None or isinstance(exception, HTMLParseError),
         msg="Received exception %s" % force_text(exception),
     )
     if resp.status_code != 200:
         failed_urls.append(url)
         self.logger.warning(
             "Response code for url %s from referer %s should be 200 but code is %s, user %s"
             % (url, referer, resp.status_code, self.logged_user.user)
         )
     gt.assert_not_equal(
         resp.status_code,
         500,
         msg="Response code for url %s from referer %s is 500, user %s" % (url, referer, self.logged_user.user),
     )
コード例 #46
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
    def test_smart_model_clean_pre_delete(self):
        class PreDeleteTestProxySmartModel(TestProxySmartModel):
            class Meta:
                proxy = True
                verbose_name = 'testmodel'
                verbose_name_plural = 'testmodels'

            class SmartMeta:
                is_cleaned_pre_save = False
                is_cleaned_pre_delete = True

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

        obj = PreDeleteTestProxySmartModel.objects.create(name=10 * 'a')
        obj_pk = obj.pk
        obj.delete(is_cleaned_pre_delete=False)
        assert_false(PreDeleteTestProxySmartModel.objects.filter(pk=obj_pk).exists())
コード例 #47
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
    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)
コード例 #48
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
    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)
コード例 #49
0
ファイル: __init__.py プロジェクト: matllubos/django-security
 def test_json_request_should_not_be_truncated_with_another_method(self):
     self.c.post('/admin/login/', data=json.dumps({'a': 50 * 'a'}),
                 content_type='application/json')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(input_logged_request.request_body, '{"a": "' + 40* 'a' + '...')
     assert_true(input_logged_request.request_body.endswith('...'))
コード例 #50
0
ファイル: fields.py プロジェクト: druids/django-chamber
 def test_should_assert_form_field(self, field_name, currency, kwargs_to_remove):
     field = TestFieldsModel._meta.get_field(field_name)  # pylint: disable=W0212
     assert_equal(currency, field.currency)
     form_field = field.formfield()
     assert_true(isinstance(form_field.widget, form_fields.PriceNumberInput))
     assert_equal(field.currency, form_field.widget.placeholder)
コード例 #51
0
ファイル: __init__.py プロジェクト: matllubos/django-security
 def test_response_body_should_be_truncated(self):
     self.post('/admin/login/', data={'username': 20 * 'a', 'password': 20 * 'b'})
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.response_body), 10)
     assert_true(input_logged_request.response_body.endswith('...'))
コード例 #52
0
ファイル: __init__.py プロジェクト: matllubos/django-security
 def test_json_request_should_be_truncated_with_another_method_and_standard_method_too(self):
     self.c.post('/admin/login/', data=json.dumps({50 * 'a': 50 * 'a', 50 * 'b': 50 * 'b'}),
                 content_type='application/json')
     input_logged_request = InputLoggedRequest.objects.get()
     assert_equal(len(input_logged_request.request_body), 100)
     assert_true(input_logged_request.request_body.endswith('...'))
コード例 #53
0
ファイル: fieldsets.py プロジェクト: druids/django-pyston
 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({}))
コード例 #54
0
ファイル: __init__.py プロジェクト: druids/django-chamber
    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()))
コード例 #55
0
ファイル: fields.py プロジェクト: druids/django-chamber
 def test_should_check_total_price_form_field(self):
     field = TestFieldsModel._meta.get_field('total_price')  # pylint: disable=W0212
     assert_equal(ugettext_lazy('CZK'), field.currency)
     form_field = field.formfield()
     assert_true(isinstance(form_field.widget, form_fields.PriceNumberInput))
コード例 #56
0
ファイル: __init__.py プロジェクト: matllubos/django-chamber
 def test_should_keep_spacing(self, expected, value, autoescape):
     escaped_value = keep_spacing(value, autoescape)
     assert_equal(expected, escaped_value)
     assert_true(isinstance(escaped_value, SafeData))
コード例 #57
0
ファイル: fields.py プロジェクト: druids/django-chamber
 def test_random_file_path_should_be_generated_from_class_name(self):
     instance = CSVRecord()
     filename = 'filename.txt'
     path = generate_random_upload_path(instance, filename)
     assert_true(path.startswith('csvrecord/'))
     assert_true(path.endswith('/{}'.format(filename)))