I'm stuck in a situation.
Below is the illustration of same.
I'm passing the values through argument parse. Values of a, b , c.
Code is -
initial_foo(args):
**codes**
args.a, args.b are used here.
If I print args
, it returns self.args = argsparse.Namespace(a='hii',b='bye',c='yolo')
. Now if I pass args
in initial_foo(self.args)
it automatically picks up the values provided through args
.
Now, I want to test this initial_foo(args)
method. So, probably I can do is that setting up the same self.args = argsparse.Namespace(a='hii',b='bye',c='yolo')
and passing in initial_foo
method. What if I don't want to use this.
Is there any other solution of the same ?
Anything which we can do through ```**locals() ?
Please let me know if you have any doubts.
1 Answer 1
If you are thinking on how to unittest the initial_foo
without creating an argparse.Namespace object, then you could pass initial_foo
any object which with properties 'a', 'b', 'c'
and allows dot
notation call.
locals()
doesn't work because that gives you a dict
. dictionary elements are accessed through index (__getitem__
), not dot operator (__getattr__
)
You could create a class, with these props and pass in an object of that class.
class Data(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
initial_foo(Data(1,2,3))
Or pass in a named tuple
from collections import namedtuple
data = namedtuple('data', ['a', 'b', 'c'])
initial_foo(data(1,2,3))
Anything similar should work too.
self.args
object? The use of argsparse implies you are getting these arguments from the command line, right? So why not callinital_foo
viainital_foo('hii', 'bye', 'yolo')
?initial_foo(args)
is only using 2 arguments. So, if I pass args it automatically reads the value of args of the givenargs.a
andargs.b
. Thing is this is just an example. In my code, I'm passing 10 args andfoo_method
is using 5 arguments. But my main question is for testing pupose. How to perform that. I know you will help me .thanks!inital_foo(args.a, args.b)
. Most of the time if you have over, say, 7 arguments to a function, that is a good clue you should refactor to make your functions smaller and require less data passing. I'm not sure I can help you without a real code sample here.