lundi 25 janvier 2021

How to call function with argparse arguments in unit tests?

Please help my to write the unit test to this:

I have a simple program with one function which return only doubled "name" when run program with argparse argument --double. Otherwise returns 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()

Aucun commentaire:

Enregistrer un commentaire