【问题标题】:How To Programmatically Set Up Wagtail Root Page For Tests Utilizing The StaticLiveServerTestCase Suite如何使用 StaticLiveServerTestCase 套件以编程方式设置 Wagtail 根页面以进行测试
【发布时间】:2021-01-09 01:53:58
【问题描述】:

这个问题类似于another question here on stack overflow

我正在使用 Django's StaticLiveServerTestCase 向我的 wagtail 网站添加测试。下面是我手头的代码库示例:

class ExampleTest(StaticLiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Chrome()

    def test_example_test(self):
        self.assertContains("Contact Page", self.browser.content)
    [...]

因此,当我使用 python manage.py test 运行此测试时,测试失败,因为出现 500 错误。 请记住,我使用的是 wagtail 而不是单独使用 Vanilla Django。我还使用 Django 的 Site 框架,而不是 Wagtail 的 Site 框架,因为 allauth 只允许与 Django 的 Site 框架一起使用。

@override_settings(DEBUG=True) 应用到这样的测试后:

@override_settings(DEBUG=True)
class ExampleTest(StaticLiveServerTestCase):
        def setUp(self):
            self.browser = webdriver.Chrome()
    
        def test_example_test(self):
            self.assertContains("Contact Page", self.browser.content)
        [...]

测试仍然失败,因为正在加载的页面是 wagtail 默认页面。

我的问题是,我如何将另一个页面设置为根/默认 wagtail 页面,以便当对 localhost:8000 [或测试服务器提供的任何其他端口号] 的请求是进入主页(即 http://localhost:8000/),我看到的是新页面而不是 wagtail 默认页面?

谢谢。

【问题讨论】:

    标签: wagtail


    【解决方案1】:

    由于StaticLiveServerTestCase 创建了一个新的[临时]“测试”数据库[包括运行migrationsmigrate],wagtail 在初始之后将所有站点和页面重置为初始状态wagtail start [mysite] 命令。

    这意味着,如果您想成为根页面的任何其他 Page,则必须对指令进行硬编码才能做到这一点。

    以下是实现此目的的方法。 建议在类的setUpClass 方法中设置这些指令——通常是其他测试类可以继承的class Main() 类;从而鼓励 D.R.Y

    class Main(StaticLiveServerTestCase):
        @classmethod
        def setUpClass(cls):
            super(Main, cls).setUpClass()
            cls.root = Page.objects.get(id=1).specific
            cls.new_default_home_page = Index(
                title="New Home Page Index",
                slug="index",
            )
            cls.root.add_child(instance=cls.new_default_home_page)
            cls.site = Site.objects.get(id=1)
            cls.site.root_page = cls.new_default_home_page
            cls.site.save()
            cls.browser = Chrome()
    

    现在我的测试类(无论它们在哪里)可以从这个类继承并立即获得整个新主页设置。例如:

    # ExampleTest() inherits from Main() for ease of Wagtail Page setup: avoiding repetition of setUpClass().
    class ExampleTest(Main):
        def test_example_test(self):
            self.assertContains("Contact Page", self.browser.title)
        [...]
    

    希望有一天这对那里的人有所帮助。 此解决方案适用于:wagtail==2.7.4 不保证高于此版本的任何内容都可以按照 wagtail 的代码库要求运行。但是,这不太可能行不通。

    【讨论】:

      猜你喜欢
      • 2020-11-06
      • 2012-04-25
      • 2019-01-12
      • 1970-01-01
      • 2011-03-15
      • 2011-01-31
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多