I have a class that takes argparse
args with many options:
class A:
def __init__(self, args):
self.args = args
def something(self):
if self.args.option1:
...
...
p = argparse.ArgumentParser()
p.add_argument("--option1", action="store_true")
p.add_argument("--option2", action="store_true")
...
args = p.parse_args()
a = A(args)
a.something()
Now I want to test that
def test_something():
a = A(...) # What to put here?
It would be nice if I could have Mock
that returns False
for every option. I could write
def test_something():
m = Mock()
for attr in ["option1", "option2"]:
setattr(m, attr, lambda: False)
a = A(m)
...
But there can be dozens of options and I am pretty sure it should be possible to do that in some elegant way without listing them.
How to achieve my goal without listing all parser options again?
CodePudding user response:
You don't need a mock. You can either call p.parse_args
with an explicit list of arguments, or you can construct an appropriate Namespace
instance manually.
def test_something():
# If you have access to p
args = p.parse_args([]) # produces Namespace(option1=False, option2=False)
a = A(args)
or
from argparse import Namespace
def test_something():
args = Namespace(option1=False, option2=False)
a = A(args)
CodePudding user response:
During writing the question such solution came to my mind:
class FalseMock(Mock):
def __getattr__(self, name: str):
return lambda: False
But doesn't seem elegant enough for me, maybe some of you have different ideas?