1

How can I run lxml with 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()

When running the example above I get this error:

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

I am using lxml 3.6.4 and pyfakefs 3.1 in Python 2.7.13 on macOS 10.12.4

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
Oskar Persson
  • 6,605
  • 15
  • 63
  • 124
  • I can reproduce the error with the same versions of Python, lxml and pyfakefs on Windows 10. It works if xml.etree.ElementTree is used instead of lxml. – mzjn Apr 25 '17 at 17:22

1 Answers1

0

Just for reference: lxml does not work with pyfakefs. From the documentation:

pyfakefs will not work with Python libraries (other than os and io) that use C libraries to access the file system, because it cannot patch the underlying C libraries’ file access functions

And from the troubleshooting chapter:

pyfakefs uses C libraries to access the file system. There is no way no make such a module work with pyfakefs–if you want to use it, you have to patch the whole module. In some cases, a library implemented in Python with a similar interface already exists. An example is lxml, which can be substituted with ElementTree in most cases for testing.

(replacing lxml with xml.etree.ElementTree as an alternative for testing has also been mentioned in the comments by @mzjn).

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46