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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
# Copyright 2013 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import stat
import shutil
from tests import TestCase, mkdtemp
from quodlibet.util.atomic import atomic_save
class Tatomic_save(TestCase):
def setUp(self):
self.dir = mkdtemp()
def tearDown(self):
shutil.rmtree(self.dir)
def test_basic(self):
filename = os.path.join(self.dir, "foo.txt")
with open(filename, "wb") as fobj:
fobj.write(b"nope")
with atomic_save(filename, "wb") as fobj:
fobj.write(b"foo")
temp_name = fobj.name
with open(filename, "rb") as fobj:
self.assertEqual(fobj.read(), b"foo")
self.assertFalse(os.path.exists(temp_name))
self.assertEqual(os.listdir(self.dir), [os.path.basename(filename)])
def test_non_exist(self):
filename = os.path.join(self.dir, "foo.txt")
with atomic_save(filename, "wb") as fobj:
fobj.write(b"foo")
temp_name = fobj.name
with open(filename, "rb") as fobj:
self.assertEqual(fobj.read(), b"foo")
self.assertFalse(os.path.exists(temp_name))
self.assertEqual(os.listdir(self.dir), [os.path.basename(filename)])
def test_readonly(self):
filename = os.path.join(self.dir, "foo.txt")
with open(filename, "wb") as fobj:
fobj.write(b"nope")
dir_mode = os.stat(self.dir).st_mode
file_mode = os.stat(filename).st_mode
# setting directory permissions doesn't work under Windows, so make
# the file read only, so the rename fails. On the other hand marking
# the file read only doesn't make rename fail on unix, so make the
# directory read only as well.
os.chmod(filename, stat.S_IREAD)
os.chmod(self.dir, stat.S_IREAD)
try:
with self.assertRaises(OSError):
with atomic_save(filename, "wb") as fobj:
fobj.write(b"foo")
finally:
# restore permissions
os.chmod(self.dir, dir_mode)
os.chmod(filename, file_mode)
with open(filename, "rb") as fobj:
self.assertEqual(fobj.read(), b"nope")
self.assertEqual(os.listdir(self.dir), [os.path.basename(filename)])
|