Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to run unit test which testing the script with argparse attributes?

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()
question from:https://stackoverflow.com/questions/65950740/how-to-run-unit-test-which-testing-the-script-with-argparse-attributes

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...