How to mock out some functions inside a module which I want to be imported?

Viewed 287

CAUTION: This situation was happened because of a mistake. Check my answer.

I have a python file (myfile.py) which I want to test its content with Pytest. (The content is changing dynamically)
I've wrote this code:

import importlib

def test_myfile(capsys, monkeypatch):
    monkeypatch.setattr('builtins.input', lambda s: "some_input")

    # Create a module from the custom Problem file and import it
    my_module = importlib.import_module("myfile")

    # Rest of the test script

when I run the test I'm getting this error:

OSError: reading from stdin while output is captured

The error has been produced because there is an input() instruction in myfile.py and it means that mocking that function was futile.

My Question:
How can I mock out some functions inside a module I want to import?

1 Answers

Finally I found that I was looking wrong place to find a solution.
actually I use pytest to check a learner response and grade it. this was the way I did that at the moment I asked this question.

py.test test_runner.py test_case.py -v

This will test the user response which is saved in test_case.py ( I get the second parameter inside my test method and load its content and for example run a desired function ). Then I was examining the report of pytest to see if there was an error or failure to decide about the result. (pass/failure) normally pytest was failing if there was an error in users code (e.g. syntax error) or if the test was failing (e.g. didn't return what it must return)

This time there was an error I didn't want to stop the test. I want to mock out input() function in users code. when I was running the command, before running my test method, pytest imported both files to collect test methods. It was failing to import test_case.py because of the input() function. It was not even reach the line I asked to mock that function and failed in the init stage.

At last to fix the problem I've added a parameter to py.test and now I'm running test process like this:

py.test test_runner.py --program test_case.py -v

In this form pytest doesn't look in test_case.py for test methods and doesn't fail.

hope this experience helps someone else

Related