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

tests: FileNotFound consistently raised & tested #110

Merged
merged 1 commit into from
Feb 3, 2025
Merged
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
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ repos:
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
args: ["--unsafe"]
- id: debug-statements
- id: end-of-file-fixer
types: [python]
Expand Down
23 changes: 16 additions & 7 deletions AFMReader/asd.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
"""For decoding and loading .asd AFM file format into Python Numpy arrays."""

from __future__ import annotations
import errno
import os
from pathlib import Path
import sys

if sys.version_info.minor < 11:
from typing import Any, BinaryIO
from typing_extensions import Self
else:
from typing import Any, BinaryIO, Self


import numpy as np
import numpy.typing as npt
Expand All @@ -32,6 +28,14 @@
skip_bytes,
)


if sys.version_info.minor < 11:
from typing import Any, BinaryIO
from typing_extensions import Self
else:
from typing import Any, BinaryIO, Self


logger.enable(__package__)

# mypy: disable-error-code="assignment"
Expand Down Expand Up @@ -181,7 +185,7 @@ def calculate_scaling_factor(
raise ValueError(f"channel {channel} not known for .asd file type.")


def load_asd(file_path: Path, channel: str):
def load_asd(file_path: str | Path, channel: str):
"""
Load a .asd file.

Expand Down Expand Up @@ -209,6 +213,11 @@ def load_asd(file_path: Path, channel: str):
"""
# Ensure the file path is a Path object
file_path = Path(file_path)
filename = file_path.stem
# Check the file exists and raise an error if not
if not file_path.is_file():
logger.error(f"[{filename}] File not found : {file_path}")
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
# Open the file in binary mode
with Path.open(file_path, "rb", encoding=None) as open_file: # pylint: disable=unspecified-encoding
file_version = read_file_version(open_file)
Expand Down
7 changes: 7 additions & 0 deletions AFMReader/ibw.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""For decoding and loading .ibw AFM file format into Python Numpy arrays."""

from __future__ import annotations
import errno
import os
from pathlib import Path

import numpy as np
Expand Down Expand Up @@ -72,6 +74,10 @@ def load_ibw(file_path: Path | str, channel: str) -> tuple[np.ndarray, float]:
logger.info(f"Loading image from : {file_path}")
file_path = Path(file_path)
filename = file_path.stem
# Check the file exists and raise an error if not
if not file_path.is_file():
logger.error(f"[{filename}] File not found : {file_path}")
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
try:
scan = binarywave.load(file_path)
logger.info(f"[{filename}] : Loaded image from : {file_path}")
Expand All @@ -86,6 +92,7 @@ def load_ibw(file_path: Path | str, channel: str) -> tuple[np.ndarray, float]:
logger.info(f"[{filename}] : Extracted channel {channel}")
except FileNotFoundError:
logger.error(f"[{filename}] File not found : {file_path}")
raise
except ValueError:
logger.error(f"[{filename}] : {channel} not in {file_path.suffix} channel list: {labels}")
raise
Expand Down
10 changes: 8 additions & 2 deletions tests/test_asd.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pathlib import Path
import pytest

from AFMReader.asd import load_asd
from AFMReader import asd

BASE_DIR = Path.cwd()
RESOURCES = BASE_DIR / "tests" / "resources"
Expand All @@ -23,8 +23,14 @@ def test_load_asd(file_name: str, channel: str, number_of_frames: int, pixel_to_
result_metadata = dict

file_path = RESOURCES / file_name
result_frames, result_pixel_to_nm_scaling, result_metadata = load_asd(file_path, channel)
result_frames, result_pixel_to_nm_scaling, result_metadata = asd.load_asd(file_path, channel)

assert len(result_frames) == number_of_frames # type: ignore
assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
assert isinstance(result_metadata, dict)


def test_load_asd_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
asd.load_asd("nonexistant_file.asd", channel="TP")
6 changes: 6 additions & 0 deletions tests/test_gwy.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,9 @@ def test_read_gwy_component_dtype() -> None:
value = gwy.read_gwy_component_dtype(open_binary_file)
assert isinstance(value, str)
assert value == "D"


def test_load_gwy_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
gwy.load_gwy("nonexistant_file.gwy", channel="TP")
10 changes: 8 additions & 2 deletions tests/test_ibw.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from AFMReader.ibw import load_ibw
from AFMReader import ibw

BASE_DIR = Path.cwd()
RESOURCES = BASE_DIR / "tests" / "resources"
Expand All @@ -28,10 +28,16 @@ def test_load_ibw(
result_pixel_to_nm_scaling = float

file_path = RESOURCES / file_name
result_image, result_pixel_to_nm_scaling = load_ibw(file_path, channel) # type: ignore
result_image, result_pixel_to_nm_scaling = ibw.load_ibw(file_path, channel) # type: ignore

assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
assert isinstance(result_image, np.ndarray)
assert result_image.shape == image_shape
assert result_image.dtype == image_dtype
assert result_image.sum() == image_sum


def test_load_ibw_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
ibw.load_ibw("nonexistant_file.ibw", channel="TP")
10 changes: 8 additions & 2 deletions tests/test_jpk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from AFMReader.jpk import load_jpk
from AFMReader import jpk

BASE_DIR = Path.cwd()
RESOURCES = BASE_DIR / "tests" / "resources"
Expand All @@ -32,10 +32,16 @@ def test_load_jpk(
result_pixel_to_nm_scaling = float

file_path = RESOURCES / file_name
result_image, result_pixel_to_nm_scaling = load_jpk(file_path, channel) # type: ignore
result_image, result_pixel_to_nm_scaling = jpk.load_jpk(file_path, channel) # type: ignore

assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
assert isinstance(result_image, np.ndarray)
assert result_image.shape == image_shape
assert result_image.dtype == image_dtype
assert result_image.sum() == image_sum


def test_load_jpk_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
jpk.load_jpk("nonexistant_file.jpk", channel="TP")
6 changes: 6 additions & 0 deletions tests/test_spm.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,9 @@ def test__spm_pixel_to_nm_scaling(
mock_pxs.return_value = [(x, unit), (y, unit)] # issue is that pxs is a func that returns the data
result = spm.spm_pixel_to_nm_scaling(filename, spm_channel_data)
assert result == expected_px2nm


def test_load_spm_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
spm.load_spm("nonexistant_file.spm", channel="TP")
10 changes: 8 additions & 2 deletions tests/test_topostats.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import numpy as np

from AFMReader.topostats import load_topostats
from AFMReader import topostats

BASE_DIR = Path.cwd()
RESOURCES = BASE_DIR / "tests" / "resources"
Expand Down Expand Up @@ -66,7 +66,7 @@ def test_load_topostats(
result_data = dict

file_path = RESOURCES / file_name
result_image, result_pixel_to_nm_scaling, result_data = load_topostats(file_path)
result_image, result_pixel_to_nm_scaling, result_data = topostats.load_topostats(file_path)

assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
assert isinstance(result_image, np.ndarray)
Expand All @@ -76,3 +76,9 @@ def test_load_topostats(
assert result_image.sum() == image_sum
if topostats_file_version >= 0.2:
assert isinstance(result_data["img_path"], Path)


def test_load_topostats_file_not_found() -> None:
"""Ensure FileNotFound error is raised."""
with pytest.raises(FileNotFoundError):
topostats.load_topostats("nonexistant_file.topostats")