10

我正在查看类似的问题,但找不到我的问题的答案。

我在派生自 unittest.TestCase 的 python 类中编写了测试

class TestEffortFormula(unittest.TestCase)

我需要对测试下达命令(请不要告诉我我不应该依赖测试的命令,我只是这样做)。

在我需要对测试下达命令之前,我用来运行测试的命令是:

unittest.main(testRunner=TeamcityTestRunner())

然后我想让订单消失,所以我尝试了以下操作:

loader = unittest.TestLoader()
loader.sortTestMethodsUsing(None)
loader.loadTestsFromTestCase(TestEffortFormula)
suite = loader.suiteClass()

但是从这里我不知道如何运行测试,特别是testRunner=TeamcityTestRunner() 像我以前那样。

感谢你的帮助

4

2 回答 2

6

Option 1.

One solution to this (as a workaround) was given here - which suggests writing the tests in numbered methods step1, step2, etc., then collecting and storing them via dir(self) and yielding them to one test_ method which trys each.

Not ideal but does what you expect. Each test sequence has to be a single TestClass (or adapt the method given there to have more than one sequence generating method).

Option 2.

Another solution, also in the linked question, is you name your tests alphabetically+numerically sorted so that they will execute in that order.

But in both cases, write monolithic tests, each in their own Test Class.

P.S. I agree with all the comments that say unit testing shouldn't be done this way; but there are situations where unit test frameworks (like unittest and pytest) get used to do integration tests which need modular independent steps to be useful. Also, if QA can't influence Dev to write modular code, these kinds of things have to be done.

于 2015-05-17T13:59:20.133 回答
2

我已经搜索了很长时间来自己解决这个问题。这个问题
中 的一个答案正是您所需要的。

应用于您的代码:

ln = lambda f: getattr(TestEffortFormula, f).im_func.func_code.co_firstlineno
lncmp = lambda _, a, b: cmp(ln(a), ln(b))
unittest.TestLoader.sortTestMethodsUsing = lncmp

suite = unittest.TestLoader().loadTestsFromTestCase(TestEffortFormula)
unittest.TextTestRunner(failfast=True).run(suite)

不幸的是,设置unittest.TestLoader.sortTestMethodsUsing=None不起作用,尽管有记录表明这应该避免按字母顺序对测试进行排序。

于 2016-06-01T08:40:37.280 回答