你如何为 python 模块的 argparse 部分编写测试? [英] How do you write tests for the argparse portion of a python module?
问题描述
我有一个使用 argparse 库的 Python 模块.我如何为代码库的那部分编写测试?
I have a Python module that uses the argparse library. How do I write tests for that section of the code base?
推荐答案
你应该重构你的代码并将解析移动到一个函数中:
You should refactor your code and move the parsing to a function:
def parse_args(args):
parser = argparse.ArgumentParser(...)
parser.add_argument...
# ...Create your parser as you like...
return parser.parse_args(args)
然后在您的 main
函数中,您应该使用以下命令调用它:
Then in your main
function you should just call it with:
parser = parse_args(sys.argv[1:])
(其中表示脚本名称的 sys.argv
的第一个元素被删除,以免在 CLI 操作期间将其作为附加开关发送.)
(where the first element of sys.argv
that represents the script name is removed to not send it as an additional switch during CLI operation.)
在您的测试中,您可以使用您想要测试的任何参数列表调用解析器函数:
In your tests, you can then call the parser function with whatever list of arguments you want to test it with:
def test_parser(self):
parser = parse_args(['-l', '-m'])
self.assertTrue(parser.long)
# ...and so on.
这样您就不必为了测试解析器而执行应用程序的代码.
This way you'll never have to execute the code of your application just to test the parser.
如果您稍后需要在应用程序中更改和/或向解析器添加选项,请创建一个工厂方法:
If you need to change and/or add options to your parser later in your application, then create a factory method:
def create_parser():
parser = argparse.ArgumentParser(...)
parser.add_argument...
# ...Create your parser as you like...
return parser
如果您愿意,您可以稍后对其进行操作,并且测试可能如下所示:
You can later manipulate it if you want, and a test could look like:
class ParserTest(unittest.TestCase):
def setUp(self):
self.parser = create_parser()
def test_something(self):
parsed = self.parser.parse_args(['--something', 'test'])
self.assertEqual(parsed.something, 'test')
这篇关于你如何为 python 模块的 argparse 部分编写测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!