Skip to content

Instantly share code, notes, and snippets.

@pitrk
Last active November 15, 2023 13:34
Show Gist options
  • Save pitrk/9db7dd9eb1c1e24f2e53edb116d09880 to your computer and use it in GitHub Desktop.
Save pitrk/9db7dd9eb1c1e24f2e53edb116d09880 to your computer and use it in GitHub Desktop.
Mock file with string in Python

Mock file with string in Python

This is an example on how to mock a file with string.

Use case

Testing a function which opens a file and does some kind of operation on it.

About the example

Let us make a function which takes json from file and returns some data. In this example, we want to take data from this API and return name of each planet and its surface temperature in a list.

Instead of creating a mock file, we can limit ourselves to short string with only necessary information.

Example with @mock_patch decorator and corresponding function are shown.

Sources

# Python 3.7
import json
from typing import List
def celestial_bodies_temperatures(filename: str) -> List(List(str, int)):
return_list = []
with open(filename) as f:
data = json.load(f)
for each_planet in data:
return_list.append(
[each_planet["name"],
int(each_planet["surfaceTemperature"])]
)
return return_list
# Python 3.7
import unittest
import unittest.mock
from .function import celestial_bodies_temperatures
class TestFunction(unittest.TestCase):
mock_file_content = """
[{"name": "Earth","surfaceTemperature": 288},
{"name": "Mars", "surfaceTemperature": 260}]
"""
def test_celestial_bodies_temperatures_returns_list_correctly_with(self):
with unittest.mock.patch(
'builtins.open',
new=unittest.mock.mock_open(read_data=self.mock_file_content),
create=True
) as file_mock:
self.assertEqual(
celestial_bodies_temperatures('/dev/null'),
[["Earth", 288], ["Mars", 260]]
)
@unittest.mock.patch(
'builtins.open',
new=unittest.mock.mock_open(read_data=mock_file_content),
create=True
)
def test_celestial_bodies_temperatures_returns_list_correctly_decorator(self):
self.assertEqual(
celestial_bodies_temperatures('/dev/null'),
[["Earth", 288], ["Mars", 260]]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment