Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

python - How to call function with argparse arguments in unittests?

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))
  1. run in cmd python code.py test-name I have a result: test-name
  2. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do the accessing of parsed data outside of the function, and pass the data in. Then it doesn't matter where the data comes from:

def double_name(new_name, double):
  if double:
    return new_name + new_name
  else:
    return new_name

print(double_name(args.name, args.double))

Then:

self.assertEqual(code.double_name('test-name', False), 'test-name')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...