unit testing - How do you write tests for the argparse portion of a python module? -


i have python module uses argparse library. how write tests section of code base?

you should refactor code , move parsing function:

def parse_args(args):     parser = argparse.argumentparser(...)     parser.add_argument...     # ...create parser like...     return parser.parse_args(args) 

then in main function should call with:

parser = parse_args(sys.argv[1:]) 

(where first element of sys.argv represents script name removed not send additional switch during cli operation.)

in tests, can call parser function whatever list of arguments want test with:

def test_parser(self):     parser = parse_args(['-l', '-m'])     self.asserttrue(parser.long)     # ...and on. 

this way you'll never have execute code of application test parser.

if need change and/or add options parser later in application, create factory method:

def create_parser():     parser = argparse.argumentparser(...)     parser.add_argument...     # ...create parser like...     return parser 

you can later manipulate if want, , test like:

class parsertest(unittest.testcase):     def setup(self):         self.parser = create_parser()      def test_something(self):         parsed = self.parser.parse_args(['--something', 'test'])         self.assertequal(parsed.something, 'test') 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -