Skip to content

Commit f2938aa

Browse files
committed
update python init logic
1 parent 23d1285 commit f2938aa

File tree

3 files changed

+47
-30
lines changed

3 files changed

+47
-30
lines changed

python/pyproject.toml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,9 @@ features = ["pyo3/extension-module"]
1818

1919
[build-system]
2020
requires = ["maturin>=1.5,<2.0"]
21-
build-backend = "maturin"
21+
build-backend = "maturin"
22+
23+
[dependency-groups]
24+
dev = [
25+
"pytest>=8.3.5",
26+
]

python/src/lib.rs

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -189,25 +189,23 @@ impl OntoEnv {
189189
env_logger::init();
190190
});
191191

192-
let config_path = path;
193-
194-
let env = if config.is_none() && config_path.as_ref().map_or(false, |p| p.exists()) {
192+
let config_path = path.unwrap_or_else(|| PathBuf::from("."));
193+
let env = if let Some(c) = config {
194+
// if temporary is true, create a new OntoEnv
195+
if c.cfg.temporary {
196+
OntoEnvRs::init(c.cfg, recreate).map_err(anyhow_to_pyerr)
197+
} else if !recreate {
198+
// if temporary is false, load from the directory
199+
OntoEnvRs::load_from_directory(config_path, read_only)
200+
.map_err(anyhow_to_pyerr)
201+
} else {
202+
// if temporary is false and recreate is true, create a new OntoEnv
203+
OntoEnvRs::init(c.cfg, recreate).map_err(anyhow_to_pyerr)
204+
}
205+
} else {
195206
// If no config but a valid path is given, attempt to load from the directory
196-
OntoEnvRs::load_from_directory(config_path.as_ref().unwrap().clone(), read_only)
207+
OntoEnvRs::load_from_directory(config_path, read_only)
197208
.map_err(anyhow_to_pyerr)
198-
} else if !recreate {
199-
// if recreate is 'false', try to load from the directory
200-
OntoEnvRs::load_from_directory(config_path.as_ref().unwrap().clone(), read_only)
201-
.map_err(anyhow_to_pyerr)
202-
} else if let Some(c) = config {
203-
// If a config is provided, initialize a new OntoEnv. 'recreate' will be true here
204-
// (else it would have been loaded from the directory in the previous step)
205-
OntoEnvRs::init(c.cfg, recreate).map_err(anyhow_to_pyerr)
206-
} else {
207-
// Return an error if neither a valid path nor a config is provided
208-
Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
209-
"Either a Config or a valid path must be provided.",
210-
))
211209
}?;
212210

213211
let inner = Arc::new(Mutex::new(env));

python/tests/test_ontoenv.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55
import shutil
66
import os
77

8+
89
# Fixture to create a temporary directory for each test
910
@pytest.fixture
1011
def temp_dir(tmp_path):
1112
"""Provides a temporary directory path for tests."""
1213
yield tmp_path
1314
# Cleanup happens automatically via pytest's tmp_path fixture
1415

16+
1517
# Fixture to create a temporary directory with a pre-initialized OntoEnv
1618
@pytest.fixture
1719
def existing_env_dir(tmp_path):
@@ -23,11 +25,12 @@ def existing_env_dir(tmp_path):
2325
env = OntoEnv(config=cfg, path=env_path, recreate=True)
2426
# Add a dummy file to ensure the env is not empty if needed later
2527
# For now, just initializing is enough to create the .ontoenv structure
26-
env.flush() # Ensure data is written if not temporary
28+
env.flush() # Ensure data is written if not temporary
2729
del env
2830
yield env_path
2931
# Cleanup happens automatically via pytest's tmp_path fixture
3032

33+
3134
def test_init_with_config_new_dir(temp_dir):
3235
"""Test initializing OntoEnv with a Config in a new directory."""
3336
env_path = temp_dir / "new_env"
@@ -36,7 +39,10 @@ def test_init_with_config_new_dir(temp_dir):
3639
cfg = Config(root=str(env_path), temporary=False)
3740
env = OntoEnv(config=cfg, path=env_path, recreate=True)
3841
assert (env_path / ".ontoenv").is_dir()
39-
assert env.store_path() is not None # Assuming store_path handles non-temporary envs
42+
assert (
43+
env.store_path() is not None
44+
) # Assuming store_path handles non-temporary envs
45+
4046

