python - 如何模拟包含库中的变量

标签 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

我该如何 mock 这个?这有可能吗?

最佳答案

当然,问题在于您无法模拟使用它的 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'

另请注意,模拟仅针对单个测试的范围进行,因此您不能像 BuiltIn 那样在测试模块顶部导入文件在那里未打补丁,引发上下文错误。

关于python - 如何模拟包含库中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51043304/

相关文章:

python - 发生异常时测试失败的正确断言是什么?

python - 简化嵌套 for 循环

Python:列表数组中的唯一值

python - 将非顺序列表元素分配给变量

python - 在所有测试中修补多个模块变量

Python 使用 pytest_mock 在函数中模拟多个查询

python - 使用多个条件的 Pandas 逻辑索引

python - python中如何响应线程中的异常

python - 在 pytest 产量 fixture 中使用 request.function 时出现 AttributeError

python - 运行 pytest 时 more-itertools 中的语法无效