Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

patch & test pathlib #701

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import pathlib

import git

Expand All @@ -24,9 +25,15 @@ def test_patch_open(proj_path):
with node.state.magic_patch():
with open(node.outs, "r") as f:
assert f.read() == "Hello World"
assert pathlib.Path(node.outs).read_text() == "Hello World"
with pathlib.Path(node.outs).open("r") as f:
assert f.read() == "Hello World"

with open(node.outs, "r") as f:
assert f.read() == "Lorem Ipsum"
assert pathlib.Path(node.outs).read_text() == "Lorem Ipsum"
with pathlib.Path(node.outs).open("r") as f:
assert f.read() == "Lorem Ipsum"

listdir = os.listdir(node.nwd)

Expand Down
20 changes: 17 additions & 3 deletions zntrack/core/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ def magic_patch(self) -> typing.ContextManager:
Opening a relative path will use the Node's file system.
Opening an absolute path will use the local file system.
"""
original_open = open
import builtins

original_open = builtins.open
original_listdir = os.listdir

def _open(file, *args, **kwargs):
Expand All @@ -84,6 +86,17 @@ def _open(file, *args, **kwargs):

return original_open(file, *args, **kwargs)

def _read_text(file, *args, **kwargs):
if file == "params.yaml":
with original_open(file, *args, **kwargs) as f:
return f.read()

if not pathlib.Path(file).is_absolute():
return self.fs.read_text(file, *args, **kwargs)

with original_open(file, *args, **kwargs) as f:
return f.read()

def _listdir(path, *args, **kwargs):
if not pathlib.Path(path).is_absolute():
return self.fs.listdir(path, detail=False)
Expand All @@ -93,8 +106,9 @@ def _listdir(path, *args, **kwargs):
with unittest.mock.patch("builtins.open", _open):
with unittest.mock.patch("__main__.open", _open):
with unittest.mock.patch("os.listdir", _listdir):
# Jupyter Notebooks replace open with io.open
yield
with unittest.mock.patch("pathlib.Path.read_text", _read_text):
with unittest.mock.patch("pathlib.Path.open", _open):
yield


class _NameDescriptor(zninit.Descriptor):
Expand Down