0

I am trying to run a basic unit test on Python 2.6 that takes arguments with argparse.

I am limited in my environment and cannot install any further libraries or use any modules for testing but unittest.

However I believe the answer lies here:

How do you write tests for the argparse portion of a python module?

However I am having trouble refactoring the provided main answer with my code.

Without refactoring my example code I have provided, can someone please show me the light and show me how to write a unittest for the below code, that takes the -H and -S on the fly?

Thanks in advance.


#!python
import argparse
import sys

try:
    HOSTNAME = sys.argv[2]
    SOMESTRING = sys.argv[3]
except IndexError:
    print "Please Enter the Hostname and Somestring"


def argparse_msg():
    return "testscript_example -H somehost -S somestring"


def check_arg(args=None):
    parser = argparse.ArgumentParser(description="A Test Example", usage=argparse_msg())
    parser.add_argument("-H", "--host",
                        help="HostName",
                        required=True)

    parser.add_argument("-S", "--somestring",
                        help="HostName",
                        required=True)

    results = parser.parse_args(args)

    return (results.host, results.somestring)


def message_test():
    print HOSTNAME + " " + SOMESTRING


def main():
    message_test()


if __name__ == "__main__":
    HOSTNAME, SOMESTRING = check_arg(sys.argv[1:])
    main()
Gavin Jones
  • 185
  • 1
  • 3
  • 15
  • When using `unittest` (or other testing package), you can't supply commandline values for your own script. The commandline is for `unittest` itself (which has its own parser). Other links: https://stackoverflow.com/questions/51710083/how-to-run-pytest-with-a-specified-test-directory-on-a-file-that-uses-argparse, https://stackoverflow.com/questions/42331049/how-to-test-python-classes-that-depend-on-argparse – hpaulj Apr 02 '19 at 05:27
  • Still trying to get my head around it, would be great if you could show a basic example in code.... – Gavin Jones Apr 02 '19 at 05:40

1 Answers1

2

To facilitate test class, I have modified the code as following:

  • Removed global variables (e.g.: HOSTNAME, SOMESTRING)
  • Passed parameters to functions
  • Returned string from function rather than printing (from message_test and main)

Updated code receiver.py:

#!python
import argparse
import sys


def argparse_msg():
    return "testscript_example -H somehost -S somestring"


def check_arg(args=None):
    parser = argparse.ArgumentParser(description="A Test Example", usage=argparse_msg())
    parser.add_argument("-H", "--host",
                        help="HostName",
                        required=True)
    parser.add_argument("-S", "--somestring",
                        help="HostName",
                        required=True)
    results = parser.parse_args(args)
    return (results.host, results.somestring)


def message_test(HOSTNAME, SOMESTRING):
    return "{} {}".format(HOSTNAME, SOMESTRING)


def main(HOSTNAME, SOMESTRING):
    return message_test(HOSTNAME, SOMESTRING)


if __name__ == "__main__":
    HOSTNAME, SOMESTRING = check_arg(sys.argv[1:])
    print(main(HOSTNAME, SOMESTRING))

Output of running receiver.py:

python receiver.py -H localhost -S demo
localhost demo

Test file (test_receiver.py):

from receiver import check_arg
import unittest

class ParserTest(unittest.TestCase):

    def test_main(self):
        HOSTNAME, SOMESTRING = check_arg(['-H', 'test', '-S', 'sample string'])
        self.assertEqual(HOSTNAME, 'test')
        self.assertEqual(SOMESTRING, 'sample string')        

if __name__ == '__main__':
    unittest.main()

Output of running the test_receiver.py:

python test_receiver.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
arshovon
  • 13,270
  • 9
  • 51
  • 69