如何在pytest中将单元测试和集成测试分开 [英] How to keep Unit tests and Integrations tests separate in pytest

查看:291
本文介绍了如何在pytest中将单元测试和集成测试分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据维基百科和各种

According to Wikipedia and various articles it is best practice to divide tests into Unit tests (run first) and Integration tests (run second), where Unit tests are typically very fast and should be run with every build in a CI environment, however Integration tests take longer to run and should be more of a daily run.

有没有办法在pytest中将它们分开?大多数项目似乎没有多个测试文件夹,因此有没有一种方法可以确保我仅根据情况(CI与每日构建)运行单元和/或集成?在计算测试覆盖率时,我假设我必须同时运行两者.

Is there a way to divide these in pytest? Most projects don't seem to have multiple test folders, so is there a way to make sure I only run Unit, Integration or both according to the situtation (CI vs daily builds)? When calculating test coverage, I assume I will have to run both.

在尝试将测试划分为这些类别时,我会采用正确的方法吗?在执行此操作的项目中是否有一个很好的例子?

Am I going about this the right way in attempting to divide the tests into these categories? Is there a good example somewhere of a project that has done this?

推荐答案

是的,您可以使用pytest.mark装饰器标记测试.

Yes, you can mark tests with the pytest.mark decorator.

示例:

def unit_test_1():
    # assert here

def unit_test_2():
    # assert here

@pytest.mark.integtest
def integration_test():
    # assert here

现在,从命令行中,您可以仅对单元测试运行pytest -m "not integtest",仅对集成测试运行pytest -m integtest,对所有测试运行普通pytest.

Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

(如果需要,您也可以使用pytest.mark.unit装饰单元测试,但我发现这有点乏味/冗长)

(You can also decorate your unit tests with pytest.mark.unit if you want, but I find that slightly tedious/verbose)

有关详细信息,请参见文档.

See the documentation for more information.

这篇关于如何在pytest中将单元测试和集成测试分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