def _get_request(self, path='/', post=False, **headers): if post: request = RequestFactory(**headers).post(path) else: request = RequestFactory(**headers).get(path) middleware = SessionMiddleware() middleware.process_request(request) messages_middleware = MessageMiddleware() messages_middleware.process_request(request) request.session.save() return request
class MiddlewareTests(unittest.TestCase): def setUp(self): self.middleware = MessageMiddleware() def test_response_without_messages(self): """ MessageMiddleware is tolerant of messages not existing on request. """ request = HttpRequest() response = HttpResponse() self.middleware.process_response(request, response)
def test_admin_fieldsets(self): post_admin = admin.site._registry[Post] request = self.get_page_request('/', self.user_staff, r'/en/blog/?app_config=%s' % self.app_config_1.pk, edit=False) # Use placeholder self.app_config_1.app_data.config.use_placeholder = True self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertFalse('post_text' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_placeholder = False self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertTrue('post_text' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_placeholder = True self.app_config_1.save() # Use abstract self.app_config_1.app_data.config.use_abstract = True self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertTrue('abstract' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_abstract = False self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertFalse('abstract' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_abstract = True self.app_config_1.save() with self.settings(BLOG_MULTISITE=True): fsets = post_admin.get_fieldsets(request) self.assertTrue('sites' in fsets[1][1]['fields'][0]) with self.settings(BLOG_MULTISITE=False): fsets = post_admin.get_fieldsets(request) self.assertFalse('sites' in fsets[1][1]['fields'][0]) request = self.get_page_request('/', self.user, r'/en/blog/?app_config=%s' % self.app_config_1.pk, edit=False) fsets = post_admin.get_fieldsets(request) self.assertTrue('author' in fsets[1][1]['fields'][0]) with self.login_user_context(self.user): request = self.get_request('/', 'en', user=self.user, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertContains(response, '<option value="%s">%s</option>' % ( self.category_1.pk, self.category_1.safe_translation_getter('name', language_code='en') ))
def test_admin_post_text(self): page1, page2 = self.get_pages() post = self._get_post(self.data['en'][0]) with self.settings(BLOG_USE_PLACEHOLDER=False): data = {'post_text': 'ehi text'} request = self.post_request(page1, 'en', data=data, path='/en/?edit_fields=post_text') msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.edit_field(request, post.pk, 'en') modified_post = Post.objects.get(pk=post.pk) self.assertEqual(modified_post.safe_translation_getter('post_text'), data['post_text'])
def test_admin_post_text(self): pages = self.get_pages() post = self._get_post(self._post_data[0]['en']) with self.login_user_context(self.user): with self.settings(BLOG_USE_PLACEHOLDER=False): data = {'post_text': 'ehi text', 'title': 'some title'} request = self.post_request(pages[0], 'en', user=self.user, data=data, path='/en/?edit_fields=post_text') msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.edit_field(request, post.pk, 'en') self.assertEqual(response.status_code, 200) modified_post = Post.objects.language('en').get(pk=post.pk) self.assertEqual(modified_post.safe_translation_getter('post_text'), data['post_text'])
def test_admin_auto_author(self): pages = self.get_pages() data = deepcopy(self._post_data[0]['en']) with self.login_user_context(self.user): self.app_config_1.app_data.config.set_author = True self.app_config_1.save() data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) self.assertEqual(Post.objects.get(translations__slug='first-post').author_id, request.user.pk) self.app_config_1.app_data.config.set_author = False self.app_config_1.save() data = deepcopy(self._post_data[1]['en']) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) self.assertEqual(Post.objects.get(translations__slug='second-post').author_id, None) with self.settings(BLOG_AUTHOR_DEFAULT='staff'): self.app_config_1.app_data.config.set_author = True self.app_config_1.save() data = deepcopy(self._post_data[2]['en']) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 3) self.assertEqual(Post.objects.get(translations__slug='third-post').author.username, 'staff')
def get_page_request(self, page, user, path=None, edit=False, lang_code='en', disable=False): path = path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang_code if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} if disable: request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None request.current_page = page mid = MessageMiddleware() mid.process_request(request) return request
def test_admin_auto_author(self): page1, page2 = self.get_pages() request = self.get_page_request('/', self.user_staff, r'/en/blog/', edit=False) data = deepcopy(self.data['en'][0]) with self.settings(BLOG_AUTHOR_DEFAULT=True): data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 1) self.assertEqual(Post.objects.get(translations__slug='first-post').author_id, request.user.pk) with self.settings(BLOG_AUTHOR_DEFAULT=False): data = deepcopy(self.data['en'][1]) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 2) self.assertEqual(Post.objects.get(translations__slug='second-post').author_id, None) with self.settings(BLOG_AUTHOR_DEFAULT='staff'): data = deepcopy(self.data['en'][2]) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 3) self.assertEqual(Post.objects.get(translations__slug='third-post').author.username, 'staff')
def test_admin_clear_menu(self): """ Tests that after changing apphook config menu structure the menu content is different: new value is taken immediately into account """ pages = self.get_pages() post = self._get_post(self._post_data[0]['en']) request = self.get_page_request(None, self.user, r'/en/page-two/') first_nodes = menu_pool.get_nodes(request) with pause_knocks(post): with self.login_user_context(self.user): data = dict(namespace='sample_app', app_title='app1', object_name='Blog') data['config-menu_structure'] = MENU_TYPE_NONE data['config-sitemap_changefreq'] = 'weekly' data['config-sitemap_priority'] = '0.5' request = self.post_request(pages[0], 'en', user=self.user, data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) config_admin = admin.site._registry[BlogConfig] response = config_admin.change_view(request, str(self.app_config_1.pk)) second_nodes = menu_pool.get_nodes(request) self.assertNotEqual(len(first_nodes), len(second_nodes))
def test_can_consume_an_action_token(self): # Setup actions.register(Action1) token = AccountActionTokenFactory.create(action='action-1') user = User.objects.create_user( username='******', password='******', email='*****@*****.**') session_middleware = SessionMiddleware() message_middleware = MessageMiddleware() request = self.factory.post('/') session_middleware.process_request(request) message_middleware.process_request(request) request.user = user view = AccountActionConsumeView.as_view() # Run response = view(request, key=token.key) # Check self.assertEqual(response.status_code, 302) token.refresh_from_db() self.assertTrue(token.is_consumed)
def setUp(self): self.middleware = MessageMiddleware()
def test_admin_site(self): pages = self.get_pages() post = self._get_post(self._post_data[0]['en']) # no restrictions, sites are assigned with self.login_user_context(self.user): data = { 'sites': [self.site_1.pk, self.site_2.pk], 'title': 'some title', 'app_config': self.app_config_1.pk } request = self.post_request(pages[0], 'en', user=self.user, data=data, path='/en/') self.assertEquals(post.sites.count(), 0) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.change_view(request, str(post.pk)) self.assertEqual(response.status_code, 302) post = self.reload_model(post) self.assertEquals(post.sites.count(), 2) post.sites.clear() post = self.reload_model(post) # user only allowed on 2 sites, can add both self.user.sites.add(self.site_2) self.user.sites.add(self.site_3) post.sites.add(self.site_1) post.sites.add(self.site_2) self.user = self.reload_model(self.user) with self.login_user_context(self.user): data = { 'sites': [self.site_2.pk, self.site_3.pk], 'title': 'some title', 'app_config': self.app_config_1.pk } request = self.post_request(pages[0], 'en', user=self.user, data=data, path='/en/') self.assertEquals(post.sites.count(), 2) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin._sites = None response = post_admin.change_view(request, str(post.pk)) self.assertEqual(response.status_code, 302) post = self.reload_model(post) self.assertEquals(post.sites.count(), 3) self.user.sites.clear() post.sites.clear() # user only allowed on 2 sites, can remove one of his sites post = self.reload_model(post) post.sites.add(self.site_1) post.sites.add(self.site_2) post.sites.add(self.site_3) self.user.sites.add(self.site_2) self.user.sites.add(self.site_3) with self.login_user_context(self.user): data = { 'sites': [self.site_3.pk], 'title': 'some title', 'app_config': self.app_config_1.pk } request = self.post_request(pages[0], 'en', user=self.user, data=data, path='/en/') self.assertEquals(post.sites.count(), 3) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin._sites = None response = post_admin.change_view(request, str(post.pk)) self.assertEqual(response.status_code, 302) post = self.reload_model(post) self.assertEquals(post.sites.count(), 2) self.user.sites.clear() post.sites.clear() # user only allowed on 2 sites, if given sites is empty, the site with no permission on # is kept post = self.reload_model(post) post.sites.add(self.site_1) post.sites.add(self.site_3) self.user.sites.add(self.site_2) self.user.sites.add(self.site_3) with self.login_user_context(self.user): data = { 'sites': [], 'title': 'some title', 'app_config': self.app_config_1.pk } request = self.post_request(pages[0], 'en', user=self.user, data=data, path='/en/') self.assertEquals(post.sites.count(), 2) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin._sites = None response = post_admin.change_view(request, str(post.pk)) self.assertEqual(response.status_code, 302) post = self.reload_model(post) self.assertEquals(post.sites.count(), 1) self.user.sites.clear() post.sites.clear() post = self.reload_model(post)
def test_admin_auto_author(self): page1, page2 = self.get_pages() request = self.get_page_request('/', self.user_staff, r'/en/blog/', edit=False) data = deepcopy(self.data['en'][0]) with self.settings(BLOG_AUTHOR_DEFAULT=True): data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 1) self.assertEqual( Post.objects.get(translations__slug='first-post').author_id, request.user.pk) with self.settings(BLOG_AUTHOR_DEFAULT=False): data = deepcopy(self.data['en'][1]) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 2) self.assertEqual( Post.objects.get(translations__slug='second-post').author_id, None) with self.settings(BLOG_AUTHOR_DEFAULT='staff'): data = deepcopy(self.data['en'][2]) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk request = self.post_request(page1, 'en', data=data) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin.add_view(request) self.assertEqual(Post.objects.count(), 3) self.assertEqual( Post.objects.get( translations__slug='third-post').author.username, 'staff')
def test_audit_log_presence_upload(self): # Delete the CPCat records that were loaded with the fixtures ExtractedCPCat.objects.all().delete() self.assertEqual(len(ExtractedCPCat.objects.all()), 0, "Should be empty before upload.") # upload file usr = User.objects.get(username="******") in_mem_sample_csv = make_upload_csv("sample_files/presence_good.csv") req_data = {"extfile-extraction_script": 5, "extfile-submit": "Submit"} req_data.update(self.mng_data) req = self.factory.post("/datagroup/49/", data=req_data) req.FILES["extfile-bulkformsetfileupload"] = in_mem_sample_csv middleware = SessionMiddleware() middleware.process_request(req) req.session.save() middleware = MessageMiddleware() middleware.process_request(req) req.session.save() req.user = usr resp = views.data_group_detail(request=req, pk=49) self.assertContains(resp, "3 extracted records uploaded successfully.") logs = AuditLog.objects.all() self.assertEquals(8, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNone(log.old_value) self.assertIsNotNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("I", log.action, "Should be Insert action") logs.delete() # update chems = ExtractedListPresence.objects.all() for chem in chems: chem.raw_cas = "test raw cas" chem.raw_chem_name = "test raw chem name" chem.report_funcuse = "report func use" chem.save() logs = AuditLog.objects.all() self.assertEquals(9, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNotNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("U", log.action, "Should be Update action") logs.delete() # delete chems.delete() logs = AuditLog.objects.all() self.assertEquals(9, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNotNone(log.old_value) self.assertIsNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("D", log.action, "Should be Delete action") dg = DataGroup.objects.get(pk=49) dg.delete()
class MessageMixinTests(test.TestCase): def setUp(self): self.rf = test.RequestFactory() self.middleware = MessageMiddleware() def get_request(self, *args, **kwargs): request = self.rf.get("/") self.middleware.process_request(request) return request def get_response(self, request, view): response = view(request) self.middleware.process_response(request, response) return response def get_request_response(self, view, *args, **kwargs): request = self.get_request(*args, **kwargs) response = self.get_response(request, view) return request, response def test_add_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, "test") return HttpResponse("OK") request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, "test") self.assertEqual(msg[0].level, messages.SUCCESS) def test_get_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, "success") self.messages.add_message(messages.WARNING, "warning") content = ",".join(m.message for m in self.messages.get_messages()) return HttpResponse(content) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(response.content, b"success,warning") def test_get_level(self): class TestView(MessageMixin, View): def get(self, request): return HttpResponse(self.messages.get_level()) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(int(response.content), messages.INFO) # default def test_set_level(self): class TestView(MessageMixin, View): def get(self, request): self.messages.set_level(messages.WARNING) self.messages.add_message(messages.SUCCESS, "success") self.messages.add_message(messages.WARNING, "warning") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(msg, [Message(messages.WARNING, "warning")]) @override_settings(MESSAGE_LEVEL=messages.DEBUG) def test_debug(self): class TestView(MessageMixin, View): def get(self, request): self.messages.debug("test") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.DEBUG, "test")) def test_info(self): class TestView(MessageMixin, View): def get(self, request): self.messages.info("test") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.INFO, "test")) def test_success(self): class TestView(MessageMixin, View): def get(self, request): self.messages.success("test") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.SUCCESS, "test")) def test_warning(self): class TestView(MessageMixin, View): def get(self, request): self.messages.warning("test") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.WARNING, "test")) def test_error(self): class TestView(MessageMixin, View): def get(self, request): self.messages.error("test") return HttpResponse("OK") request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.ERROR, "test")) def test_invalid_attribute(self): class TestView(MessageMixin, View): def get(self, request): self.messages.invalid() return HttpResponse("OK") with self.assertRaises(AttributeError): self.get_request_response(TestView.as_view()) @pytest.mark.skipif( django.VERSION < (1, 5), reason="Some features of MessageMixin are only available in " "Django >= 1.5" ) def test_wrapper_available_in_dispatch(self): """ Make sure that self.messages is available in dispatch() even before calling the parent's implementation. """ class TestView(MessageMixin, View): def dispatch(self, request): self.messages.add_message(messages.SUCCESS, "test") return super(TestView, self).dispatch(request) def get(self, request): return HttpResponse("OK") request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, "test") self.assertEqual(msg[0].level, messages.SUCCESS) def test_API(self): """ Make sure that our assumptions about messages.api are still valid. """ # This test is designed to break when django.contrib.messages.api # changes (items being added or removed). excluded_API = set() if django.VERSION >= (1, 7): excluded_API.add("MessageFailure") self.assertEqual(_MessageAPIWrapper.API | excluded_API, set(messages.api.__all__))
def setUp(self): self.rf = test.RequestFactory() self.middleware = MessageMiddleware()
class MessageMixinTests(test.TestCase): def setUp(self): self.rf = test.RequestFactory() self.middleware = MessageMiddleware() def get_request(self, *args, **kwargs): request = self.rf.get('/') self.middleware.process_request(request) return request def get_response(self, request, view): response = view(request) self.middleware.process_response(request, response) return response def get_request_response(self, view, *args, **kwargs): request = self.get_request(*args, **kwargs) response = self.get_response(request, view) return request, response def test_add_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, 'test') return HttpResponse('OK') request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, 'test') self.assertEqual(msg[0].level, messages.SUCCESS) def test_get_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, 'success') self.messages.add_message(messages.WARNING, 'warning') content = ','.join(m.message for m in self.messages.get_messages()) return HttpResponse(content) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(response.content, b"success,warning") def test_get_level(self): class TestView(MessageMixin, View): def get(self, request): return HttpResponse(self.messages.get_level()) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(int(response.content), messages.INFO) # default def test_set_level(self): class TestView(MessageMixin, View): def get(self, request): self.messages.set_level(messages.WARNING) self.messages.add_message(messages.SUCCESS, 'success') self.messages.add_message(messages.WARNING, 'warning') return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(msg, [Message(messages.WARNING, 'warning')]) @override_settings(MESSAGE_LEVEL=messages.DEBUG) def test_debug(self): class TestView(MessageMixin, View): def get(self, request): self.messages.debug("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.DEBUG, 'test')) def test_info(self): class TestView(MessageMixin, View): def get(self, request): self.messages.info("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.INFO, 'test')) def test_success(self): class TestView(MessageMixin, View): def get(self, request): self.messages.success("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.SUCCESS, 'test')) def test_warning(self): class TestView(MessageMixin, View): def get(self, request): self.messages.warning("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.WARNING, 'test')) def test_error(self): class TestView(MessageMixin, View): def get(self, request): self.messages.error("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.ERROR, 'test')) def test_invalid_attribute(self): class TestView(MessageMixin, View): def get(self, request): self.messages.invalid() return HttpResponse('OK') with self.assertRaises(AttributeError): self.get_request_response(TestView.as_view()) @pytest.mark.skipif( DJANGO_VERSION < (1, 5), reason='Some features of MessageMixin are only available in ' 'Django >= 1.5') def test_wrapper_available_in_dispatch(self): """ Make sure that self.messages is available in dispatch() even before calling the parent's implementation. """ class TestView(MessageMixin, View): def dispatch(self, request): self.messages.add_message(messages.SUCCESS, 'test') return super(TestView, self).dispatch(request) def get(self, request): return HttpResponse('OK') request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, 'test') self.assertEqual(msg[0].level, messages.SUCCESS) def test_API(self): """ Make sure that our assumptions about messages.api are still valid. """ # This test is designed to break when django.contrib.messages.api # changes (items being added or removed). excluded_API = set() if DJANGO_VERSION >= (1, 7): excluded_API.add('MessageFailure') self.assertEqual(_MessageAPIWrapper.API | excluded_API, set(messages.api.__all__))
class FormHelpersTest(TestCase): def setUp(self): self.request = HttpRequest() self.request.user = User() self.request.session = {} self.request.method = 'POST' # Need MessageMiddleware to add the _messages storage backend # to requests self.message_middleware = MessageMiddleware() self.message_middleware.process_request(self.request) def test_object_editing_list_error_message(self): """Does object_editing_list show an error message when it should? """ form_helpers.object_editing_list(request=self.request, object_list=[MockObject()], form_class=MockInvalidForm, ignore_errors=False, ignore_post=False, ignore_objects=[]) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) error_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]}) self.assertEqual(len(error_message_divs), 1) self.assertTrue( 'lease correct the errors' in error_message_divs[0].text) def test_object_editing_list_success_message(self): """Does object_editing_list show a message when everything is ok? """ form_helpers.object_editing_list(request=self.request, object_list=[MockObject()], form_class=MockValidForm, ignore_errors=False, ignore_post=False, ignore_objects=[]) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue( 'hanges were saved successfully' in success_message_divs[0].text) def test_object_ordering_error_message(self): """Does object_ordering show an error message when it should? """ form_helpers.object_ordering(request=self.request, object_list=[MockObject()], form_class=MockInvalidForm, ignore_errors=False, ignore_post=False, ignore_objects=[]) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) error_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]}) self.assertEqual(len(error_message_divs), 1) self.assertTrue('Unable to update order' in error_message_divs[0].text) def test_object_ordering_success_message(self): """Does object_ordering show a message when everything is ok? """ form_helpers.object_ordering(request=self.request, object_list=[MockObject()], form_class=MockValidForm, ignore_errors=False, ignore_post=False, ignore_objects=[]) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue( 'Order was updated successfully' in success_message_divs[0].text) def test__perform_save_form_error_message(self): """Does _perform_save_form show an error message when it should? """ FAIL_MSG = 'better luck next time' form_helpers._perform_save_form(request=self.request, instance=None, prefix=None, form_class=MockInvalidForm, fail_msg=FAIL_MSG) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) error_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]}) self.assertEqual(len(error_message_divs), 1) self.assertTrue(FAIL_MSG in error_message_divs[0].text) def test__perform_save_form_success_message(self): """Does _perform_save_form show a success message when it should? """ SAVE_MSG = 'winner!' form_helpers._perform_save_form(request=self.request, instance=None, prefix=None, form_class=MockValidForm, save_msg=SAVE_MSG) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue(SAVE_MSG in success_message_divs[0].text) def test_basic_save_form_success_message(self): """Does basic_save_form show a success message when it should? """ form_helpers.basic_save_form(request=self.request, instance=None, prefix=None, form_class=MockValidForm) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue( 'hanges saved successfully' in success_message_divs[0].text) def test_save_new_form_rows_invalid_form_error_message(self): """Does save_new_form_rows show an error msg when a form is invalid? """ with testfixtures.Replacer() as r: r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm', MockInvalidForm) form_helpers.save_new_form_rows(request=self.request, prefix=None, form_class=MockInvalidForm, instance_class=MockObject) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) error_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]}) self.assertEqual(len(error_message_divs), 1) self.assertTrue( MockInvalidForm.COUNTER_MESSAGE in error_message_divs[0].text) def test_save_new_form_rows_error_saving_error_message(self): """Does save_new_form_rows show an error msg when saving fails? """ with testfixtures.Replacer() as r: r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm', MockValidForm) r.replace( 'stars.apps.helpers.forms.form_helpers._perform_save_form', lambda w, x, y, z, show_message: (MockValidForm(), None, False)) form_helpers.save_new_form_rows(request=self.request, prefix=None, form_class=MockValidForm, instance_class=MockObject) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) error_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]}) self.assertEqual(len(error_message_divs), 1) self.assertTrue( MockValidForm.SAVE_ERROR_MESSAGE in error_message_divs[0].text) def test_save_new_form_rows_success_message(self): """Does save_new_form_rows show a success message when it succeeds? """ with testfixtures.Replacer() as r: r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm', MockValidForm) r.replace( 'stars.apps.helpers.forms.form_helpers._perform_save_form', lambda w, x, y, z, show_message: (MockValidForm(), None, True)) form_helpers.save_new_form_rows(request=self.request, prefix=None, form_class=MockValidForm, instance_class=MockValidForm) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue( '1 new' and 'were created successfully' in success_message_divs[0].text) def test_confirm_unlock_form_success_message(self): """Does confirm_unlock_form show a success message upon unlocking? """ MODEL_LABEL = 'buick century' with testfixtures.Replacer() as r: r.replace('stars.apps.helpers.forms.form_helpers.confirm_form', lambda x, y: (None, True)) r.replace('stars.apps.helpers.forms.form_helpers._get_model_label', lambda x: MODEL_LABEL) form_helpers.confirm_unlock_form(self.request, MockObject()) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue(MODEL_LABEL and 'was unlocked' in success_message_divs[0].text) def test_confirm_delete_form_success_message(self): """Does confirm_delete_form show a success message after deleting? """ MODEL_LABEL = 'toyota mr2' with testfixtures.Replacer() as r: r.replace('stars.apps.helpers.forms.form_helpers.confirm_form', lambda x, y: (None, True)) r.replace('stars.apps.helpers.forms.form_helpers._get_model_label', lambda x: MODEL_LABEL) form_helpers.confirm_delete_form(request=self.request, instance=MockObject(), delete_method=lambda: True) response = render(self.request, 'base.html') soup = BeautifulSoup(response.content) success_message_divs = soup.find_all( 'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]}) self.assertEqual(len(success_message_divs), 1) self.assertTrue(MODEL_LABEL and 'was deleted' in success_message_divs[0].text)
def test_audit_log_chem_upload(self): req_data = { "extfile-extraction_script": 5, "extfile-weight_fraction_type": 1, "extfile-submit": "Submit", } req_data.update(self.mng_data) req = self.factory.post(path="/datagroup/6/", data=req_data) req.user = User.objects.get(username="******") middleware = SessionMiddleware() middleware.process_request(req) req.session.save() middleware = MessageMiddleware() middleware.process_request(req) req.session.save() # upload chem req.FILES[ "extfile-bulkformsetfileupload"] = self.generate_valid_chem_csv() resp = views.data_group_detail(request=req, pk=6) self.assertContains(resp, "3 extracted records uploaded successfully.") # get audit logs logs = AuditLog.objects.all() self.assertEquals(13, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNone(log.old_value) self.assertIsNotNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("I", log.action, "Should be Insert action") logs.delete() # bulk update fields chems = ExtractedChemical.objects.filter(component="Test Component") for chemical in chems: chemical.raw_min_comp = "min comp" chemical.raw_max_comp = "max comp" chemical.raw_central_comp = "central comp" chemical.unit_type_id = 1 chemical.report_funcuse = "report func use" chemical.ingredient_rank = 5 chemical.lower_wf_analysis = 0.01 chemical.central_wf_analysis = 0.44 chemical.upper_wf_analysis = 0.88 ExtractedChemical.objects.bulk_update( chems, [ "raw_min_comp", "raw_max_comp", "raw_central_comp", "unit_type_id", "report_funcuse", "ingredient_rank", "upper_wf_analysis", "central_wf_analysis", "lower_wf_analysis", ], ) logs = AuditLog.objects.all() self.assertEquals(27, len(logs), "Should have log entries") self.assertEquals( 3, sum(log.field_name == "raw_min_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "raw_max_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "raw_central_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "unit_type_id" for log in logs)) self.assertEquals( 3, sum(log.field_name == "report_funcuse" for log in logs)) self.assertEquals( 3, sum(log.field_name == "ingredient_rank" for log in logs)) self.assertEquals( 3, sum(log.field_name == "upper_wf_analysis" for log in logs)) self.assertEquals( 3, sum(log.field_name == "central_wf_analysis" for log in logs)) self.assertEquals( 3, sum(log.field_name == "lower_wf_analysis" for log in logs)) for log in logs: self.assertEquals(log.model_name, "extractedchemical") self.assertIsNotNone(log.object_key) self.assertIsNotNone(log.field_name) self.assertIsNotNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("U", log.action, "Should be Update action") logs.delete() # change rid for chem in chems: chem.rid = "test rid" chem.save() logs = AuditLog.objects.all() self.assertEquals(3, len(logs), "Should have log entries") for log in logs: self.assertEquals(log.model_name, "rawchem") self.assertEquals("rid", log.field_name) self.assertIsNone(log.old_value) self.assertEquals("test rid", log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("U", log.action, "Should be Update action") logs.delete() # delete chemicals for chemical in chems: chemical.delete() logs = AuditLog.objects.all() self.assertEquals(36, len(logs), "Should have log entries") self.assertEquals( 3, sum(log.field_name == "raw_min_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "raw_max_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "raw_central_comp" for log in logs)) self.assertEquals( 3, sum(log.field_name == "unit_type_id" for log in logs)) self.assertEquals( 3, sum(log.field_name == "report_funcuse" for log in logs)) self.assertEquals( 3, sum(log.field_name == "ingredient_rank" for log in logs)) self.assertEquals( 3, sum(log.field_name == "upper_wf_analysis" for log in logs)) self.assertEquals( 3, sum(log.field_name == "central_wf_analysis" for log in logs)) self.assertEquals( 3, sum(log.field_name == "lower_wf_analysis" for log in logs)) self.assertEquals(3, sum(log.field_name == "raw_cas" for log in logs)) self.assertEquals( 3, sum(log.field_name == "raw_chem_name" for log in logs)) self.assertEquals(3, sum(log.field_name == "rid" for log in logs)) for log in logs: self.assertIsNotNone(log.object_key) self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNone(log.new_value) self.assertIsNotNone(log.old_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("D", log.action, "Should be Delete action") dg = DataGroup.objects.get(pk=6) dg.delete()
def test_audit_log_functionaluse_upload(self): dd_id = 500 dd = DataDocument.objects.get(pk=dd_id) dd_pdf = dd.pdf_url() sample_csv = ( "data_document_id,data_document_filename,prod_name," "doc_date,rev_num,raw_category,raw_cas,raw_chem_name,report_funcuse" "\n" "%s," "%s," "sample functional use product," "2018-04-07," "," "raw PUC," "RAW-CAS-01," "raw chemname 01," "surfactant" % (dd_id, dd_pdf)) sample_csv_bytes = sample_csv.encode(encoding="UTF-8", errors="strict") in_mem_sample_csv = InMemoryUploadedFile( io.BytesIO(sample_csv_bytes), field_name="extfile-bulkformsetfileupload", name="Functional_use_extract_template.csv", content_type="text/csv", size=len(sample_csv), charset="utf-8", ) req_data = {"extfile-extraction_script": 5, "extfile-submit": "Submit"} req_data.update(self.mng_data) req = self.factory.post("/datagroup/50/", data=req_data) req.FILES["extfile-bulkformsetfileupload"] = in_mem_sample_csv middleware = SessionMiddleware() middleware.process_request(req) req.session.save() middleware = MessageMiddleware() middleware.process_request(req) req.session.save() req.user = User.objects.get(username="******") self.assertEqual( len(ExtractedFunctionalUse.objects.filter( extracted_text_id=dd_id)), 0, "Empty before upload.", ) # Now get the response resp = views.data_group_detail(request=req, pk=50) self.assertContains(resp, "1 extracted record uploaded successfully.") self.assertEqual( len(ExtractedFunctionalUse.objects.filter( extracted_text_id=dd_id)), 1, "One new ExtractedFunctionalUse after upload.", ) logs = AuditLog.objects.all() self.assertEquals(3, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNone(log.old_value) self.assertIsNotNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("I", log.action, "Should be Insert action") logs.delete() # update efs = ExtractedFunctionalUse.objects.filter(extracted_text_id=dd_id) for ef in efs: ef.report_funcuse = "test func use" ef.save() logs = AuditLog.objects.all() self.assertEquals(1, len(logs), "Should have log entries") for log in logs: self.assertEquals(log.model_name, "extractedfuncationaluse") self.assertEquals(log.field_name, "report_funcuse") self.assertIsNotNone(log.new_value) self.assertEquals(log.new_value, "test func use") self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("U", log.action, "Should be Update action") logs.delete() # delete for ef in efs: ef.delete() logs = AuditLog.objects.all() self.assertEquals(3, len(logs), "Should have log entries") for log in logs: self.assertIsNotNone(log.model_name) self.assertIsNotNone(log.field_name) self.assertIsNotNone(log.old_value) self.assertIsNone(log.new_value) self.assertIsNotNone(log.date_created) self.assertIsNotNone(log.user_id) self.assertEquals("D", log.action, "Should be delete action")
def test_admin_auto_author(self): pages = self.get_pages() data = deepcopy(self._post_data[0]['en']) with self.login_user_context(self.user): self.app_config_1.app_data.config.set_author = True self.app_config_1.save() data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) self.assertEqual( Post.objects.get(translations__slug='first-post').author_id, request.user.pk) self.app_config_1.app_data.config.set_author = False self.app_config_1.save() data = deepcopy(self._post_data[1]['en']) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) self.assertEqual( Post.objects.get(translations__slug='second-post').author_id, None) with self.settings(BLOG_AUTHOR_DEFAULT='staff'): self.app_config_1.app_data.config.set_author = True self.app_config_1.save() data = deepcopy(self._post_data[2]['en']) data['date_published_0'] = now().strftime('%Y-%m-%d') data['date_published_1'] = now().strftime('%H:%M:%S') data['categories'] = self.category_1.pk data['app_config'] = self.app_config_1.pk request = self.post_request(pages[0], 'en', user=self.user, data=data, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 3) self.assertEqual( Post.objects.get( translations__slug='third-post').author.username, 'staff')
class MessageMixinTests(test.TestCase): def setUp(self): self.rf = test.RequestFactory() self.middleware = MessageMiddleware() def get_request(self, *args, **kwargs): request = self.rf.get('/') self.middleware.process_request(request) return request def get_response(self, request, view): response = view(request) self.middleware.process_response(request, response) return response def get_request_response(self, view, *args, **kwargs): request = self.get_request(*args, **kwargs) response = self.get_response(request, view) return request, response def test_add_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, 'test') return HttpResponse('OK') request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, 'test') self.assertEqual(msg[0].level, messages.SUCCESS) def test_get_messages(self): class TestView(MessageMixin, View): def get(self, request): self.messages.add_message(messages.SUCCESS, 'success') self.messages.add_message(messages.WARNING, 'warning') content = ','.join( m.message for m in self.messages.get_messages()) return HttpResponse(content) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(response.content, b"success,warning") def test_get_level(self): class TestView(MessageMixin, View): def get(self, request): return HttpResponse(self.messages.get_level()) _, response = self.get_request_response(TestView.as_view()) self.assertEqual(int(response.content), messages.INFO) # default def test_set_level(self): class TestView(MessageMixin, View): def get(self, request): self.messages.set_level(messages.WARNING) self.messages.add_message(messages.SUCCESS, 'success') self.messages.add_message(messages.WARNING, 'warning') return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(msg, [Message(messages.WARNING, 'warning')]) @override_settings(MESSAGE_LEVEL=messages.DEBUG) def test_debug(self): class TestView(MessageMixin, View): def get(self, request): self.messages.debug("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.DEBUG, 'test')) def test_info(self): class TestView(MessageMixin, View): def get(self, request): self.messages.info("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.INFO, 'test')) def test_success(self): class TestView(MessageMixin, View): def get(self, request): self.messages.success("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.SUCCESS, 'test')) def test_warning(self): class TestView(MessageMixin, View): def get(self, request): self.messages.warning("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.WARNING, 'test')) def test_error(self): class TestView(MessageMixin, View): def get(self, request): self.messages.error("test") return HttpResponse('OK') request, _ = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0], Message(messages.ERROR, 'test')) def test_invalid_attribute(self): class TestView(MessageMixin, View): def get(self, request): self.messages.invalid() return HttpResponse('OK') with self.assertRaises(AttributeError): self.get_request_response(TestView.as_view()) def test_wrapper_available_in_dispatch(self): """ Make sure that self.messages is available in dispatch() even before calling the parent's implementation. """ class TestView(MessageMixin, View): def dispatch(self, request): self.messages.add_message(messages.SUCCESS, 'test') return super(TestView, self).dispatch(request) def get(self, request): return HttpResponse('OK') request, response = self.get_request_response(TestView.as_view()) msg = list(request._messages) self.assertEqual(len(msg), 1) self.assertEqual(msg[0].message, 'test') self.assertEqual(msg[0].level, messages.SUCCESS) def test_API(self): """ Make sure that our assumptions about messages.api are still valid. """ # This test is designed to break when django.contrib.messages.api # changes (items being added or removed). excluded_API = set() excluded_API.add('MessageFailure')
def test_admin_fieldsets(self): post_admin = admin.site._registry[Post] request = self.get_page_request('/', self.user_staff, r'/en/blog/?app_config=%s' % self.app_config_1.pk, edit=False) # Use placeholder self.app_config_1.app_data.config.use_placeholder = True self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertFalse('post_text' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_placeholder = False self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertTrue('post_text' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_placeholder = True self.app_config_1.save() # Use abstract self.app_config_1.app_data.config.use_abstract = True self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertTrue('abstract' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_abstract = False self.app_config_1.save() fsets = post_admin.get_fieldsets(request) self.assertFalse('abstract' in fsets[0][1]['fields']) self.app_config_1.app_data.config.use_abstract = True self.app_config_1.save() with self.settings(BLOG_MULTISITE=True): fsets = post_admin.get_fieldsets(request) self.assertTrue('sites' in fsets[1][1]['fields'][0]) with self.settings(BLOG_MULTISITE=False): fsets = post_admin.get_fieldsets(request) self.assertFalse('sites' in fsets[1][1]['fields'][0]) request = self.get_page_request('/', self.user, r'/en/blog/?app_config=%s' % self.app_config_1.pk, edit=False) fsets = post_admin.get_fieldsets(request) self.assertTrue('author' in fsets[1][1]['fields'][0]) with self.login_user_context(self.user): request = self.get_request('/', 'en', user=self.user, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] response = post_admin.add_view(request) self.assertContains( response, '<option value="%s">%s</option>' % (self.category_1.pk, self.category_1.safe_translation_getter('name', language_code='en'))) self.assertContains(response, 'id="id_sites" name="sites"') self.user.sites.add(self.site_1) with self.login_user_context(self.user): request = self.get_request('/', 'en', user=self.user, path=r'/en/blog/?app_config=%s' % self.app_config_1.pk) msg_mid = MessageMiddleware() msg_mid.process_request(request) post_admin = admin.site._registry[Post] post_admin._sites = None response = post_admin.add_view(request) response.render() self.assertNotContains(response, 'id="id_sites" name="sites"') post_admin._sites = None self.user.sites.clear()