import unittest import os from os import path import shutil import tempfile class TestOS(unittest.TestCase): def setUp(self): self.tmp = tempfile.mkdtemp() self.tmp_fd = os.open(self.tmp, os.O_DIRECTORY) def tearDown(self): os.close(self.tmp_fd) shutil.rmtree(self.tmp) def test_rename(self): foo = path.join(self.tmp, 'foo') bar = path.join(self.tmp, 'bar') baz = path.join(self.tmp, 'bar', 'baz') os.mkdir(foo) os.mkdir(bar) open(baz, 'xb').close() with self.assertRaises(OSError) as cm: os.rename(foo, bar) self.assertEqual(str(cm.exception), '[Errno 39] Directory not empty: {!r}'.format(bar) ) def test_rename_with_dir_fd(self): foo = path.join(self.tmp, 'foo') bar = path.join(self.tmp, 'bar') baz = path.join(self.tmp, 'bar', 'baz') os.mkdir(foo) os.mkdir(bar) open(baz, 'xb').close() with self.assertRaises(OSError) as cm: os.rename('foo', 'bar', src_dir_fd=self.tmp_fd, dst_dir_fd=self.tmp_fd, ) self.assertEqual(str(cm.exception), "[Errno 39] Directory not empty: 'bar'" ) if __name__ == '__main__': unittest.main()