I am trying to test my JsonWrite class and its write_json function that takes data from api and write it to a json file. This is my class.
import json
class JsonWriter:
def write_json(self, weights, filename):
try:
json_data = json.dumps(weights, indent=4)
with open(filename, 'w') as f:
f.write(json_data)
f.close()
except Exception as e:
return False, e
return True, None
Should I break this write_json function to smaller units or is there a way of testing it? So far I have only mocked what it returns if everything is OK. But I think that isn't the right way of doing it. What am I missing here?
class JsonWrite(unittest.TestCase):
@patch("argo_connectors.io.jsonwrite.JsonWriter.write_json")
def test_read_file_data(self, mock_write_json):
mock_write_json.return_value = True, None
if __name__ == '__main__':
unittest.main()
CodePudding user response:
You can try something like this:
- Testing the dumping
- Testing the writing
I hope this helps you...
import json
DEBUG = False
class JsonWriter:
def dumps(self, weights):
try:
return True, json.dumps(weights, indent=4)
except Exception as e:
return False, e
def write(self, json_data, filename):
try:
with open(filename, 'w') as f:
f.write(json_data)
except Exception as e:
return False, e
return True, None
def test_dumps(weigths, succeeded, data):
success, result = json_writer.dumps(weigths)
if DEBUG:
print(success, "==", succeeded, "and", result, "==", data)
assert success == succeeded and result == data
def test_write(json_data, filename, succeeded, exception):
success, error = json_writer.write(json_data, filename)
if DEBUG:
print(success, "==", succeeded, "and", success, "==", exception)
assert success == succeeded and error == exception
json_writer = JsonWriter()
test_dumps({}, True, "{}")
test_write("{}", "out.json", True, None)
print("All tests succeeded")
CodePudding user response:
This is my solution for passing test and failing it:
mock_json = [
{'id': 5414470, 'name': 'mike'},
{'id': 5414472, 'name': 'tom'},
{'id': 5414232, 'name': 'pete'},
]
mock_filename = "mock_file.json"
class JsonWriteTest(unittest.TestCase):
def test_save_data_to_file(self):
with patch('builtins.open', unittest.mock.mock_open()) as m:
data_writer = JsonWriter(mock_json, 'mock_file.json')
data_writer.write_json()
m.assert_called_once_with('mock_file.json', 'w')
handle = m()
handle.write.assert_called_once_with('[\n {\n "id": 5414470,\n "name": "mike"\n },\n {\n "id": 5414472,\n "name": "tom"\n },\n {\n "id": 5414232,\n "name": "pete"\n }\n]')`
def test_fail_jsonwrite(self):
mock_jsondumps = Mock(name='json.dumps')
mock_jsondumps.side_effect = Exception("Mocked error")
with patch('json.dumps', mock_jsondumps):
writer = JsonWriter({'mock_key': 'mock_value'}, mock_filename)
result, error = writer.write_json()
self.assertEqual(result, False)
self.assertEqual(str(error), 'Mocked error')