代码之家  ›  专栏  ›  技术社区  ›  guettli

PyTest fixtures:让数据持久化(Django)

  •  0
  • guettli  · 技术社区  · 5 年前

    我喜欢pytest django装置,并在django应用程序中使用它们。

    但有时我希望有数据可以利用。

    到目前为止,pytest fixture只在临时数据库中。

    我的目标是:我希望在django web GUI中有一个按钮。如果我按下按钮 按钮我的pytest装置列表应该在普通数据库中被调用。

    如果我试图在django视图中直接调用fixtures,我会得到以下消息:

    Failed: Fixture "waiting_for_activation_user" called directly. Fixtures are not meant to be called directly,
    but are created automatically when test functions request them as parameters.
    See https://docs.pytest.org/en/stable/fixture.html for more information about fixtures, and
    https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code.
    

    当然,我可以忽略测试夹具的存在,并在Django ORM方法的帮助下实现“创建测试数据”按钮 update_or_create() .但这不好,因为 我需要实现两次测试数据的创建

    有人有解决方案吗,这样我只需要编写一次代码来创建测试数据,并且我可以使用它两次(一次用于pytext fixture,一次用于按钮)?

    1 回复  |  直到 5 年前
        1
  •  1
  •   schillingt    5 年前

    我会将您希望在普通web应用程序中使用的部分fixture提取到某种类型的factory模块或类中。然后对新零件进行测试,以确认工厂按预期工作。

    然而,我不会尝试在web应用程序中直接使用pytest夹具。