diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..bcbe4e5ae --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,65 @@ +# AGENTS.md + +`citrine-python` is the Python SDK for the Citrine Platform. Users install it from PyPI as `citrine`. It calls the platform REST APIs and builds on the `gemd` package from `gemd-python`. + +## Layout + +| Path | Contents | +|------|----------| +| `src/citrine/citrine.py` | `Citrine`, the client entry point | +| `src/citrine/_session.py` | HTTP session, auth, and request logging | +| `src/citrine/resources/` | Platform resources and their collections, such as projects, teams, and datasets | +| `src/citrine/informatics/` | AI Engine models: predictors, design spaces, constraints, and workflows | +| `src/citrine/gemtables/`, `src/citrine/gemd_queries/` | GEM Table definitions and GEMD query criteria | +| `src/citrine/_rest/`, `src/citrine/_serialization/` | Base collection and pagination classes, and the base classes for serialization | +| `src/citrine/__version__.py` | Package version, read by setuptools | +| `tests/` | Unit tests, which mirror `src/citrine/`. Shared fakes and factories are in `tests/utils/` | +| `docs/source/` | Sphinx source in `.rst` | +| `scripts/` | Test runner, version-bump check, and docs build | + +## Commands + +CI installs dependencies with pip from `requirements.txt` and `test_requirements.txt`, which pin exact versions. The repo has no `uv.lock`, and CI uses none of the dependency groups in `pyproject.toml`. Set up a virtual environment the same way: + +```bash +pip install -r requirements.txt -r test_requirements.txt +pip install --no-deps -e . +``` + +| Task | Command | +|------|---------| +| Lint | `flake8 src/citrine` | +| Format | `ruff format src tests` | +| Expired deprecations | `derp src src/citrine/__version__.py` | +| Tests with coverage | `pytest --cov=src/citrine --cov-report term-missing:skip-covered --cov-config=tox.ini --no-cov-on-fail --cov-fail-under=100 tests/` | +| Version-bump check | `python scripts/validate_version_bump.py`. It runs `git fetch origin` first. | +| Version check, lint, deprecations, and tests | `scripts/run_tests.sh`. It exits with an error on `main`. | +| Docs | `pip install -r doc_requirements.txt`, then `make -C docs html` | + +## CI gates + +Pull requests into `main` and `release/**` run `.github/workflows/pr-checks.yml` and `pr-tests.yml`. Both call shared workflows in `CitrineInformatics/common-gh-actions`. To pass, a PR needs: + +1. A higher version in `src/citrine/__version__.py` than `origin/main` has. +2. A clean `flake8` run on `src/citrine`. +3. No `removed_in` deprecation at or below the current version, checked by `derp`. +4. Passing tests at 100% line coverage, on Python 3.10 through 3.14, on Linux, macOS, and Windows. + +The docs job builds with `-W` but has `continue-on-error`, so doc warnings do not block. Publishing a GitHub release deploys to PyPI and GitHub Pages. + +## Conventions + +- Style is PEP 8 with a 99-character code limit and a 119-character docstring limit. `tox.ini` holds the flake8 config and its ignore list. +- Lint with `flake8` and format with `ruff format`. `pyproject.toml` holds the ruff config. +- Write Numpy-style docstrings. Sphinx autogenerates `docs/source/reference/`, which git ignores. +- Make arguments keyword-only, except a first argument that is required, obvious, and shared by similar methods. +- Name an object's own identifier `uid`. Name the identifier of another type `_id`, such as `bar_id`. +- Mark unsupported experimental APIs with `[ALPHA]` at the start of the docstring. +- Add runtime dependencies to `pyproject.toml` and pin them in `requirements.txt`. Pin test-only dependencies in `test_requirements.txt`. +- `Citrine()` reads `CITRINE_API_KEY` and `CITRINE_API_HOST` when the caller passes no `api_key` or `host`. Unit tests use fake sessions from `tests/utils/` and run offline. + +## Further reading + +- `CONTRIBUTING.md`: style rules, logging, docs layout, and the release-notes template +- `.github/pull_request_template.md`: the PR checklist +- Published docs: https://citrineinformatics.github.io/citrine-python/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/citrine/__version__.py b/src/citrine/__version__.py index f5752882d..fc30498fa 100644 --- a/src/citrine/__version__.py +++ b/src/citrine/__version__.py @@ -1 +1 @@ -__version__ = "5.3.0" +__version__ = "5.4.0" diff --git a/src/citrine/_utils/removed_features.py b/src/citrine/_utils/removed_features.py new file mode 100644 index 000000000..b74da545f --- /dev/null +++ b/src/citrine/_utils/removed_features.py @@ -0,0 +1,175 @@ +"""Stand-ins for the names of features the Citrine Platform has removed. + +The platform removed generative design and design space sampling. +Their public names still import, so an existing script reaches a clear error, not an ImportError. +Importing one of these names emits a DeprecationWarning. +Constructing one of the classes, or calling a method on it, raises FeatureRemovedError. +Version 6.0.0 deletes this module and every name it supplies. +""" + +from collections.abc import Callable, Iterable +from warnings import warn + +from gemd.enumeration.base_enumeration import BaseEnumeration + +from citrine.exceptions import FeatureRemovedError + +DEPRECATED_IN = "5.4.0" +REMOVED_IN = "6.0.0" + +GENERATIVE_DESIGN_REMOVED = "Generative design has been removed from the Citrine Platform." +SAMPLING_REMOVED = "Design space sampling has been removed from the Citrine Platform." + + +class _RemovedClassMeta(type): + """Raise FeatureRemovedError when code reads a method the removed class no longer has.""" + + def __getattr__(cls, name: str): + if name.startswith("__"): + raise AttributeError(name) + raise FeatureRemovedError(cls._removal_message) + + +class _RemovedClass(metaclass=_RemovedClassMeta): + """Base of a class whose platform feature was removed.""" + + _removal_message: str + + def __init__(self, *args, **kwargs): + raise FeatureRemovedError(self._removal_message) + + +class GenerativeDesignInput(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = GENERATIVE_DESIGN_REMOVED + + +class GenerativeDesignResult(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = GENERATIVE_DESIGN_REMOVED + + +class GenerativeDesignExecution(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = GENERATIVE_DESIGN_REMOVED + + +class GenerativeDesignExecutionCollection(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = GENERATIVE_DESIGN_REMOVED + + +class FingerprintType(BaseEnumeration): + """Removed along with generative design. Its members remain for existing scripts.""" + + AP = "AP" + PHCO = "PHCO" + BPF = "BPF" + PATH = "PATH" + ECFP4 = "ECFP4" + ECFP6 = "ECFP6" + FCFP4 = "FCFP4" + FCFP6 = "FCFP6" + + +class StructureExclusion(BaseEnumeration): + """Removed along with generative design. Its members remain for existing scripts.""" + + DOUBLE_BONDS = "DOUBLE_BONDS" + TRIPLE_BONDS = "TRIPLE_BONDS" + ANIONS = "ANIONS" + CATIONS = "CATIONS" + IONS = "IONS" + BORON = "BORON" + PHOSPHORUS = "PHOSPHORUS" + SULFUR = "SULFUR" + NITROGEN = "NITROGEN" + OXYGEN = "OXYGEN" + FLUORINE = "FLUORINE" + BROMINE = "BROMINE" + IODINE = "IODINE" + CHLORINE = "CHLORINE" + + +class SampleDesignSpaceInput(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = SAMPLING_REMOVED + + +class SampleDesignSpaceExecution(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = SAMPLING_REMOVED + + +class SampleDesignSpaceExecutionCollection(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = SAMPLING_REMOVED + + +class SampleSearchSpaceResultCandidate(_RemovedClass): + """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" + + _removal_message = SAMPLING_REMOVED + + +_REMOVED_NAMES = { + cls.__name__: cls + for cls in ( + GenerativeDesignInput, + GenerativeDesignResult, + GenerativeDesignExecution, + GenerativeDesignExecutionCollection, + FingerprintType, + StructureExclusion, + SampleDesignSpaceInput, + SampleDesignSpaceExecution, + SampleDesignSpaceExecutionCollection, + SampleSearchSpaceResultCandidate, + ) +} + + +def deprecated_names( + module_name: str, removal_message: str, names: Iterable[str] +) -> Callable[[str], type]: + """Build a module ``__getattr__`` that supplies removed names with a DeprecationWarning. + + The legacy module must not bind these names itself. + Python calls a module's ``__getattr__`` only for names the module lacks. + + Parameters + ---------- + module_name: str + The ``__name__`` of the module that used to define the names. + removal_message: str + The sentence that states which feature the platform removed. + names: Iterable[str] + The removed names the module supplies. + + Returns + ------- + Callable[[str], type] + A function to assign to the module's ``__getattr__``. + + """ + supplied = {name: _REMOVED_NAMES[name] for name in names} + + def __getattr__(name: str) -> type: + if name not in supplied: + raise AttributeError(f"module {module_name!r} has no attribute {name!r}") + warn( + f"{module_name}.{name} is deprecated as of {DEPRECATED_IN} and will be removed " + f"in {REMOVED_IN}. {removal_message}", + DeprecationWarning, + stacklevel=2, + ) + return supplied[name] + + return __getattr__ diff --git a/src/citrine/informatics/design_candidate.py b/src/citrine/informatics/design_candidate.py index d93386901..01db3d2b8 100644 --- a/src/citrine/informatics/design_candidate.py +++ b/src/citrine/informatics/design_candidate.py @@ -1,4 +1,5 @@ from citrine._serialization import properties +from citrine._utils import removed_features as _removed_features from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine._serialization.serializable import Serializable @@ -203,3 +204,8 @@ class HierarchicalDesignCandidate(Serializable["HierarchicalDesignCandidate"]): """:int: rank by score amongst other candidates produced by the design workflow""" material = properties.Object(HierarchicalDesignMaterial, "material") """:HierarchicalDesignMaterial: the material returned by the design workflow""" + + +__getattr__ = _removed_features.deprecated_names( + __name__, _removed_features.SAMPLING_REMOVED, ["SampleSearchSpaceResultCandidate"] +) diff --git a/src/citrine/informatics/design_spaces/sample_design_space.py b/src/citrine/informatics/design_spaces/sample_design_space.py index 5c64576ca..fa82a2e7b 100644 --- a/src/citrine/informatics/design_spaces/sample_design_space.py +++ b/src/citrine/informatics/design_spaces/sample_design_space.py @@ -1,12 +1,11 @@ -"""Design space sampling has been removed; this name remains so existing scripts fail clearly.""" +"""Design space sampling has been removed from the Citrine Platform. -from citrine.exceptions import FeatureRemovedError +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" -SAMPLING_REMOVED = "Design space sampling has been removed from the Citrine Platform." +from citrine._utils import removed_features - -class SampleDesignSpaceInput: - """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" - - def __init__(self, *args, **kwargs): - raise FeatureRemovedError(SAMPLING_REMOVED) +__getattr__ = removed_features.deprecated_names( + __name__, removed_features.SAMPLING_REMOVED, ["SampleDesignSpaceInput"] +) diff --git a/src/citrine/informatics/design_spaces/top_level_design_space.py b/src/citrine/informatics/design_spaces/top_level_design_space.py index a883aa5b0..61b576be6 100644 --- a/src/citrine/informatics/design_spaces/top_level_design_space.py +++ b/src/citrine/informatics/design_spaces/top_level_design_space.py @@ -8,7 +8,7 @@ from citrine._serialization.serializable import Serializable from citrine._session import Session from citrine.exceptions import FeatureRemovedError -from citrine.informatics.design_spaces.sample_design_space import SAMPLING_REMOVED +from citrine._utils.removed_features import SAMPLING_REMOVED __all__ = ["TopLevelDesignSpace"] diff --git a/src/citrine/informatics/executions/__init__.py b/src/citrine/informatics/executions/__init__.py index b6f4c26d6..d0499409f 100644 --- a/src/citrine/informatics/executions/__init__.py +++ b/src/citrine/informatics/executions/__init__.py @@ -1,3 +1,11 @@ # flake8: noqa from .predictor_evaluation import * from .design_execution import * + +from citrine._utils import removed_features as _removed_features + +__getattr__ = _removed_features.deprecated_names( + __name__, + _removed_features.GENERATIVE_DESIGN_REMOVED, + ["GenerativeDesignExecution", "GenerativeDesignResult"], +) diff --git a/src/citrine/informatics/executions/generative_design_execution.py b/src/citrine/informatics/executions/generative_design_execution.py new file mode 100644 index 000000000..f244ca69d --- /dev/null +++ b/src/citrine/informatics/executions/generative_design_execution.py @@ -0,0 +1,13 @@ +"""Generative design has been removed from the Citrine Platform. + +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" + +from citrine._utils import removed_features + +__getattr__ = removed_features.deprecated_names( + __name__, + removed_features.GENERATIVE_DESIGN_REMOVED, + ["GenerativeDesignExecution", "GenerativeDesignResult"], +) diff --git a/src/citrine/informatics/executions/sample_design_space_execution.py b/src/citrine/informatics/executions/sample_design_space_execution.py new file mode 100644 index 000000000..2ec68f0d5 --- /dev/null +++ b/src/citrine/informatics/executions/sample_design_space_execution.py @@ -0,0 +1,13 @@ +"""Design space sampling has been removed from the Citrine Platform. + +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" + +from citrine._utils import removed_features + +__getattr__ = removed_features.deprecated_names( + __name__, + removed_features.SAMPLING_REMOVED, + ["SampleDesignSpaceExecution", "SampleSearchSpaceResultCandidate"], +) diff --git a/src/citrine/informatics/generative_design.py b/src/citrine/informatics/generative_design.py index 0a13918e5..02c9b247e 100644 --- a/src/citrine/informatics/generative_design.py +++ b/src/citrine/informatics/generative_design.py @@ -1,46 +1,13 @@ -"""Generative design has been removed; these names remain so existing scripts fail clearly.""" +"""Generative design has been removed from the Citrine Platform. -from gemd.enumeration.base_enumeration import BaseEnumeration +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" -from citrine.exceptions import FeatureRemovedError +from citrine._utils import removed_features -GENERATIVE_DESIGN_REMOVED = "Generative design has been removed from the Citrine Platform." - - -class GenerativeDesignInput: - """Removed. Constructing one raises :class:`~citrine.exceptions.FeatureRemovedError`.""" - - def __init__(self, *args, **kwargs): - raise FeatureRemovedError(GENERATIVE_DESIGN_REMOVED) - - -class FingerprintType(BaseEnumeration): - """Removed along with generative design; kept so scripts reach the removal error.""" - - AP = "AP" - PHCO = "PHCO" - BPF = "BPF" - PATH = "PATH" - ECFP4 = "ECFP4" - ECFP6 = "ECFP6" - FCFP4 = "FCFP4" - FCFP6 = "FCFP6" - - -class StructureExclusion(BaseEnumeration): - """Removed along with generative design; kept so scripts reach the removal error.""" - - DOUBLE_BONDS = "DOUBLE_BONDS" - TRIPLE_BONDS = "TRIPLE_BONDS" - ANIONS = "ANIONS" - CATIONS = "CATIONS" - IONS = "IONS" - BORON = "BORON" - PHOSPHORUS = "PHOSPHORUS" - SULFUR = "SULFUR" - NITROGEN = "NITROGEN" - OXYGEN = "OXYGEN" - FLUORINE = "FLUORINE" - BROMINE = "BROMINE" - IODINE = "IODINE" - CHLORINE = "CHLORINE" +__getattr__ = removed_features.deprecated_names( + __name__, + removed_features.GENERATIVE_DESIGN_REMOVED, + ["GenerativeDesignInput", "GenerativeDesignResult", "FingerprintType", "StructureExclusion"], +) diff --git a/src/citrine/resources/generative_design_execution.py b/src/citrine/resources/generative_design_execution.py new file mode 100644 index 000000000..80c7ec9e0 --- /dev/null +++ b/src/citrine/resources/generative_design_execution.py @@ -0,0 +1,13 @@ +"""Generative design has been removed from the Citrine Platform. + +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" + +from citrine._utils import removed_features + +__getattr__ = removed_features.deprecated_names( + __name__, + removed_features.GENERATIVE_DESIGN_REMOVED, + ["GenerativeDesignExecutionCollection", "GenerativeDesignExecution", "GenerativeDesignInput"], +) diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index 424e1a196..4404d0b1c 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -53,6 +53,17 @@ class IngestionErrorType(BaseEnumeration): INCOMPATIBLE_UNITS = "incompatible_units" EXISTING_TEMPLATE_WITH_REAL_BOUNDS = "existing_template_with_real_bounds" EMPTY_ASPECT_NAME = "empty_aspect_name" + FILE_EXTENSION_IS_NOT_DEFINED = "file_extension_is_not_defined" + MISSING_ROW_IDENTIFIER = "missing_row_identifier" + DATASET_FILE_ID_NOT_FOUND = "dataset_file_id_not_found" + DATASET_FILE_VERSION_NOT_FOUND = "dataset_file_version_not_found" + EMPTY_FILE = "empty_file" + TYPE_HINT_NOT_FOUND = "type_hint_not_found" + TYPE_HINT_FOUND_MULTIPLE_TIMES = "type_hint_found_multiple_times" + DECODE_FILE_ERROR = "decode_file_error" + CIRCULAR_REFERENCE = "circular_reference" + TEMPLATE_NOT_FOUND_FOR_COLUMN = "template_not_found_for_column" + MIXED_AMOUNT_AND_INGREDIENT = "mixed_amount_and_ingredient" class IngestionErrorLevel(BaseEnumeration): @@ -63,11 +74,18 @@ class IngestionErrorLevel(BaseEnumeration): INFO = "info" +class _IngestionErrorTypeProperty(properties.Enumeration): + """Maps error types this SDK doesn't know yet to UNKNOWN_ERROR, so the trace's msg survives.""" + + def _deserialize(self, value: str) -> IngestionErrorType: + return IngestionErrorType.from_str(value) or IngestionErrorType.UNKNOWN_ERROR + + class IngestionErrorTrace(Resource["IngestionErrorTrace"]): """[ALPHA] Detailed information about an ingestion issue.""" family = properties.Enumeration(IngestionErrorFamily, "family") - error_type = properties.Enumeration(IngestionErrorType, "error_type") + error_type = _IngestionErrorTypeProperty(IngestionErrorType, "error_type") level = properties.Enumeration(IngestionErrorLevel, "level") msg = properties.String("msg") dataset_file_id = properties.Optional(properties.UUID(), "dataset_file_id", default=None) diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index 767645410..b54cf5b86 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -10,7 +10,7 @@ from citrine._session import Session from citrine._utils.functions import format_escaped_url from citrine.exceptions import FeatureRemovedError -from citrine.informatics.generative_design import GENERATIVE_DESIGN_REMOVED +from citrine._utils.removed_features import GENERATIVE_DESIGN_REMOVED from citrine.resources.branch import BranchCollection from citrine.resources.descriptors import DescriptorMethods from citrine.resources.design_space import DesignSpaceCollection diff --git a/src/citrine/resources/sample_design_space_execution.py b/src/citrine/resources/sample_design_space_execution.py new file mode 100644 index 000000000..4cc5b7f7e --- /dev/null +++ b/src/citrine/resources/sample_design_space_execution.py @@ -0,0 +1,17 @@ +"""Design space sampling has been removed from the Citrine Platform. + +Importing a name from this module emits a DeprecationWarning. +Using one of its classes raises :class:`~citrine.exceptions.FeatureRemovedError`. +""" + +from citrine._utils import removed_features + +__getattr__ = removed_features.deprecated_names( + __name__, + removed_features.SAMPLING_REMOVED, + [ + "SampleDesignSpaceExecutionCollection", + "SampleDesignSpaceExecution", + "SampleDesignSpaceInput", + ], +) diff --git a/tests/resources/test_ingestion.py b/tests/resources/test_ingestion.py index f214e5361..85798fbae 100644 --- a/tests/resources/test_ingestion.py +++ b/tests/resources/test_ingestion.py @@ -364,3 +364,52 @@ def _raise_exception(): ) with pytest.raises(IngestionException, match="Missing ingredient"): ingest.build_objects() + + +@pytest.mark.parametrize( + "error_type", + [ + "file_extension_is_not_defined", + "missing_row_identifier", + "dataset_file_id_not_found", + "dataset_file_version_not_found", + "empty_file", + "type_hint_not_found", + "type_hint_found_multiple_times", + "decode_file_error", + "circular_reference", + "template_not_found_for_column", + "mixed_amount_and_ingredient", + ], +) +def test_status_parses_server_error_types(error_type): + status = IngestionStatus.build( + IngestionStatusResponseDataFactory( + errors=[ + { + "family": "data", + "error_type": error_type, + "level": "error", + "msg": "Server-side ingestion error", + } + ] + ) + ) + assert status.errors[0].error_type == IngestionErrorType(error_type) + + +def test_status_falls_back_on_unknown_error_type(): + status = IngestionStatus.build( + IngestionStatusResponseDataFactory( + errors=[ + { + "family": "data", + "error_type": "some_future_error", + "level": "error", + "msg": "A server-only ingestion error", + } + ] + ) + ) + assert status.errors[0].error_type == IngestionErrorType.UNKNOWN_ERROR + assert status.errors[0].msg == "A server-only ingestion error" diff --git a/tests/test_removed_features.py b/tests/test_removed_features.py index c8dd586fb..ed95265bd 100644 --- a/tests/test_removed_features.py +++ b/tests/test_removed_features.py @@ -1,29 +1,107 @@ -"""Removed platform features must fail locally with the platform's own message.""" +"""Removed platform features warn on import and fail on use, with the platform's own message.""" +import importlib import re +import subprocess +import sys import uuid +import warnings import pytest +from packaging.version import Version +from citrine.__version__ import __version__ +from citrine._utils.removed_features import REMOVED_IN from citrine.exceptions import CitrineException, FeatureRemovedError from citrine.informatics.design_spaces import ProductDesignSpace -from citrine.informatics.design_spaces.sample_design_space import SampleDesignSpaceInput -from citrine.informatics.generative_design import ( - FingerprintType, - GenerativeDesignInput, - StructureExclusion, -) from citrine.resources.project import Project from tests.utils.session import FakeSession GENERATIVE_DESIGN_REMOVED = "Generative design has been removed from the Citrine Platform." SAMPLING_REMOVED = "Design space sampling has been removed from the Citrine Platform." +# Each (module, name) pair that a released version of citrine-python let a script import. +REMOVED_IMPORTS = [ + ("citrine.informatics.generative_design", "GenerativeDesignInput", GENERATIVE_DESIGN_REMOVED), + ("citrine.informatics.generative_design", "GenerativeDesignResult", GENERATIVE_DESIGN_REMOVED), + ("citrine.informatics.generative_design", "FingerprintType", GENERATIVE_DESIGN_REMOVED), + ("citrine.informatics.generative_design", "StructureExclusion", GENERATIVE_DESIGN_REMOVED), + ("citrine.informatics.executions", "GenerativeDesignExecution", GENERATIVE_DESIGN_REMOVED), + ("citrine.informatics.executions", "GenerativeDesignResult", GENERATIVE_DESIGN_REMOVED), + ( + "citrine.informatics.executions.generative_design_execution", + "GenerativeDesignExecution", + GENERATIVE_DESIGN_REMOVED, + ), + ( + "citrine.informatics.executions.generative_design_execution", + "GenerativeDesignResult", + GENERATIVE_DESIGN_REMOVED, + ), + ( + "citrine.resources.generative_design_execution", + "GenerativeDesignExecutionCollection", + GENERATIVE_DESIGN_REMOVED, + ), + ( + "citrine.resources.generative_design_execution", + "GenerativeDesignExecution", + GENERATIVE_DESIGN_REMOVED, + ), + ( + "citrine.resources.generative_design_execution", + "GenerativeDesignInput", + GENERATIVE_DESIGN_REMOVED, + ), + ( + "citrine.informatics.design_spaces.sample_design_space", + "SampleDesignSpaceInput", + SAMPLING_REMOVED, + ), + ("citrine.informatics.design_candidate", "SampleSearchSpaceResultCandidate", SAMPLING_REMOVED), + ( + "citrine.informatics.executions.sample_design_space_execution", + "SampleDesignSpaceExecution", + SAMPLING_REMOVED, + ), + ( + "citrine.informatics.executions.sample_design_space_execution", + "SampleSearchSpaceResultCandidate", + SAMPLING_REMOVED, + ), + ( + "citrine.resources.sample_design_space_execution", + "SampleDesignSpaceExecutionCollection", + SAMPLING_REMOVED, + ), + ( + "citrine.resources.sample_design_space_execution", + "SampleDesignSpaceExecution", + SAMPLING_REMOVED, + ), + ( + "citrine.resources.sample_design_space_execution", + "SampleDesignSpaceInput", + SAMPLING_REMOVED, + ), +] + +REMOVED_ENUMERATIONS = {"FingerprintType", "StructureExclusion"} + +REMOVED_CLASSES = [entry for entry in REMOVED_IMPORTS if entry[1] not in REMOVED_ENUMERATIONS] + def raises_removed(message: str): return pytest.raises(FeatureRemovedError, match=f"^{re.escape(message)}$") +def import_removed(module_name: str, name: str): + """Import a removed name, and suppress the warning that tests below assert on.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + return getattr(importlib.import_module(module_name), name) + + @pytest.fixture def session() -> FakeSession: return FakeSession() @@ -47,18 +125,91 @@ def design_space(session, project) -> ProductDesignSpace: def test_removal_error_is_a_citrine_exception(): assert issubclass(FeatureRemovedError, CitrineException) - - -def test_generative_design_script_fails_at_the_input(session): - with raises_removed(GENERATIVE_DESIGN_REMOVED): - GenerativeDesignInput( - seeds=["C"], - fingerprint_type=FingerprintType.ECFP4, - min_fingerprint_similarity=0.1, - mutation_per_seed=25, - structure_exclusions=[StructureExclusion.IONS], - ) - assert session.num_calls == 0 + assert issubclass(FeatureRemovedError, AttributeError) + + +@pytest.mark.parametrize("module_name, name, message", REMOVED_IMPORTS) +def test_importing_a_removed_name_warns(module_name, name, message): + expected = ( + f"{module_name}.{name} is deprecated as of 5.4.0 and will be removed in 6.0.0. {message}" + ) + with pytest.warns(DeprecationWarning, match=f"^{re.escape(expected)}$") as record: + exec(f"from {module_name} import {name}", {}) + # The warning names the importing code, so Python shows it by default in a script. + assert record[0].filename == "" + + +@pytest.mark.parametrize("module_name, name, message", REMOVED_CLASSES) +def test_constructing_a_removed_class_raises(module_name, name, message): + removed_class = import_removed(module_name, name) + with raises_removed(message): + removed_class() + with raises_removed(message): + removed_class(seeds=["C"], n_candidates=50) + + +@pytest.mark.parametrize("module_name, name, message", REMOVED_CLASSES) +def test_calling_a_method_of_a_removed_class_raises(module_name, name, message): + removed_class = import_removed(module_name, name) + for method in ("build", "trigger", "list", "get", "results"): + with raises_removed(message): + getattr(removed_class, method) + + +def test_removed_classes_answer_introspection(): + removed_class = import_removed( + "citrine.informatics.generative_design", "GenerativeDesignInput" + ) + assert not hasattr(removed_class, "__wrapped__") + assert isinstance(object(), removed_class) is False + + +def test_removed_enumerations_keep_their_members(): + fingerprint_type = import_removed("citrine.informatics.generative_design", "FingerprintType") + exclusion = import_removed("citrine.informatics.generative_design", "StructureExclusion") + assert fingerprint_type.ECFP4.value == "ECFP4" + assert exclusion.IONS.value == "IONS" + + +def test_the_same_class_comes_from_every_module(): + from_informatics = import_removed( + "citrine.informatics.executions", "GenerativeDesignExecution" + ) + from_resources = import_removed( + "citrine.resources.generative_design_execution", "GenerativeDesignExecution" + ) + assert from_informatics is from_resources + + +def test_unknown_names_raise_without_a_warning(): + module = importlib.import_module("citrine.informatics.generative_design") + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(AttributeError, match="has no attribute 'NoSuchName'"): + module.NoSuchName + exec("from citrine.informatics.executions import *", {}) + + +def test_importing_citrine_emits_no_removal_warning(): + script = ( + "import warnings\n" + "warnings.simplefilter('always')\n" + "with warnings.catch_warnings(record=True) as record:\n" + " import citrine\n" + " import citrine.informatics.executions\n" + " import citrine.informatics.design_candidate\n" + " import citrine.informatics.generative_design\n" + " import citrine.informatics.design_spaces.sample_design_space\n" + " import citrine.informatics.executions.generative_design_execution\n" + " import citrine.informatics.executions.sample_design_space_execution\n" + " import citrine.resources.generative_design_execution\n" + " import citrine.resources.sample_design_space_execution\n" + "print(sum('removed from the Citrine Platform' in str(w.message) for w in record))\n" + ) + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=True + ) + assert result.stdout.strip() == "0" def test_generative_design_executions_raise(project, session): @@ -67,12 +218,6 @@ def test_generative_design_executions_raise(project, session): assert session.num_calls == 0 -def test_sampling_script_fails_at_the_input(session): - with raises_removed(SAMPLING_REMOVED): - SampleDesignSpaceInput(n_candidates=50) - assert session.num_calls == 0 - - def test_sample_design_space_executions_raise(design_space, session): with raises_removed(SAMPLING_REMOVED): design_space.sample_design_space_executions.trigger(None) @@ -83,3 +228,11 @@ def test_removed_accessors_are_absent_to_introspection(project, design_space, se assert not hasattr(project, "generative_design_executions") assert not hasattr(design_space, "sample_design_space_executions") assert session.num_calls == 0 + + +def test_removed_names_are_gone_by_version_6(): + assert Version(__version__) < Version(REMOVED_IN), ( + f"Version {REMOVED_IN} removes generative design and design space sampling. " + "Delete citrine._utils.removed_features, the modules that import it, " + "FeatureRemovedError's accessors, and this test file." + )