re. this comment #30195 (review) and needing to use the full path again, I think it is that rename(...)
returns a new Path
instance, which is then the ‘correct’ one to use going forwards for further changes you want to happen on-disk (alas Python has no ‘use of moved value’ concept like Rust et al. that could’ve pointed this out).
I think the way to think of this is that a Path
is just a path, not a file-handle, so you can have a Path instance that doesn’t exist, because for all Python knows you might be wanting to create it – so .rename(...)
on a Path that doesn’t exist changes the path instance but of-course can’t change the actual filesystem because it doesn’t exist.
0>>> from pathlib import Path
1>>> # Make a Path and rename it to add `".copy"` on the end:
2>>> p = Path("README.md")
3>>> p.exists()
4True
5>>> q = p.rename("README.md.copy") # capture the return value in `q`
6>>>
7>>> # We still have the Path instance called `p`...
8>>> p
9PosixPath('README.md')
10>>> # ...but it doesn't exist anymore (becuase we just renamed it)
11>>> p.exists()
12False
13>>> # `.rename` returned a new Path instance, which *does* exist
14>>> q
15PosixPath('README.md.copy')
16>>> q.exists()
17True
18>>>
19>>> # Just to prove the rename happened:
20>>> [item.name for item in Path(".").iterdir() if "md" in item.name]
21['README.md.copy']
22>>>
23>>> # Rename again to move it back to the original name...
24>>> r = q.rename("README.md")
25>>> r
26PosixPath('README.md')
27>>> r.exists()
28True
29>>> # Because `p` and `r` now have the same name, the original `p` also 'exists' again:
30>>> p.exists(), q.exists(), r.exists()
31(True, False, True)
So:
0 # Renaming the block file to induce unsuccessful block read
1 blk_dat = (self.nodes[0].blocks_path / "blk00000.dat")
2 assert blk_dat.exists()
3 blk_dat_moved = blk_dat.rename("blk00000.dat.moved")
4 assert not blk_dat.exists()
5
6 # listsinceblock(nodes1_last_blockhash) should now fail as blocks are not accessible
7 assert_raises_rpc_error(-32603, "Can't read block from disk",
8 self.nodes[0].listsinceblock, nodes1_last_blockhash)
9
10 # Restoring block file
11 blk_dat_moved.rename("blk00000.dat")
12 assert blk_dat.exists()
Also suggest naming change to “moved” or “backup” instead of “copy” as you’re not copying?
And additional assert
s to check that the files exist and don’t when expected (maybe overkill, but prevents unexpected pass/fails for some other reason than you renaming the file)