简体   繁体   中英

Python 2.x: How to mock subprocess.Popen if stdin=PIPE

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM