我是 python 菜鸟。 我对应该如何为实际应用程序构建和运行 python 单元测试感到困惑,即如果我有一个从 main 方法启动的程序,我应该能够通过相同的方法启动该程序的单元测试入口点? 因此,我正在尝试创建一个程序,其中一个参数应该告诉程序运行单元测试而不是正常执行(见下文),但也能够接受 unittest.main() 可以接受的所有参数。如果我采取的方法是正确的,我将不胜感激关于以 pythonic 方式分离实际程序执行和单元测试的更好方法的任何建议,或者对以下示例的任何帮助:
class MyClass
def write_to_file(self, file):
open(file, 'w').write("Hello world!")
class MyClassTest (unittest.TestCase)
self.mc = MyClass()
self.test_file = os.path.join(os.path.curdir, "a_file.txt")
def setUp(self):
pass
def test_write_to_file(self):
try:
write_to_file(self.test_file)
except IOError:
self.fail("Error!")
if __name__== "__main__":
parser = argparse.ArgumentParser(description="Some desc")
group = parser.add_mutually_exclusive_group()
group.add_argument("-w", "--write", help=': write hello world to given file')
group.add-argument("-t", "--test", help=': run unit tests, use "all" to run all tests')
args = parser.parse_args(sys.argv[1:])
mcl = MyClass()
if args.write:
mcl.write_to_file(args.write)
# below is the questionnable part
if args.test:
#removing -t or --test argument because otherwise unittest.main() will complain
del sys.argv[1:]
if args.test == "all":
unittest.main()
else:
# Adding the argument that was specified after the -t into the sys.argv to be picked up by the unittest.main() - doesn't work correctly (1)
sys.argv.append(args.test)
unittest.main()
(1) 如果我使用 -t MyTestCase 选项指定执行 MyClass,我希望它能够根据帮助消息 unittest.main() 运行,但它说有一个 AttributeError: 'module' object has没有属性 MyTestCase
谢谢!
请您参考如下方法:
我会将类(被测“单元”)单独放在一个文件中,而“主”程序和单元测试则放在另外两个文件中。后者将是可执行脚本;第一个将由他们简单地导入。
