简体   繁体   中英

Python mocking and patching https client for unit tests

I am writing unit tests and I need to mock a library to test my database result, but I am not sure of what the mock syntax would be for my test. Sample pseudo code:

in utils.py

import hvac

def setup_client():
    client = hvac.Client(url="vault.internal", verify=False)
    # More customized client logic here
    return client

in my function code api.py :

from utils import setup_client

def send_and_save(data: str):
    client = setup_client()
    result = client.send("test_data")
    # Pseudo code to save to the database 
    database.save(data)

I want to be able to write a test that tests that send_and_save method saved data into the database in api.py without needing to call setup_client() at all.

What I've attempted in test_api.py

@patch("utils.setup_client", autospec=True)
def test_data_processed():
    // Code to trigger send_and_save("test_data") here. Note that I cannot test 
    // send_and_save("data") 
    // by calling it directly since this is part of a legacy
    // integration test than a unit test just for send_and_save

    setup_client.return_value = None
    assert database.get("key") == "test_data"

I am still getting an error from python trying to setup the client as if it's running the real client. How do I setup mock and patch to bypass this?

Your patch should point to where the function is being called, not where the function exists.

patch decorator

@patch("api.setup_client", autospec=True)
def test_data_processed():
    mocked_client = MagicMock()
    mocked_client.send.return_value = 'Fake result'
    setup_client.return_value = mocked_client
    assert database.get("key") == "test_data"

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