Skip to content

Commit

Permalink
Write tests for fs module
Browse files Browse the repository at this point in the history
  • Loading branch information
mar10 committed Oct 4, 2024
1 parent f34f17a commit 5961935
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 49 deletions.
26 changes: 16 additions & 10 deletions nutree/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Methods and classes to support file system related functionality.
"""

from datetime import datetime
from operator import attrgetter, itemgetter
from pathlib import Path
from typing import Optional, Union
Expand Down Expand Up @@ -33,29 +34,34 @@ def __init__(
def __repr__(self):
if self.is_dir:
return f"[{self.name}]"
return f"{self.name!r}, {self.size:,} bytes"
assert self.mdate is not None
mdt = datetime.fromtimestamp(self.mdate).isoformat(sep=" ", timespec="seconds")
return f"{self.name!r}, {self.size:,} bytes, {mdt}"


class FileSystemTree(Tree):
def serialize_mapper(self, node: Node, data: dict):
DEFAULT_KEY_MAP = {} # don't replace 's' with 'str'

@classmethod
def serialize_mapper(cls, node: Node, data: dict):
"""Callback for use with :meth:`~nutree.tree.Tree.save`."""
inst = node.data
if inst.is_dir:
data.update({"n": inst.name, "d": True})
else:
data.update({"n": inst.name, "s": inst.size})
data.update({"n": inst.name, "s": inst.size, "m": inst.mdate})
return data

@staticmethod
def deserialize_mapper(parent: Node, data: dict):
@classmethod
def deserialize_mapper(cls, parent: Node, data: dict):
"""Callback for use with :meth:`~nutree.tree.Tree.load`."""
v = data["v"]
if "d" in v:
return FileSystemEntry(v["n"], is_dir=True, size=0)
return FileSystemEntry(v["n"], is_dir=False, size=v["s"])
# v = data["v"]
if "d" in data:
return FileSystemEntry(data["n"], is_dir=True)
return FileSystemEntry(data["n"], size=data["s"], mdate=data["m"])


def load_tree_from_fs(path: Union[str, Path], *, sort: bool = True) -> Tree:
def load_tree_from_fs(path: Union[str, Path], *, sort: bool = True) -> FileSystemTree:
"""Scan a filesystem folder and store as tree.
Args:
Expand Down
7 changes: 4 additions & 3 deletions nutree/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,13 @@ def count_unique(self) -> int:
"""
return len(self._nodes_by_data_id)

def serialize_mapper(self, node: Node, data: dict) -> dict | None:
@classmethod
def serialize_mapper(cls, node: Node, data: dict) -> dict | None:
"""Used as default `mapper` argument for :meth:`save`."""
return data

@staticmethod
def deserialize_mapper(parent: Node, data: dict) -> str | object | None:
@classmethod
def deserialize_mapper(cls, parent: Node, data: dict) -> str | object | None:
"""Used as default `mapper` argument for :meth:`load`."""
raise NotImplementedError(
f"Override this method or pass a mapper callback to evaluate {data}."
Expand Down
4 changes: 2 additions & 2 deletions nutree/typed_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def first_sibling(self, *, any_kind=False) -> TypedNode:
for n in pc:
if n._kind == self._kind:
return n
raise AssertionError("Internal error")
raise AssertionError("Internal error") # pragma: no cover

def last_sibling(self, *, any_kind=False) -> TypedNode:
"""Return last sibling `of the same kind` (may be self)."""
Expand All @@ -181,7 +181,7 @@ def last_sibling(self, *, any_kind=False) -> TypedNode:
for n in reversed(pc):
if n._kind == self._kind:
return n
raise AssertionError("Internal error")
raise AssertionError("Internal error") # pragma: no cover

def prev_sibling(self, *, any_kind=False) -> TypedNode | None:
"""Return predecessor `of the same kind` or None if node is first sibling."""
Expand Down
34 changes: 0 additions & 34 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@
# pyright: reportRedeclaration=false
# pyright: reportOptionalMemberAccess=false

import os
import re
from pathlib import Path
from typing import Any, Union

import pytest
from nutree import AmbiguousMatchError, IterMethod, Node, Tree
from nutree.common import SkipBranch, StopTraversal, check_python_version
from nutree.fs import load_tree_from_fs

from . import fixture

Expand Down Expand Up @@ -1263,34 +1260,3 @@ def pred(node):
╰── b11
""",
)


class TestFS:
@pytest.mark.skipif(os.name == "nt", reason="windows has different eol size")
def test_fs_linux(self):
path = Path(__file__).parent / "fixtures"

# We check for unix line endings/file sizes (as used on travis)
tree = load_tree_from_fs(path)
assert fixture.check_content(
tree,
"""
FileSystemTree<*>
├── 'file_1.txt', 13 bytes
╰── [folder_1]
╰── 'file_1_1.txt', 15 bytes
""",
)

tree = load_tree_from_fs(path, sort=False)
assert "[folder_1]" in fixture.canonical_repr(tree)

@pytest.mark.skipif(os.name != "nt", reason="windows has different eol size")
def test_fs_windows(self):
path = Path(__file__).parent / "fixtures"
# Cheap test only,
tree = load_tree_from_fs(path)
assert "[folder_1]" in fixture.canonical_repr(tree)

tree = load_tree_from_fs(path, sort=False)
assert "[folder_1]" in fixture.canonical_repr(tree)
68 changes: 68 additions & 0 deletions tests/test_fs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# (c) 2021-2024 Martin Wendt; see https://github.com/mar10/nutree
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportRedeclaration=false
# pyright: reportOptionalMemberAccess=false

import os
import shutil
from pathlib import Path

import pytest
from nutree.fs import FileSystemTree, load_tree_from_fs

from . import fixture


class TestFS:
@pytest.mark.skipif(os.name == "nt", reason="windows has different eol size")
def test_fs_linux(self):
path = Path(__file__).parent / "fixtures"

# We check for unix line endings/file sizes (as used on travis)
tree = load_tree_from_fs(path)
assert fixture.check_content(
tree,
"""
FileSystemTree<*>
├── 'file_1.txt', 13 bytes, 2022-04-14 21:35:21
╰── [folder_1]
╰── 'file_1_1.txt', 15 bytes, 2022-04-14 21:35:21
""",
)

tree = load_tree_from_fs(path, sort=False)
assert "[folder_1]" in fixture.canonical_repr(tree)

@pytest.mark.skipif(os.name != "nt", reason="windows has different eol size")
def test_fs_windows(self):
path = Path(__file__).parent / "fixtures"
# Cheap test only,
tree = load_tree_from_fs(path)
assert "[folder_1]" in fixture.canonical_repr(tree)

tree = load_tree_from_fs(path, sort=False)
assert "[folder_1]" in fixture.canonical_repr(tree)

def test_fs_serialize(self):
KEEP_FILES = True
path = Path(__file__).parent / "fixtures"
# Cheap test only,
tree = load_tree_from_fs(path)

with fixture.WritableTempFile("r+t", suffix=".json") as temp_file:
tree.save(
temp_file.name,
mapper=tree.serialize_mapper,
)

if KEEP_FILES: # save to tests/temp/...
shutil.copy(
temp_file.name,
Path(__file__).parent / "temp/test_serialize_fs.json",
)

tree_2 = FileSystemTree.load(temp_file.name, mapper=tree.deserialize_mapper)

assert fixture.trees_equal(tree, tree_2, ignore_tree_name=True)

0 comments on commit 5961935

Please sign in to comment.