简体   繁体   English

pytest - 如何在特定测试后执行 function

[英]pytest - How to execute a function after specific tests

I have some tests organized in several classes.我在几个班级组织了一些测试。 I already have a test fixture with scope=class so that it would run before suite(class) of tests.我已经有一个 scope=class 的测试夹具,这样它就可以在测试套件(类)之前运行。 However, I need to execute a function after some specific tests.但是,经过一些特定测试后,我需要执行 function 。 Lets say I have 100 tests in a class, I already have a fixture that will execute a function before these tests, but I also want to run a function after 2-3 of these tests.假设我在 class 中有 100 次测试,我已经有一个夹具可以在这些测试之前执行 function,但我也想在这些测试之后运行 ZC1C425268E68385D1AB5074C17A94F14-4。

What is the best approach to achieve that?实现这一目标的最佳方法是什么? Can it be done with fixtures or anything else?可以用固定装置或其他东西来完成吗?

First, write a fixture that will execute after a test finishes:首先,编写一个将在测试完成后执行的夹具:

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

Docs: Fixture finalization / executing teardown code文档: 夹具完成/执行拆卸代码

Now mark each test that should invoke this fixture with usefixtures("foo") :现在用usefixtures("foo")标记每个应该调用这个夹具的测试:

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

Docs: Use fixtures in classes and modules with usefixtures文档: 在类和模块中使用带有usefixtures的fixture

If you are using the python's built-in unittest module you can override the tearDown method to run something after each test in a class.如果您使用的是 python 的内置 unittest 模块,您可以覆盖tearDown方法以在 class 中的每个测试之后运行一些东西。

If you are using pytest's framework and using pytests fixtures, you can use the yield keyword in your fixtures.如果您使用 pytest 的框架并使用 pytests 夹具,则可以在夹具中使用yield关键字。

It's documented in https://doc.pytest.org/en/latest/fixture.html#teardown-cleanup-aka-fixture-finalization .它记录在https://doc.pytest.org/en/latest/fixture.html#teardown-cleanup-aka-fixture-finalization中。

If you know the specific tests you want to run after you could set up the tests in a.csv with different values for each test for Example (index) (column) (column) Tests Test# Complete?如果您知道要运行的特定测试,则可以在 a.csv 中设置测试,每个测试的值不同,例如(索引)(列)(列) 测试 测试# 完成了吗? test 1 1 T test 2 2 F测试 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 

This isn't the prettiest solution but it works这不是最漂亮的解决方案,但它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM