In python how would I pass an argument from the command line to a unittest function. Here is the code so far… I know it\'s wrong.
class TestingClass(unittes
So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:
import sys
import unittest
class MyTest(unittest.TestCase):
USERNAME = "jemima"
PASSWORD = "password"
def test_logins_or_something(self):
print('username : {}'.format(self.USERNAME))
print('password : {}'.format(self.PASSWORD))
if __name__ == "__main__":
if len(sys.argv) > 1:
MyTest.USERNAME = sys.argv.pop()
MyTest.PASSWORD = sys.argv.pop()
unittest.main()
that will let you run with:
python mytests.py ausername apassword
You need the argv.pops so your command line params don't mess with unittest's own...
[update] The other thing you might want to look into is using environment variables:
import os
import unittest
class MyTest(unittest.TestCase):
USERNAME = "jemima"
PASSWORD = "password"
def test_logins_or_something(self):
print('username : {}'.format(self.USERNAME))
print('password : {}'.format(self.PASSWORD))
if __name__ == "__main__":
MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)
MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
unittest.main()
That will let you run with:
TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py
and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...