Please help me to write the unit test to this:
I have a simple program with one function which returns only doubled "name" when run the program with argparse argument --double
. Otherwise returns a single name
# code.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument('-d', '--double', action="store_true")
args = parser.parse_args()
def double_name(new_name):
if args.double:
return new_name + new_name
else:
return new_name
print(double_name(args.name))
- run in cmd
python code.py test-name
I have a result: test-name
- run in cmd
python code.py test-name -d
I have a result: test-nametest-name
I want to write unittest to check this function, but I don't know how to call this function with argparse arguments in unit test.
# test_code.py
import unittest
import code
class Test_Code(unittest.TestCase):
def test_double_name(self):
# without -d
self.assertEqual(code.double_name('test-name'), 'test-name')
# with -d
self.assertEqual(code.double_name('test-name'), 'test-nametest-name')
if __name__ == "__main__":
unittest.main()
How should look the run command this test? If I add to code:
code.args = code.parser.parse_args(["test-name", "-d"])
the standard commands python -m unittest test_code.py
raise AttributeError
AttributeError: 'module' object has no attribute 'py'
question from:
https://stackoverflow.com/questions/65886922/how-to-call-function-with-argparse-arguments-in-unittests 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…