0

Considering a simple program like:

  • main.py
  • Reader.py
  • test_Reader.py

Let's assume Reader.py is 100% coverage-tested by test_Reader.py.

How would one go with testing a main that would look like this:

from Reader import myClass
import argparse
if __name__ == '__main__':
    # argparsing eluded
    parser = argparse.ArgumentParser(description='my descrition')
    parser.add_argument('myarg1', nargs='?',
                default = 1)
    parser.add_argument('myarg2', nargs='?',
                default = 1)
    args = parser.parse_args()
    myClass(args.myarg1, args.myarg2)

How would one go with that? My first argument was that the algorithm is so simple it does not require to be tested. However, I am not sure if there is a reason why you would need to test that.

I know mocking argparse requires some mocking as explained in this question : Pytest with argparse: how to test user is prompted for confirmation? But is it worth the effort to actually mock something that simple (all the actual operations are in the other module)?

PackSciences
  • 135
  • 1
  • 6
  • 3
    Refactor. If you had a function that was used like `args = parse(sys.argv)`, it would be easy to test. – jonrsharpe Jun 15 '22 at 16:11
  • 1
    A starting point might be to move the code from the `if __name__ == '__main__':` block into a function. Then you can test the function without having get through the name check – Anentropic Jun 15 '22 at 16:11
  • @Anentropic Do you include the name check inside the function or not? – PackSciences Jun 15 '22 at 16:35
  • no, so have like `if __name__ == '__main__': main()` – Anentropic Jun 15 '22 at 16:41
  • Is there any point to that all things considered? Because like you test almost nothing since you just check that Class(arg1,arg2) with arg1 = 1 and arg2 = 2 returns Class(1,2). – PackSciences Jun 15 '22 at 16:43
  • I thought the point was to test the arg parsing? Up to you if it's worth it, depends how complicated. Maybe good to check that objects are instantiated correctly though. – Anentropic Jun 15 '22 at 16:43
  • Have a look here https://jugmac00.github.io/blog/testing-argparse-applications-the-better-way/ – dosas Jun 22 '22 at 08:54

0 Answers0