Issue
I am trying to mock below function
from subprocess import Popen, PIPE
def run_query():
sql_cmd = "Some Query"
process = Popen(["sqlplus", "-S", "/", "as", "sysdba"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
process.stdin.write(sql_cmd)
(process_stdout, process_stderr) = process.communicate()
Below is the test function I wrote:
@patch('subprocess.Popen')
def test_run_query(Popen):
Popen.return_value.communicate.return_value = (2, 1)
However, I am getting below error
Error occured while running sql command
Error output:
[Errno 2] No such file or directory
F
I tried other stackoverflow post but this kind of example is not there. Any help please.
Solution
You are patching Popen
within the wrong namespace.
You need to patch the name Popen
in the namespace where it is looked up, not where it is defined. Assuming mypackage/mymodule.py
is the module in which run_query
is defined:
from mypackage.mymodule import run_query
@patch('mypackage.mymodule.Popen')
def test_run_query(mock_popen):
proc = mock_popen.return_value
proc.communicate.return_value = "2", "1"
out, err = run_query()
assert out == "2"
assert err == "1"
proc.stdin.write.assert_called_once_with("Some Query")
See Where to patch in the mock documentation for more info.
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.