python unittest计数测试

时间:2015-02-13 13:04:19

标签: python python-unittest

unittest是否可以使用选项来计算跳过测试的总测试次数和运行次数。并且运行后测试次数失败(我知道它可以在输出中看到)。如果我想以编程方式将它转换为json,我想将它转储到json中

很多

3 个答案:

答案 0 :(得分:6)

经过多次试验和错误后,我终于有了这个工作......

基于scoffey's answer

希望它有所帮助。

import unittest

class MyTest(unittest.TestCase):

    currentResult = None # holds last result object passed to run method

    @classmethod
    def setResult(cls, amount, errors, failures, skipped):
        cls.amount, cls.errors, cls.failures, cls.skipped = \
            amount, errors, failures, skipped

    def tearDown(self):
        amount = self.currentResult.testsRun
        errors = self.currentResult.errors
        failures = self.currentResult.failures
        skipped = self.currentResult.skipped
        self.setResult(amount, errors, failures, skipped)

    @classmethod
    def tearDownClass(cls):
        print("\ntests run: " + str(cls.amount))
        print("errors: " + str(len(cls.errors)))
        print("failures: " + str(len(cls.failures)))
        print("success: " + str(cls.amount - len(cls.errors) - len(cls.failures)))
        print("skipped: " + str(len(cls.skipped)))

    def run(self, result=None):
        self.currentResult = result # remember result for use in tearDown
        unittest.TestCase.run(self, result) # call superclass run method

    def testA(self):
        self.assertTrue(True) # succeeds

    def testB(self):
        self.assertTrue(False) # fails

    def testC(self):
        self.assertTrue(1 + None is None) # raises TypeError

    @unittest.skip("skip it") # skipped
    def testD(self):
        self.assertTrue("whatever")

if __name__ == '__main__':
    unittest.main() 

使用

运行脚本
python test.py > result.txt

的Result.txt:

tests run: 3
errors: 1
failures: 1
success: 1
skipped: 1

我不确定这是最好的方法,但它有效。 Unittest模块易于使用但很难掌握,现在我觉得我对此知之甚少。

答案 1 :(得分:1)

我不知道unittest以JSON报告的任何方式。我知道nose正在以XML格式输出结果:

nosetests --with-xunit --xunit-file=mytests.xml mytests.py

以下是此XML文件的摘录:

<testsuite name="nosetests" tests="3" errors="0" failures="1" skip="1">

如果您不介意XML格式,那么这是一个需要考虑的解决方案。我还听说鼻子有一个JSON插件,但还没玩过它。

答案 2 :(得分:1)

我使用单元测试TestSuite(Ref)。

在运行后打开,它将返回一个TextTestResult,其中包含具有失败,错误和跳过的列表,具有Test_runs的值等等。

这是一个“最小”的工作示例,说明了我将如何做。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
相关问题