python - 在测试将文本文件作为输入的功能时,如何为测试用例传入字符串?
问题描述
我想为一个类充分测试一些功能:
- 将强制文本 (
.txt
) 文件作为输入 - 执行一些任意操作
- 能够提供结果
以下是此设置的示例:
# my_class.py
class MyClass:
def __init__(self, file):
self.__some_attr = dict(MyClass.__process_text_file(file)
# ...
@staticmethod
def __process_text_file(file):
# file actually used here
for line in open(file):
# ...
yield ("something unique derived from 'line'", "something derived from 'line'")
def get_thing(self):
# ...
return self.__some_attr
使用 提供测试输入pytest
时,我能够成功传入本地文件,并按预期通过测试:
# test_my_class.py
class TestMyClass:
def test_input(self):
expected = (
"expected\n"
"results"
)
input_file = "path/to/input_file.txt"
under_test = MyClass(input_file)
assert under_test.get_thing() == expected
# success
为了完整起见,这可能是一个示例输入文件:
# input_file.txt
something that leads to the expected
processed results
我希望能够在测试方法中使用字符串,以便于测试多个(可能是参数化的)案例,并避免.txt
为我可能希望包含的任何案例提供夹具文件。
传入时string
:
input_file = (
"this\n"
"that"
)
我得到以下信息(如预期的那样):
def __process_text_file(file):
> for line in open(file):
E OSError: [Errno 22] Invalid argument: 'this\nthat'
传入时StringIO
:
input_file = StringIO(
"this\n"
"that"
)
我得到以下信息(如预期的那样):
def __process_text_file(file):
> for line in open(file):
E TypeError: expected str, bytes or os.PathLike object, not _io.StringIO
考虑到输入是文本文件的要求,我怎样才能最好地转换和使用字符串作为测试方法中的输入?
解决方案
这应该使用 StringIO
import io
input_file = io.StringIO(u"your text goes here") # takes unicode as argument
不要在多个带引号的单独字符串中破坏字符串,而是试试这个 -
"this\nthat"
推荐阅读
- python - Pandas 中的子字符串元素
- java - android - 当应用程序未运行时通过 Intent 从通知中获取数据
- apache-spark - 如何将日志从纱线容器转发到 s3?
- php - 字符串和重音 PHP 的问题
- javascript - 手风琴按钮不会在 WordPress 中切换
- c# - 如何在文本框中设置 DateFormat(语言)?
- python - 在 Jupyter Notebook 中运行 Python 脚本,并传递参数
- docker - 如何从docker中的neo4j获取转储?
- sql - 在我的虚拟机中,链接到数据库的应用程序未在其他虚拟机中打开的位置打开?
- python - 为什么“NONE”出现在我的输出中