unittest ddt 單個用例執行使用


環境: windows 10, JetBrains PyCharm 2017.3.2 , python3.5
由於需要單用例執行, 而 ddt使用后不支持,顯示找不到該方法 `AttributeError: type object 'xxx'(類) has no attribute 'xxx'(方法)
查看ddt源碼,可知ddt 在使用傳參后會對方法名重新定義 定義格式為: 源方法名+ 入參相關數據,所以添加的時候 把改了名字的方法名傳入就可以實現了.

# test_xxx.py
import unittest

import ddt


@ddt.ddt
class MyTest01(unittest.TestCase):
    # @ddt.data(["a1","a2"],["b1","b2"])
    # def dataget(self,p1,p2):
    #     print("data:{}-{}".format(p1,p2))
    @ddt.data(["a5","a2"],["b1","b2"])
    @ddt.unpack
    def test_02_aa(self,p1,p2):
        print("test02: {}-{}".format(p1,p2))


    def test_01_aa(self):
        print("test01")

    def test_03_aa(self):
        print("test03")


def mySuitePrefixAdd(MyClass,cases):
    '''
    根據前綴添加測試用例-可用於ddt數據用例
    :param MyClass:
    :param cases:
    :return:
    '''
    test_list = []
    testdict = MyClass.__dict__
    if isinstance(cases,str):
        cases = [cases]
    for case in cases:
        tmp_cases = filter(lambda cs:cs.startswith(case) and callable(getattr(MyClass,cs)),testdict)
        for tmp_case in tmp_cases:
            test_list.append(MyClass(tmp_case))
    suite = unittest.TestSuite()
    suite.addTests(test_list)
    return suite


if __name__ == "__main__":

    runner = unittest.TextTestRunner()
    runner.run(mySuitePrefixAdd(MyTest01,"test_02_aa"))

而pycharm 實現右鍵選擇用例執行, 在安裝目錄: helpers/pycharm/_xxxx_unittest_runner.py 解析分析 targets 參數,也可以實現


def targetsReBuild(targets):
    target_dir_path = os.getcwd().split("\\")[-1]
    if targets:
        target_path, target_class, target_method = targets[0].split(".")
    if target_path:
        target_module = __import__("{}.{}".format(target_dir_path,target_path))
        target_class_dir = eval("dir({}.{}.{})".format('target_module',target_path,target_class))
        target_path_dit = eval("dir({}.{})".format('target_module',target_path))
        # 解析targets

        if 'ddt' in target_path_dit: #使用了ddt
            target_collect = []
            # 有ddt則使用前綴匹配
            for target_index,target in enumerate(targets):
                target_path, target_class, target_method = target.split(".")
                tm = eval("{}.{}.{}".format('target_module',target_path,target_class))
                targets_tmp = filter(lambda cs:cs.startswith(target_method+"_") \
                                               and callable(getattr(tm,cs)),\
                                     target_class_dir)
                targets_tmp = list(targets_tmp)
                # 裝換成list判斷是否為空
                if targets_tmp:

                    for t in targets_tmp:
                        target_collect.append("{}.{}.{}".format(target_path,target_class,t))
                else:
                    target_collect.append("{}.{}.{}".format(target_path,target_class,target_method))
            # 掃描完成
            targets = target_collect
    return targets

if __name__ == '__main__':
    path, targets, additional_args = jb_start_tests()
    targets = targetsReBuild(targets) ###########在此處添加該方法

    args = ["python -m unittest"]
    .
    .
    . #其他不變


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM