简体   繁体   English

python 单元测试计数测试

[英]python unittest count tests

Is it possible with unittest to have an option tou count the number of total test number of skipped tests and number of run. unittest 是否有可能有一个选项来计算跳过测试的总测试数和运行数。 And after the run the number of test failed (I know that it can be seen in the output).运行后测试失败的次数(我知道可以在输出中看到)。 I would like to dump it in a json if I wan take it programatically that would be great如果我想以编程方式使用它,我想将它转储到 json 中,那就太好了

Thx a lot多谢

After many trials and errors, I finally got this working... 经过多次试验和错误,我终于完成了这项工作......

Based on scoffey's answer . 基于scoffey的回答

Hope it helps. 希望能帮助到你。

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() 

run script with 用脚本运行脚本

python test.py > result.txt

result.txt: 的Result.txt:

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

I'm not sure this is the best way, but it's working. 我不确定这是最好的方法,但它有效。 Unittest module is easy to use but hard to master, now I feel I know little about it. Unittest模块易于使用但很难掌握,现在我觉得我对此知之甚少。

I don't know any way for unittest to report in JSON. 我不知道unittest以JSON报告的任何方式。 I am aware that nose is outputing result in XML format: 我知道nose正在以XML格式输出结果:

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

Here is an excerpt from this XML file: 以下是此XML文件的摘录:

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

If you don't mind XML format, then this is a solution to consider. 如果您不介意XML格式,那么这是一个需要考虑的解决方案。 I also heard that nose has a JSON plug-in, but have not played with it yet. 我还听说鼻子有一个JSON插件,但还没玩过它。

I Uses the unittests TestSuite ( Ref ). 我使用单元测试TestSuite( 参考 )。

On after run it returns a TextTestResult, that contains a list with Failures, Errors and Skipped, a value with Test_runs, and more. 在运行之后,它返回一个TextTestResult,其中包含一个包含Failures,Errors和Skipped的列表,一个包含Test_runs的值等等。

Here are a "minimum" working example, on how I would do it. 这是一个“最小”的工作示例,关于我将如何做。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import unittest


class TestDummy(unittest.TestCase):
    """A Dummy UnitTesting class."""

    def test_failure(self):
        """Fails on test."""
        self.fail(msg="Need a failure")

    @unittest.skip("Need a Skipper")
    def test_skipping(self):
        """Skippes on test."""
        pass

    def test_error(self):
        """Gives a error on test."""
        self.not_a_thing()

    def test_pass(self):
        """Need a test that passes."""
        pass


def warp_test_suite(testcase_class):
    """Load tests from a specific set of TestCase classes."""
    suite = unittest.TestSuite()
    tests = unittest.defaultTestLoader.loadTestsFromTestCase(testcase_class)
    suite.addTest(tests)
    return suite


if __name__ == "__main__":
    import json  # For saving a JSON-file

    # The test results dictionary, for the JSON.
    result_value = {"Failures": 0, "Errors": 0, "Skipped": 0, "Test Runs": 0}

    # Setup and run the Test
    runner = unittest.TextTestRunner()
    TextTestResult = runner.run(warp_test_suite(TestDummy))

    # Passes the Result
    result_value["Failures"] += len(TextTestResult.failures)
    result_value["Errors"] += len(TextTestResult.errors)
    result_value["Skipped"] += len(TextTestResult.skipped)
    result_value["Test Runs"] += TextTestResult.testsRun

    # Save the result to a JSON-file.
    with open("result_data.json", 'w') as fp:
            json.dump(result_value, fp, indent=3)

If you review to source code, you may found this line:如果查看源代码,您可能会发现这一行:

        self.result = testRunner.run(self.test)
    if self.exit:
        sys.exit(not self.result.wasSuccessful())

So what you need to do is write code like this:所以你需要做的是编写如下代码:

    result = unittest.main(exit=False).result
    print(result.testsRun)

Remember to set exit args to be False.请记住将退出参数设置为 False。 Then you can use result.result to output testing summary.然后你可以使用 result.result 来 output 测试总结。

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

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