def test_open_fns(tmpdir): tmpfile = os.path.join(tmpdir, 'file1') with pytest.raises(FileNotFoundError): util.open_file(tmpfile) with util.open_file(tmpfile, create=True) as f: f.write(b'56') with util.open_file(tmpfile) as f: assert f.read(3) == b'56' # Test open_truncate truncates and creates with util.open_truncate(tmpfile) as f: assert f.read(3) == b'' tmpfile = os.path.join(tmpdir, 'file2') with util.open_truncate(tmpfile) as f: assert f.read(3) == b''
def write_raw_block(self, block, height): '''Write a raw block to disk.''' with util.open_truncate(self.raw_block_path(height)) as f: f.write(block) # Delete old blocks to prevent them accumulating try: del_height = self.min_undo_height(height) - 1 os.remove(self.raw_block_path(del_height)) except FileNotFoundError: pass
async def _get_to_file(self, rest_url, filename): full_url = self.current_url() + rest_url async with self.block_semaphore: with open_truncate(filename) as file: async with self.session.get(full_url) as resp: kind = resp.headers.get('Content-Type', None) if kind != 'application/octet-stream': text = await resp.text() text = text.strip() or resp.reason raise ServiceRefusedError(text) size = 0 async for part, _ in resp.content.iter_chunks(): size += await run_in_thread(file.write, part) return size