简体   繁体   English

如何排序python unittest发现测试?

[英]How to sort python unittest discover tests?

I created my bunch of Python tests using the Python unittest format. 我使用Python unittest格式创建了一堆Python测试。

Now I'm able to run them with 现在我可以运行它们了

python -m unittest discover -s TestDirectory -p '*.py' -v

I finds them all, and runs them. 我找到了所有,然后运行它们。

Now there's a subtle difference whether I run the tests on Windows, or on Linux. 现在,无论是在Windows上还是在Linux上运行测试,都会有细微差别。 Indeed, on Windows the tests are run in alphabetical order, whereas on Linux the tests are run in no apparent human specific discoverable order, even if always the same. 实际上,在Windows上,测试按字母顺序运行,而在Linux上,测试运行时没有明显的人类特定的可发现顺序,即使总是相同。

The trouble is I relied on the first two letters of the test file to sort the order of execution of the tests. 麻烦的是我依靠测试文件的前两个字母来排序测试的执行顺序。 Not that they have to be run in a specific order, but to have some kind of informational tests, showing version data in their output to appear first in the test run log. 并不是说它们必须以特定的顺序运行,而是要进行某种信息测试,在其输出中显示版本数据首先出现在测试运行日志中。

Is there something I can do to run the tests also in alphabetical order on Linux? 在Linux上,我是否可以按字母顺序运行测试?

I have not tried this, but I imagine that one thing you could do is override the TestSuite class to add a sort function. 我没有试过这个,但我想你可以做的一件事就是覆盖TestSuite类来添加一个sort函数。 Then you can call the sort function before calling the unittest run function. 然后你可以在调用unittest run函数之前调用sort函数。 So, in an 'AllTests.py' script, you could add something like this: 因此,在'AllTests.py'脚本中,您可以添加如下内容:

class SortableSuite(unittest.TestSuite):
    def sort(self):
        self._tests.sort(cmp=lambda x,y: x._testMethodName < y._testMethodName)
    def run(self,testResult):
        #or if you don't want to run a sort() function, you can override the run
        #function to automatically sort.
        self._tests.sort(cmp=lambda x,y: x._testMethodName < y._testMethodName)
        return unittest.TestSuite.run(self,testResult)

loader = unittest.TestLoader()
loader.suiteClass = SortableSuite
suite = loader.loadTestFromTestCases(collectedTests)
suite.sort()
suite.run(defaultTestResult())

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

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