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()
2
  • code is a package name in Python - don't use it for your module. Commented Jan 29, 2021 at 8: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. Commented Jan 29, 2021 at 8:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.