我如何模拟python中的sys.platform的价值

发布于 2025-01-24 19:19:58 字数 379 浏览 3 评论 0原文

我的目的是嘲笑Python中的Sys.s.platform的价值为Linux,而不是为我的UNITSESTS而不是Win32。我发现有些人使用Mock.patch,但这并没有改变Sys.platform的值,以执行Python会话。

有什么方法可以在Python会话中嘲笑该价值?

谢谢

解决方案: 我找到了解决这个问题的解决方案。问题是我在一个脚本中嘲笑sys.platform,在另一个脚本中,我是SYS的ImportInt平台。对于Python来说,这不是同一回事,我为该平台获得了另一个价值。

我解决的方式是通过介绍通往平台的整个路径: module_1.submodule_1.platform = mock.magicmock(return_value ='whthing')

My aim is to mock the value of sys.platform in python to be linux instead of win32 for my unittests. I found that some people use mock.patch but that does not change the value of sys.platform for the rest of execution of the python session.

Is there any way to mock that value for ever in the python session?

Thanks

Solution:
I found the solution to this problem. The issue was that I was mocking sys.platform in one script and in another I was importint platform from sys. That is not the same thing for python and I was getting another value for the platform.

The way I solved this was by mocing the whole path to platform:
module_1.submodule_1.platform = mock.MagicMock(return_value='whatever')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲜肉鲜肉永远不皱 2025-01-31 19:19:58

希望这是您要寻找的,这就是我能够模拟平台(在Mac上运行)的方式:

myfunc.py

import sys

# function that I am testing
def print_os():
    if sys.platform == "win32":
        return "We are Windows"
    elif sys.platform == "darwin":
        return "We are Darwin"
    elif sys.platform == "linux":
        return "We are Linux"

myfunc_test.py

import unittest
from unittest.mock import patch

import myfunc


@patch('sys.platform', 'linux')
class TestOS(unittest.TestCase):
    def test_print_os(self):
        self.assertEqual(myfunc.print_os(), "We are Linux")

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

测试:

$ python -m unittest -v myfunc_test.py
test_print_os (main_test.TestOS) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Hope this is what you are looking for, here is how I was able to mock the platform (running on Mac):

myfunc.py

import sys

# function that I am testing
def print_os():
    if sys.platform == "win32":
        return "We are Windows"
    elif sys.platform == "darwin":
        return "We are Darwin"
    elif sys.platform == "linux":
        return "We are Linux"

myfunc_test.py

import unittest
from unittest.mock import patch

import myfunc


@patch('sys.platform', 'linux')
class TestOS(unittest.TestCase):
    def test_print_os(self):
        self.assertEqual(myfunc.print_os(), "We are Linux")

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

testing:

$ python -m unittest -v myfunc_test.py
test_print_os (main_test.TestOS) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文