Oskar Persson
Oskar Persson

Reputation: 6765

Real file system accessed when running lxml with pyfakefs

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

Upvotes: 1

Views: 311

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16855

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).

Upvotes: 0

Related Questions