python跨平台测试:模拟os.name

时间:2015-05-26 12:37:31

标签: python testing mocking nose

模拟os.name的正确方法是什么?

我正在尝试对使用os.name构建适合平台的字符串的一些跨平台代码进行单元测试。我在Windows机器上运行,但想测试可以在posix或windows上运行的代码。

我试过了:

production_code.py

from os import name as os_name

def platform_string():
    if 'posix' == os_name:
      return 'posix-y path'
    elif 'nt' == os_name:
      return 'windows-y path'
    else:
      return 'unrecognized OS'

test_code.py

import production as production 
from nose.tools import patch, assert_true

class TestProduction(object):
    def test_platform_string_posix(self):
    """
    """
    with patch.object(os, 'name') as mock_osname:
        mock_osname = 'posix'
        result = production.platform_string()
    assert_true('posix-y path' == result)

此操作失败,因为os不在test_code.py的全局范围内。如果import中的'os'为test_code.py,那么我们将始终获得os.name=='nt'

我也试过了:

def test_platform_string_posix(self):
    """
    """
    with patch('os.name', MagicMock(return_value="posix")):
        result = production.platform_string()
    assert_true('posix-y path' == result)

在测试中,但这似乎不起作用,因为os.name是属性而不是具有返回值的方法。

编辑: 澄清以回应评论

  1. mock docs (1st paragraph)似乎直接猴子修补os.name可能会变得混乱,例如断言被提出
  2. 我们实际上只是根据os.name更改路径。虽然测试将在Windows和posix机器上运行,但我希望能够完全覆盖,而不需要在每次进行小编辑时为机器提供资源。

1 个答案:

答案 0 :(得分:2)

根据Where to patch,您应该在os_name中修补production_code。通过

from os import name as os_name

您在名为os.name的{​​{1}}模块中创建production_code引用:之后(在导入时加载)更改os_name无效{{1}参考。

os.name
相关问题