Home > Mobile >  Mocking an entire function with parameters in Python
Mocking an entire function with parameters in Python

Time:09-29

I have this Python code normally running on a distant server that I want to test locally:

from af.data import Variable

def create_file():
    main_client = file.Client()
    directory = main_client.create(Variable.get("DIR_NAME"))

As I am developing locally and do not have access to the remote service providing the af.data.Variable class, I'd like to mock the Variable.get(str) function, but I'd like to be able—in my own mock—to return some value based on the passed the str parameter. So far, I've found only ways to mock a function to some pre-defined static values using side_effect of unittest.

How can I do that?

CodePudding user response:

after the Peter's comment, here is the solution (pretty straightforward):

from unittest.mock import Mock
from af.data import Variable
import os

def side_effect(arg):
   """Put here whatever logic you want to put in your mock, here's an example of reading a system environment variable"""
    return os.getenv(arg)

mock = Mock()
mock.get.side_effect = side_effect
Variable = mock

"""Then just use the Variable.get method as you would do in production environment, it should be mocked to the side_effect function declared above"""
  • Related