0

I have got a simple program my_code.py with argparse and test_code.py with the test code. Please help me with how I should run correctly the test_code.py. When I try basic commands I get an error like below:

test: python -m unittest test_code.py

AttributeError: 'module' object has no attribute 'py'

test case: python -m unittest test_code.Test_Code

python -m unittest: error: too few arguments

test method: python -m unittest test_code.Test_Code.test_double_name

python.exe -m unittest: error: the following arguments are required: name


    # my_code.py
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("name")
    parser.add_argument('-d', '--double', action="store_true")
    
    def double_name(new_name):
      if args.double:
        return new_name + new_name
      else:
        return new_name
    
    if __name__ == "__main__":
        args = parser.parse_args()
        print(double_name(args.name))

    # test_code.py
    import unittest
    import my_code
    
    class Test_Code(unittest.TestCase):
    
      def test_double_name(self):
        my_code.args = my_code.parser.parse_args([])
        self.assertEqual(my_code.double_name('test-name'), 'test-name')
    
        my_code.args = my_code.parser.parse_args(["test-name", "-d"])
        self.assertEqual(my_code.double_name('test-name'), 'test-nametest-name')
    
    if __name__ == "__main__":
      unittest.main()
Pshowo
  • 1
  • 2
  • `code` is a package name in Python - don't use it for your module. – MrBean Bremen Jan 29 '21 at 08:13
  • Also, separate the arg parsing code from your function, e.g. pass the result of the arg parsing to the function. You can put the arg parsing in a separate function, if you want to test that, too. – MrBean Bremen Jan 29 '21 at 08:15

1 Answers1

1

Hello your parser usage is not correct for calling variable

code.py

code.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "--name",
    metavar="name",
    type=str,
)
parser.add_argument(
    "--double",
    metavar="double",
    type=str,
)


def double_name(new_name):
    if args.double:
        return new_name + new_name
    else:
        return new_name


if __name__ == "__main__":
    args = parser.parse_args()
    print(double_name(args.name))

For Testing argparse, You can review This Post