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)
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())
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())
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')
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_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()))
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)
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)
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)
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')
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)
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)
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__', ))
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)
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)
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)
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)
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())
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())
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)
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))
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])
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)
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))
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')
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)
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()
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' )
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])
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)
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)
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
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
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)
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)
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_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)
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())
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_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, [])
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())
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)
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'
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()))
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)
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)
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)
def test_should_validate_positive_price_field(self): assert_raises(PersistenceException, change_and_save, self.inst, total_price=-100)
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)
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())