如何在包含的库中模拟变量

时间:2018-06-26 12:46:26

标签: python pytest

伙计,

在将file.py包含到test_file.py的过程中出现问题,即:

file.py使用机器人库BuiltIn

from robot.libraries.BuiltIn import BuiltIn

DEFAULT_IPHY_TTI_TRACE_DIR =
os.path.join(BuiltIn().get_variable_value('${OUTPUT_DIR}'), 'iphy_tti_trace')

当我尝试在自己的file.py中加入test_file.py

import pytest
#import file.py

我收到:

test_file.py:8: in <module>
/opt/ute/python/lib/python2.7/site-packages/robot/libraries/BuiltIn.py:1331: in get_variable_value
return self._variables[self._get_var_name(name)]
/opt/ute/python/lib/python2.7/site-packages/robot/libraries/BuiltIn.py:75: in _variables
return self._namespace.variables
/opt/ute/python/lib/python2.7/site-packages/robot/libraries/BuiltIn.py:71: in _namespace
return self._get_context().namespace
/opt/ute/python/lib/python2.7/site-packages/robot/libraries/BuiltIn.py:66: in _get_context
raise RobotNotRunningError('Cannot access execution context')
E   RobotNotRunningError: Cannot access execution context

我该如何嘲笑?这有可能吗?

1 个答案:

答案 0 :(得分:1)

当然,问题是您不能模拟使用BuiltIn的类(在file.py中)。您必须在声明的地方(在robot.libraries.BuiltIn中模拟该类。

使用mocks

from unittest.mock import patch, MagicMock


def _test_default_iphy_tti_trace_dir():
    with patch('robot.libraries.BuiltIn.BuiltIn.get_variable_value', return_value='/foo/bar'):
        import file
        assert file.DEFAULT_IPHY_TTI_TRACE_DIR == '/foo/bar/iphy_tti_trace'

使用monkeypatch fixture

def test_default_iphy_tti_trace_dir(monkeypatch):
    def mocked_get(self, name):
        return '/foo/bar'

    monkeypatch.setattr('robot.libraries.BuiltIn.BuiltIn.get_variable_value', mocked_get)
    import file
    assert file.DEFAULT_IPHY_TTI_TRACE_DIR == '/foo/bar/iphy_tti_trace'

还请注意,仅在单个测试的范围内进行了模拟,因此您不能import file位于测试模块的顶部,因为BuiltIn将在那里未打补丁,从而引发了上下文错误。