首页 > 解决方案 > 如何在测试期间创建 Wagtail 重定向

问题描述

我有一个依赖于 wagtail 重定向的测试用例,但我似乎无法启动它:

from django.test import TestCase
from wagtail.contrib.redirects.models import Redirect


class LocalizedRedirectTests(TestCase):
    def test_plain_redirect(self):
        """
        Test that the base redirect works.
        """
        Redirect.objects.create(
            old_path='/test',
            redirect_link='http://example.com'
        )
        response = self.client.get('/test')
        print(response)

self.client.get由于在 url 模式列表中找不到重定向,因此出现此错误:

======================================================================
ERROR: test_plain_redirect (testapp.wagtailcustomization.tests.LocalizedRedirectTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/dockerpythonvenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/app/dockerpythonvenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 100, in _get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/app/dockerpythonvenv/lib/python3.7/site-packages/django/urls/resolvers.py", line 567, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})
django.urls.exceptions.Resolver404: {'tried': [[<URLPattern 'robots.txt' [name='robots_file']>], ...snip..., 'path': 'test/'}

之后它会抛出一个静态文件错误:

Traceback (most recent call last):
  File "/testapp/wagtailcustomization/tests.py", line 14, in test_plain_redirect
    response = self.client.get('/test/', follow=True)
  
  ...snip...
  
  File "/testapp/wagtailpages/views.py", line 26, in custom404_view
    html = render(request, '404.html')

  ...snip...

  File "/app/dockerpythonvenv/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name
    raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for '_css/main.compiled.css'

我还尝试将其缓存为redirect = ...然后使用redirect.save(),但结果相同,我还尝试使用显式添加站点site = Site.objects.first(),然后将其作为site=sitekwarg 传递,但这也具有相同的结果。然后我尝试了 static Redirect.add_redirect,但即便如此:同样的结果。

如何在测试期间创建重定向,self.client.get(...)使其启动?

标签: wagtail

解决方案


解决方案有两个:(1)使用override_settings修复静态资产错误,(2)将重定向构建为普通对象,然后save()

from django.test import TestCase
from wagtail.contrib.redirects.models import Redirect
from django.test.utils import override_settings


# Safeguard against the fact that static assets and views might be hosted remotely,
# see https://docs.djangoproject.com/en/3.1/topics/testing/tools/#urlconf-configuration
@override_settings(STATICFILES_STORAGE="django.contrib.staticfiles.storage.StaticFilesStorage")
class LocalizedRedirectTests(TestCase):
    def test_plain_redirect(self):
        """
        Test that the base redirect works.
        """
        redirect = Redirect(old_path='/test', redirect_link='http://example.com')
        redirect.save()
        response = self.client.get('/test')
        ...

此外,如果您有一个多级重定向(例如/test=> /,然后由于 i18n,另一个/=> /en/),您需要遵循重定向,然后检查结果response.redirect_chain

        ...
        response = self.client.get('/test/', follow=True)
        self.assertEqual(response.redirect_chain, [
          ('/', 301),
          ('/en/', 302),
        ])

使用正确的 301 或 302 值,具体取决于它是永久重定向还是临时重定向。


推荐阅读