def setUp(self): setup_test_template_loader({"404.html": "", "admin/change_form.html": "", "zinnia/entry_detail.html": ""}) self.original_wysiwyg = settings.WYSIWYG settings.WYSIWYG = None Author.objects.create_user("user", "*****@*****.**", "password") Author.objects.create_superuser("admin", "*****@*****.**", "password")
def setUp(self): templates = { "dslforms/form.html": template_form, "dslforms/missing-form.html": template_missing_form, "dslforms/missing-display.html": template_missing_display, } setup_test_template_loader(templates)
def test_content_preview(self): template_to_use = "admin/zinnia/entry/preview.html" setup_test_template_loader({template_to_use: ""}) response = self.admin.content_preview(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEquals(response.context_data["preview"], "<p></p>") self.assertEquals(response["Content-Type"], "text/html; charset=utf-8")
def setUp(self): templates = { "email.html": EMAIL, "html-email.html": HTML_EMAIL, "multi-email.html": MULTI_EMAIL, } setup_test_template_loader(templates)
def test_zinnia_trackback(self): setup_test_template_loader({"404.html": ""}) response = self.client.post("/trackback/404/") self.assertEquals(response.status_code, 404) restore_template_loaders() self.assertEquals(self.client.post("/trackback/1/").status_code, 301) self.assertEquals(self.client.get("/trackback/1/").status_code, 301) entry = Entry.objects.get(slug="test-1") entry.pingback_enabled = False entry.save() self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>1</error>\n <message>Trackback is not enabled for " "Test 1</message>\n \n</response>\n", ) entry.pingback_enabled = True entry.save() with self.assertNumQueries(4): self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>0</error>\n \n</response>\n", ) self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>1</error>\n <message>Trackback is already registered" "</message>\n \n</response>\n", )
def test_comment_success(self): with self.assertNumQueries(0): response = self.client.get("/comments/success/") self.assertTemplateUsed(response, "comments/zinnia/entry/posted.html") self.assertEquals(response.context["comment"], None) with self.assertNumQueries(1): response = self.client.get("/comments/success/?c=42") self.assertEquals(response.context["comment"], None) comment = comments.get_model().objects.create( comment="My Comment 1", content_object=self.category, site=self.site, is_public=False ) setup_test_template_loader({"comments/zinnia/entry/posted.html": "", "zinnia/entry_list.html": ""}) with self.assertNumQueries(1): response = self.client.get("/comments/success/?c=1") self.assertEquals(response.context["comment"], comment) comment.is_public = True comment.save() with self.assertNumQueries(5): response = self.client.get("/comments/success/?c=1", follow=True) self.assertEquals( response.redirect_chain, [("http://testserver/comments/cr/13/1/#comment-1-by-", 301), ("http://example.com/categories/tests/", 302)], ) restore_template_loaders()
def test_zinnia_entry_detail_login_password(self): setup_test_template_loader( {'zinnia/entry_detail.html': '', 'zinnia/login.html': '', 'zinnia/password.html': ''}) entry = self.create_published_entry() entry.password = '******' entry.login_required = True entry.save() with self.assertNumQueries(4): response = self.client.get('/2010/01/01/my-test-entry/') self.assertTemplateUsed(response, 'zinnia/login.html') with self.assertNumQueries(11): response = self.client.post('/2010/01/01/my-test-entry/', {'username': '******', 'password': '******'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/password.html') self.assertEquals(response.context['error'], False) with self.assertNumQueries(6): response = self.client.post('/2010/01/01/my-test-entry/', {'entry_password': '******'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/entry_detail.html') restore_template_loaders()
def test_zinnia_category_list(self): setup_test_template_loader({"zinnia/category_list.html": ""}) self.check_publishing_context("/categories/", 1, friendly_context="category_list", queries=0) entry = Entry.objects.all()[0] entry.categories.add(Category.objects.create(title="New category", slug="new-category")) self.check_publishing_context("/categories/", 2) restore_template_loaders()
def test_wymeditor(self): template_to_use = 'admin/zinnia/entry/wymeditor.js' setup_test_template_loader({template_to_use: ''}) response = self.admin.wymeditor(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEqual(len(response.context_data['lang']), 2) self.assertEqual(response['Content-Type'], 'application/javascript')
def test_zinnia_trackback(self): setup_test_template_loader( {'404.html': ''}) response = self.client.post('/trackback/404/') self.assertEquals(response.status_code, 404) restore_template_loaders() self.assertEquals( self.client.post('/trackback/1/').status_code, 301) self.assertEquals( self.client.get('/trackback/1/').status_code, 301) entry = Entry.objects.get(slug='test-1') entry.pingback_enabled = False entry.save() self.assertEquals( self.client.post('/trackback/1/', {'url': 'http://example.com'}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' '<error>1</error>\n <message>Trackback is not enabled for ' 'Test 1</message>\n \n</response>\n') entry.pingback_enabled = True entry.save() with self.assertNumQueries(5): self.assertEquals( self.client.post('/trackback/1/', {'url': 'http://example.com'}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' '<error>0</error>\n \n</response>\n') self.assertEquals( self.client.post('/trackback/1/', {'url': 'http://example.com'}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' '<error>1</error>\n <message>Trackback is already registered' '</message>\n \n</response>\n')
def setUp(self): setup_test_template_loader({ "basic.html": "Basic", "block.html": "{% block short %}short{% endblock %} {% block long %}long{% endblock %}", "headline.html": "{{ headline }}", "has space.html": "Spaced", })
def test_zinnia_trackback(self): setup_test_template_loader({"404.html": ""}) response = self.client.post("/trackback/404/") self.assertEquals(response.status_code, 404) restore_template_loaders() self.assertEquals(self.client.post("/trackback/1/").status_code, 301) self.assertEquals(self.client.get("/trackback/1/").status_code, 301) entry = Entry.objects.get(slug="test-1") self.assertEquals(entry.trackback_count, 0) entry.trackback_enabled = False entry.save() self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>1</error>\n <message>Trackback is not enabled for " "Test 1</message>\n \n</response>\n", ) entry.trackback_enabled = True entry.save() connect_discussion_signals() get_user_flagger() # Memoize user flagger for stable query number with self.assertNumQueries(6): self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>0</error>\n \n</response>\n", ) disconnect_discussion_signals() entry = Entry.objects.get(pk=entry.pk) self.assertEquals(entry.trackback_count, 1) self.assertEquals( self.client.post("/trackback/1/", {"url": "http://example.com"}).content, '<?xml version="1.0" encoding="utf-8"?>\n<response>\n \n ' "<error>1</error>\n <message>Trackback is already registered" "</message>\n \n</response>\n", )
def test_comment_success(self): setup_test_template_loader( {'comments/zinnia/entry/posted.html': '', 'zinnia/entry_list.html': ''}) with self.assertNumQueries(0): response = self.client.get('/comments/success/') self.assertTemplateUsed(response, 'comments/zinnia/entry/posted.html') self.assertEquals(response.context['comment'], None) with self.assertNumQueries(1): response = self.client.get('/comments/success/?c=42') self.assertEquals(response.context['comment'], None) comment = comments.get_model().objects.create( comment='My Comment 1', content_object=self.category, site=self.site, is_public=False) with self.assertNumQueries(1): response = self.client.get('/comments/success/?c=1') self.assertEquals(response.context['comment'], comment) comment.is_public = True comment.save() with self.assertNumQueries(5): response = self.client.get('/comments/success/?c=1', follow=True) self.assertEquals( response.redirect_chain[1], ('http://example.com/categories/tests/', 302)) restore_template_loaders()
def test_content_preview(self): template_to_use = 'admin/zinnia/entry/preview.html' setup_test_template_loader({template_to_use: ''}) response = self.admin.content_preview(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEqual(response.context_data['preview'], '<p></p>') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_wymeditor(self): template_to_use = "admin/zinnia/entry/wymeditor.js" setup_test_template_loader({template_to_use: ""}) response = self.admin.wymeditor(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEquals(len(response.context_data["lang"]), 2) self.assertEquals(response["Content-Type"], "application/javascript")
def test_zinnia_entry_archive_year(self): setup_test_template_loader( {'zinnia/archives/2010/entry_archive_year.html': ''}) response = self.check_publishing_context('/2010/', 2, 3, 'entry_list') self.assertTemplateUsed( response, 'zinnia/archives/2010/entry_archive_year.html') restore_template_loaders()
def setUp(self): disconnect_entry_signals() disconnect_discussion_signals() # Clear the cache of user flagger to avoid error on MySQL get_user_flagger.cache_clear() # Use default URL shortener backend, to avoid networks errors self.original_shortener = shortener_settings.URL_SHORTENER_BACKEND shortener_settings.URL_SHORTENER_BACKEND = "zinnia.url_shortener." "backends.default" # Set up a stub around urlopen import zinnia.xmlrpc.pingback self.original_urlopen = zinnia.xmlrpc.pingback.urlopen zinnia.xmlrpc.pingback.urlopen = self.fake_urlopen # Set a short template for entry_detail to avoid rendering errors setup_test_template_loader( { "zinnia/entry_detail.html": "<html><head><title>{{ object.title }}</title></head>" "<body>{{ object.html_content|safe }}</body></html>", "404.html": "404", } ) # Preparing site self.site = Site.objects.get_current() # Creating tests entries self.author = Author.objects.create_user(username="******", email="*****@*****.**") self.category = Category.objects.create(title="test", slug="test") params = { "title": "My first entry", "content": "My first content", "slug": "my-first-entry", "creation_date": datetime(2010, 1, 1, 12), "status": PUBLISHED, } self.first_entry = Entry.objects.create(**params) self.first_entry.sites.add(self.site) self.first_entry.categories.add(self.category) self.first_entry.authors.add(self.author) params = { "title": "My second entry", "content": "My second content with link " 'to <a href="http://%s%s">first entry</a>' " and other links : %s %s." % ( self.site.domain, self.first_entry.get_absolute_url(), "http://example.com/error-404/", "http://external/", ), "slug": "my-second-entry", "creation_date": datetime(2010, 1, 1, 12), "status": PUBLISHED, } self.second_entry = Entry.objects.create(**params) self.second_entry.sites.add(self.site) self.second_entry.categories.add(self.category) self.second_entry.authors.add(self.author) # Instanciating the server proxy self.server = ServerProxy("http://example.com/xmlrpc/", transport=TestTransport())
def test_zinnia_tag_detail(self): setup_test_template_loader({"zinnia/tag/tests/entry_list.html": "", "404.html": ""}) response = self.check_publishing_context("/tags/tests/", 2, 3, "entry_list", 2) self.assertTemplateUsed(response, "zinnia/tag/tests/entry_list.html") self.assertEquals(response.context["tag"].name, "tests") response = self.client.get("/tags/404/") self.assertEquals(response.status_code, 404) restore_template_loaders()
def test_zinnia_entry_archive_index(self): template_name_today = 'zinnia/archives/%s/entry_archive.html' % \ date.today().strftime('%Y/%m/%d') setup_test_template_loader( {template_name_today: ''}) response = self.check_publishing_context('/', 2, 3, 'entry_list') self.assertTemplateUsed(response, template_name_today) restore_template_loaders()
def test_403_template(self): # Set up a test 403.html template. setup_test_template_loader({"403.html": "This is a test template for a 403 Forbidden error."}) try: response = self.client.get("/views/raises403/") self.assertContains(response, "test template", status_code=403) finally: restore_template_loaders()
def test_403(self): # Ensure no 403.html template exists to test the default case. setup_test_template_loader({}) try: response = self.client.get('/views/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) finally: restore_template_loaders()
def test_zinnia_tag_list(self): setup_test_template_loader({"zinnia/tag_list.html": ""}) self.check_publishing_context("/tags/", 1, friendly_context="tag_list", queries=1) entry = Entry.objects.all()[0] entry.tags = "tests, tag" entry.save() self.check_publishing_context("/tags/", 2) restore_template_loaders()
def test_zinnia_entry_random(self): setup_test_template_loader( {'zinnia/entry_detail.html': ''}) response = self.client.get('/random/', follow=True) self.assertTrue(response.redirect_chain[0][0].startswith( 'http://testserver/2010/')) self.assertEquals(response.redirect_chain[0][1], 302) restore_template_loaders()
def test_zinnia_category_detail(self): setup_test_template_loader( {'zinnia/category/tests/entry_list.html': ''}) response = self.check_publishing_context( '/categories/tests/', 2, 3, 'entry_list', 2) self.assertTemplateUsed( response, 'zinnia/category/tests/entry_list.html') self.assertEquals(response.context['category'].slug, 'tests') restore_template_loaders()
def test_zinnia_author_detail(self): setup_test_template_loader( {'zinnia/author/admin/entry_list.html': ''}) response = self.check_publishing_context( '/authors/admin/', 2, 3, 'entry_list', 2) self.assertTemplateUsed( response, 'zinnia/author/admin/entry_list.html') self.assertEquals(response.context['author'].username, 'admin') restore_template_loaders()
def test_zinnia_entry_archive_week(self): setup_test_template_loader({"zinnia/archives/2010/week/00/entry_archive_week.html": ""}) response = self.check_publishing_context("/2010/week/00/", 1, 2, "entry_list", 1) self.assertTemplateUsed(response, "zinnia/archives/2010/week/00/entry_archive_week.html") # All days in a new year preceding the first Monday # are considered to be in week 0. self.assertEquals(response.context["week"], date(2009, 12, 28)) self.assertEquals(response.context["week_end_day"], date(2010, 1, 3)) restore_template_loaders()
def setUp(self): templates = { "field.html": Template("{{ field }}"), "field-type.html": Template("{{ input_type }}"), "label.html": Template("{{ field.label }}"), "context.html": Template("{{ variable }}"), "kwargs.html": Template("{{ x }} {{ y }}"), } setup_test_template_loader(templates)
def test_zinnia_author_list(self): setup_test_template_loader({"zinnia/author_list.html": ""}) self.check_publishing_context("/authors/", 1, friendly_context="author_list", queries=0) user = Author.objects.create(username="******", email="*****@*****.**") self.check_publishing_context("/authors/", 1) entry = Entry.objects.all()[0] entry.authors.add(user) self.check_publishing_context("/authors/", 2) restore_template_loaders()
def setUp(self): disconnect_entry_signals() disconnect_discussion_signals() # Clean the memoization of user flagger to avoid error on MySQL try: del user_flagger_[()] except KeyError: pass # Use default URL shortener backend, to avoid networks errors self.original_shortener = shortener_settings.URL_SHORTENER_BACKEND shortener_settings.URL_SHORTENER_BACKEND = 'zinnia.url_shortener.'\ 'backends.default' # Set up a stub around urlopen import zinnia.xmlrpc.pingback self.original_urlopen = zinnia.xmlrpc.pingback.urlopen zinnia.xmlrpc.pingback.urlopen = self.fake_urlopen # Set a short template for entry_detail to avoid rendering errors setup_test_template_loader( {'zinnia/entry_detail.html': '<html><head><title>{{ object.title }}</title></head>' '<body>{{ object.html_content|safe }}</body></html>', '404.html': '404'}) # Preparing site self.site = Site.objects.get_current() # Creating tests entries self.author = Author.objects.create_user(username='******', email='*****@*****.**') self.category = Category.objects.create(title='test', slug='test') params = {'title': 'My first entry', 'content': 'My first content', 'slug': 'my-first-entry', 'creation_date': datetime(2010, 1, 1, 12), 'status': PUBLISHED} self.first_entry = Entry.objects.create(**params) self.first_entry.sites.add(self.site) self.first_entry.categories.add(self.category) self.first_entry.authors.add(self.author) params = {'title': 'My second entry', 'content': 'My second content with link ' 'to <a href="http://%s%s">first entry</a>' ' and other links : %s %s.' % ( self.site.domain, self.first_entry.get_absolute_url(), 'http://example.com/error-404/', 'http://external/'), 'slug': 'my-second-entry', 'creation_date': datetime(2010, 1, 1, 12), 'status': PUBLISHED} self.second_entry = Entry.objects.create(**params) self.second_entry.sites.add(self.site) self.second_entry.categories.add(self.category) self.second_entry.authors.add(self.author) # Instanciating the server proxy self.server = ServerProxy('http://example.com/xmlrpc/', transport=TestTransport())
def test_403_template(self): # Set up a test 403.html template. setup_test_template_loader( {'403.html': 'This is a test template for a 403 Forbidden error.'} ) try: response = self.client.get('/views/raises403/') self.assertContains(response, 'test template', status_code=403) finally: restore_template_loaders()
def test_zinnia_entry_detail_password(self): setup_test_template_loader({ 'zinnia/entry_detail.html': '', 'zinnia/password.html': '' }) entry = self.create_published_entry() entry.password = '******' entry.save() with self.assertNumQueries(1): response = self.client.get('/2010/01/01/my-test-entry/') self.assertTemplateUsed(response, 'zinnia/password.html') self.assertEquals(response.context['error'], False) with self.assertNumQueries(4): response = self.client.post('/2010/01/01/my-test-entry/', {'entry_password': '******'}) self.assertTemplateUsed(response, 'zinnia/password.html') self.assertEquals(response.context['error'], True) with self.assertNumQueries(5): response = self.client.post('/2010/01/01/my-test-entry/', {'entry_password': '******'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/entry_detail.html') restore_template_loaders()
def test_zinnia_category_detail_paginated(self): """Test case reproducing issue #42 on category detail view paginated""" setup_test_template_loader({'zinnia/entry_list.html': ''}) for i in range(PAGINATION): params = { 'title': 'My entry %i' % i, 'content': 'My content %i' % i, 'slug': 'my-entry-%i' % i, 'creation_date': datetime(2010, 1, 1), 'status': PUBLISHED } entry = Entry.objects.create(**params) entry.sites.add(self.site) entry.categories.add(self.category) entry.authors.add(self.author) response = self.client.get('/categories/tests/') self.assertEquals(len(response.context['object_list']), PAGINATION) response = self.client.get('/categories/tests/?page=2') self.assertEquals(len(response.context['object_list']), 2) response = self.client.get('/categories/tests/page/2/') self.assertEquals(len(response.context['object_list']), 2) self.assertEquals(response.context['category'].slug, 'tests') restore_template_loaders()
def test_templates(self): "Tests to make sure that embed behaves with complex includes and extends" template_tests = self.get_template_tests() # Register our custom template loader. Shamelessly cribbed from django/tests/regressiontests/templates/tests.py:384. cache_loader = setup_test_template_loader( dict([(name, t[0]) for name, t in template_tests.iteritems()]), use_cached_loader=True, ) failures = [] tests = template_tests.items() tests.sort() # Turn TEMPLATE_DEBUG off, because tests assume that. old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False # Set TEMPLATE_STRING_IF_INVALID to a known string. old_invalid = settings.TEMPLATE_STRING_IF_INVALID expected_invalid_str = 'INVALID' # Run tests for name, vals in tests: xx, context, result = vals try: test_template = loader.get_template(name) output = test_template.render(template.Context(context)) except Exception: exc_type, exc_value, exc_tb = sys.exc_info() if exc_type != result: tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb)) failures.append("Template test %s -- FAILED. Got %s, exception: %s\n%s" % (name, exc_type, exc_value, tb)) continue if output != result: failures.append("Template test %s -- FAILED. Expected %r, got %r" % (name, result, output)) # Cleanup settings.TEMPLATE_DEBUG = old_td settings.TEMPLATE_STRING_IF_INVALID = old_invalid restore_template_loaders() self.assertEqual(failures, [], "Tests failed:\n%s\n%s" % ('-'*70, ("\n%s\n" % ('-'*70)).join(failures)))
def setUp(self): templates = { "template.html": Template("content here"), } setup_test_template_loader(templates)
def setUpClass(cls): cls.context = Context({'form': TestForm()}) for key, tmpl in cls.PARTIALS.items(): cls.TEMPLATES[key] = cls.TEMPLATE_BASE.format(tmpl) setup_test_template_loader(cls.TEMPLATES)
def test_markitup(self): template_to_use = 'admin/zinnia/entry/markitup.js' setup_test_template_loader({template_to_use: ''}) response = self.admin.markitup(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEqual(response['Content-Type'], 'application/javascript')
def setUp(self): """We don't need to generate the full template to make the tests working""" super(ZinniaCustomDetailViews, self).setUp() setup_test_template_loader({'zinnia/entry_search.html': ''})
def test_zinnia_entry_channel(self): setup_test_template_loader({'zinnia/entry_list.html': ''}) self.check_publishing_context('/channel-test/', 2, 3, 'entry_list', 1) restore_template_loaders()
def test_autocomplete_tags(self): template_to_use = 'admin/zinnia/entry/autocomplete_tags.js' setup_test_template_loader({template_to_use: ''}) response = self.admin.autocomplete_tags(self.request) self.assertTemplateUsed(response, template_to_use) self.assertEquals(response['Content-Type'], 'application/javascript')
def setUp(self): templates = { "email.html": EMAIL, "missing.html": MISSING, } setup_test_template_loader(templates)
{% load pipejam %} {% block bs %} {% asset_ref "style1" %} {% asset_ref "angular" %} {% endblock %} ''', 'extends_outofblock': ''' {% extends 'base' %} {% load pipejam %} {% asset_ref "style1" %} {% asset_ref "angular" %} ''', } setup_test_template_loader(TEMPLATES) DEFAULT_SETTINGS = { 'STATIC_URL': '/static/', 'PIPEJAM_PROCESSORS': { 'js': { 'processor': 'pipejam.processors.PipelineScriptProcessor', }, 'css': { 'processor': 'pipejam.processors.PipelineStylesheetProcessor', 'type': 'text/css', }, }, 'PIPELINE_JS': { 'angular': { 'source_files': ('js/angular.js', ),
def inhibit_templates(self, *template_names): """ Set templates with no content to bypass the rendering time. """ setup_test_template_loader( dict(map(lambda x: (x, ''), template_names)))
def test_templates(self): from django.test.utils import setup_test_template_loader from django.test.utils import restore_template_loaders template_tests = self.get_template_tests() filter_tests = {} #filters.get_filter_tests() # Quickly check that we aren't accidentally using a name in both # template and filter tests. overlapping_names = [name for name in filter_tests if name in template_tests] assert not overlapping_names, 'Duplicate test name(s): %s' % ', '.join(overlapping_names) template_tests.update(filter_tests) cache_loader = setup_test_template_loader( dict([(name, t[0]) for name, t in template_tests.iteritems()]), use_cached_loader=True, ) failures = [] # Turn TEMPLATE_DEBUG off, because tests assume that. old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False # Set TEMPLATE_STRING_IF_INVALID to a known string. old_invalid = settings.TEMPLATE_STRING_IF_INVALID expected_invalid_str = 'INVALID' #Set ALLOWED_INCLUDE_ROOTS so that ssi works. old_allowed_include_roots = settings.ALLOWED_INCLUDE_ROOTS settings.ALLOWED_INCLUDE_ROOTS = ( os.path.dirname(os.path.abspath(__file__)), ) try: # Openblock: Original code copied from django regression tests # didn't have a try/finally block here, which meant any failure # below would cause failure to restore template loaders etc., # with disastrous effects for other test suites. tests = template_tests.items() tests.sort() # Warm the URL reversing cache. This ensures we don't pay the cost # warming the cache during one of the tests. urlresolvers.reverse('ebpub-homepage') for name, vals in tests: if isinstance(vals[2], tuple): normal_string_result = vals[2][0] invalid_string_result = vals[2][1] if isinstance(invalid_string_result, tuple): expected_invalid_str = 'INVALID %s' invalid_string_result = invalid_string_result[0] % invalid_string_result[1] template_base.invalid_var_format_string = True try: template_debug_result = vals[2][2] except IndexError: template_debug_result = normal_string_result else: normal_string_result = vals[2] invalid_string_result = vals[2] template_debug_result = vals[2] if 'LANGUAGE_CODE' in vals[1]: activate(vals[1]['LANGUAGE_CODE']) else: activate('en-us') for invalid_str, template_debug, result in [ ('', False, normal_string_result), (expected_invalid_str, False, invalid_string_result), ('', True, template_debug_result) ]: settings.TEMPLATE_STRING_IF_INVALID = invalid_str settings.TEMPLATE_DEBUG = template_debug for is_cached in (False, True): try: try: test_template = loader.get_template(name) except ShouldNotExecuteException: failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Template loading invoked method that shouldn't have been invoked." % (is_cached, invalid_str, template_debug, name)) try: output = self.render(test_template, vals) except ShouldNotExecuteException: failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Template rendering invoked method that shouldn't have been invoked." % (is_cached, invalid_str, template_debug, name)) except ContextStackException: failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Context stack was left imbalanced" % (is_cached, invalid_str, template_debug, name)) continue except Exception: exc_type, exc_value, exc_tb = sys.exc_info() if exc_type != result: tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb)) failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Got %s, exception: %s\n%s" % (is_cached, invalid_str, template_debug, name, exc_type, exc_value, tb)) continue if output != result: failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Expected %r, got %r" % (is_cached, invalid_str, template_debug, name, result, output)) cache_loader.reset() if 'LANGUAGE_CODE' in vals[1]: deactivate() if template_base.invalid_var_format_string: expected_invalid_str = 'INVALID' template_base.invalid_var_format_string = False finally: restore_template_loaders() deactivate() settings.TEMPLATE_DEBUG = old_td settings.TEMPLATE_STRING_IF_INVALID = old_invalid settings.ALLOWED_INCLUDE_ROOTS = old_allowed_include_roots self.assertEqual(failures, [], "Tests failed:\n%s\n%s" % ('-'*70, ("\n%s\n" % ('-'*70)).join(failures)))
def setUp(self): disconnect_entry_signals() disconnect_discussion_signals() # Clear the cache of user flagger to avoid error on MySQL get_user_flagger.cache_clear() # Use default URL shortener backend, to avoid networks errors self.original_shortener = shortener_settings.URL_SHORTENER_BACKEND shortener_settings.URL_SHORTENER_BACKEND = 'zinnia.url_shortener.'\ 'backends.default' # Set up a stub around urlopen import zinnia.xmlrpc.pingback self.original_urlopen = zinnia.xmlrpc.pingback.urlopen zinnia.xmlrpc.pingback.urlopen = self.fake_urlopen # Set a short template for entry_detail to avoid rendering errors setup_test_template_loader({ 'zinnia/entry_detail.html': '<html><head><title>{{ object.title }}</title></head>' '<body>{{ object.html_content|safe }}</body></html>', '404.html': '404' }) # Preparing site self.site = Site.objects.get_current() # Creating tests entries self.author = Author.objects.create_user(username='******', email='*****@*****.**') self.category = Category.objects.create(title='test', slug='test') params = { 'title': 'My first entry', 'content': 'My first content', 'slug': 'my-first-entry', 'creation_date': datetime(2010, 1, 1, 12), 'status': PUBLISHED } self.first_entry = Entry.objects.create(**params) self.first_entry.sites.add(self.site) self.first_entry.categories.add(self.category) self.first_entry.authors.add(self.author) params = { 'title': 'My second entry', 'content': 'My second content with link ' 'to <a href="http://%s%s">first entry</a>' ' and other links : %s %s.' % (self.site.domain, self.first_entry.get_absolute_url(), 'http://example.com/error-404/', 'http://external/'), 'slug': 'my-second-entry', 'creation_date': datetime(2010, 1, 1, 12), 'status': PUBLISHED } self.second_entry = Entry.objects.create(**params) self.second_entry.sites.add(self.site) self.second_entry.categories.add(self.category) self.second_entry.authors.add(self.author) # Instanciating the server proxy self.server = ServerProxy('http://example.com/xmlrpc/', transport=TestTransport())