diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 5e1cc0d..48e507f 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -33,19 +33,19 @@ example_operation.validate() | UpdateDropdownOption | Updates the name of an existing option in a dropdown. | 6 | | ArchiveDropdownOption | Archives an existing option in a dropdown. | 7 | | ReorderDropdownOptions | Reorders the options in an existing dropdown. | 8 | -| ArchiveDropdown | Archives an existing dropdown. | 19 | +| ArchiveDropdown | Archives an existing dropdown. | 18 | ### Entity Schema Operations | Operation Class | Description | Order | |--------------------------------|-----------------------------------------------------------------------------|-------| | CreateEntitySchema | Creates a new entity schema with specified fields. | 9 | -| UnarchiveEntitySchema | Unarchives an archived entity schema. | 10 | +| UnarchiveEntitySchema | Unarchives an archived entity schema. | 10 | | CreateEntitySchemaField | Creates a new field in an existing entity schema. | 11 | -| UpdateEntitySchemaNameTemplate | Updates the name template of an existing entity schema. | 12 | -| UpdateEntitySchema | Updates the properties of an existing entity schema. | 13 | -| UnarchiveEntitySchemaField | Unarchives an archived field in an entity schema. | 14 | -| UpdateEntitySchemaField | Updates the properties of an existing field in an entity schema. | 15 | +| UpdateEntitySchema | Updates the properties of an existing entity schema. | 12 | +| UnarchiveEntitySchemaField | Unarchives an archived field in an entity schema. | 13 | +| UpdateEntitySchemaField | Updates the properties of an existing field in an entity schema. | 14 | +| UpdateEntitySchemaNameTemplate | Updates the name template of an existing entity schema. | 15 | | ArchiveEntitySchemaField | Archives an existing field in an entity schema. | 16 | | ReorderEntitySchemaFields | Reorders the fields in an existing entity schema. | 17 | | ArchiveEntitySchema | Archives an existing entity schema. | 18 | diff --git a/liminal/base/base_operation.py b/liminal/base/base_operation.py index 4f3bfb7..879a45e 100644 --- a/liminal/base/base_operation.py +++ b/liminal/base/base_operation.py @@ -16,10 +16,10 @@ 9. CreateEntitySchema 10. UnarchiveEntitySchema 11. CreateEntitySchemaField - 12. UpdateEntitySchemaNameTemplate - 13. UpdateEntitySchema - 14. UnarchiveEntitySchemaField - 15. UpdateEntitySchemaField + 12. UpdateEntitySchema + 13. UnarchiveEntitySchemaField + 14. UpdateEntitySchemaField + 15. UpdateEntitySchemaNameTemplate 16. ArchiveEntitySchemaField 17. ReorderEntitySchemaFields 18. ArchiveEntitySchema diff --git a/liminal/base/compare_operation.py b/liminal/base/compare_operation.py index 4abca7e..6605164 100644 --- a/liminal/base/compare_operation.py +++ b/liminal/base/compare_operation.py @@ -6,8 +6,14 @@ class CompareOperation(BaseModel): op: BaseOperation reverse_op: BaseOperation + # Overrides op.order when this operation must run at a different point than its type's default. + order_override: int | None = None model_config = ConfigDict(arbitrary_types_allowed=True) + @property + def sort_order(self) -> int: + return self.op.order if self.order_override is None else self.order_override + def __lt__(self, other: "CompareOperation") -> bool: - return self.op.order < other.op.order + return self.sort_order < other.sort_order diff --git a/liminal/base/properties/base_field_properties.py b/liminal/base/properties/base_field_properties.py index 5f85013..10dd7a5 100644 --- a/liminal/base/properties/base_field_properties.py +++ b/liminal/base/properties/base_field_properties.py @@ -94,6 +94,11 @@ def unset_unit_name(self) -> BaseFieldProperties: self.__pydantic_fields_set__.remove("unit_name") return self + def unset_parent_link(self) -> BaseFieldProperties: + if "parent_link" in self.__pydantic_fields_set__: + self.__pydantic_fields_set__.remove("parent_link") + return self + def set_type(self, new_type: BenchlingFieldType) -> BaseFieldProperties: self.type = new_type return self diff --git a/liminal/base/properties/base_schema_properties.py b/liminal/base/properties/base_schema_properties.py index b3e48f1..e95a6e6 100644 --- a/liminal/base/properties/base_schema_properties.py +++ b/liminal/base/properties/base_schema_properties.py @@ -105,6 +105,11 @@ def set_naming_strategies( self.naming_strategies = value return self + def unset_naming_strategies(self) -> BaseSchemaProperties: + if "naming_strategies" in self.__pydantic_fields_set__: + self.__pydantic_fields_set__.remove("naming_strategies") + return self + def merge(self, new_props: BaseSchemaProperties) -> dict[str, Any]: """Creates a diff between the current schema properties and the new schema properties. Sets value to None if the values are equal, otherwise sets the value to the new value. diff --git a/liminal/entity_schemas/compare.py b/liminal/entity_schemas/compare.py index e62522a..bd3f45e 100644 --- a/liminal/entity_schemas/compare.py +++ b/liminal/entity_schemas/compare.py @@ -26,6 +26,9 @@ LOGGER = logging.getLogger(__name__) +# Template based naming strategies need the name template, so the order is overridden to be set right after it. +NAME_TEMPLATE_NAMING_STRATEGY_ORDER = UpdateEntitySchemaNameTemplate.order + 1 + def compare_entity_schemas( benchling_service: BenchlingService, schema_names: set[str] | None = None @@ -237,26 +240,50 @@ def compare_entity_schemas( ) ) if benchling_schema_props != model.__schema_properties__: - ops.append( - CompareOperation( - op=UpdateEntitySchema( - model.__schema_properties__.warehouse_name, - BaseSchemaProperties( - **benchling_schema_props.merge( - model.__schema_properties__ - ) + new_schema_props = BaseSchemaProperties( + **benchling_schema_props.merge(model.__schema_properties__) + ) + rollback_schema_props = BaseSchemaProperties( + **model.__schema_properties__.merge(benchling_schema_props) + ) + model_strategies = ( + model.__schema_properties__.naming_strategies or set() + ) + benchling_strategies = benchling_schema_props.naming_strategies or set() + # A template based naming strategy needs the name template, which runs after UpdateEntitySchema. + # So when one is being added, set all the naming strategies in their own operation after the template. + if any( + BenchlingNamingStrategy.is_template_based(s) + for s in model_strategies - benchling_strategies + ): + new_schema_props.unset_naming_strategies() + rollback_schema_props.unset_naming_strategies() + ops.append( + CompareOperation( + op=UpdateEntitySchema( + model_wh_name, + BaseSchemaProperties( + naming_strategies=model_strategies + ), ), - ), - reverse_op=UpdateEntitySchema( - model.__schema_properties__.warehouse_name, - BaseSchemaProperties( - **model.__schema_properties__.merge( - benchling_schema_props - ) + reverse_op=UpdateEntitySchema( + model_wh_name, + BaseSchemaProperties( + naming_strategies=benchling_strategies + ), + ), + order_override=NAME_TEMPLATE_NAMING_STRATEGY_ORDER, + ) + ) + if new_schema_props.model_dump(exclude_unset=True) != {}: + ops.append( + CompareOperation( + op=UpdateEntitySchema(model_wh_name, new_schema_props), + reverse_op=UpdateEntitySchema( + model_wh_name, rollback_schema_props ), ), - ), - ) + ) if benchling_name_template != model.__name_template__: ops.append( CompareOperation( @@ -300,8 +327,24 @@ def compare_entity_schemas( for p in field_props if (p.unit_name and p.warehouse_name) } + # A link field is created without a target, and Benchling only accepts + # parent_link on a field that has one, so it is set with the target. + parent_links_to_update = { + p.warehouse_name + for p in field_props + if (p.parent_link and p.entity_link and p.warehouse_name) + } field_props = [ - f.unset_tooltip().unset_entity_link().unset_unit_name() + f.unset_tooltip() + .unset_entity_link() + .unset_unit_name() + .unset_parent_link() + for f in field_props + ] + field_props = [ + f.unset_parent_link() + if f.warehouse_name in parent_links_to_update + else f for f in field_props ] field_props = [ @@ -337,32 +380,20 @@ def compare_entity_schemas( ) ) # Benchling api does not allow for setting a custom warehouse_name. - # Benchling api also does not allow for setting the name template. # Because of this, we need to run a separate UpdateEntitySchema to set the warehouse_name if it is different from the snakecase version of the model name. - # We also need to set the template based naming_strategies separately, since the name template must first be set. - new_schema_props = BaseSchemaProperties() - rollback_schema_props = BaseSchemaProperties() + # Later operations on this schema use the model's warehouse_name. if model_wh_name != benchling_given_wh_name: - new_schema_props.warehouse_name = model_wh_name - rollback_schema_props.warehouse_name = benchling_given_wh_name - if ( - model.__schema_properties__.naming_strategies - - standard_naming_strategies - ): - new_schema_props.naming_strategies = ( - model.__schema_properties__.naming_strategies - ) - rollback_schema_props.naming_strategies = standard_naming_strategies - if new_schema_props.model_dump(exclude_unset=True) != {}: ops.append( CompareOperation( op=UpdateEntitySchema( benchling_given_wh_name, - new_schema_props, + BaseSchemaProperties(warehouse_name=model_wh_name), ), reverse_op=UpdateEntitySchema( model_wh_name, - rollback_schema_props, + BaseSchemaProperties( + warehouse_name=benchling_given_wh_name + ), ), ) ) @@ -382,6 +413,9 @@ def compare_entity_schemas( ) rollback_field_props.entity_link = None rollback_field_props.type = BenchlingFieldType.ENTITY_LINK + if wh_field_name in parent_links_to_update: + new_field_props.parent_link = True + rollback_field_props.parent_link = False if tooltip_value := tooltips_to_update.get(wh_field_name): new_field_props.tooltip = tooltip_value rollback_field_props.tooltip = None @@ -403,11 +437,12 @@ def compare_entity_schemas( ) # Benchling api also does not allow for setting the name template when Creating an Entity Schema, since it is a different endpoint. # Because of this, we need to run a separate UpdateEntitySchemaNameTemplate using the name template endpoint to set the name template on the newly created Entity Schema. + # The name template update runs after the field updates above, since a part can need a link target or parent link set there. if benchling_given_name_template != model.__name_template__: ops.append( CompareOperation( op=UpdateEntitySchemaNameTemplate( - benchling_given_wh_name, + model_wh_name, BaseNameTemplate( **benchling_given_name_template.merge( model.__name_template__ @@ -415,7 +450,7 @@ def compare_entity_schemas( ), ), reverse_op=UpdateEntitySchemaNameTemplate( - benchling_given_wh_name, + model_wh_name, BaseNameTemplate( **model.__name_template__.merge( benchling_given_name_template @@ -424,6 +459,28 @@ def compare_entity_schemas( ), ) ) + # Template based naming_strategies need the name template, so they are set right after it. + if ( + model.__schema_properties__.naming_strategies + - standard_naming_strategies + ): + ops.append( + CompareOperation( + op=UpdateEntitySchema( + model_wh_name, + BaseSchemaProperties( + naming_strategies=model.__schema_properties__.naming_strategies + ), + ), + reverse_op=UpdateEntitySchema( + model_wh_name, + BaseSchemaProperties( + naming_strategies=standard_naming_strategies + ), + ), + order_override=NAME_TEMPLATE_NAMING_STRATEGY_ORDER, + ) + ) model_operations[model.__schema_properties__.warehouse_name] = ops running_benchling_schema_names = [ diff --git a/liminal/entity_schemas/operations.py b/liminal/entity_schemas/operations.py index a592a9d..0edaa43 100644 --- a/liminal/entity_schemas/operations.py +++ b/liminal/entity_schemas/operations.py @@ -41,7 +41,7 @@ class CreateEntitySchema(BaseOperation): - order: ClassVar[int] = 80 + order: ClassVar[int] = 90 def __init__( self, @@ -165,7 +165,7 @@ def _validate_unarchive( class ArchiveEntitySchema(BaseOperation): - order: ClassVar[int] = 170 + order: ClassVar[int] = 180 def __init__(self, wh_schema_name: str) -> None: self.wh_schema_name = wh_schema_name @@ -193,7 +193,7 @@ def _validate(self, benchling_service: BenchlingService) -> EntitySchemaModel: class UnarchiveEntitySchema(BaseOperation): - order: ClassVar[int] = 90 + order: ClassVar[int] = 100 def __init__(self, wh_schema_name: str) -> None: self.wh_schema_name = wh_schema_name @@ -290,7 +290,7 @@ def _validate(self, benchling_service: BenchlingService) -> EntitySchemaModel: class UpdateEntitySchemaNameTemplate(BaseOperation): - order: ClassVar[int] = 110 + order: ClassVar[int] = 150 def __init__( self, @@ -329,7 +329,7 @@ def describe(self) -> str: class CreateEntitySchemaField(BaseOperation): - order: ClassVar[int] = 100 + order: ClassVar[int] = 110 def __init__( self, @@ -442,7 +442,7 @@ def validate(self, benchling_service: BenchlingService) -> None: class ArchiveEntitySchemaField(BaseOperation): - order: ClassVar[int] = 150 + order: ClassVar[int] = 160 def __init__( self, wh_schema_name: str, wh_field_name: str, index: int | None = None @@ -634,7 +634,7 @@ def _validate(self, benchling_service: BenchlingService) -> EntitySchemaModel: class ReorderEntitySchemaFields(BaseOperation): - order: ClassVar[int] = 160 + order: ClassVar[int] = 170 def __init__(self, wh_schema_name: str, new_order: list[str]) -> None: self.wh_schema_name = wh_schema_name diff --git a/liminal/tests/conftest.py b/liminal/tests/conftest.py index 5441bfc..eb0b016 100644 --- a/liminal/tests/conftest.py +++ b/liminal/tests/conftest.py @@ -531,3 +531,97 @@ def __init__( self.list_dropdown_field = list_dropdown_field return [MockEntityOne, MockEntityTwo] + + +@pytest.fixture +def mock_cell_line_subclasses() -> list[type[BaseModel]]: + """A parent schema and a batch schema whose name uses the parent's lot number.""" + from liminal.orm.name_template_parts import ( + FieldPart, + ParentLotNumberPart, + SeparatorPart, + ) + + class CellLine(BaseModel): + __schema_properties__ = SchemaProperties( + name="Cell Line", + warehouse_name="cell_line", + prefix="CL", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[BenchlingNamingStrategy.NEW_IDS], + ) + species: SqlColumn = Column(name="Species", type=Type.TEXT, required=False) + + def __init__(self, species: str | None = None) -> None: + self.species = species + + class CellLineBatch(BaseModel): + __schema_properties__ = SchemaProperties( + name="Cell Line Batch", + warehouse_name="cl_batch", + prefix="CLB", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE], + ) + __name_template__ = NameTemplate( + parts=[ + FieldPart(wh_field_name="parent_cell_line"), + SeparatorPart(value="-"), + ParentLotNumberPart(wh_field_name="parent_cell_line"), + ] + ) + parent_cell_line: SqlColumn = Column( + name="Parent Cell Line", + type=Type.ENTITY_LINK, + required=False, + entity_link="cell_line", + parent_link=True, + ) + + def __init__(self, parent_cell_line: str | None = None) -> None: + self.parent_cell_line = parent_cell_line + + return [CellLine, CellLineBatch] + + +@pytest.fixture +def mock_template_naming_subclass() -> list[type[BaseModel]]: + """A schema in code that uses a name template and REPLACE_NAMES_WITH_TEMPLATE.""" + from liminal.orm.name_template_parts import TextPart + + class TemplateEntity(BaseModel): + __schema_properties__ = SchemaProperties( + name="Template Entity", + warehouse_name="template_entity", + prefix="TemplateEntity", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[ + BenchlingNamingStrategy.NEW_IDS, + BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE, + ], + ) + __name_template__ = NameTemplate(parts=[TextPart(value="template_text")]) + + def __init__(self) -> None: + pass + + return [TemplateEntity] + + +@pytest.fixture +def mock_plain_naming_subclass() -> list[type[BaseModel]]: + """A schema in code with no name template and no template based naming strategy.""" + + class PlainEntity(BaseModel): + __schema_properties__ = SchemaProperties( + name="Plain Entity", + warehouse_name="plain_entity", + prefix="PlainEntity", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[BenchlingNamingStrategy.NEW_IDS], + ) + + def __init__(self) -> None: + pass + + return [PlainEntity] diff --git a/liminal/tests/test_entity_schema_compare.py b/liminal/tests/test_entity_schema_compare.py index 7fc36e8..246d7b4 100644 --- a/liminal/tests/test_entity_schema_compare.py +++ b/liminal/tests/test_entity_schema_compare.py @@ -15,9 +15,11 @@ UpdateEntitySchemaField, UpdateEntitySchemaNameTemplate, ) -from liminal.enums import BenchlingFieldType +from liminal.enums import BenchlingEntityType, BenchlingFieldType +from liminal.enums.benchling_naming_strategy import BenchlingNamingStrategy from liminal.orm.name_template import NameTemplate -from liminal.orm.name_template_parts import TextPart +from liminal.orm.name_template_parts import ParentLotNumberPart, TextPart +from liminal.orm.schema_properties import SchemaProperties class TestCompareEntitySchemas: @@ -158,6 +160,8 @@ def test_compare_benchling_schema_fields( # type: ignore[no-untyped-def] missing_field[0][2].pop("string_field_req") mock_get_benchling_entity_schemas.return_value = missing_field invalid_models = compare_entity_schemas(mock_benchling_sdk) + # Only new schemas override the default operation order. + assert all(c.order_override is None for c in invalid_models["mock_entity"]) assert len(invalid_models["mock_entity"]) == 1 assert isinstance( invalid_models["mock_entity"][0].op, CreateEntitySchemaField @@ -400,3 +404,232 @@ def test_compare_benchling_schema_fields( # type: ignore[no-untyped-def] invalid_models["mock_entity"][0].op, UpdateEntitySchemaNameTemplate ) assert invalid_models["mock_entity"][0].op.update_name_template.parts == [] + + def test_compare_benchling_schemas_create_link_order( # type: ignore[no-untyped-def] + self, mock_cell_line_subclasses + ) -> None: + """A new schema's name template can use a parent's lot number, so it runs after the parent link is set.""" + with ( + patch( + "liminal.entity_schemas.compare.get_converted_entity_schemas" + ) as mock_get_benchling_entity_schemas, + patch( + "liminal.orm.base_model.BaseModel.get_all_subclasses" + ) as mock_get_all_subclasses, + ): + mock_get_all_subclasses.return_value = mock_cell_line_subclasses + mock_get_benchling_entity_schemas.return_value = [] + compared = compare_entity_schemas(Mock()) + batch_ops = [c.op for c in sorted(compared["cl_batch"])] + + assert [type(op) for op in batch_ops] == [ + CreateEntitySchema, + UpdateEntitySchema, + UpdateEntitySchemaField, + UpdateEntitySchemaNameTemplate, + UpdateEntitySchema, + ] + create, rename, link, template, naming = batch_ops + assert isinstance(create, CreateEntitySchema) + assert isinstance(rename, UpdateEntitySchema) + assert isinstance(link, UpdateEntitySchemaField) + assert isinstance(template, UpdateEntitySchemaNameTemplate) + assert isinstance(naming, UpdateEntitySchema) + + # The link is created without a target, which is set in the follow-up field update. + created_field = create.fields[0] + assert "entity_link" not in created_field.model_fields_set + assert "parent_link" not in created_field.model_fields_set + + assert rename.wh_schema_name == "cell_line_batch" + assert rename.update_props.model_dump(exclude_unset=True) == { + "warehouse_name": "cl_batch" + } + + assert link.wh_schema_name == "cl_batch" + assert link.update_props.entity_link == "cell_line" + assert link.update_props.parent_link is True + + assert template.wh_schema_name == "cl_batch" + # The failure in #271: a parent lot number part needs its field to already be a parent link with a target. + lot_number_fields = { + part.wh_field_name + for part in template.update_name_template.parts + if isinstance(part, ParentLotNumberPart) + } + assert lot_number_fields == {"parent_cell_line"} + template_index = batch_ops.index(template) + parent_links_set_before_template = { + op.wh_field_name + for op in batch_ops[:template_index] + if isinstance(op, UpdateEntitySchemaField) + and op.update_props.parent_link is True + and op.update_props.entity_link is not None + } + assert lot_number_fields <= parent_links_set_before_template + assert naming.wh_schema_name == "cl_batch" + assert naming.update_props.model_dump(exclude_unset=True) == { + "naming_strategies": { + BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE + } + } + + # Across schemas, every field update runs before any new schema's template. + all_ops = [ + c.op for c in sorted(compared["cl_batch"] + compared["cell_line"]) + ] + last_field_update = max( + i + for i, op in enumerate(all_ops) + if isinstance(op, UpdateEntitySchemaField) + ) + first_template = min( + i + for i, op in enumerate(all_ops) + if isinstance(op, UpdateEntitySchemaNameTemplate) + ) + assert last_field_update < first_template + + # The downgrade runs the reverse operations in the opposite order. + downgrade_ops = [ + c.reverse_op for c in reversed(sorted(compared["cl_batch"])) + ] + assert [type(op) for op in downgrade_ops] == [ + UpdateEntitySchema, + UpdateEntitySchemaNameTemplate, + UpdateEntitySchemaField, + UpdateEntitySchema, + ArchiveEntitySchema, + ] + assert isinstance(downgrade_ops[0], UpdateEntitySchema) + assert downgrade_ops[0].update_props.model_dump(exclude_unset=True) == { + "naming_strategies": {BenchlingNamingStrategy.NEW_IDS} + } + + def test_compare_benchling_schemas_add_template_naming_strategy( # type: ignore[no-untyped-def] + self, mock_template_naming_subclass + ) -> None: + """Adding REPLACE_NAMES_WITH_TEMPLATE sets the name template first, then the naming strategy.""" + with ( + patch( + "liminal.entity_schemas.compare.get_converted_entity_schemas" + ) as mock_get_benchling_entity_schemas, + patch( + "liminal.orm.base_model.BaseModel.get_all_subclasses" + ) as mock_get_all_subclasses, + ): + mock_get_all_subclasses.return_value = mock_template_naming_subclass + benchling_props = SchemaProperties( + name="Template Entity", + warehouse_name="template_entity", + prefix="TemplateEntity", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[BenchlingNamingStrategy.NEW_IDS], + ) + mock_get_benchling_entity_schemas.return_value = [ + (benchling_props, NameTemplate(), {}) + ] + compared = compare_entity_schemas(Mock()) + ops = sorted(compared["template_entity"]) + assert [type(c.op) for c in ops] == [ + UpdateEntitySchemaNameTemplate, + UpdateEntitySchema, + ] + template, naming = ops + assert isinstance(template.op, UpdateEntitySchemaNameTemplate) + assert isinstance(naming.op, UpdateEntitySchema) + assert isinstance(naming.reverse_op, UpdateEntitySchema) + assert naming.op.update_props.model_dump(exclude_unset=True) == { + "naming_strategies": { + BenchlingNamingStrategy.NEW_IDS, + BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE, + } + } + assert naming.reverse_op.update_props.model_dump(exclude_unset=True) == { + "naming_strategies": {BenchlingNamingStrategy.NEW_IDS} + } + + # Other schema property changes stay in the early UpdateEntitySchema, without the template strategy. + benchling_props.prefix = "OldPrefix" + compared = compare_entity_schemas(Mock()) + ops = sorted(compared["template_entity"]) + assert [type(c.op) for c in ops] == [ + UpdateEntitySchema, + UpdateEntitySchemaNameTemplate, + UpdateEntitySchema, + ] + early = ops[0].op + assert isinstance(early, UpdateEntitySchema) + assert early.update_props.model_dump(exclude_unset=True) == { + "prefix": "TemplateEntity" + } + assert ops[0].reverse_op.update_props.model_dump( # type: ignore[attr-defined] + exclude_unset=True + ) == {"prefix": "OldPrefix"} + + def test_compare_benchling_schemas_remove_template_naming_strategy( # type: ignore[no-untyped-def] + self, mock_plain_naming_subclass + ) -> None: + """Removing REPLACE_NAMES_WITH_TEMPLATE clears the naming strategy before the name template.""" + with ( + patch( + "liminal.entity_schemas.compare.get_converted_entity_schemas" + ) as mock_get_benchling_entity_schemas, + patch( + "liminal.orm.base_model.BaseModel.get_all_subclasses" + ) as mock_get_all_subclasses, + ): + mock_get_all_subclasses.return_value = mock_plain_naming_subclass + benchling_props = SchemaProperties( + name="Plain Entity", + warehouse_name="plain_entity", + prefix="PlainEntity", + entity_type=BenchlingEntityType.CUSTOM_ENTITY, + naming_strategies=[ + BenchlingNamingStrategy.NEW_IDS, + BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE, + ], + ) + benchling_template = NameTemplate(parts=[TextPart(value="template_text")]) + mock_get_benchling_entity_schemas.return_value = [ + (benchling_props, benchling_template, {}) + ] + compared = compare_entity_schemas(Mock()) + ops = sorted(compared["plain_entity"]) + assert [type(c.op) for c in ops] == [ + UpdateEntitySchema, + UpdateEntitySchemaNameTemplate, + ] + naming, template = ops + assert isinstance(naming.op, UpdateEntitySchema) + assert isinstance(naming.reverse_op, UpdateEntitySchema) + assert isinstance(template.op, UpdateEntitySchemaNameTemplate) + assert isinstance(template.reverse_op, UpdateEntitySchemaNameTemplate) + assert naming.op.update_props.model_dump(exclude_unset=True) == { + "naming_strategies": {BenchlingNamingStrategy.NEW_IDS} + } + assert template.op.update_name_template.parts == [] + + # The downgrade restores the name template first, then the naming strategy. + assert naming.reverse_op.update_props.model_dump(exclude_unset=True) == { + "naming_strategies": { + BenchlingNamingStrategy.NEW_IDS, + BenchlingNamingStrategy.REPLACE_NAMES_WITH_TEMPLATE, + } + } + assert template.reverse_op.update_name_template.parts == [ + TextPart(value="template_text") + ] + + def test_name_template_runs_between_field_update_and_field_archive(self) -> None: + orders = { + UpdateEntitySchemaField.order, + UpdateEntitySchemaNameTemplate.order, + ArchiveEntitySchemaField.order, + } + assert ( + UpdateEntitySchemaField.order + < UpdateEntitySchemaNameTemplate.order + < ArchiveEntitySchemaField.order + ) + assert len(orders) == 3