blob: 78115569c7d06572f7e8a49b98fd0828815d7b48 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# Copyright 2023 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from pathlib import Path
import tempfile
import unittest
import atomic_write_file
class TestAtomicWrite(unittest.TestCase):
"""Test atomic_write."""
def test_atomic_write(self):
"""Test that atomic write safely writes."""
prior_contents = "This is a test written by patch_utils_unittest.py\n"
new_contents = "I am a test written by patch_utils_unittest.py\n"
with tempfile.TemporaryDirectory(
prefix="patch_utils_unittest"
) as dirname:
dirpath = Path(dirname)
filepath = dirpath / "test_atomic_write.txt"
with filepath.open("w", encoding="utf-8") as f:
f.write(prior_contents)
def _t():
with atomic_write_file.atomic_write(
filepath, encoding="utf-8"
) as f:
f.write(new_contents)
raise Exception("Expected failure")
self.assertRaises(Exception, _t)
with filepath.open(encoding="utf-8") as f:
lines = f.readlines()
self.assertEqual(lines[0], prior_contents)
with atomic_write_file.atomic_write(
filepath, encoding="utf-8"
) as f:
f.write(new_contents)
with filepath.open(encoding="utf-8") as f:
lines = f.readlines()
self.assertEqual(lines[0], new_contents)
if __name__ == "__main__":
unittest.main()
|