Last active
August 29, 2015 14:15
-
-
Save sivy/7bf5fff5999859098bbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_or_update(self, item_id, data): | |
if not self.validate(data): | |
raise ValidationError('Validation error!') | |
file_path = self._filepath(item_id) | |
existing_data = {} | |
try: | |
with open(file_path, 'r') as f: | |
content = f.read() | |
existing_data = json.loads(content) | |
except IOError: | |
pass | |
with open(file_path, 'w') as f: | |
existing_data.update(data) | |
f.write(json.dumps(existing_data, indent=4)) | |
return existing_data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mock | |
from lib.backends import FilestoreHandler | |
def test_filestore_create_or_update__update(): | |
data_dir = 'tests/instance-data/' | |
fsdatastore = FilestoreHandler(data_dir) | |
start_data = { | |
'uuid': 'abc123', | |
} | |
start_datastr = json.dumps(start_data, indent=4) | |
add_data = { | |
'terminate_user': '[email protected]', | |
} | |
final_data = dict(start_data.items() + add_data.items()) | |
final_datastr = json.dumps(final_data, indent=4) | |
data_file_arg = os.path.join(data_dir, "abc123.json") | |
with mock.patch(open_name, create=True) as mock_open: | |
mock_open.return_value = mock.MagicMock(spec=file) | |
file_handle = mock_open.return_value.__enter__.return_value | |
file_handle.read = mock.Mock() | |
file_handle.read.return_value = start_datastr | |
updated_data = fsdatastore.update('abc123', add_data) | |
mock_open.assert_any_call(data_file_arg, 'r') | |
mock_open.assert_any_call(data_file_arg, 'w') | |
file_handle.read.assert_called_once() | |
file_handle.write.assert_called_with( | |
final_datastr) | |
assert updated_data | |
assert updated_data == final_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment