如何在单元测试中自动生成测试用例号?

How can generate automatically test case number in unittest?(如何在单元测试中自动生成测试用例号?)
本文介绍了如何在单元测试中自动生成测试用例号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何自动生成单元测试中的测试用例数量?我的意思是类似于TEST_01、TEST_02、TEST_{生成编号}之类的内容。

import unittest 

class TestSum(unittest.TestCase): 
    def test_01_sum(self): 
        self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") 

    def test_02_sum_tuple(self): 
        self.assertEqual(sum((1, 2, 2)), 6, "Should be 6") 

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

推荐答案

要在运行时实现这一点,您实际上可以重命名测试类的测试方法:

def generate_test_numbers(test_class):
    counter = 1
    for method_name in dir(test_class):
        if not method_name.startswith('test_N_'):
            continue
        method = getattr(test_class, method_name)
        if not callable(method):
            continue
        new_method_name = method_name.replace('_N_', '_{:02d}_'.format(counter))
        counter += 1
        setattr(test_class, new_method_name, method)
        delattr(test_class, method_name)
    return test_class

您可以简单地从Main:

调用此函数
generate_test_numbers(TestSum)

或者按照@VPfB的建议,将其用作类修饰符:

@generate_test_numbers
class TestSum(unittest.TestCase): 
    def test_N_sum(self): 
        self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") 

    def test_N_sum_tuple(self): 
        self.assertEqual(sum((1, 2, 2)), 6, "Should be 6") 

任何一个都将输出(带-v)

test_01_sum (__main__.TestSum) ... ok
test_02_sum_tuple (__main__.TestSum) ... FAIL

======================================================================
FAIL: test_02_sum_tuple (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "q.py", line 8, in test_N_sum_tuple
    self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
AssertionError: 5 != 6 : Should be 6

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

这篇关于如何在单元测试中自动生成测试用例号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)