写入文件在单元测试中不起作用

时间:2018-03-27 08:41:37

标签: python python-2.7 unit-testing

我有一个函数可以将一些数据写入文件。我在python解释器中运行它并且它正如预期的那样工作但是当我在unittest中运行它时它只创建文件并且不写入任何内容。 这是我的代码:

def write(text):
    with open('test.db', 'a') as db:
        db.write(text)

当我在python解释器test.db中更新它时,但是当我从unittest运行它时它不起作用而且没有添加到test.db。我需要进行unittest更改,我该如何解决?

以下是完整代码:

# dbwrapper/file.py

class Status:
    UP = 'up'
    DOWN = 'down' 

class FileWrapper:
    def __init__(self, path):
        self.path = path

    def get_service_status(self, service_id):
        for line in self._reverse_readline():
            service_id, time_string, status = line.split('#')
            service_id = service_id.strip().replace('\\n', '\n').replace('\@', '#')
            time_string = time_string.strip()
            status = status.strip()
            if service_id == self.service_id:
                return status
        return Status.UP

    def set_service_status(self, service_id, status):
        if status not in self.status_list:
            raise InvalidStatus
        with open(self.path, 'a') as db:
            db.write(
                '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{
                    'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'),
                    'time': datetime.utcnow(),
                    'status': status
                }
            )
            print '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{
                    'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'),
                    'time': datetime.utcnow(),
                    'status': status
                }
    def _reverse_readline(self, buf_size=8192):
        """a generator that returns the lines of a file in reverse order"""
        with open(self.path, 'w+') as fh:
            segment = None
            offset = 0
            fh.seek(0, os.SEEK_END)
            file_size = remaining_size = fh.tell()
            while remaining_size > 0:
                offset = min(file_size, offset + buf_size)
                fh.seek(file_size - offset)
                buffer = fh.read(min(remaining_size, buf_size))
                remaining_size -= buf_size
                lines = buffer.split('\n')
                # the first line of the buffer is probably not a complete line so
                # we'll save it and append it to the last line of the next buffer
                # we read
                if segment is not None:
                    # if the previous chunk starts right from the beginning of line
                    # do not concact the segment to the last line of new chunk
                    # instead, yield the segment first 
                    if buffer[-1] is not '\n':
                        lines[-1] += segment
                    else:
                        yield segment
                segment = lines[0]
                for index in range(len(lines) - 1, 0, -1):
                    if len(lines[index]):
                        yield lines[index]
            # Don't yield None if the file was empty
            if segment is not None:
                yield segment


# test/test_dbwrapper.py
class TestFileWrapper(unittest.TestCase):
    PATH = 'test.db'
    SERVICE_ID = '#test_service\n'

    def setUp(self):
        self.filewrapper = FileWrapper(self.PATH)

    def tearDown(self):
        self.filewrapper = None
        # os.remove(self.PATH)

    def test_status(self):
        self.assertEqual(
            self.filewrapper.get_service_status(self.SERVICE_ID),
            Status.UP
        )
        self.filewrapper.set_service_status(self.SERVICE_ID, Status.DOWN)
        self.assertEqual(
            self.filewrapper.get_service_status(self.SERVICE_ID),
            Status.DOWN
        )

我用这个命令运行它:

python -m test.test_dbwrapper

1 个答案:

答案 0 :(得分:0)

无论环境如何,单元测试都应该完美无缺;一个简单而糟糕的想法是编写一些使用真实文件的单元测试,并简单地测试读写。但顺便说一句,在这里你可以看到一个测试函数的例子,它在文件上写了一些东西:

import unittest


class TestExample(unittest.TestCase):

    def test_something(self):
        f = open('filename.txt', 'w')
        f.write('The owls are not what they seem')
        f.close()

        f = open('filename.txt', 'r')
        txt = f.read()
        f.close()
        self.assertEqual(txt, 'The owls are not what they seem')


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

当你使用python 2运行它时:

$ python2 test.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

文件名的内容:

$ cat filename.txt 
The owls are not what they seem