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