Django inclusion tag works with the dev server but fails tests

168 Views Asked by At

I'm trying to implement JSON-LD metadata for my blog site based using a template tag:

@register.inclusion_tag('common_content/json-ld.html', takes_context=True)
def page_json_ld(context):
    """
    Renders JSON-LD for a page

    :param context: parent template context
    :type context: dict
    :return: context for json-ld template
    :rtype: dict
    """
    site_url = '{}://{}'.format(
        context['request'].scheme,
        context['request'].get_host()
    )
    json_ld = {
        '@context': 'http://schema.org',
        '@type': 'WebPage',
        'name': context['menu_link'].page.title,
        'url': site_url + context['request'].path,
        'description': context['menu_link'].page.meta_description,
        'image': {
            '@type': 'imageObject',
            'url': site_url + context['menu_link'].page.featured_image.url,
            'height': context['menu_link'].page.featured_image.height,
            'width': context['menu_link'].page.featured_image.width
        },
    }
    return {'json_ld': json.dumps(json_ld, indent=2)}

json-ld.html template:

<script type="application/ld+json">
{{ json_ld|safe }}
</script>

Here are models.py for my pages app that I'm trying to implement JSON-LD for:

from django.db import models
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from tinymce import models as tinymce
from filebrowser.fields import FileBrowseField


class Page(models.Model):
    """
    Represents a rich-text page that is not a blog post, e.g 'About me'
    """
    title = models.CharField(verbose_name=_('Page Title'), max_length=200)
    keywords = models.CharField(verbose_name=_('Keywords'), max_length=200, blank=True)
    content = tinymce.HTMLField(verbose_name=_('Page Content'))
    last_updated = models.DateTimeField(verbose_name=_('Last Updated'), auto_now=True)
    featured_image = FileBrowseField(verbose_name=_('Featured Image'), max_length=1024,
                                     extensions=['.jpg', '.jpeg', '.png'], blank=True)
    meta_description = models.TextField(verbose_name=_('Description'), max_length=160, blank=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = _('Page')
        #Translators: General plural without a number
        verbose_name_plural = _('Pages')
        ordering = ('title',)


class MenuLinkQuerySet(models.QuerySet):
    """Custom QuerySet for MenuLinks"""
    def have_pages(self):
        """Get MenuLinks that have attached pages"""
        return self.filter(page__isnull=False)


class MenuLink(models.Model):
    """
    Represents a link in the site navigation menu
    """
    caption = models.CharField(verbose_name=_('Caption'), max_length=200)
    slug = models.SlugField(verbose_name=_('Slug'), max_length=200, unique=True)
    page = models.ForeignKey(Page, verbose_name=_('Page'), blank=True, null=True)
    show_side_panel = models.BooleanField(verbose_name=_('Show side Panel'), default=False)
    position = models.PositiveIntegerField(verbose_name=_('Position'), default=0, blank=False, null=False)
    objects = MenuLinkQuerySet.as_manager()

    def get_absolute_url(self):
        return reverse('pages:page', kwargs={'slug': self.slug})

    def __str__(self):
        return self.caption

    class Meta:
        verbose_name = _('Menu Link')
        verbose_name_plural = _('Menu Links')
        ordering = ('position',)

As you can see, I'm usig FileBrowseField from django-filebrowser to add a featured image for a page.

All this works as expected with Django developement server (manage.py runserver), i.e. a page is displayed in a browser and JSON-LD is rendered correctly. But when I try to run a test for the respective view, it fails with the following reason:

 File "/home/roman/Projects/romans_blog/pages/templatetags/pages_tags.py", line 45, in page_json_ld
    'url': site_url + context['menu_link'].page.featured_image.url,
AttributeError: 'str' object has no attribute 'url'

The test case that fails:

from django.core.urlresolvers import reverse
from django.test import TestCase
from .models import Page, MenuLink


class PageViewTestCase(TestCase):
    def test_opening_page_view(self):
        page = Page(title='Lorem Ipsum', content='<b>Lorem ipsum dolor sit amet.</b>')
        page.save()
        link1 = MenuLink(caption='Page 1', slug='page-1', page=page)
        link1.save()
        link2 = MenuLink(caption='Page 2', slug='page-2')
        link2.save()
        response = self.client.get(reverse('pages:page', kwargs={'slug': 'page-1'}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Lorem ipsum dolor sit amet.')
        response = self.client.get(reverse('pages:page', kwargs={'slug': 'page-2'}))
        self.assertEqual(response.status_code, 404)

So the question is: why does the same code behave differently in the dev server and the test runner? That is, why does page.featured_image field has correct type in the dev server but is cast to str during tests?

1

There are 1 best solutions below

0
On

As it turned out, it was my mistake: my test model instances did not have featured images, and for this code to work featured_image field must hold an actual image, e.g.:

from filebrowser.base import FileObject
from .models import Page

page = Page(
           title='Lorem Ipsum',
           content='<b>Lorem ipsum dolor sit amet.</b>',
           featured_image=FileObject('http://via.placeholder.com/350x150')
           )
page.save()

Otherwise, the featured_image field evaluates to an empty string, as I understand.