Question
use tempfile() and @contextmanager to re-write atomic-writer tests and cases are written below, all tests must pass import os from tempfile import TemporaryDirectory from unittest
use tempfile() and @contextmanager to re-write atomic-writer
tests and cases are written below, all tests must pass
import os from tempfile import TemporaryDirectory from unittest import TestCase
class FakeFileFailure(IOError): pass
class TestAtomics(TestCase):
def test_writer(self):
with TemporaryDirectory() as tmpdir:
file = os.path.join(tmpdir, 'asdf.txt')
with atomic_write(file) as f: f.write('asdf') assert f.name.endswith('.txt') assert not os.path.isfile(file) assert os.path.isfile(file)
with open(file) as f: assert f.read() == 'asdf'
def test_atomic_fail(self): with TemporaryDirectory() as tmpdir: file = os.path.join(tmpdir, 'asdf.txt') with atomic_write(file, as_file=False) as f: f.write('asdf') assert f.name.endswith('.txt') assert not os.path.isfile(file) assert os.path.isfile(file)
with open(file) as f: assert f.read() == 'asdf'
class AtomicWriteTests(TestCase):
def test_atomic_write(self): with TemporaryDirectory() as tmp: fp = os.path.join(tmp, 'asdf.txt')
with atomic_write(fp, 'w') as f: assert not os.path.exists(fp) tmpfile = f.name f.write('asfd')
assert not os.path.exists(tmpfile) assert os.path.exists(fp)
with open(fp) as f: self.assertEqual(f.read(), 'asdf')
def test_atomic_failure(self): with TemporaryDirectory() as tmp: fp = os.path.join(tmp, 'asdf.txt')
with self.assertRaises(FakeFileFailure): with atomic_write(fp, 'w') as f: tmpfile = f.name assert os.path.exists(tmpfile) raise FakeFileFailure()
assert not os.path.exists(tmpfile) assert not os.path.exists(fp)
def test_file_exists(self):
raise NotImplementedError()
if __name__ == '__main__': main()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started