def form_valid(self, form): if form.instance.target_date <= timezone.now(): return render(self.request, 'coplay/message.html', {'message': 'תאריך היעד חייב להיות בעתיד' + str( form.instance.target_date), 'rtl': 'dir="rtl"'}) form.instance.parent = self.discussion form.instance.responsible = self.request.user resp = super(CreateTaskView, self).form_valid(form) form.instance.parent.unlock() t = Template(""" {{task.responsible.get_full_name|default:task.responsible.username}} הבטיח/ה ש :\n "{{task.goal_description}} "\n עד {{task.target_date | date:"d/n/Y H:i"}} """) trunkated_subject_and_detailes = t.render(Context({"task": form.instance})) discussion_task_email_updates(form.instance, trunkated_subject_and_detailes, self.request.user, trunkated_subject_and_detailes) self.discussion.start_follow(self.request.user) return resp
def test_custom_bound_field(): from django.forms.boundfield import BoundField extra = 'xyxyxyxyxyx' class CustomBoundField(BoundField): @property def auto_id(self): return extra class MyCharField(forms.CharField): def get_bound_field(self, form, field_name): return CustomBoundField(form, self, field_name) class MyForm(forms.Form): f = MyCharField() def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout('f') template = Template('{% load crispy_forms_tags %}\n{% crispy form "bootstrap3" %}') rendered = template.render(Context({'form': MyForm(data={'f': 'something'})})) assert extra in rendered
def test_cached_show_placeholder_preview(self): from django.core.cache import cache cache.clear() page = create_page('Test', 'col_two.html', 'en', published=True) placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='<b>Test</b>') request = RequestFactory().get('/') user = User(username="******", password="******", is_superuser=True, is_staff=True, is_active=True) user.save() request.current_page = page.publisher_public request.user = user template = Template( "{% load cms_tags %}{% show_placeholder slot page 'en' 1 %}") context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) with self.assertNumQueries(5): output = template.render(context) self.assertIn('<b>Test</b>', output) add_plugin(placeholder, TextPlugin, 'en', body='<b>Test2</b>') request = RequestFactory().get('/?preview') request.current_page = page request.user = user context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) with self.assertNumQueries(5): output = template.render(context) self.assertIn('<b>Test2</b>', output)
def render_and_email(to_list, subject, text_template = None, html_template = None, context_dic = None): ''' This method gets a list of recipients, a subject text, text_template (for showing in web readers and mobile apps), an HTML_template for displaying in browsers and a context dictionary, renders templates with context and sends an email. Note that if text_template is a filename, method loads it, otherwise uses it as string (And same for html_template). ''' from_email = '*****@*****.**' context = Context(context_dic) if text_template: try: plaintext = get_template(text_template) except: plaintext = Template(text_template) text_content = plaintext.render(context) else: text_content = '(EMPTY)' msg = EmailMultiAlternatives(subject, text_content, from_email, to_list) if html_template: try: htmly = get_template(html_template) except: htmly = Template(html_template) html_content = htmly.render(context) msg.attach_alternative(html_content, "text/html") msg.send()
def conflict(request, target=None, template_name='409.html'): """ 409 error handler. Templates: :template:`409.html` Context: target The model to save saved The object stored in the db that produce the conflict or None if not found (ie. deleted) request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: template = Template( '<h1>Conflict</h1>' '<p>The request was unsuccessful due to a conflict. ' 'The object changed during the transaction.</p>') try: saved = target.__class__.objects.get(pk=target.pk) except target.__class__.DoesNotExists: saved = None ctx = RequestContext(request, {'target': target, 'saved': saved, 'request_path': request.path}) return ConflictResponse(template.render(ctx))
def test_render_model_add_block(self): from django.core.cache import cache from cms.test_utils.project.sampleapp.models import Category cache.clear() page = create_page('Test', 'col_two.html', 'en', published=True) template = Template( "{% load cms_tags %}{% render_model_add_block category %}wrapped{% endrender_model_add_block %}") user = self._create_user("admin", True, True) request = RequestFactory().get('/') request.user = user request.current_page = page request.session = {} request.toolbar = CMSToolbar(request) request.toolbar.edit_mode = True request.toolbar.is_staff = True context = RequestContext(request, {'category': Category()}) with self.assertNumQueries(0): output = template.render(context) expected = 'cms_plugin cms_plugin-sampleapp-category-add-0 ' 'cms_render_model_add' self.assertIn(expected, output) # Now test that it does NOT render when not in edit mode request = RequestFactory().get('/') request.user = user request.current_page = page request.session = {} request.toolbar = CMSToolbar(request) context = RequestContext(request, {'category': Category()}) with self.assertNumQueries(0): output = template.render(context) expected = 'wrapped' self.assertEqual(expected, output)
def test_template_creation(self): self.assertObjectDoesNotExist(Stack.objects.all(), code='foobar') self.assertObjectDoesNotExist(Placeholder.objects.all(), slot='foobar') t = Template('{% load stack_tags %}{% stack "foobar" %}') t.render(self.get_context('/')) self.assertObjectExist(Stack.objects.all(), code='foobar', creation_method=Stack.CREATION_BY_TEMPLATE) self.assertObjectExist(Placeholder.objects.all(), slot='foobar')
def test_amp_in_link_with_class(self): page = Page(name='Explore') html = ('<p><a class="external something" ' 'href="http://example.org/?t=1&i=2">hi</a></p>') template = Template(html_to_template_text(html)) rendered = template.render(Context({'page': page})) self.failUnless('http://example.org/?t=1&i=2' in rendered)
def get_rendered(value): request = self.request_factory.get('/') t = Template(self.loadstatement + '{{ value|rendered|safe }}') c = Context({'value': value, 'request': request}) rendered = t.render(c) return rendered
def test_cached_show_placeholder_sekizai(self): from django.core.cache import cache cache.clear() from cms.test_utils import project User = get_user_model() template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates', 'show_placeholder') page = create_page('Test', 'col_two.html', 'en') placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN') request = RequestFactory().get('/') request.user = User() request.current_page = page with SettingsOverride(TEMPLATE_DIRS=[template_dir]): template = Template( "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}") context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output) context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output)
def get_random_question(exp, uuid): experiment = Experiment.objects.get(id=exp) questions = Question.objects.filter(experiment=experiment) question_template = Template(experiment.template.template) all_questions = len(questions) try: user = User.objects.get(uuid=uuid) questions = questions.exclude(answer__user=user) except: pass questions = questions.order_by('?') if len(questions) > 0: question = questions[0] question_data = question.question.split("\n") question_id = question.id question_text = question_template.render( Context({"question": question_data})) else: question_id = -1 question_text = "Finished!" return {"id": question_id, "text": question_text, "left": len(questions), "all": all_questions, "percent": (all_questions - len(questions)) * 100 / all_questions, "time": time()}
def test_raises_if_the_required_arguments_are_not_passed(self): # Setup request = self.request_factory.get('/') request.user = self.u1 ForumPermissionHandlerMiddleware().process_request(request) context = Context({'request': request}) templates = [ '{% get_permission \'can_download_files\' request.user as user_can_download_files %}' '{% if user_can_download_files %}CAN_DOWNLOAD{% else %}CANNOT_DOWNLOAD{% endif %}', '{% get_permission \'can_edit_post\' request.user as user_can_edit_post %}' '{% if user_can_edit_post %}CAN_EDIT{% else %}CANNOT_EDIT{% endif %}', '{% get_permission \'can_edit_post\' request.user as user_can_edit_post %}' '{% if user_can_edit_post %}CAN_EDIT{% else %}CANNOT_EDIT{% endif %}', '{% get_permission \'can_add_post\' request.user as user_can_add_post %}' '{% if user_can_add_post %}CAN_ADD_POST{% else %}CANNOT_ADD_POST{% endif %}', '{% get_permission \'can_vote_in_poll\' request.user as user_can_vote_in_poll %}' '{% if user_can_vote_in_poll %}CAN_VOTE{% else %}CANNOT_VOTE{% endif %}', ] # Run & check for raw_template in templates: t = Template(self.loadstatement + raw_template) with pytest.raises(TypeError): t.render(context)
def update_task_status_description( task , description, user, result_picture = None): if user is None: return None, 'no user provided' if description is None: return None, 'no description' if user != task.responsible: return None, 'only the responsible can update the description' poll_for_task_complition( task) if( task.final_state): return None, 'target date passed' task.status_description = description task.result_picture = result_picture task.save() task.parent.save()#verify that the entire disscusion is considered updated t = Template(""" {{task.responsible.get_full_name|default:task.responsible.username}} הודיע/ה ש :\n "{{task.get_status_description}} "\n """) trunkated_subject_and_detailes = t.render(Context({"task": task})) discussion_task_email_updates(task, trunkated_subject_and_detailes, user, trunkated_subject_and_detailes) return task, None
def send_notification(email, context, settings_value, subject): notification_template = Template(get_settings_value(settings_value)) notification_context = context message = notification_template.render(notification_context) subject = subject to = [email] send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to, True)
def test_compiled_file_already_exists_file_is_not_written_again(self): template = Template(""" {% load coldbrew %} {% coffeescript "scripts/test-already-exists.coffee" %} """) # Render it once. compiled_filename = template.render(RequestContext({})).strip() first_access = os.path.getatime("%s/%s" % (settings.STATIC_ROOT, compiled_filename)) # ...and delete it. os.remove("%s/%s" % (settings.STATIC_ROOT, compiled_filename)) # Now render it agian. compiled_filename_again = template.render(RequestContext({})).strip() second_access = os.path.getatime("%s/%s" % (settings.STATIC_ROOT, compiled_filename_again)) # The file will have been accessed again. self.assertGreater(second_access, first_access) # Render it a third time - this time the file will already exist. compiled_filename_yet_again = template.render(RequestContext({})).strip() third_access = os.path.getatime("%s/%s" % (settings.STATIC_ROOT, compiled_filename_yet_again)) # Since the file already existed, we won't have written again self.assertEqual(third_access, second_access) # ...and finally delete the file now that the test is over. os.remove("%s/%s" % (settings.STATIC_ROOT, compiled_filename_yet_again))
def conflict(request, target=None, template_name='409.html'): """409 error handler. :param request: Request :param template_name: `409.html` :param target: The model to save """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: template = Template( '<h1>Conflict</h1>' '<p>The request was unsuccessful due to a conflict. ' 'The object changed during the transaction.</p>') try: saved = target.__class__._default_manager.get(pk=target.pk) except target.__class__.DoesNotExist: saved = None ctx = {'target': target, 'saved': saved, 'request_path': request.path} return ConflictResponse(template.render(ctx))
def tag_simple_page(context, *args, **kwargs): #collect params template_name = kwargs.get('template_name', 'common/tag_simple_page.html') position_nav_mask = kwargs.get('position_nav_mask', 15) position_content_mask = kwargs.get('position_content_mask', 15) extra_pos = kwargs.get('extra_pos', 0) #old versionget('extra_pos', 0) la = len(args) if la > 0: position_content_mask = args[0] if la > 1: position_nav_mask = args[1] if la > 2 and len(args[2]) > 0: template_name = args[2] if la > 3: extra_pos = args[3] request = context['request'] sps = [] if hasattr(request, 'simple_page') and request.simple_page: for sp in request.simple_page: if sp.position_nav & position_nav_mask > 0 and sp.position_content & position_content_mask > 0 and sp.extra_pos == extra_pos: if sp.is_content_template: t = Template(sp.content) c = Context(context) sp.content = t.render(c) sps.append(sp) return render_to_string(template_name, {'sps': sps}, context_instance=context)
def test_direct_embed_tag(self): template = Template(""" {% load embed_video_tags %} {% video "http://www.youtube.com/watch?v=jsrRJyHBvzw" "large" %} """) rendered = u'<iframe width="960" height="720" src="http://www.youtube.com/embed/jsrRJyHBvzw?wmode=opaque" frameborder="0" allowfullscreen></iframe>' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_can_render_a_list_of_forums_according_to_their_minimum_tree_level(self): # Setup forums = Forum.objects.all() request = self.request_factory.get('/') middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.user = self.user ForumPermissionMiddleware().process_request(request) t = Template(self.loadstatement + '{% forum_list forums %}') c = Context({'forums': forums, 'request': request}) expected_out = render_to_string( 'machina/forum/forum_list.html', { 'forums': forums, 'user': self.user, 'root_level': 0, 'root_level_middle': 1, 'root_level_sub': 2, } ) # Run rendered = t.render(c) # Check assert rendered != '' assert rendered == expected_out
def render_text(self): """Return the text rendering if the filetype is md or txt""" if self.get_email_type() == 'html': return None template = Template(self.get_template()) return template.render(Context(self.payload))
def user_follow_start_email_updates(follower_user, following_user, inverse_following): t = Template(""" {{follower_user.get_full_name|default:follower_user.username}} התחיל/ה לעקוב אחרי פתיחת הפעילויות שלך """) subject = t.render(Context({"follower_user": follower_user})) html_message = render_to_string("coplay/user_follow_email_update.html", {'ROOT_URL': kuterless.settings.SITE_URL, 'follower_user': follower_user, 'html_title': string_to_email_subject(subject), 'details': subject, 'inverse_following': inverse_following}) # with open( "output.html" , "w") as debug_file: # debug_file.write(html_message) if following_user.email != None: send_html_message(subject, html_message, '*****@*****.**', [following_user.email])
def update_task_description(request, pk): if request.method == 'POST': # If the form has been submitted... form = UpdateTaskForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data# Process the data in form.cleaned_data try: task = Task.objects.get(id=int(pk)) except Task.DoesNotExist: return HttpResponse('Task not found') user = request.user if user == task.responsible: task.update_status_description( form.cleaned_data['status_description']) t = Template(""" {{task.responsible.get_full_name|default:task.responsible.username}} הודיע/ה ש :\n "{{task.get_status_description}} "\n """) trunkated_subject_and_detailes = t.render(Context({"task": task})) discussion_task_email_updates(task, trunkated_subject_and_detailes, request.user, trunkated_subject_and_detailes) return HttpResponseRedirect( task.get_absolute_url()) # Redirect after POST return HttpResponseRedirect('coplay_root') # Redirect after POST
def user_follow_start_email_updates(follower_user, following_user, inverse_following): t = Template(""" {{follower_user.get_full_name|default:follower_user.username}} התחיל/ה לעקוב אחרי פתיחת הפעילויות שלך """) subject = t.render(Context({"follower_user": follower_user})) html_message = render_to_string("coplay/user_follow_email_update.html", {'ROOT_URL': kuterless.settings.SITE_URL, 'follower_user': follower_user, 'html_title': string_to_email_subject(subject), 'details': subject, 'inverse_following': inverse_following}) # with open( "output.html" , "w") as debug_file: # debug_file.write(html_message) if following_user.email != None and following_user.userprofile.recieve_updates: send_html_message(subject, html_message, '*****@*****.**', [following_user.email]) post_update_to_user(following_user.id, header = string_to_email_subject(subject), content = subject, sender_user_id = follower_user.id, details_url = reverse('coplay:user_coplay_report', kwargs={'username': follower_user}))
def test_lookup_in_staticfiles_dirs(self): template = Template(""" {% load less %} {% less "another_test.less" %} """) compiled_filename_re = re.compile(r"LESS_CACHE/another_test-[a-f0-9]{12}.css") compiled_filename = template.render(self._get_request_context()).strip() self.assertTrue(bool(compiled_filename_re.match(compiled_filename))) compiled_path = os.path.join(self.django_settings.STATIC_ROOT, compiled_filename) compiled_content = open(compiled_path).read().strip() compiled = """#header-from-staticfiles-dir h1 { color: red; }""" self.assertEquals(compiled_content, compiled) template = Template(""" {% load less %} {% less "prefix/another_test.less" %} """) compiled_filename_re = re.compile(r"LESS_CACHE/prefix/another_test-[a-f0-9]{12}.css") compiled_filename = template.render(self._get_request_context()).strip() self.assertTrue(bool(compiled_filename_re.match(compiled_filename))) compiled_path = os.path.join(self.django_settings.STATIC_ROOT, compiled_filename) compiled_content = open(compiled_path).read().strip() compiled = """#header-from-staticfiles-dir-with-prefix h1 { color: red; }""" self.assertEquals(compiled_content, compiled)
def test_embed_whitelist_reject(self): html = ('<span class="plugin embed"><iframe src="http://evil.com"' '></iframe></span>') template = Template(html_to_template_text(html)) rendered = template.render(Context()) self.failUnless(('The embedded URL is not on the list of approved ' 'providers') in rendered)
def user_glimpsed_another_user_s_discussion( user, discussion , views_counter = 0): t = Template(""" {{user.get_full_name|default:user.username}} צפה/תה בפעילות שלך "{{discussion.title}}" בפעם ה {{views_counter}} """) # t = Template(""" # צפה/תה ב "{{discussion.title}}" בפעם ה {{views_counter}} # """) trunkated_subject_and_detailes = t.render(Context({"discussion": discussion, 'user': user, 'views_counter': views_counter})) mailing_list = [] mailing_list.append(discussion.owner) discussion_email_updates( discussion = discussion, subject = trunkated_subject_and_detailes, logged_in_user = user, details = trunkated_subject_and_detailes, url_id = '', mailing_list = mailing_list) user.account.deposit_and_return_transaction_if_ok( title = u"צפיה בפעילות של מישהו אחר", positive_item_price = 2, url = discussion.get_absolute_url())
def test_cached_show_placeholder_sekizai(self): from django.core.cache import cache cache.clear() from cms.test_utils import project template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates', 'show_placeholder') page = create_page('Test', 'col_two.html', 'en') placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN') request = RequestFactory().get('/') request.user = self.get_staff_user_with_no_permissions() request.current_page = page if DJANGO_1_7: override = {'TEMPLATE_DIRS': [template_dir], 'CMS_TEMPLATES': []} else: override = {'TEMPLATES': deepcopy(settings.TEMPLATES)} override['TEMPLATES'][0]['DIRS'] = [template_dir] with self.settings(**override): template = Template( "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}") context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output) context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output)
def render_html(self): """Return rendered HTML if the email is html or md""" if self.get_email_type() not in ['html', 'md']: return None # render content and fix urls/emails template = self.get_template() template = Template(template) template = template.render(Context(self.payload)) if not self.urls_resolved: template = self.fix_urls(template) if self.get_email_type() == 'md': template = markdown(template) self.payload['site'] = Site.objects.get_current() if not self.use_base_template: return template base_template = ( "{{% extends '{base_template}' %}}{{% block {block_name} %}}\n" "{template}\n" "{{% endblock %}}" ).format( base_template=settings.EMAILMELD_BASE_TEMPLATE, block_name="content", template=template, ) base_template = Template(base_template) base_template = base_template.render(Context(self.payload)) return base_template
def render(self, context): filepath = self.filepath if not self.legacy_filepath: filepath = filepath.resolve(context) if not include_is_allowed(filepath): if settings.DEBUG: return "[Didn't have permission to include file]" else: return '' # Fail silently for invalid includes. try: fp = open(filepath, 'r') output = fp.read() fp.close() except IOError: output = '' if self.parsed: try: t = Template(output, name=filepath) return t.render(context) except TemplateSyntaxError, e: if settings.DEBUG: return "[Included template had syntax error: %s]" % e else: return '' # Fail silently for invalid included templates.
def render_to_response(self, context, **response_kwargs): if self.template_string: context = RequestContext(self.request, context) template = Template(self.template_string) return HttpResponse(template.render(context)) else: return super(ClassDetail, self).render_to_response(context, **response_kwargs)
def test_embed_whitelist_accept(self): html = ('<span class="plugin embed"><iframe ' 'src="http://www.youtube.com/embed/JVRsWAjvQSg"' '></iframe></span>') template = Template(html_to_template_text(html)) rendered = template.render(Context()) self.failUnless( '<iframe src="http://www.youtube.com/embed/JVRsWAjvQSg"></iframe>' in rendered)
def get_message(self, context): ''' Build response message with passed context :param context: required an obj instance to display information {user} and {reply_to} to generate correct response :return: ''' t = Template(self.message) return t.render(Context(context))
def test_tag_backend_variable_soundcloud(self): template = Template(""" {% load embed_video_tags %} {% video 'https://soundcloud.com/glassnote/mumford-sons-i-will-wait' as soundcloud %} {{ soundcloud.backend }} {% endvideo %} """) rendered = 'SoundCloudBackend' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_tag_backend_variable_youtube(self): template = Template(""" {% load embed_video_tags %} {% video 'http://www.youtube.com/watch?v=jsrRJyHBvz' as youtube %} {{ youtube.backend }} {% endvideo %} """) rendered = 'YoutubeBackend' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_tag_backend_variable_vimeo(self): template = Template(""" {% load embed_video_tags %} {% video 'https://vimeo.com/72304002' as vimeo %} {{ vimeo.backend }} {% endvideo %} """) rendered = 'VimeoBackend' self.assertEqual(template.render(self._grc()).strip(), rendered)
def send(self, email, context={}): template = Template(self.body) message = EmailMessage(self.subject, template.render(Context(context)), from_email=config.email, to=[email], bcc=[config.email], headers={'Reply-To': config.email}) message.send()
def get_rendered(poll, user): request = self.request_factory.get('/') request.user = user t = Template(self.loadstatement + '{% if poll|has_been_completed_by:request.user %}' 'HAS_VOTED{% else %}HAS_NOT_VOTED{% endif %}') c = Context({'poll': poll, 'request': request}) rendered = t.render(c) return rendered
def test_missing_required_perm_arguments(self): tmpl = """ {% if perm.permitter_test.CanEditObject %} fail {% endif %} """ req = HttpRequest() req.user = User() tmpl, ctx = Template(tmpl), RequestContext(req) self.assertRaises(KeyError, lambda: tmpl.render(ctx))
def test_user_size(self): template = Template(""" {% load embed_video_tags %} {% video 'http://www.youtube.com/watch?v=jsrRJyHBvzw' as ytb %} {% video ytb '800x800' %} {% endvideo %} """) rendered = u'''<iframe width="800" height="800" src="http://www.youtube.com/embed/jsrRJyHBvzw?wmode=opaque" frameborder="0" allowfullscreen></iframe>''' self.assertEqual(template.render(self._grc()).strip(), rendered)
def get_rendered(topics, user): request = self.get_request() request.user = user ForumPermissionMiddleware().process_request(request) t = Template( self.loadstatement + '{% get_unread_topics topics request.user as unread_topics %}') c = Context({'topics': topics, 'request': request}) rendered = t.render(c) return c, rendered
def test_tag_vimeo(self): template = Template(""" {% load embed_video_tags %} {% video 'https://vimeo.com/72304002' as vimeo %} {{ vimeo.url }} {% endvideo %} """) rendered = 'http://player.vimeo.com/video/72304002' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_tag_youtube(self): template = Template(""" {% load embed_video_tags %} {% video 'http://www.youtube.com/watch?v=jsrRJyHBvzw' as ytb %} {{ ytb.url }} {% endvideo %} """) rendered = 'http://www.youtube.com/embed/jsrRJyHBvzw?wmode=opaque' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_link_to_tag(self): a = Page(name='Front Page', region=self.region) a.content = (u'<a href="tags/cats">dummy</a>') a.save() context = Context({'page': a, 'region': self.region}) template = Template(html_to_template_text(a.content, context)) html = template.render(context) self.assertEqual(html, u'<a href="tags/cats" class="tag_link">dummy</a>')
def test_inclusion_tag4(self): ''' Test the show_es_gene_section tag - given a range on a sequence ''' t = Template('{% load gene_tags %}' + '{% show_es_gene_section seqid=seqid ' + 'start_pos=start_pos end_pos=end_pos%}') context = {'seqid': '1', 'start_pos': 2431888, 'end_pos': 2880054} c = Context(context) rendered = t.render(c) self.assertIn("PANK4", rendered)
def test_inclusion_tag2(self): ''' Test the show_es_gene_section tag - given a gene symbol ''' t = Template('{% load gene_tags %}' + '{% show_es_gene_section gene_symbol=gene %}') context = {'gene': 'PTPN22'} c = Context(context) rendered = t.render(c) self.assertIn("PTPN22", rendered) self.assertIn("9652", rendered) self.assertIn("protein_coding", rendered)
def _template_render_and_send(subject, source, user, screenName, new_username): t = Template(source) body = t.render( Context({ 'user': user, 'screenName': screenName, 'new_username': new_username, })) mail_services.plain_send_mail(user.email, subject, body, settings.ADMAIL_FROM_EMAIL)
def test_embed(self): template = Template(""" {% load embed_video_tags %} {% video 'http://www.youtube.com/watch?v=jsrRJyHBvzw' as ytb %} {{ ytb|embed:'large' }} {% endvideo %} """) rendered = '<iframe width="960" height="720" src="http://www.youtube.com/embed/jsrRJyHBvzw?wmode=opaque" frameborder="0" allowfullscreen></iframe>' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_tag_youtube_with_query(self): # Test KEY=VALUE arguments when used as a tag block. template = Template(""" {% load embed_video_tags %} {% video 'http://www.youtube.com/watch?v=jsrRJyHBvzw' rel=0 as ytb %} {{ ytb.url }} {% endvideo %} """) rendered = 'http://www.youtube.com/embed/jsrRJyHBvzw?wmode=opaque&rel=0' self.assertEqual(template.render(self._grc()).strip(), rendered)
def test_can_provide_the_last_post_of_a_forum(self): # Setup t = Template(self.loadstatement + '{% get_forum_last_post forum user as var %}') c = Context({'forum': self.forum_1, 'user': self.user}) # Run rendered = t.render(c) # Check assert rendered == '' assert c['var'] == self.post_1
def _add_css_styles(self, epub_book): """Adds default css styles and custom css text if exists in config""" book_css = [] try: epub_book.add_item( ebooklib.epub.EpubItem( uid='default.css', content=self._get_default_style(), file_name='{}/{}'.format(STYLES_DIR, 'default.css'), media_type='text/css' ) ) book_css.append('default.css') except Exception as e: logger.info('Default style was not added %s.', e) if self.theme_name: content = self._get_theme_style() if self.theme_name == 'custom': try: data = json.loads(self.config['theme']['custom'].encode('utf8')) tmpl = Template(content) content = tmpl.render(data) except: logger.exception("Fails with custom theme.") item = ebooklib.epub.EpubItem( uid='theme.css', content=content, file_name='{}/{}'.format(STYLES_DIR, 'theme.css'), media_type='text/css' ) epub_book.add_item(item) book_css.append('theme.css') # we need to add css from publishing settings screen settings_style = self.config.get('settings', {}).get('styling', None) if settings_style: item = ebooklib.epub.EpubItem( uid='custom_style.css', content=settings_style, file_name='{}/{}'.format(STYLES_DIR, 'custom_style.css'), media_type='text/css' ) epub_book.add_item(item) book_css.append('custom_style.css') return book_css
def test_inclusion_tag3(self): ''' Test the show_es_gene_section tag - given a position on a sequence ''' t = Template('{% load gene_tags %}' + '{% show_es_gene_section seqid=seqid start_pos=pos %}') context = {'seqid': '1', 'pos': 113813811} c = Context(context) rendered = t.render(c) self.assertIn("PTPN22", rendered) self.assertIn("9652", rendered) self.assertIn("protein_coding", rendered)
def test_endless_include(self): """ Should detect endless loops and give an error message """ a = Page(name='Front Page') a.content = '<a class="plugin includepage" href="Front_Page">dummy</a>' a.save() context = Context({'page': a}) template = Template(html_to_template_text(a.content, context)) html = template.render(context) self.failUnless(('Unable to include <a href="/Front_Page">Front Page' '</a>: endless include loop') in html)
def test_template_creation(self): self.assertObjectDoesNotExist(StaticPlaceholder.objects.all(), code='foobar') self.assertObjectDoesNotExist(Placeholder.objects.all(), slot='foobar') t = Template('{% load cms_tags %}{% static_placeholder "foobar" %}') t.render(self.get_context('/')) self.assertObjectExist( StaticPlaceholder.objects.all(), code='foobar', creation_method=StaticPlaceholder.CREATION_BY_TEMPLATE) self.assertEqual(Placeholder.objects.filter(slot='foobar').count(), 2)
def test_inline_coffeescript(self): template = Template(""" {% load coldbrew %} {% inlinecoffeescript %}console.log "Hello, World" {% endinlinecoffeescript %} """) hopeful_result = u"""(function() {\n console.log("Hello, World");\n }).call(this);""" actual_result = template.render(RequestContext({})).strip() self.assertEqual(actual_result, hopeful_result)
def test_single_page_template(self): for x in range(0, self.perpage): get_user_model().objects.create(username="******" % x) paginator = Paginator(get_user_model().objects.all(), per_page=self.perpage) t = Template('{% load pagination %}{% pagination page_obj %}') c = Context({"page_obj": paginator.page(1)}) output = t.render(c) regex = re.compile(r'^\s*$', re.MULTILINE) self.assertRegexpMatches(output, regex)
def test_local(self): self.assertObjectDoesNotExist(StaticPlaceholder.objects.all(), code='foobar') self.assertObjectDoesNotExist(Placeholder.objects.all(), slot='foobar') t = Template('{% load cms_tags %}{% static_placeholder "foobar" site or %}No Content{% endstatic_placeholder %}') rendered = t.render(self.get_context('/')) self.assertIn("No Content", rendered) for p in Placeholder.objects.all(): add_plugin(p, 'TextPlugin', 'en', body='test') rendered = t.render(self.get_context('/')) self.assertNotIn("No Content", rendered) self.assertEqual(StaticPlaceholder.objects.filter(site_id__isnull=False, code='foobar').count(), 1)
def test_include_nonexistant(self): """ Should give an error message when including nonexistant page """ a = Page(name='Front Page') a.content = '<a class="plugin includepage" href="New page">dummy</a>' a.save() context = Context({'page': a}) template = Template(html_to_template_text(a.content, context)) html = template.render(context) self.failUnless(('Unable to include <a href="/New_page"' ' class="missing_link">New page</a>') in html)
def get_rendered(post, user): request = self.get_request() request.user = user t = Template( self.loadstatement + '{% if post|posted_by:request.user %}OWNER{% else %}NO_OWNER{% endif %}' ) c = Context({'post': post, 'request': request}) rendered = t.render(c) return rendered
def test_can_translate_a_given_url_in_another_language(self): # Setup url = reverse('public:journal:journal_list') request = self.factory.get(url) request.resolver_match = resolve(url) t = Template(self.loadstatement + '{% trans_current_url "en" %}') c = Context({'request': request}) # Run rendered = t.render(c) # Check self.assertEqual(rendered, '/en/journals/')