Unit testing: How can i import test classes dynamically and run?

空扰寡人 提交于 2019-12-25 16:37:02

问题


I'm doing a simple script to run and test my code. How can i import dinamically and run my test classes?


回答1:


This is the solution that I found to import and dynamically run my test classes.

import glob
import os
import imp
import unittest

def execute_all_tests(tests_folder):
    test_file_strings = glob.glob(os.path.join(tests_folder, 'test_*.py'))
    suites = []
    for test in test_file_strings:
        mod_name, file_ext = os.path.splitext(os.path.split(test)[-1])
        py_mod = imp.load_source(mod_name, test)
        suites.append(unittest.defaultTestLoader.loadTestsFromModule(py_mod))
    text_runner = unittest.TextTestRunner().run(unittest.TestSuite(suites))



回答2:


Install pytest, and run your tests with a command like:

py.test src

That's it. Py.test will load all test_*.py files, find all def test_* calls inside them, and run each one for you.

The board is having trouble answering your question because it's in "why is water wet?" territory; all test rigs come with runners that automatically do what your code snip does, so you only need read the tutorial for one to get started.

And major props for writing auto tests at all; they put you above 75% of all programmers.




回答3:


This solution is too simple and perform what i want.

import unittest

def execute_all_tests(tests_folder):
    suites = unittest.TestLoader().discover(tests_folder)
    text_runner = unittest.TextTestRunner().run(suites)


来源:https://stackoverflow.com/questions/31682362/unit-testing-how-can-i-import-test-classes-dynamically-and-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!