我有一个代码示例:
from argparse import ArgumentParser
class Wrapper(object):
def __init__(self):
self.modules = set(['gpfs_server', 'gpfs_client'])
self.services = set(['gpfs'])
def get_opts():
parse_wrapper = Wrapper()
parser = ArgumentParser()
parser.add_argument("-i", "--info", dest="show_all",
action = "store_true",
default=False,
help="Show supported services")
args, unknown = parser.parse_known_args()
args.sub_args = []
if unknown:
if unknown[0] not in parse_wrapper.services:
unknown.insert(0, 'base')
args.service = unknown[0]
unknown.remove(unknown[0])
args.sub_args.extend(list(unknown))
return args
我正试图为它编写单元测试。
from mock import patch, Mock, MagicMock
import unittest2 as unittest
import parser
class TestParser(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
reload(parser)
@patch('parser.ArgumentParser')
@patch('parser.Wrapper')
def test_get_opt(self, wrp, arg):
wrp.services = set(['gpfs'])
args_mock = MagicMock()
arg.return_value.add_argument = MagicMock()
arg.return_value.parse_known_args.return_value = (args_mock, ['gpfs', 'status'])
result = parser.get_opts()
self.assertEqual(result, (args_mock, ['gpfs']))
但它不起作用。首先,它返回Namespace,因此不会模拟parse_known_args。其次,它在断言时失败,因为Namespace对象没有 dict 。
self = Namespace(service='base', show_all=False, sub_args=['-v', '--cov', 'gpfs', '--junit-xml', './gpfs-coverage.xml', 'gpfs']), other = 'gpfs'
def __eq__(self, other):
> return vars(self) == vars(other)
E TypeError: vars() argument must have __dict__ attribute
我哪里错了?应该如何测试argparse?