【问题标题】:pytest - How to execute a function after specific testspytest - 如何在特定测试后执行功能
【发布时间】:2021-01-07 13:54:53
【问题描述】:

我在几个班级组织了一些测试。我已经有一个 scope=class 的测试夹具,这样它就可以在测试套件(类)之前运行。但是,我需要在一些特定测试后执行一个函数。假设我在一个类中有 100 个测试,我已经有一个夹具可以在这些测试之前执行一个函数,但我还想在这些测试中的 2-3 个之后运行一个函数。

实现这一目标的最佳方法是什么?可以用固定装置或其他东西来完成吗?

【问题讨论】:

    标签: python testing pytest fixtures test-fixture


    【解决方案1】:

    首先,编写一个将在测试完成后执行的夹具:

    @pytest.fixture
    def foo():
        yield
        print("do stuff after test")
    

    文档:Fixture finalization / executing teardown code

    现在用usefixtures("foo")标记每个应该调用这个fixture的测试:

    @pytest.mark.usefixtures("foo")
    def test_spam():
        ...
    

    文档:Use fixtures in classes and modules with usefixtures

    【讨论】:

    • 谢谢,正是我想要的。
    • @Override12 如果该答案正是您想要的,请接受它。
    【解决方案2】:

    如果您使用的是 python 的内置 unittest 模块,您可以覆盖 tearDown 方法以在类中的每个测试之后运行一些东西。

    如果您使用 pytest 的框架并使用 pytests 夹具,则可以在夹具中使用 yield 关键字。

    它记录在https://doc.pytest.org/en/latest/fixture.html#teardown-cleanup-aka-fixture-finalization

    【讨论】:

    • 我正在使用 pytest,但这对我没有帮助,因为我不想在每次测试或所有测试后进行拆解,我希望在特定测试后进行拆解。例如我运行了 100 个测试,我想在测试 30、45 和 70 之后运行一个函数
    【解决方案3】:

    如果您知道要运行的特定测试,则可以在 .csv 中为每个测试设置不同值的测试 例如 (索引) (列) (列) 测试 测试# 完成了吗? 测试 1 1 T 测试 2 2 F

    import pandas as pd 
    #makes panda read your file and sets the variable as the data in the file
    data = pd.read_csv("filename.csv") 
    #Gets the value from the column 'test#' and 'complete' and sets as a variable
    Var1 = DataFrame.get_value("the number test you want to take", 'Complete?')
    If Var1 = T 
       #Run the rest of your program here
    #Then you can just repeat this for the other tests you want to check for 
    

    这不是最漂亮的解决方案,但它确实有效

    【讨论】:

    • 谢谢,我会记住这一点。老实说,我希望有一个更优雅的解决方案。我想象装饰器可能被用来实现这样的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2021-12-29
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多