Skip to content

Commit 3cf9e5d

Browse files
authored
Merge pull request #110 from AFM-SPM/ns-rse/80-file-not-found
2 parents aed385c + ac9753c commit 3cf9e5d

9 files changed

Lines changed: 68 additions & 15 deletions

File tree

.pre-commit-config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ repos:
77
- id: check-merge-conflict
88
- id: check-toml
99
- id: check-yaml
10+
args: ["--unsafe"]
1011
- id: debug-statements
1112
- id: end-of-file-fixer
1213
types: [python]

AFMReader/asd.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
"""For decoding and loading .asd AFM file format into Python Numpy arrays."""
22

33
from __future__ import annotations
4+
import errno
5+
import os
46
from pathlib import Path
57
import sys
68

7-
if sys.version_info.minor < 11:
8-
from typing import Any, BinaryIO
9-
from typing_extensions import Self
10-
else:
11-
from typing import Any, BinaryIO, Self
12-
139

1410
import numpy as np
1511
import numpy.typing as npt
@@ -32,6 +28,14 @@
3228
skip_bytes,
3329
)
3430

31+
32+
if sys.version_info.minor < 11:
33+
from typing import Any, BinaryIO
34+
from typing_extensions import Self
35+
else:
36+
from typing import Any, BinaryIO, Self
37+
38+
3539
logger.enable(__package__)
3640

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

183187

184-
def load_asd(file_path: Path, channel: str):
188+
def load_asd(file_path: str | Path, channel: str):
185189
"""
186190
Load a .asd file.
187191
@@ -209,6 +213,11 @@ def load_asd(file_path: Path, channel: str):
209213
"""
210214
# Ensure the file path is a Path object
211215
file_path = Path(file_path)
216+
filename = file_path.stem
217+
# Check the file exists and raise an error if not
218+
if not file_path.is_file():
219+
logger.error(f"[{filename}] File not found : {file_path}")
220+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
212221
# Open the file in binary mode
213222
with Path.open(file_path, "rb", encoding=None) as open_file: # pylint: disable=unspecified-encoding
214223
file_version = read_file_version(open_file)