4147
def test_init_with_config_existing_empty_dir(temp_dir):
4248
"""Test initializing OntoEnv with a Config in an existing empty directory."""
@@ -48,6 +54,7 @@ def test_init_with_config_existing_empty_dir(temp_dir):
4854
assert (env_path / ".ontoenv").is_dir()
4955
assert env.store_path() is not None
5056

57+
5158
def test_init_load_from_existing_dir(existing_env_dir):
5259
"""Test initializing OntoEnv by loading from an existing directory."""
5360
assert (existing_env_dir / ".ontoenv").is_dir()
@@ -57,6 +64,7 @@ def test_init_load_from_existing_dir(existing_env_dir):
5764
assert env.store_path() == str(existing_env_dir / ".ontoenv" / "store.db")
5865
# Add more checks if the fixture pre-populates data
5966

67+
6068
def test_init_recreate_existing_dir(existing_env_dir):
6169
"""Test initializing OntoEnv with recreate=True on an existing directory."""
6270
assert (existing_env_dir / ".ontoenv").is_dir()
@@ -73,6 +81,7 @@ def test_init_recreate_existing_dir(existing_env_dir):
7381
assert not (existing_env_dir / ".ontoenv" / "dummy.txt").exists()
7482
assert len(env.get_ontology_names()) == 0
7583

84+
7685
# Note: This test assumes add() raises an error for read-only mode.
7786
# The Rust ReadOnlyPersistentGraphIO::add returns Err, which should map to PyErr.
7887
def test_init_read_only(existing_env_dir):
@@ -82,39 +91,43 @@ def test_init_read_only(existing_env_dir):
8291

8392
# Attempting to modify should fail
8493
with pytest.raises(ValueError, match="Cannot add to read-only store"):
85-
# Use a dummy file path or URL
94+
# Use a dummy file path or URL
8695
env.add("file:///dummy.ttl")
8796

97+
8898
def test_init_no_config_no_path_error():
8999
"""Test initializing OntoEnv without config or valid path fails."""
90100
# Assuming current dir '.' does not contain a valid .ontoenv
91101
# Clean up potential leftover .ontoenv in cwd just in case
92102
if os.path.exists(".ontoenv"):
93-
if os.path.isfile(".ontoenv"):
94-
os.remove(".ontoenv")
95-
else:
96-
shutil.rmtree(".ontoenv")
103+
if os.path.isfile(".ontoenv"):
104+
os.remove(".ontoenv")
105+
else:
106+
shutil.rmtree(".ontoenv")
97107

98108
# Expecting failure because '.' likely doesn't contain a valid .ontoenv
99-
with pytest.raises(ValueError, match="OntoEnv directory not found at ."):
100-
OntoEnv() # No args
109+
with pytest.raises(ValueError, match="OntoEnv directory not found at: \"./.ontoenv\""):
110+
OntoEnv() # No args
111+
101112

102113
def test_init_path_no_env_error(temp_dir):
103114
"""Test initializing OntoEnv with a path to a dir without .ontoenv fails."""
104115
env_path = temp_dir / "no_env_here"
105116
env_path.mkdir()
106117
assert not (env_path / ".ontoenv").exists()
107118
# Expecting failure because the specified path doesn't contain a .ontoenv dir
108-
with pytest.raises(ValueError, match=f"OntoEnv directory not found at {env_path}"):
119+
absolute_path = (env_path / ".ontoenv").resolve()
120+
with pytest.raises(ValueError, match=f"OntoEnv directory not found at: \"{absolute_path}\""):
109121
# This fails because load_from_directory expects .ontoenv unless recreate=True
110-
OntoEnv(path=env_path)
122+
OntoEnv(path=env_path)
123+
111124

112125
def test_init_temporary(temp_dir):
113126
"""Test initializing OntoEnv with temporary=True."""
114127
env_path = temp_dir / "temp_env_root"
115128
# temporary envs don't persist to disk relative to root
116129
cfg = Config(root=str(env_path), temporary=True, strict=False)
117-
env = OntoEnv(config=cfg) # Path shouldn't matter for temporary
130+
env = OntoEnv(config=cfg) # Path shouldn't matter for temporary
118131

119132
# .ontoenv directory should NOT be created at the root
120133
assert not (env_path / ".ontoenv").exists()
@@ -137,4 +150,5 @@ def test_init_temporary(temp_dir):
137150
# Catch other potential errors (like network) during add
138151
pass
139152

153+
140154
# TODO: Add tests for offline mode, different resolution policies, includes/excludes etc.

0 commit comments

Comments
 (0)