使用pyfakefs运行lxml时出错

时间:2017-04-25 09:19:21

标签: python mocking lxml

如何使用lxml运行pyfakefs

import os
import unittest
from lxml import etree
from pyfakefs import fake_filesystem_unittest

class TestExample(fake_filesystem_unittest.TestCase):
    def setUp(self):
        self.setUpPyfakefs()

    def test_lxml(self):
        os.mkdir('/test')

        root = etree.Element("root")
        tree = etree.ElementTree(root)
        tree.write('/test/file.xml')

if __name__ == "__main__":
    unittest.main()

运行上面的示例时,我收到此错误:

Traceback (most recent call last):
  File "example_test.py", line 25, in test_lxml
  File "src/lxml/lxml.etree.pyx", line 2033, in lxml.etree._ElementTree.write (src/lxml/lx
ml.etree.c:63707)
  File "src/lxml/serializer.pxi", line 512, in lxml.etree._tofilelike (src/lxml/lxml.etree
.c:134950)
  File "src/lxml/serializer.pxi", line 571, in lxml.etree._create_output_buffer (src/lxml/
lxml.etree.c:135614)
  File "src/lxml/serializer.pxi", line 560, in lxml.etree._create_output_buffer (src/lxml/
lxml.etree.c:135415)
IOError: [Errno 2] No such file or directory

我在macOS 10.12.4上的Python 2.7.13中使用lxml 3.6.4和pyfakefs 3.1

1 个答案:

答案 0 :(得分:0)

仅供参考:lxml不适用于pyfakefs。来自documentation

pyfakefs不适用于使用C库访问文件系统的Python库(除了os和io之外),因为它无法修补基础C库的文件访问功能

在故障排除一章中:

pyfakefs使用C库访问文件系统。绝对不可能使此类模块与pyfakefs一起使用-如果要使用它,则必须修补整个模块。在某些情况下,已经存在以Python实现的具有类似接口的库。一个示例就是lxml,在大多数情况下可以用ElementTree替换它进行测试。

(@ mzjn的评论中也提到了将lxml替换为xml.etree.ElementTree作为测试的替代方法)。