Python尾部文件读取

时间:2016-11-13 15:30:56

标签: python io fifo with-statement

在测试中,我将stderr重定向到文件中并尝试以尾部方式读取它。 所以这里是重定向:

class RedirectedEnv(object):
    def __init__(self, stderr=None):
        self._stderr = stderr or sys.stderr

    def __enter__(self):
        self.old_stderr = sys.stderr
        self.old_stderr.flush()
        self.old_exit = getattr(sys, 'exit')
        sys.stderr = self._stderr

        def mock_exit():
            raise Exception
        sys.exit = mock_exit

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._stderr.flush()
        sys.stderr = self.old_stderr
        sys.exit = self.old_exit

        self._stderr.close()

及其用法:

def test_invalid_args(self):
    with RedirectedEnv(stderr=tempfile.NamedTemporaryFile()):
        for args in [['-id', '123456789.00'], ['-i'], ['-i', '0'], ['-i', '../some_invalid_path/not_exist.json']]:
            try:
                self.parser.parse(args)
            except Exception:
                sys.stderr.flush()
                self.assertTrue(sys.stderr.readlines()[0].startswith("usage:")) <<-- here I need help

有一些优雅的方法吗? (不要将enumeratetell()seek()混为一谈)也许某些FIFO queue带有文件界面?

1 个答案:

答案 0 :(得分:1)

您可以为每个测试创建一个新文件,并在前面搜索以获取其值。由于您没有使用文件名,我已移至TemporaryFile

def test_invalid_args(self):
    for args in [['-id', '123456789.00'], ['-i'], ['-i', '0'], ['-i', '../some_invalid_path/not_exist.json']]:
        with RedirectedEnv(stderr=tempfile.TemporaryFile()):
            try:
                self.parser.parse(args)
                raise AssertionError("should have failed")
            except Exception:
                sys.stderr.seek(0)
                self.assertTrue(sys.stderr.readline().startswith("usage:"))