Pythonic 相当于 ./foo.py < bar.png

标签 python unit-testing

我有一个从 sys.stdin 读取的 Python 程序, 所以我可以用 ./foo.py < bar.png 来调用它.如何从另一个 Python 模块中测试此代码?也就是说,如何在运行测试脚本时将 stdin 设置为指向文件的内容?我不想做类似 ./test.py < test.png 的事情.我不认为我可以使用 fileinput ,因为输入是二进制的,我只想处理一个文件。使用 Image.open(sys.stdin) 打开文件来自 PIL .

最佳答案

您应该概括您的脚本,以便除了用作独立程序外,还可以从测试脚本中调用它。这是执行此操作的示例脚本:

#! /usr/bin/python

import sys

def read_input_from(file):
    print file.read(),

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # filename supplied, so read input from that
        filename = sys.argv[1]
        file = open(filename)
    else:
        # no filename supplied, so read from stdin
        file = sys.stdin
    read_input_from(file)

如果使用文件名调用,将显示该文件的内容。否则,将显示从标准输入读取的输入。 (能够在命令行上传递文件名可能是对 foo.py 脚本的有用改进。)

在测试脚本中,您现在可以使用文件调用 foo.py 中的函数,例如:

#! /usr/bin/python

import foo

file = open("testfile", "rb")
foo.read_input_from(file)

关于Pythonic 相当于 ./foo.py < bar.png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948247/

相关文章:

python - 如何在 Robot Framework 中编写 if 语句的多个条件

python - 我如何在 Django 中处理这样的数据库 ORM 情况?

python - Scrapy,验证码登录失败

Node.JS:测试代码与生产代码组织

c# - 使用 Reactive Extensions 对事件进行单元测试

firebase - 使用 @firebase/testing 连接到 Firestore 模拟器

javascript - ReactJS:如何测试 ref?

ios - 在单元测试中模拟iOS应用程序版本号

python - 沿 numpy 数组的一个轴随机保留不为零的单个元素

python - Matplotlib:seaborn 导入后忽略 matplotlibrc 文件