Python unittest:如何只运行测试文件的一部分? [英] Python unittest: how to run only part of a test file?

查看:35
本文介绍了Python unittest:如何只运行测试文件的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试文件,其中包含花费大量时间的测试(它们将计算发送到集群并等待结果).所有这些都在特定的 TestCase 类中.

I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.

由于它们需要时间,而且不太可能中断,我希望能够选择是否运行该测试子集(最好的方法是使用命令行参数,即";./tests.py --offline"或类似的东西),所以当我有时间时,我可以经常快速地运行大部分测试,偶尔运行整个测试集.

Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "./tests.py --offline" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.

现在,我只使用 unittest.main() 来开始测试.

For now, I just use unittest.main() to start the tests.

推荐答案

默认的 unittest.main() 使用默认的测试加载器从运行 main 的模块中创建一个 TestSuite.

The default unittest.main() uses the default test loader to make a TestSuite out of the module in which main is running.

您不必使用此默认行为.

You don't have to use this default behavior.

例如,您可以制作三个 unittest.TestSuite实例.

You can, for example, make three unittest.TestSuite instances.

  1. 快"子集.

  1. The "fast" subset.

fast = TestSuite()
fast.addTests(TestFastThis)
fast.addTests(TestFastThat)

  • 慢"子集.

  • The "slow" subset.

    slow = TestSuite()
    slow.addTests(TestSlowAnother)
    slow.addTests(TestSlowSomeMore)
    

  • 整体"设置.

  • The "whole" set.

    alltests = unittest.TestSuite([fast, slow])
    

  • 请注意,我已经调整了 TestCase 名称以指示 Fast vs. Slow.你可以子类unittest.TestLoader 解析类名并创建多个加载器.

    Note that I've adjusted the TestCase names to indicate Fast vs. Slow. You can subclass unittest.TestLoader to parse the names of classes and create multiple loaders.

    然后您的主程序可以使用 optparse 解析命令行参数href="https://docs.python.org/dev/library/argparse.html" rel="nofollow noreferrer">argparse(从 2.7 或 3.2 开始可用)来快速选择您想要运行的套件,缓慢或全部.

    Then your main program can parse command-line arguments with optparse or argparse (available since 2.7 or 3.2) to pick which suite you want to run, fast, slow or all.

    或者,您可以相信 sys.argv[1] 是三个值之一,并使用像这样简单的东西

    Or, you can trust that sys.argv[1] is one of three values and use something as simple as this

    if __name__ == "__main__":
        suite = eval(sys.argv[1])  # Be careful with this line!
        unittest.TextTestRunner().run(suite)
    

    这篇关于Python unittest:如何只运行测试文件的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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