Reputation: 583
I have written the following function :
def get_env_id(id):
with open(pathlib.Path(__file__).parent / 'srm.json') as file:
data = json.load(file)
return data.get(id)
I am performing unit test on the above function. I want to mock the file within the function with some json file. The json file content is as follows:
{"id":{"0":1,"1":2,"2":3},"value":{"0":20,"1":30,"2":40}}
Upvotes: 0
Views: 336
Reputation: 11346
You can use mock_open
from unnitest package, something like:
from unittest.mock import patch, mock_open
BASE_PATH = pathlib.Path(__file__).parent
MOCK_DATA = {"id": {"0": 1, "1": 2, "2": 3}, "value": {"0": 20, "1": 30, "2": 40}}
def get_env_id(id):
with open(BASE_PATH / 'srm.json') as file:
data = json.load(file)
return data.get(id)
@patch("builtins.open", new_callable=mock_open, read_data=json.dumps(MOCK_DATA))
def test_get_env_id(mock_file):
id = get_env_id("id")
assert id == {"0": 1, "1": 2, "2": 3}
mock_file.assert_called_once()
mock_file.assert_called_with(BASE_PATH / 'srm.json')
Upvotes: 1