【问题标题】:Pytest delete db after testsPytest 测试后删除数据库
【发布时间】:2019-10-10 18:17:49
【问题描述】:

我在 pytest-django 中有一个测试套件,我想在测试开始时创建一个数据库,然后在测试完成后立即删除它,以便在不保留大量数据的情况下模拟场景。 任何帮助,将不胜感激。提前致谢!

【问题讨论】:

  • 查看tearDownClass。您可以在那里重置数据库。或者在你的 pytest 配置中。

标签: django pytest pytest-django


【解决方案1】:

使用yield 语句而不是return 来利用fixture teardown。这允许您设置数据库,根据需要返回任何数据,然后执行任何清理。如果您希望无论是否声明使用夹具的测试函数都对每个测试执行此操作,请将autouse 设置为True。

@pytest.fixture(autouse=False)
def db():
    # Setup DB here

    # Yield some data, database connection or nothing at all
    yield None

    # Delete DB here when the test ends

def test_something(db):
    # Database will be ready here and db will contain whatever
    # db() function yields. With autouse=True you don't need to
    # set the db fixture as the function param.
    pass

【讨论】:

  • "# 测试结束时在此处删除 DB" - 你能告诉我怎么做吗?
  • @Vadim 这实际上取决于您使用的数据库以及用于访问它的 Python 包。
  • 我还没有删除数据库,但是我在yield之后删除了对象。当测试失败时,它们不会被删除。我不确定整个数据库。
  • 在这个例子中,这个数据库应该被传递给每个测试吗?如果测试失败或出错会发生什么?
  • 在这个例子中,这个数据库应该被传递给每个测试吗?这取决于你的情况。如果您的测试需要使用 db 夹具产生的对象,那么您需要将其设置为测试函数参数。如果夹具需要在每次测试之前/之后设置/拆卸数据库,但您不需要它产生的结果,那么最好设置 @pytest.fixture(autouse=True) 并且您不需要声明它。 如果测试失败或错误会发生什么? 夹具的yield 之后的拆卸部分应该继续进行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 2019-02-08
相关资源
最近更新 更多