3

I am creating a test case in python using unittest module.

I did create a parsing argument list that i want to get from user. But when i use that argument while executing the python script, it gives error: "option -i not recognized Usage: testing.py [options] [test] [...]"

code snippet:

class Testclass(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Hello Class"

    def test_addnum(self):
        print "Execute the test case"
        #parser = parse_args(['-i'])
        print 'simple_value     =', args.inputfile

    def parse_args():
        parser = argparse.ArgumentParser()
        parser.add_argument('-i', help='input file', dest='inputfile')
        ns, args = parser.parse_known_args(namespace=unittest)
        #args = parser.parse_args()
        return ns, sys.argv[:1] + args

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

The error m getting on executing the above script with -i somefile.txt is:

option -i not recognized
Usage: testing.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

Examples:
  testing.py                               - run default set of tests
  testing.py MyTestSuite                   - run suite 'MyTestSuite'
  testing.py MyTestCase.testSomething      - run MyTestCase.testSomething
  testing.py MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase

Any help would be appreciated.

5
  • can you also paste the relevant parts from the script? Commented May 29, 2017 at 7:25
  • this is the script only which i want to execute, but when i execute it with option -i somefile.txt it gives error as "option -i not recognized" Commented May 29, 2017 at 7:43
  • never the less, if you want help, you need to show what DOES not work. Your tests work. Do you expect people to guess why your code is not working? Commented May 29, 2017 at 7:44
  • May be we are not at the same pace. Umm, this is the sample code i was trying to take argument from user which i want to print in my testcase "add_num". So I tried this code and executed it with python testing.py -i somefile.c Commented May 29, 2017 at 7:54
  • unittest.main() runs it's own argparse (or equivalent parser). That's the one that's objecting to the -i command. It doesn't even get to the point of running your test case. Commented May 29, 2017 at 18:02

4 Answers 4

8

This script captures the -i command, while still allowing unittest.main to do its own commandline parsing:

import unittest

class Testclass(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Hello Class"

    def test_addnum(self):
        print "Execute the test case"
        #parser = parse_args(['-i'])
        print 'simple_value     =', args.inputfile

import argparse
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', help='input file', dest='inputfile')
    ns, args = parser.parse_known_args(namespace=unittest)
    #args = parser.parse_args()
    return ns, sys.argv[:1] + args

if __name__ == '__main__':
    import sys
    args, argv = parse_args()   # run this first
    print(args, argv)
    sys.argv[:] = argv       # create cleans argv for main()
    unittest.main()

produces:

1113:~/mypy$ python stack44236745.py -i testname -v
(<module 'unittest' from '/usr/lib/python2.7/unittest/__init__.pyc'>, ['stack44236745.py', '-v'])
Hello Class
test_addnum (__main__.Testclass) ... Execute the test case
simple_value     = testname
ok

----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

It looks rather kludgy, but does seem to work.

The idea is to run your own parser first, capturing the -i input, and putting the rest back into sys.argv. Your definition of parse_args suggests that you are already trying to do that.

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

1 Comment

Thanks hpaulj, it worked. Yes it looks kludgy but I found one more solution to it. Hope both the solutions will help someone else facing the same problem. Posting again as an answer
4

Thanks hpaulj, your solution really helped me and I found one more solution for this problem. Hope it helps someone else facing the same issue.

import unittest
import argparse
import sys

class Testclass(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Hello Class"

    def test_addnum(self):
        print "Execute the test case"
        #parser = parse_args(['-i'])
        print 'simple_value     =', args.inputfile

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', help='input file', dest='inputfile')
    parser.add_argument('unittest_args', nargs='*')
    args = parser.parse_args()
    sys.argv[1:] = args.unittest_args
    unittest.main()

Now executing the script with option -i as python testing.py -i somefile.txt gives result as

Hello Class
Execute the test case
simple_value     = somefile.txt
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Comments

0

Your code is setting up your argument parser using

argparse.ArgumentParser()
parser.add_argument('-i', help='input file', dest='inputfile')

in a method of your test class. But I see no indication that the code is actually calling the method.

So at the time you start the program, the parser does not yet exist, because the method TestClass.parse_args() hasn't been called yet.

Move the creation of the parser and specification of its parameters out of the class so that the code calls it when the program starts.

3 Comments

Even after putting the lines outside the method and also outside the class, in both the cases, its giving the same error.
Is your code perhaps setting up another parser that doesn't recognize -i?
I have posted the exact error in the question itself.
0

You are running unittest.main() as the main program. So it's complaining rightfully that it does not know about the option you wrote:

"option -i not recognized"

If you want to create your own test suite launcher you should look into TextTestRunner

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.