darksky
darksky

Reputation: 21019

Python unittest module command line arguments without main

I am trying to pass in command line arguments to my unit tests. However, I am not using an if __name__ == '__main__' block, as everything is packaged as a relative path. So calling python path/to/test.py will throw this error:

from .setup import Utilities
ValueError: Attempted relative import in non-package

I am calling the tests as follows: python -m unittest test_file.test_name. This startups with the setUpModule() function. However, it seems that the command line parsing happens before that function somewhere in the unit test library, so passing in anything that is not a module throws an error. So doing: python -m unittest test_file.test_name arg1 throws: ImportError: No module named arg1.

Is there any way around this, without having to use if __name__ == '__main__'?

Upvotes: 2

Views: 636

Answers (1)

hpaulj
hpaulj

Reputation: 231325

Asking unittest for help gives the following message

$ ../python3 -m unittest -h
Usage: python3 -m unittest [options]

Options:
  -h, --help      show this help message and exit
  -v, --verbose   Verbose output
  -q, --quiet     Quiet output
  -f, --failfast  Stop on first fail or error
  -c, --catch     Catch ctrl-C and display results so far
  -b, --buffer    Buffer stdout and stderr during tests

The unittest doc describes these further. So unittest takes some options (and even one subcommand, discover). But I don't see evidence of a way to pass options through to your own module.

Playing around with -m unittest a bit more, it is evident that unittest tries to parse any options (e.g. -z). And everything else like your arg1 is part of the list of modules to test.

Upvotes: 1

Related Questions