【发布时间】:2021-03-22 03:55:07
【问题描述】:
我想为以下函数编写单元测试:
#!/usr/bin/env python3
"""IPv4 validation using `ipaddress module` and argparse."""
import argparse
from ipaddress import ip_address
def parse_cli_args():
"""
Command line parser for subnet of interest.
Args:
--ip 0.0.0.0
Returns:
String, e.g. 0.0.0.0
"""
parser = argparse.ArgumentParser(description="IPv4 address of interest.")
parser.add_argument("--ip", action="store", type=ip_address,\
required=True,\
help="IP address of interest, e.g. 0.0.0.0")
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_cli_args()
print(args.ip)
按预期工作,例如:
python3 test.py --ip 192.168.1.1
192.168.1.1
python3 test.py --ip derp
用法:test.py [-h] --ip IP test.py:错误:参数--ip:无效的 ip_address 值:'derp'
python3 test.py --ip
用法:test.py [-h] --ip IP test.py: error: argument --ip: 期望一个参数
如何在单元测试中模拟这三个条件?
我尝试了一些变体:
import unittest
from unittest.mock import patch
class ParseCLIArgs(unittest.TestCase):
"""Unit tests."""
@patch('builtins.input', return_value='192.168.1.1')
def test_parse_cli_args_01(self, input):
"""Valid return value."""
self.assertIsInstance(parse_cli_args(), ipaddress.IPv4Address)
if __name__ == '__main__':
unittest.main()
没有成功。我做错了什么,我该如何解决?
编辑我更进一步:
class ParseCLIArgs(unittest.TestCase):
def setUp(self):
self.parser = parse_cli_args()
def test_parser_cli_args(self):
parsed = self.parser.parse_args(['--ip', '192.168.1.1'])
self.assertIs(parsed.ip, '192.168.1.1')
if __name__ == '__main__':
unittest.main()
失败:TypeError: isinstance() arg 2 must be a type or tuple of types。我相信这是因为该函数实际上会转换用户输入。
【问题讨论】:
-
不详细阅读您的问题,我将进行一般性观察。测试框架作品通常有自己的解析器和命令行参数。因此,在此基础上添加您自己的论点可能会很棘手。我不建议在测试框架中包含
argparse。至于你的问题,不完整。 “没有成功”是对您的问题的不充分描述。 -
我想编写一个模拟有效用户输入的测试,例如
--ip 192.168.1.1。提供的测试失败并出现以下错误:usage: test2.py [-h] --ip IP test2.py: error: the following arguments are required: --ip,表明我实际上并没有正确传递模拟。
标签: python-3.x argparse python-unittest python-mock