0

I have file settings.py which looks like:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument("-var", "--variable", dest="variable", default="qwerty",
                    type=str, help="specify variable")
args = parser.parse_args()

variable = args.variable

Test file test_var.py imports that settings.py:

import settings


class TestVar:
    def test_001(self):
        pass

When I laucnh pytest var_test.py::TestVar.test_001 following error is raised:

usage: _jb_pytest_runner.py [-h] [-var VARIABLE]
_jb_pytest_runner.py: error: unrecognized arguments: var_test.py::TestVar::test_001

var_test.py:None (var_test.py)
var_test.py:1: in <module>
    import settings
settings.py:7: in <module>
    args = parser.parse_args()
C:\Python36\lib\argparse.py:1733: in parse_args
    self.error(msg % ' '.join(argv))
C:\Python36\lib\argparse.py:2389: in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
C:\Python36\lib\argparse.py:2376: in exit
    _sys.exit(status)
E   SystemExit: 2

If settings.py is not imported then test executes without error. Why that error raises and how can I import setting.py in test file?

masb
  • 13
  • 1
  • 5
  • 4
    The argument to `pytest` is being parsed by your argument parser, which doesn't expect any non-option arguments. You probably want at least the call to `parser.parse_args()`, if not more of the code, in a `if __name__ == "__main__"` block to prevent it from being executed when `settings.py` is simply imported. – chepner Sep 21 '18 at 20:22
  • Unfortunately that is not an option in my case – masb Sep 22 '18 at 06:32
  • 2
    You don't really have a choice; you have to change `settings.py` *somehow*, because right now `parser.parse_args()` gets called when you import `settings`, and it's parsing the contents of `sys.argv`. – chepner Sep 22 '18 at 13:29

0 Answers0