Skip to content

Commit

Permalink
add unit test and update pytest settings
Browse files Browse the repository at this point in the history
  • Loading branch information
KedoKudo committed Dec 4, 2024
1 parent c5a7443 commit 3ccd1cd
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 7 deletions.
11 changes: 11 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,14 @@ pre-commit = "^4.0.1"
# --------------------------------------------- #
# The rest all 3rd party plugins configurations #
# --------------------------------------------- #
[tool.pytest.ini_options]
pythonpath = [
".", "src", "scripts"
]
testpaths = ["tests"]
python_files = ["test*.py"]
norecursedirs = [".git", "tmp*", "_tmp*", "__pycache__", "*dataset*", "*data_set*"]

[tool.ruff]
line-length = 120
select = ["A", "ARG","ASYNC","BLE","C90", "E", "F", "I", "N", "UP032", "W"]
30 changes: 23 additions & 7 deletions src/pleiades/core/data_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ def _initialize_cache(self) -> None:
for category in DataCategory:
try:
category_path = self._get_category_path(category)
with resources.files('pleiades.data').joinpath(category_path).iterdir() as path:
self._cached_files[category] = {
item for item in path
if item.suffix in self._VALID_EXTENSIONS[category]
}
data_path = resources.files('pleiades.data').joinpath(category_path)
self._cached_files[category] = {
item.name for item in data_path.iterdir()
if item.suffix in self._VALID_EXTENSIONS[category]
}
except Exception as e:
logger.error(f"Failed to initialize cache for {category}: {str(e)}")
self._cached_files[category] = set()
Expand Down Expand Up @@ -136,10 +136,10 @@ def list_files(self, category: Optional[DataCategory] = None) -> Dict[DataCatego
if category is not None:
if not isinstance(category, DataCategory):
raise ValueError(f"Invalid category: {category}")
return {category: [p.name for p in sorted(self._cached_files[category])]}
return {category: sorted(self._cached_files[category])}

return {
cat: [p.name for p in sorted(self._cached_files[cat])]
cat: sorted(self._cached_files[cat])
for cat in DataCategory
}

Expand Down Expand Up @@ -227,6 +227,11 @@ def get_mass_data(self, element: str, mass_number: int) -> Optional[IsotopeMassD
atomic_mass_fine = line[110:124].replace("*", "nan").replace("#", ".0")

if "nan" not in [atomic_mass_coarse, atomic_mass_fine]:
# use string concatenation to combine the two parts
# e.g. "238" + "050786.936"
# -> "238050786.936"
# -> 238050786.936/1e6
# = 238.050786936
atomic_mass = float(atomic_mass_coarse + atomic_mass_fine) / 1e6
else:
atomic_mass = float("nan")
Expand Down Expand Up @@ -310,6 +315,17 @@ def get_mat_number(self, isotope: str) -> Optional[int]:
element, nucleon = isotope.split('-')

with self.get_file_path(DataCategory.ISOTOPES, "neutrons.list").open() as f:
# Line matching breakdown:
# "496) 92-U -238 IAEA EVAL-DEC14 IAEA Consortium 9237"
# When line matches pattern
# We get groups:
# match.group(1) = "92"
# match.group(2) = "U"
# match.group(3) = "238"
# Check if constructed string matches input:
# match.expand(r"\2-\3") = "U-238"
# If match found, get MAT number:
# Take last 5 characters of line " 9237" -> 9237
pattern = r"\b\s*(\d+)\s*-\s*([A-Za-z]+)\s*-\s*(\d+)([A-Za-z]*)\b"

for line in f:
Expand Down
71 changes: 71 additions & 0 deletions tests/unit/pleiades/core/test_data_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/bin/env python
"""Unit tests for the NuclearDataManager class."""
# tests/unit/pleiades/core/test_data_manager.py
import pytest
from pleiades.core.data_manager import (
NuclearDataManager,
DataCategory,
IsotopeInfo,
IsotopeMassData,
CrossSectionPoint
)

@pytest.fixture
def data_manager():
"""Create a NuclearDataManager instance using actual package data."""
return NuclearDataManager()

def test_list_files(data_manager):
"""Test listing available files."""
files = data_manager.list_files()
assert DataCategory.ISOTOPES in files
# Test for known files that should exist
isotope_files = files[DataCategory.ISOTOPES]
assert 'isotopes.info' in isotope_files
assert 'mass.mas20' in isotope_files
assert 'neutrons.list' in isotope_files

def test_get_isotope_info_u238(data_manager):
"""Test U-238 isotope information retrieval."""
info = data_manager.get_isotope_info('U-238')
assert isinstance(info, IsotopeInfo)
# Test against known U-238 values
assert info.spin == 0.0
assert abs(info.abundance - 0.992745*100) < 1e-6

def test_get_mass_data_u238(data_manager):
"""Test U-238 mass data retrieval."""
mass_data = data_manager.get_mass_data('U', 238)
assert isinstance(mass_data, IsotopeMassData)
# Test against known U-238 values from mass.mas20
expected_mass = 238.050786936
assert abs(mass_data.atomic_mass - expected_mass) < 1e-6

def test_read_cross_section_data_u238(data_manager):
"""Test U-238 cross-section data reading."""
xs_data = data_manager.read_cross_section_data('u-n.tot', 'U-238')
assert len(xs_data) > 0
assert all(isinstance(point, CrossSectionPoint) for point in xs_data)

def test_get_mat_number_u238(data_manager):
"""Test U-238 MAT number retrieval."""
mat = data_manager.get_mat_number('U-238')
assert mat == 9237 # Verify this is the correct MAT number

# Error cases
def test_get_isotope_info_nonexistent(data_manager):
"""Test handling of nonexistent isotope."""
assert data_manager.get_isotope_info('Xx-999') is None

def test_get_isotope_info_invalid_format(data_manager):
"""Test handling of invalid isotope format."""
with pytest.raises(ValueError, match="Invalid isotope format"):
data_manager.get_isotope_info('U238')

def test_file_not_found(data_manager):
"""Test handling of nonexistent file."""
with pytest.raises(FileNotFoundError):
data_manager.get_file_path(DataCategory.ISOTOPES, "nonexistent.info")

if __name__ == '__main__':
pytest.main(['-v', __file__])

0 comments on commit 3ccd1cd

Please sign in to comment.