首页 > 解决方案 > 在测试将文本文件作为输入的功能时,如何为测试用例传入字符串?

问题描述

我想为一个类充分测试一些功能:

以下是此设置的示例:

# 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

考虑到输入是文本文件的要求,我怎样才能最好地转换和使用字符串作为测试方法中的输入?

标签: pythoninputtextfile-iopytest

解决方案


这应该使用 StringIO

import io
input_file = io.StringIO(u"your text goes here") # takes unicode as argument

不要在多个带引号的单独字符串中破坏字符串,而是试试这个 -

"this\nthat"

推荐阅读