Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 541
GGMG-he-him Avatar asked Feb 12 '23 05:02

GGMG-he-him


2 Answers

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.

like image 98
anonymous_user_13 Avatar answered Feb 15 '23 11:02

anonymous_user_13


Old question but still #1 on searches, so wanted to give my take. The accepted answer does not work if sys is imported by the package which is to be tested.

I used the following to change the value of sys.platform in a tested package:

import unittest
import sys
from unittest import mock


class TestSystemCheck(unittest.TestCase):
    """Test the mypackage import"""

    def tearDown(self):
        """Clean up after each test"""
        for key in ['mypackage', 'mypackage._mypackage', 'mypackage._system_check']:
            if key in sys.modules:
                del sys.modules[key]

    def test_check(self):
        import mypackage
        mypackage.MyClass()

    @mock.patch('sys.platform', 'unsupported_platform')
    def test_check_fail(self):
        with self.assertRaises(RuntimeError):
            import mypackage
            mypackage.MyClass()

In the example the import will fail on an unsupported platform. Note that un-importing the hidden modules of mypackage is needed to trigger a fresh import in each test.

sys.platform should probably be mocked by a mock object instead of a plain string, but I could not get that to work.

like image 28
Roberto Avatar answered Feb 15 '23 10:02

Roberto