How do I set sys.argv so I can unit test it?

Changing sys.argv at runtime is a pretty fragile way of testing. You should use mock‘s patch functionality, which can be used as a context manager to substitute one object (or attribute, method, function, etc.) with another, within a given block of code.

The following example uses patch() to effectively “replace” sys.argv with the specified return value (testargs).

try:
    # python 3.4+ should use builtin unittest.mock not mock package
    from unittest.mock import patch
except ImportError:
    from mock import patch

def test_parse_args():
    testargs = ["prog", "-f", "/home/fenton/project/setup.py"]
    with patch.object(sys, 'argv', testargs):
        setup = get_setup_file()
        assert setup == "/home/fenton/project/setup.py"

Leave a Comment