python - 需要从 lxml.etree 模块模拟 ElementTree 类的 write() 方法

标签 python unit-testing mocking lxml cython

我正在编写一个方法,该方法使用 lxml.etree 中 ElementTree 类的 write 方法。在编写测试时,我想模拟它,以便单元测试不会向我的驱动器写入一堆内容。

我的文件中的代码看起来像这样

    # myapp\gla.py
    from lxml.etree import Element, ElementTree

    def my_func(element):
        root = Element(element)
        xml = ElementTree(root)
        xml.write('path_to_file')

测试如下:

    # tests\test_gla.py
    from unittest import patch
    from myapp.gla import my_func

    @patch('myapp.gla.ElementTree.write')
    def test_my_func(self, mock_write):
        my_func('rootElement')
        mock_write.assert_called_once()

我明白了

    Traceback (most recent call last):
      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1171, in patched
        arg = patching.__enter__()
      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1243, in __enter__
        original, local = self.get_original()
      File "C:\Anaconda2\envs\py36\lib\unittest\mock.py", line 1217, in get_original
        "%s does not have the attribute %r" % (target, name)
    AttributeError: <cyfunction ElementTree at 0x000001FFB4430BC8> does not have the attribute 'write'

最佳答案

找到了我自己问题的答案。

像这样重写测试:

# tests\test_gla.py
from unittest import patch, MagicMock
from myapp.gla import my_func

@patch('myapp.gla.ElementTree')
def test_my_func(self, mock_write):
    mock_write().write = MagicMock()
    my_func('rootElement')
    mock_write().write.assert_called_once()

关于python - 需要从 lxml.etree 模块模拟 ElementTree 类的 write() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173033/

相关文章:

c# - Moq It.Is<> 不匹配

python - 针对自定义数据集微调 Azure OpenAI 模型

eclipse - 在命令行上使用gradle运行时,junit运行正常,但作为junit测试,无法在eclipse上运行

angular - 单元测试 : Mocking service that returns observables to return subjects in order to test change of values over time causes TS to throw TS2339

javascript - 将参数传递给 jest 函数

java - 行为验证的值(value)

python - Pandas 和 matplotlib : Combine two plots into one legend item

python - 为什么 Python 的 print 函数会这样?

python - 从 PayPal 应用程序检索所有付款信息

unit-testing - 如何将单元测试项目添加到我现有的 asp.net core 项目中?