如何使用Python创建未正确关闭的gzip文件?

问题描述 投票:0回答:1

我有一个应用程序偶尔需要能够读取未正确关闭的 gzip 文件。这些文件的行为如下:

>>> import gzip
>>> f = gzip.open("path/to/file.gz", 'rb')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/gzip.py", line 292, in read
    return self._buffer.read(size)
  File "/usr/lib/python3.8/gzip.py", line 498, in read
    raise EOFError("Compressed file ended before the "
EOFError: Compressed file ended before the end-of-stream marker was reached

我编写了一个函数来通过逐行读取文件并捕获

EOFError
来处理此问题,现在我想测试它。

我的测试的输入应该是一个 gz 文件,其行为方式与演示的相同。 如何在受控测试环境中实现这一点?

我真的强烈不想复制我在生产中获得的未正确关闭的文件。

python python-3.x unit-testing pytest gzip
1个回答
0
投票

非常简单:进行压缩,然后剪切结果。

导入gzip 普通= b“东西” 压缩 = gzip.compress(普通) bad_compressed = 压缩[:-1] gzip.decompress(bad_compressed) # EOFError

© www.soinside.com 2019 - 2024. All rights reserved.