AFMReader/ibw.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""For decoding and loading .ibw AFM file format into Python Numpy arrays."""
22

33
from __future__ import annotations
4+
import errno
5+
import os
46
from pathlib import Path
57

68
import numpy as np
@@ -72,6 +74,10 @@ def load_ibw(file_path: Path | str, channel: str) -> tuple[np.ndarray, float]:
7274
logger.info(f"Loading image from : {file_path}")
7375
file_path = Path(file_path)
7476
filename = file_path.stem
77+
# Check the file exists and raise an error if not
78+
if not file_path.is_file():
79+
logger.error(f"[{filename}] File not found : {file_path}")
80+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
7581
try:
7682
scan = binarywave.load(file_path)
7783
logger.info(f"[{filename}] : Loaded image from : {file_path}")
@@ -86,6 +92,7 @@ def load_ibw(file_path: Path | str, channel: str) -> tuple[np.ndarray, float]:
8692
logger.info(f"[{filename}] : Extracted channel {channel}")
8793
except FileNotFoundError:
8894
logger.error(f"[{filename}] File not found : {file_path}")
95+
raise
8996
except ValueError:
9097
logger.error(f"[{filename}] : {channel} not in {file_path.suffix} channel list: {labels}")
9198
raise

tests/test_asd.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pathlib import Path
44
import pytest
55

6-
from AFMReader.asd import load_asd
6+
from AFMReader import asd
77

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

2525
file_path = RESOURCES / file_name
26-
result_frames, result_pixel_to_nm_scaling, result_metadata = load_asd(file_path, channel)
26+
result_frames, result_pixel_to_nm_scaling, result_metadata = asd.load_asd(file_path, channel)
2727

2828
assert len(result_frames) == number_of_frames # type: ignore
2929
assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
3030
assert isinstance(result_metadata, dict)
31+
32+
33+
def test_load_asd_file_not_found() -> None:
34+
"""Ensure FileNotFound error is raised."""
35+
with pytest.raises(FileNotFoundError):
36+
asd.load_asd("nonexistant_file.asd", channel="TP")

tests/test_gwy.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,9 @@ def test_read_gwy_component_dtype() -> None:
111111
value = gwy.read_gwy_component_dtype(open_binary_file)
112112
assert isinstance(value, str)
113113
assert value == "D"
114+
115+
116+
def test_load_gwy_file_not_found() -> None:
117+
"""Ensure FileNotFound error is raised."""
118+
with pytest.raises(FileNotFoundError):
119+
gwy.load_gwy("nonexistant_file.gwy", channel="TP")

tests/test_ibw.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import numpy as np
77

8-
from AFMReader.ibw import load_ibw
8+
from AFMReader import ibw
99

1010
BASE_DIR = Path.cwd()
1111
RESOURCES = BASE_DIR / "tests" / "resources"
@@ -28,10 +28,16 @@ def test_load_ibw(
2828
result_pixel_to_nm_scaling = float
2929

3030
file_path = RESOURCES / file_name
31-
result_image, result_pixel_to_nm_scaling = load_ibw(file_path, channel) # type: ignore
31+
result_image, result_pixel_to_nm_scaling = ibw.load_ibw(file_path, channel) # type: ignore
3232

3333
assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
3434
assert isinstance(result_image, np.ndarray)
3535
assert result_image.shape == image_shape
3636
assert result_image.dtype == image_dtype
3737
assert result_image.sum() == image_sum
38+
39+
40+
def test_load_ibw_file_not_found() -> None:
41+
"""Ensure FileNotFound error is raised."""
42+
with pytest.raises(FileNotFoundError):
43+
ibw.load_ibw("nonexistant_file.ibw", channel="TP")

tests/test_jpk.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import numpy as np
77

8-
from AFMReader.jpk import load_jpk
8+
from AFMReader import jpk
99

1010
BASE_DIR = Path.cwd()
1111
RESOURCES = BASE_DIR / "tests" / "resources"
@@ -32,10 +32,16 @@ def test_load_jpk(
3232
result_pixel_to_nm_scaling = float
3333

3434
file_path = RESOURCES / file_name
35-
result_image, result_pixel_to_nm_scaling = load_jpk(file_path, channel) # type: ignore
35+
result_image, result_pixel_to_nm_scaling = jpk.load_jpk(file_path, channel) # type: ignore
3636

3737
assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
3838
assert isinstance(result_image, np.ndarray)
3939
assert result_image.shape == image_shape
4040
assert result_image.dtype == image_dtype
4141
assert result_image.sum() == image_sum
42+
43+
44+
def test_load_jpk_file_not_found() -> None:
45+
"""Ensure FileNotFound error is raised."""
46+
with pytest.raises(FileNotFoundError):
47+
jpk.load_jpk("nonexistant_file.jpk", channel="TP")

tests/test_spm.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,9 @@ def test__spm_pixel_to_nm_scaling(
7070
mock_pxs.return_value = [(x, unit), (y, unit)] # issue is that pxs is a func that returns the data
7171
result = spm.spm_pixel_to_nm_scaling(filename, spm_channel_data)
7272
assert result == expected_px2nm
73+
74+
75+
def test_load_spm_file_not_found() -> None:
76+
"""Ensure FileNotFound error is raised."""
77+
with pytest.raises(FileNotFoundError):
78+
spm.load_spm("nonexistant_file.spm", channel="TP")

tests/test_topostats.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import numpy as np
77

8-
from AFMReader.topostats import load_topostats
8+
from AFMReader import topostats
99

1010
BASE_DIR = Path.cwd()
1111
RESOURCES = BASE_DIR / "tests" / "resources"
@@ -66,7 +66,7 @@ def test_load_topostats(
6666
result_data = dict
6767

6868
file_path = RESOURCES / file_name
69-
result_image, result_pixel_to_nm_scaling, result_data = load_topostats(file_path)
69+
result_image, result_pixel_to_nm_scaling, result_data = topostats.load_topostats(file_path)
7070

7171
assert result_pixel_to_nm_scaling == pixel_to_nm_scaling
7272
assert isinstance(result_image, np.ndarray)
@@ -76,3 +76,9 @@ def test_load_topostats(
7676
assert result_image.sum() == image_sum
7777
if topostats_file_version >= 0.2:
7878
assert isinstance(result_data["img_path"], Path)
79+
80+
81+
def test_load_topostats_file_not_found() -> None:
82+
"""Ensure FileNotFound error is raised."""
83+
with pytest.raises(FileNotFoundError):
84+
topostats.load_topostats("nonexistant_file.topostats")

0 commit comments

Comments
 (0)