100

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(unittest.TestCase):

    def testEmails(self):
        assertEqual(email_from_argument, "my_email@example.com")


if __name__ == "__main__":
    unittest.main(argv=[sys.argv[1]])
    email_from_argument = sys.argv[1]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christopher H
  • 2,044
  • 6
  • 24
  • 30
  • 9
    The thing is, unit tests should be able to be run automatically, which makes passing arguments difficult. Perhaps if you explained more about what you're trying to test? – kojiro Jul 08 '12 at 03:31
  • 1
    when you run in the command line you can run python testfunction.py and the __name__ =="main" allows for this. I want to be able to run python testfunction.py my_email@example.com my_email2@example.com – Christopher H Jul 08 '12 at 03:33
  • 1
    How about using a configuration file? Would that serve? For example [Nose TestConfig](http://pypi.python.org/pypi/nose-testconfig/) – kojiro Jul 08 '12 at 03:49
  • 1
    I would prefer not to... just a preference, but maybe I should – Christopher H Jul 08 '12 at 04:43
  • 1
    Also see [python, unittest: is there a way to pass command line options to the app](https://stackoverflow.com/questions/1029891/python-unittest-is-there-a-way-to-pass-command-line-options-to-the-ap) (which is an even older question but lacks the [warning about the unit tests ideally being stand alone and not relying on outside information](https://stackoverflow.com/a/11381286/2732969)). – Anon Apr 01 '19 at 09:23

7 Answers7

167

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:', self.USERNAME)
        print('password:', 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 myusername mypassword

You need the argv.pops, so your command line parameters don't mess with unittest's own...

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:', self.USERNAME)
        print('password:', 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. The downside is it won't work quite like that on Windows...

hwjp
  • 15,359
  • 7
  • 71
  • 70
  • Looks like pytest page moved. It is now at [docs.pytest.org](https://docs.pytest.org/en/latest/getting-started.html) – Evgen Jan 02 '18 at 21:43
  • 1
    FYI, I've done something like this in the past: use "--" to separate my args from the ones that unittest might want; then I can pass the list of parameters after the "--" to my own arg parser, and remove them from sys.argv or explicitly pass the args unittest might want using unittest.main(argv=smaller_list) – Joshua Richardson Jan 10 '18 at 22:59
  • 1
    The `sys.argv.pop()` method does not seem to work in `python3`. I would love to know how this can be done in `python3`. – Yeow_Meng Apr 20 '18 at 20:57
  • 2
    @Yeow_Meng, you might need to be more specific. I'm using that with python-3.6.5 and it works. – r2evans Oct 17 '18 at 17:28
  • Very convenient if you want to run the same tests against different environments like different stages, etc. Likely environment variables are cleanest. – Samantha Atkins Aug 09 '19 at 22:07
  • This is important. I am working on a module that tests big tables from Excel and converts them into dataframes. It would be a nightmare to create the test cases and the result of operations (other datadframes) in anything other than Excel. Hence, I need to open once a workbook holding the dataframes and then have all the test cases use the same workbook without without having to open and close it repeatedly. This solution accomplishes this with flying colors. – Pablo A Perez-Fernandez Nov 30 '19 at 12:47
36

Another method for those who really want to do this in spite of the correct remarks that you shouldn't:

import unittest

class MyTest(unittest.TestCase):

    def __init__(self, testName, extraArg):
        super(MyTest, self).__init__(testName)  # calling the super class init varies for different python versions.  This works for 2.7
        self.myExtraArg = extraArg

    def test_something(self):
        print(self.myExtraArg)

# call your test
suite = unittest.TestSuite()
suite.addTest(MyTest('test_something', extraArg))
unittest.TextTestRunner(verbosity=2).run(suite)
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
steffens21
  • 699
  • 6
  • 12
  • Good Example! Another at http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html . But care passed argument not mess with the unittest's.. – Learner Mar 12 '16 at 17:35
  • Thanks. This was helpful in figuring out how to make unittest work for my particular case. – Benny Jobigan Jun 02 '16 at 22:14
  • 1
    Can I do it in a bulk? If there are multiple tests in MyTest class – Alex Jun 05 '17 at 23:55
  • Please can you tell me why have you chosen to not use unitest.main() and instead have used TestSuite/TextTestRunner? – variable Nov 18 '19 at 05:14
  • This was extremely helpful to me because I needed to run this same test with different input arguments, so using `TestSuite` is nice in order to chain the multiple instances of the tests together and run them all. Thanks! – rayryeng Feb 07 '22 at 20:54
14

Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

  • which of the dozen identical USB cards should I use for this test now?
  • which server should I use for this test now?
  • which XXX should I use?

For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

import os
import unittest


class MyTest(unittest.TestCase):
    def setUp(self):
        self.var1 = os.environ["VAR1"]
        self.var2 = os.environ["VAR2"]

    def test_01(self):
        print("var1: {}, var2: {}".format(self.var1, self.var2))

Then from the command line (tested on Linux)

$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Federico
  • 3,782
  • 32
  • 46
5

If you want to use steffens21's approach with unittest.TestLoader, you can modify the original test loader (see unittest.py):

import unittest
from unittest import suite

class TestLoaderWithKwargs(unittest.TestLoader):
    """A test loader which allows to parse keyword arguments to the
       test case class."""
    def loadTestsFromTestCase(self, testCaseClass, **kwargs):
        """Return a suite of all tests cases contained in 
           testCaseClass."""
        if issubclass(testCaseClass, suite.TestSuite):
            raise TypeError("Test cases should not be derived from "\
                            "TestSuite. Maybe you meant to derive from"\ 
                            " TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']

        # Modification here: parse keyword arguments to testCaseClass.
        test_cases = []
        for test_case_name in testCaseNames:
            test_cases.append(testCaseClass(test_case_name, **kwargs))
        loaded_suite = self.suiteClass(test_cases)

        return loaded_suite 

# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)
Community
  • 1
  • 1
sfinkens
  • 1,210
  • 12
  • 15
1

I have the same problem. My solution is after you handle with parsing arguments using argparse or another way, remove arguments from sys.argv:

sys.argv = sys.argv[:1]  

If you need, you can filter unittest arguments from main.parseArgs().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Denis Solovev
  • 79
  • 1
  • 11
0

This is my solution:

# your test class
class TestingClass(unittest.TestCase):

    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "my_email@example.com")


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

You could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests

With the above code, you should be to run your tests with runner.py my_email@example.com.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rootimbo
  • 337
  • 4
  • 10
-5

Unit testing is meant for testing the very basic functionality (the lowest level functions of the application) to be sure that your application building blocks work correctly. There is probably no formal definition of what does that exactly mean, but you should consider other kinds of testing for the bigger functionality -- see Integration testing. The unit testing framework may not be ideal for the purpose.

pepr
  • 20,112
  • 15
  • 76
  • 139
  • 11
    Yes but unittest framework itself can be used (and is used in many cases) to develop and integration test frameworks which often requires complex setup and teardown. In such a case it would be helpful to have a baseclass with test functions and params and with an inherited class with the param definition if possible or to use environment based config script. – Umar Dec 28 '18 at 09:38
  • Agreed with Umar, the unittest framework is very useful for things outside its original purpose, if you're careful it's very handy. Not least because then you integrate with all the other tools, e.g. things it can output to. – Stuart Axon Mar 11 '21 at 22:26