我使用 Python unittest
格式创建了我的一堆 Python 测试。
现在我可以运行它们了
python -m unittest discover -s TestDirectory -p '*.py' -v
我找到它们并运行它们。
现在,无论是在 Windows 上还是在 Linux 上运行测试,都存在细微差别。事实上,在 Windows 上,测试按字母顺序运行,而在 Linux 上,测试没有明显的人类特定可发现的顺序运行,即使总是相同。
问题是我依靠测试文件的前两个字母来排序测试的执行顺序。并不是说它们必须按特定顺序运行,而是要进行某种信息性测试,在其输出中显示版本数据,使其首先出现在测试运行日志中。
我可以做些什么来在 Linux 上也按字母顺序运行测试吗?
最佳答案
我没有试过这个,但我想你可以做的一件事是覆盖 TestSuite 类以添加排序功能。那么就可以在调用unittest run函数之前先调用sort函数。因此,在“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())
关于python - 如何对 python unittest 发现测试进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010476/