Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

unit testing - Pytest test file that reads from current directory

I am trying to do a unit test with Pytest on a function of the form

def function():
    with open('file.txt', 'r') as file:
        # read for information in file
    return information_from_file

I want to make a temporary directory which I can use the function to read from. This lead me to using tmpdir and tmpdir_factory, however both these options require that a path object is inputted as an argument from what I can tell. Though in this case, that isn't an option since the function is reading from the current directory rather than a directory that was inputted.

Is there a way to use Pytest in order to do a test on this kind of function?

question from:https://stackoverflow.com/questions/65908999/pytest-test-file-that-reads-from-current-directory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use mock_open, but that would be a glass-box test breaking the encapsulation of the function. If the filename changes, the test breaks. If it changes its implementation, the test breaks.

More importantly, it ignores what your test is telling you.

Testing is a great way to find out where your design is too rigid. If you find a function hard to test, its probably hard to use. Hard coded filenames are a classic example. This is an opportunity to make the code more flexible. For example, introduce a configuration object.

def function():
    with open(MyApp.config('function','file'), 'r') as file:
        # read for information in file
    return information_from_file

Exactly how this is implemented depends on your situation. You can use Python's built in ConfigParser to work with the config file. And here I've gone with an application singleton object to store application-wide information.

Then you have two tests. One which checks the default MyApp.config('function','file') is as expected. And other which sets MyApp.config('function','file') to a temp file and tests the function reads it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...