Change OS for unit testing in Python

邮差的信 提交于 2019-12-11 02:19:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/25431426/change-os-for-unit-testing-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!