I'd like to sufficiently test some functionality for a class that:
- takes a mandatory text (
.txt
) file as input - performs some arbitrary operation
- is able to provide the result
Below is an example of this setup:
# 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
When providing an test input using pytest
, I am able to successfully pass in a local file, and have the test pass as expected:
# 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
For the sake of completion, this might be an example input file:
# input_file.txt
something that leads to the expected
processed results
I would like to be able to use a string within the test method, both for ease of testing multiple (possibly parametrized) cases, and to avoid having a .txt
fixture file for any case I may wish to include.
When passing in a string
:
input_file = (
"this\n"
"that"
)
I get the following (as expected):
def __process_text_file(file):
> for line in open(file):
E OSError: [Errno 22] Invalid argument: 'this\nthat'
When passing in a StringIO
:
input_file = StringIO(
"this\n"
"that"
)
I get the following (as expected):
def __process_text_file(file):
> for line in open(file):
E TypeError: expected str, bytes or os.PathLike object, not _io.StringIO
Considering the requirement for the input to be a text file, how can I best convert and use strings as input within the test method?