python - 需要从 lxml.etree 模块模拟 ElementTree 类的 write() 方法
问题描述
我正在编写一个使用 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()
推荐阅读
- postgresql - 如何在 PostgreSQL 中存储 unsigned long?
- kotlin - 具有默认函数参数值的 Kotlin 接口
- javascript - Mongoose.js CastError:在模型“Projekt”的路径“访问”处,值“{'$gte':1}”转换为数字失败
- vba - 以特定样式运行高亮宏
- java - 连续输出数组的索引
- javascript - 由于没有执行 .appendChild,图像的可见性没有响应
- java - 如果在 Kotlin 与 Java 中声明,用作全局上下文的 MainApplication 类会崩溃
- python-3.x - 无法获取本地颁发者证书 mac OS
- algorithm - 对一个小整数数组进行排序
- bash - SSH 在 bash heredoc 中的 if 语句中没有正确退出