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

Support exceptions in Python #301

Merged
merged 5 commits into from
May 14, 2024
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
10 changes: 1 addition & 9 deletions .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.10'
python-version: '3.11'
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
Expand All @@ -138,14 +138,6 @@ jobs:
with:
name: wheels-macos-${{ matrix.platform.target }}
path: dist
- name: pytest
if: ${{ !startsWith(matrix.platform.target, 'aarch64') }}
shell: bash
run: |
set -e
pip install hifitime --find-links dist --force-reinstall --no-index -vv
pip install pytest
pytest

sdist:
runs-on: ubuntu-latest
Expand Down
4 changes: 3 additions & 1 deletion src/duration/kani_verif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ fn formal_duration_truncated_ns_reciprocity() {
// Then it does not fit on a i64, so this function should return an error
assert_eq!(
dur_from_part.try_truncated_nanoseconds(),
Err(DurationError::Overflow)
Err(Err(EpochError::Duration {
source: DurationError::Overflow,
}))
);
} else if centuries == -1 {
// If we are negative by just enough that the centuries is negative, then the truncated seconds
Expand Down
82 changes: 65 additions & 17 deletions src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,82 @@
* Documentation: https://nyxspace.com/
*/

use pyo3::{exceptions::PyException, prelude::*};
use pyo3::{
exceptions::{PyBaseException, PyException},
prelude::*,
types::{PyDict, PyTuple},
};

use crate::leap_seconds::{LatestLeapSeconds, LeapSecondsFile};
use crate::prelude::*;
use crate::ut1::Ut1Provider;

// Keep the module at the top
#[pymodule]
fn hifitime(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Epoch>()?;
m.add_class::<TimeScale>()?;
m.add_class::<TimeSeries>()?;
m.add_class::<Duration>()?;
m.add_class::<Unit>()?;
m.add_class::<LatestLeapSeconds>()?;
m.add_class::<LeapSecondsFile>()?;
m.add_class::<Ut1Provider>()?;
m.add_class::<PyEpochError>()?;
m.add_class::<PyDurationError>()?;
m.add_class::<PyParsingError>()?;
Ok(())
}

#[pyclass]
#[pyo3(name = "EpochError", extends = PyBaseException)]
pub struct PyEpochError {}

#[pymethods]
impl PyEpochError {
#[new]
#[pyo3(signature = (*_args, **_kwargs))]
fn new(_args: Bound<'_, PyTuple>, _kwargs: Option<Bound<'_, PyDict>>) -> Self {
Self {}
}
}

#[pyclass]
#[pyo3(name = "ParsingError", extends = PyBaseException)]
pub struct PyParsingError {}

#[pymethods]
impl PyParsingError {
#[new]
#[pyo3(signature = (*_args, **_kwargs))]
fn new(_args: Bound<'_, PyTuple>, _kwargs: Option<Bound<'_, PyDict>>) -> Self {
Self {}
}
}

#[pyclass]
#[pyo3(name = "DurationError", extends = PyBaseException)]
pub struct PyDurationError {}

#[pymethods]
impl PyDurationError {
#[new]
#[pyo3(signature = (*_args, **_kwargs))]
fn new(_args: Bound<'_, PyTuple>, _kwargs: Option<Bound<'_, PyDict>>) -> Self {
Self {}
}
}

// convert you library error into a PyErr using the custom exception type
impl From<EpochError> for PyErr {
fn from(err: EpochError) -> PyErr {
PyException::new_err(err.to_string())
fn from(err: EpochError) -> Self {
PyErr::new::<PyEpochError, _>(err.to_string())
}
}

impl From<ParsingError> for PyErr {
fn from(err: ParsingError) -> PyErr {
PyException::new_err(err.to_string())
PyErr::new::<PyParsingError, _>(err.to_string())
}
}

Expand All @@ -31,16 +92,3 @@ impl From<DurationError> for PyErr {
PyException::new_err(err.to_string())
}
}

#[pymodule]
fn hifitime(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Epoch>()?;
m.add_class::<TimeScale>()?;
m.add_class::<TimeSeries>()?;
m.add_class::<Duration>()?;
m.add_class::<Unit>()?;
m.add_class::<LatestLeapSeconds>()?;
m.add_class::<LeapSecondsFile>()?;
m.add_class::<Ut1Provider>()?;
Ok(())
}
17 changes: 16 additions & 1 deletion tests/python/test_epoch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from hifitime import Epoch, TimeSeries, Unit, Duration
from hifitime import Duration, Epoch, EpochError, ParsingError, TimeSeries, Unit
from datetime import datetime
import pickle

Expand All @@ -19,6 +19,13 @@ def test_strtime():

assert pickle.loads(pickle.dumps(epoch)) == epoch

try:
epoch.strftime("%o")
except ParsingError as e:
print(f"caught {e}")
else:
raise AssertionError("failed to catch parsing error")


def test_utcnow():
epoch = Epoch.system_now()
Expand Down Expand Up @@ -67,3 +74,11 @@ def test_duration_eq():

dur = Duration("37 min 26 s")
assert pickle.loads(pickle.dumps(dur)) == dur

def test_exceptions():
try:
Epoch("invalid")
except EpochError as e:
print(f"caught {e}")
else:
raise AssertionError("failed to catch epoch error")
Loading