-1

I have following code:

class WebuiSeleniumTest(unittest.TestCase):

    def setup_parser(self):
        parser = argparse.ArgumentParser(description='Automation Testing!')
        parser.add_argument('-p', '--platform', help='Platform for desired_caps', default='Mac OS X 10.9')
        parser.add_argument('-b', '--browser-name', help='Browser Name for desired_caps', default='chrome')
        parser.add_argument('-v', '--version', default='')
        return parser.parse_args()

    def test_parser(self):
        args = self.setup_parser()
        print args


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

When i try to run this in terminal with the command "python myfile.py -b firefox" I get AttributeError: 'module' object has no attribute 'firefox' and the help output is generated. When I isolate it and run it without the if __name__ == "__main__" it works fine. Why does it try to apply my passed argument on unittest ? I need it as a String in my code.

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
thraizz
  • 66
  • 8

1 Answers1

1

Calling your script with python myfile.py -b firefox does indeed go to unittest, and not to your argument parser.

Unittest tries to parse the arguments you gave, e.g. if you call your script like this:

python myfile.py --help

You see the valid options:

Usage: myfile.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:
  parse.py                               - run default set of tests
  parse.py MyTestSuite                   - run suite 'MyTestSuite'
  parse.py MyTestCase.testSomething      - run MyTestCase.testSomething
  parse.py MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase

Looking at the help output -b would buffer (I guess suppress?) stdout/stderr. The argument firefox is taken as the name of the test to run in your module. And there is no function method existing, it outputs this error:

AttributeError: 'module' object has no attribute 'firefox'

Now, what you probably want to do is to call test_parser, and if you do that with python myfile.py WebuiSeleniumTest.test_parser then you cannot pass any additional arguments. And that's probably your question in the end. There is this question which gives some possible solutions for testing argparse as unit test.

hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Great answer, not only answering my question but even teaching me where I went wrong. Exactly what I was looking for. Thank you and have a great weekend ! – thraizz Dec 15 '17 at 15:13