【问题标题】:Django view unit test conflict with custom template tagDjango查看单元测试与自定义模板标签冲突
【发布时间】:2019-12-01 10:48:45
【问题描述】:

我为我的 django 项目创建了一个自定义模板标签,它返回一个图片 url 作为 favicon

# myapp/templatetags/customtags.py

@register.simple_tag
def get_shop_favicon():
    '''
    get shop favicon
    '''
    return Shop.objects.first().favicon.url

并像这样在 base.html 中使用它

<!doctype html>
{% load storefront_tags %}
<head>
    <link rel="icon" href="{% get_shop_favicon %}" type="image/png" sizes="16x16"> 
</head>
<body>
  ...
</body>

这部分效果很好,但是在创建测试函数来测试我的视图后得到了一个 AttributeError 如下

AttributeError: 'NoneType' object has no attribute 'favicon'

这是我的测试课

# test.py
from django.test import TestCase
from django.urls import reverse

class ProductViewTest(TestCase):
    '''
    testing product views and urls
    '''
    def test_get_product_list_status_code(self):
        '''
        test to get all products
        '''
        url = reverse('prodcuts') # url name
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

注意:没有模板标签效果很好

【问题讨论】:

  • 您的模板中没有Shop 对象,因此.first() 将返回None。

标签: django django-templates django-tests


【解决方案1】:

您可能会首先在模板中添加一个检查以查看是否有任何 Shop 对象:

@register.simple_tag
def get_shop_favicon():
    '''
    get shop favicon
    '''
    if Shop.objects.first():
        return Shop.objects.first().favicon.url  
    # else return some placeholder url

【讨论】:

    【解决方案2】:

    测试数据库是空的(除非你当然填充它)。如果没有Shop 对象,则Shop.objects.first() 因而返回None。

    # test.py
    from django.test import TestCase
    from django.urls import reverse
    
    class ProductViewTest(TestCase):
        '''
        testing product views and urls
        '''
    
        def setUp(self):
            super().setUp()
            shop = Shop()
            shop.favicon = 'path/to/some/favicon.ico'
            shop.save()
    
    
        def test_get_product_list_status_code(self):
            '''
            test to get all products
            '''
            url = reverse('prodcuts') # url name
            response = self.client.get(url)
            self.assertEqual(response.status_code, 200)

    话虽如此,在模板标签中添加一个“回退”机制可能会更好,例如:

    # myapp/templatetags/customtags.py
    
    @register.simple_tag
    def get_shop_favicon():
        '''
        get shop favicon
        '''
        shop = Shop.objects.first()
        if shop:
            return shop.favicon.url
        return 'some_default_favicon.ico'

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 2020-04-02
      • 2012-01-08
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多