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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!