Skip to content

Commit

Permalink
Fix path.touch() when file already exists
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 347811114
  • Loading branch information
Conchylicultor authored and copybara-github committed Dec 16, 2020
1 parent 001b2aa commit 2d941e0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
24 changes: 23 additions & 1 deletion tensorflow_datasets/core/utils/gpath_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,29 @@ def test_open(gcs_mocked_path: pathlib.Path):
assert len(list(gcs_mocked_path.joinpath('bucket/dataset').iterdir())) == 6


def test_read_write(gcs_mocked_path: pathlib.Path): # pylint: disable=unused-argument
@pytest.mark.usefixtures('gcs_mocked_path')
def test_touch():
root_path = gpathlib.PosixGPath('gs://bucket/')
root_path.mkdir(parents=True)
assert root_path.exists()

# File don't exists, touch create it
file_path = root_path / 'test.txt'
assert not file_path.exists()
file_path.touch()
assert file_path.exists()
assert file_path.read_text() == '' # File content is empty # pylint: disable=g-explicit-bool-comparison

file_path.write_text('Some content')
file_path.touch() # Should be a no-op
assert file_path.read_text() == 'Some content' # Content still exists

with pytest.raises(FileExistsError):
file_path.touch(exist_ok=False)


@pytest.mark.usefixtures('gcs_mocked_path')
def test_read_write():

gpath = gpathlib.PosixGPath('gs://file.txt')

Expand Down
7 changes: 5 additions & 2 deletions tensorflow_datasets/core/utils/type_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,11 @@ def write_text(
def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
"""Create a file at this given path."""
del mode # Unused
if self.exists() and not exist_ok:
raise FileExistsError(f'{self} already exists.')
if self.exists():
if exist_ok:
return
else:
raise FileExistsError(f'{self} already exists.')
self.write_text('')

@abc.abstractmethod
Expand Down

0 comments on commit 2d941e0

Please sign in to comment.