2
我是Python中的noob。 我有点困惑python单元测试应该如何构建和运行的实际应用程序,即如果我有一个程序,从一个主要方法开始,我应该能够启动该程序的单元测试通过同样的入口点? 所以我试图创建一个程序的参数之一应该告诉程序运行单元测试而不是正常执行(见下文),但也能够接受unittest.main()可以接受的所有参数。我将不胜感激分左右在Python的方式实际的程序执行和单元测试或与诸如任何帮助的更好的办法任何建议之下,如果我采用的方法是正确的:运行python单元测试作为程序的一个选项
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)如果我m指定执行MyClass与-t MyTestCase选项我希望它能够按照帮助消息unittest.main()运行,但它说有一个AttributeError:'模块'对象没有属性MyTestCase
谢谢!
因为我不想更改部署模式,我只是将单元测试从模块中提取出来,它确实有效。谢谢! – 2012-03-23 16:59:13