Files
Crypto_Scam/tests/test_persistence.py
T

30 lines
1.3 KiB
Python

import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import persistence
class AtomicSnapshotTests(unittest.TestCase):
def test_failed_replace_keeps_previous_snapshot_and_cleans_temporary_file(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'position': 1})
with mock.patch.object(persistence.os, 'replace', side_effect=OSError('disk error')):
with self.assertRaises(OSError):
persistence.atomic_write_json(path, {'position': 2})
self.assertEqual(json.loads(path.read_text()), {'position': 1})
self.assertEqual(list(Path(directory).iterdir()), [path])
def test_invalid_numbers_do_not_destroy_existing_snapshot(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'balance': 100})
with self.assertRaises(ValueError):
persistence.atomic_write_json(path, {'balance': float('nan')})
self.assertEqual(json.loads(path.read_text()), {'balance': 100})