问题
I have a code sample:
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
And I'm trying to write unittests for it.
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']))
But it doesn't work. First of all, it returns Namespace, so parse_known_args is not mocked. Second, it fails on assertion, as Namespace object has no 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
Where am I wrong? How argparse should be tested?
来源:https://stackoverflow.com/questions/32393206/test-argparse-with-unittest-and-mock