Unit Testing File Modifications

后端 未结 6 1043
轮回少年
轮回少年 2020-12-29 05:47

A common task in programs I\'ve been working on lately is modifying a text file in some way. (Hey, I\'m on Linux. Everything\'s a file. And I do large-scale system admin.)

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 06:27

    For later readers who just want a way to test that code writing to files is working correctly, here is a "fake_open" that patches the open builtin of a module to use StringIO. fake_open returns a dict of opened files which can be examined in a unit test or doctest, all without needing a real file-system.

    def fake_open(module):
        """Patch module's `open` builtin so that it returns StringIOs instead of
        creating real files, which is useful for testing. Returns a dict that maps
        opened file names to StringIO objects."""
        from contextlib import closing
        from StringIO import StringIO
        streams = {}
        def fakeopen(filename,mode):
            stream = StringIO()
            stream.close = lambda: None
            streams[filename] = stream
            return closing(stream)
        module.open = fakeopen
        return streams
    

提交回复
热议问题