Search code examples
pythonunit-testingsys

Change OS for unit testing in Python


I have some python code that I've been tasked with unit testing that had different branches for different OS's. For example:

if sys.platform == 'win32':
    #DoSomething

if sys.platform == 'linux2':
    #DoSomethingElse

I want to unit test both paths. Is there some way to temporarily change the sys.platform?

Please let me know if I can provide any more information.


Solution

  • Well, you could simply do sys.platform = 'win32', but it is quite ugly solution so instead try the mock module (it has been ported to python2 too).

    >>> # in the test's setup code
    >>> from unittest import mock  # or just "import mock"
    >>> sys = mock.MagicMock()
    >>> sys.configure_mock(platform='win32')
    >>>
    >>> sys.platform
    >>> 'win32'
    

    This way of course you will have to create separate test cases for the operating systems.

    If you want to test it on 'real' OSs, use a Continuous Integration (CI) software. They can be configured to run tests on different operating systems.