diff --git a/core/capabilities/tests/test_make_private.py b/core/capabilities/tests/test_make_private.py index 3b749fe6d..a9f8875fc 100644 --- a/core/capabilities/tests/test_make_private.py +++ b/core/capabilities/tests/test_make_private.py @@ -11,17 +11,19 @@ from core.capabilities.writes import makes_private from core.code_systems.serializers import CodeSystemDetailSerializer from core.collections.models import Collection +from core.collections.serializers import CollectionCreateOrUpdateSerializer from core.collections.tests.factories import OrganizationCollectionFactory from core.common.models import CelerySignalProcessor from core.common.constants import ACCESS_TYPE_NONE, ACCESS_TYPE_VIEW, ROLE_ADMIN_ID from core.common.tests import OCLAPITestCase, OCLAPITransactionTestCase from core.concepts.tests.factories import ConceptFactory from core.importers.importer import ImportRequest, ResourceImporter -from core.importers.models import BulkImportInline +from core.importers.models import BulkImportInline, UPDATED from core.mappings.tests.factories import MappingFactory from core.orgs.models import Organization from core.orgs.tests.factories import OrganizationFactory from core.sources.models import Source +from core.sources.serializers import SourceCreateOrUpdateSerializer from core.sources.tests.factories import OrganizationSourceFactory, UserSourceFactory from core.users.tests.factories import UserProfileFactory @@ -248,26 +250,24 @@ def test_a_fhir_update_never_makes_a_private_head_viewable(self): self.assertEqual(repo.versions.get(version=resource['version']).public_access, ACCESS_TYPE_NONE) self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT]) - def test_a_fhir_update_that_would_copy_a_private_release_onto_a_viewable_head_is_refused(self): + def test_a_fhir_update_keeps_a_viewable_head_s_access_whatever_the_release_s(self): """ - It copies the release's other values too, so HEAD takes the release's access and asks make_private. A blank - access is private (public_can_view), so a blank release's is copied as it is, not as View. + The update saves onto HEAD from HEAD, not from the release the URL resolves, so a private release's access isn't + copied onto a viewable HEAD, nothing is asked about making HEAD private, and the new version, made from HEAD, + is viewable as HEAD is. A blank access is private (public_can_view) too. """ for release_access in (ACCESS_TYPE_NONE, ''): for repo, factory, resource_type, extra in self.fhir_repositories(): + kind = f'{type(repo).__name__.lower()}s' with self.subTest(resource_type=resource_type, release_access=release_access): response, resource = self.fhir_update(repo, factory, resource_type, release_access, **extra) - # FHIR routes answer every refusal as an OperationOutcome, with the body's message as its issue - self.assertEqual(response.status_code, 403, response.content) - self.assertEqual(response.json()['resourceType'], 'OperationOutcome') - self.assertEqual( - [item['details']['text'] for item in response.json()['issue']], - [PrivateGatePolicy.body['detail']]) - self.assert_asked_to_make_private(self.take_calls(), row_id=repo.id) + self.assertEqual(response.status_code, 200, response.content) + self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT]) repo.refresh_from_db() self.assertEqual(repo.public_access, ACCESS_TYPE_VIEW) - self.assertFalse(repo.versions.filter(version=resource['version']).exists()) + self.assertTrue(repo.versions.get(version=resource['version']).public_can_view) + self.assertIn(repo.mnemonic, self.anonymous_list_ids(kind)) for release, version in (('r-None', 'v3'), ('r-', 'v4')): with self.subTest(imported_onto=release): @@ -277,30 +277,11 @@ def test_a_fhir_update_that_would_copy_a_private_release_onto_a_viewable_head_is 'version': version}, ImportRequest('orgs', self.org.mnemonic, self.user.username, 'CodeSystem')) - self.assertIsInstance(result, WriteRefused) - self.assertEqual(result.detail, PrivateGatePolicy.body) + self.assertEqual(result, UPDATED) + self.assertEqual([call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT]) self.source.refresh_from_db() self.assertEqual(self.source.public_access, ACCESS_TYPE_VIEW) - def test_a_blank_release_the_policy_allows_leaves_head_and_the_new_version_private(self): - """Stored as None, which the anonymous lists read as private too.""" - PrivateGatePolicy.refuse = False - for repo, factory, resource_type, extra in self.fhir_repositories(): - kind = f'{type(repo).__name__.lower()}s' - with self.subTest(resource_type=resource_type): - self.assertIn(repo.mnemonic, self.anonymous_list_ids(kind)) - - response, resource = self.fhir_update(repo, factory, resource_type, '', **extra) - - self.assertEqual(response.status_code, 200, response.content) - # HEAD's row: the serializer then saves the same object as the new version, so it's not checked by id - self.assertEqual( - [call[2] for call in self.take_calls()], [WRITE_ACTION_EDIT, WRITE_ACTION_MAKE_PRIVATE]) - repo.refresh_from_db() - self.assertEqual(repo.public_access, ACCESS_TYPE_NONE) - self.assertFalse(repo.versions.get(version=resource['version']).public_can_view) - self.assertNotIn(repo.mnemonic, self.anonymous_list_ids(kind)) - @staticmethod def made_private_first(model, method, access=ACCESS_TYPE_NONE): """ @@ -330,6 +311,22 @@ def test_a_fhir_update_keeps_a_head_made_private_after_the_update_read_it(self): self.assertEqual(repo.public_access, ACCESS_TYPE_NONE) self.assertFalse(repo.versions.get(version=resource['version']).public_can_view) + def test_a_fhir_update_keeps_a_head_published_after_the_update_read_it(self): + """The update keeps the access HEAD has when it's saved, so a publish since it read HEAD isn't undone""" + for repo, factory, resource_type, extra in self.fhir_repositories(): + model = type(repo) + model.objects.filter(id=repo.id).update(public_access=ACCESS_TYPE_NONE) + with self.subTest(resource_type=resource_type): + with patch.object( + model, 'persist_changes', self.made_private_first(model, 'persist_changes', ACCESS_TYPE_VIEW)): + response, resource = self.fhir_update(repo, factory, resource_type, ACCESS_TYPE_NONE, **extra) + + self.assertEqual(response.status_code, 200, response.content) + self.assertNotIn(WRITE_ACTION_MAKE_PRIVATE, [call[2] for call in self.take_calls()]) + repo.refresh_from_db() + self.assertEqual(repo.public_access, ACCESS_TYPE_VIEW) + self.assertTrue(repo.versions.get(version=resource['version']).public_can_view) + def test_a_value_set_update_s_references_keep_a_head_made_private_after_head_was_saved(self): """Adding the resource's references saves HEAD again, after the lock: only who changed it, not its access.""" source = OrganizationSourceFactory(organization=self.org, canonical_url='http://example.org/cs') @@ -369,6 +366,33 @@ def test_a_fhir_update_reads_head_for_update_in_the_transaction_that_saves_it(se self.assertTrue(savepoint.startswith('SAVEPOINT '), savepoint) self.assertGreater(sqls.index(f'RELEASE {savepoint}'), save) + @staticmethod + def counted(prepare_object, queries, calls): + """`prepare_object`, recording in `calls` how many queries `queries` had captured at each call""" + def prepare(serializer, data, instance=None): + calls.append(len(queries.captured_queries)) + return prepare_object(serializer, data, instance) + return prepare + + def test_a_fhir_update_applies_the_resource_to_head_as_read_for_update(self): + """So what it keeps of HEAD is HEAD as it is once locked, an edit committed before that included""" + for repo, factory, resource_type, extra in self.fhir_repositories(): + row = f'"{type(repo)._meta.db_table}"."id" = {repo.id}' # pylint: disable=protected-access + klass = SourceCreateOrUpdateSerializer + if isinstance(repo, Collection): + klass = CollectionCreateOrUpdateSerializer + prepared_at = [] + with self.subTest(resource_type=resource_type): + with CaptureQueriesContext(connection) as queries, patch.object( + klass, 'prepare_object', self.counted(klass.prepare_object, queries, prepared_at)): + response, _ = self.fhir_update(repo, factory, resource_type, ACCESS_TYPE_VIEW, **extra) + + self.assertEqual(response.status_code, 200, response.content) + locks = [index for index, query in enumerate(queries.captured_queries) if + query['sql'].startswith('SELECT') and f'WHERE {row}' in query['sql'] and + query['sql'].endswith('FOR NO KEY UPDATE')] + self.assertTrue(locks and prepared_at and locks[0] < prepared_at[-1], (locks, prepared_at)) + def test_a_rest_edit_that_sends_no_access_keeps_the_access_a_concurrent_write_gave_the_row(self): """ The edit saves the access its row has when it's saved, not the one the request read before: a row made private diff --git a/core/capabilities/tests/test_writes.py b/core/capabilities/tests/test_writes.py index 6fa1977ff..501a4b783 100644 --- a/core/capabilities/tests/test_writes.py +++ b/core/capabilities/tests/test_writes.py @@ -8,7 +8,7 @@ from django.test import override_settings from core.capabilities.constants import ( - WRITE_ACTION_DELETE, WRITE_ACTION_EDIT, WRITE_ACTION_MAKE_PRIVATE, WRITE_ACTION_PUBLISH, + WRITE_ACTION_DELETE, WRITE_ACTION_EDIT, WRITE_ACTION_PUBLISH, ) from core.capabilities.exceptions import WriteRefused from core.capabilities.policy import GroupLimitPolicy @@ -282,10 +282,8 @@ def test_a_fhir_update_is_asked_about_the_head_it_saves_onto(self): response = self.request('put', f'{self.org.uri}CodeSystem/{self.source.mnemonic}/', resource) self.assertEqual(response.status_code, 200, response.content) - # the update copies the private release's access onto HEAD, so it's asked about making HEAD private too - # (test_make_private), and that saved row is the new version by now - self.assertEqual(ReadOnlyPolicy.calls[0], (self.user, self.source, WRITE_ACTION_EDIT)) - self.assertEqual([call[2] for call in ReadOnlyPolicy.calls[1:]], [WRITE_ACTION_MAKE_PRIVATE]) + # HEAD keeps its own access, not the private release's, so it's only an edit (test_make_private) + self.assertEqual(ReadOnlyPolicy.calls, [(self.user, self.source, WRITE_ACTION_EDIT)]) ReadOnlyPolicy.calls = [] ResourceImporter.save_fhir_resource( CodeSystemDetailSerializer, release, self.org, {**resource, 'version': 'v3'}, diff --git a/core/code_systems/serializers.py b/core/code_systems/serializers.py index 8ca4f3a25..b8ff0eb7f 100644 --- a/core/code_systems/serializers.py +++ b/core/code_systems/serializers.py @@ -282,11 +282,12 @@ def get_resource_type(_): def to_internal_value(self, data): """ Its concepts are written as the code system says (CodeSystemConceptField): whether it's a supplement, and its - language. An update that doesn't say keeps the stored ones. + language. An update that doesn't say keeps HEAD's, which it saves onto (update_head). """ + head = get(self.instance, 'head') self.context.update( - supplement=get(data, 'content', get(self.instance, 'content_type')) == CONTENT_TYPE_SUPPLEMENT, - language=get(data, 'language') or get(self.instance, 'default_locale') or settings.DEFAULT_LOCALE) + supplement=get(data, 'content', get(head, 'content_type')) == CONTENT_TYPE_SUPPLEMENT, + language=get(data, 'language') or get(head, 'default_locale') or settings.DEFAULT_LOCALE) return super().to_internal_value(data) def get_total_count(self, obj): @@ -410,27 +411,7 @@ def update(self, instance, validated_data): f' {instance.mnemonic}.'}) return instance - source = SourceCreateOrUpdateSerializer().prepare_object(validated_data, instance) - - # Preserve version specific values - source_version = source.version - source_released = source.released - - user = self.context['request'].user - - # Update HEAD first - # Determine existing source ID - source_head = source.head - source.id = source_head.id - source.version = HEAD - source.released = False # HEAD must never be released - source.custom_validation_schema = source_head.custom_validation_schema - source.version_algorithm = source_head.version_algorithm # an R4 CodeSystem has no versionAlgorithm to write - - # a FHIR resource carries no access: the update never makes a private HEAD viewable, but a private release's - # access goes onto a viewable HEAD with its other values, which asks make_private (ocl_online#698) - errors = Source.persist_changes(source, user, None, keep_private=True) - + source, errors = self.update_head(instance, validated_data, SourceCreateOrUpdateSerializer().prepare_object) if errors: self._errors.update(errors) return source @@ -447,11 +428,8 @@ def update(self, instance, validated_data): else: Concept.persist_new(concept_serializer.validated_data) - # Create new version - source.version = source_version - source.released = source_released - source.id = None # Make it synchronous for now so that the list of concepts is included in the response - errors = Source.persist_new_version(source, user, sync=True) + errors = Source.persist_new_version( + self.as_new_version(source, instance, validated_data), self.context['request'].user, sync=True) self._errors.update(errors) return source diff --git a/core/code_systems/tests.py b/core/code_systems/tests.py index 0885390ec..4346e61b8 100644 --- a/core/code_systems/tests.py +++ b/core/code_systems/tests.py @@ -976,15 +976,15 @@ def test_a_supplement_stored_without_supplements_stays_editable(self): self.assertEqual(response.status_code, 200, response.data) self.assertEqual(self.head().full_name, 'ICD-10 fr, edited') - def test_a_put_from_a_release_without_supplements_cant_clear_heads(self): - """A FHIR PUT starts from the latest release: one stored without supplements can't clear the one HEAD has.""" + def test_a_put_keeps_head_s_supplements_whatever_the_release_s(self): + """A FHIR PUT starts from HEAD: a release stored without supplements doesn't clear the one HEAD has.""" self.assertEqual(self.write().status_code, 201) Source.objects.filter(mnemonic='icd10-fr').exclude(version='HEAD').update(supplements=None) response = self.write('put', version='2', supplements=None) - self.assertEqual(response.status_code, 400) - self.assertIn('supplements', str(response.data)) + self.assertEqual(response.status_code, 200, response.data) self.assertEqual(self.head().supplements, SUPPLEMENTED) + self.assertEqual(Source.objects.get(mnemonic='icd10-fr', version='2').supplements, SUPPLEMENTED) def test_a_supplement_without_a_language_keeps_its_display_in_the_default_locale(self): """ diff --git a/core/collections/imports.py b/core/collections/imports.py index 7dcac7a5d..a031ab029 100644 --- a/core/collections/imports.py +++ b/core/collections/imports.py @@ -99,8 +99,10 @@ def get_system_version_namespace(owner_url): return Expansion.get_system_version_namespace(owner_url) def apply_parameters(self, queryset, is_concept_queryset): + """As Expansion.apply_parameters: its parameters and the imported version's own rule on retired concepts""" from core.collections.models import ExpansionParameters - return ExpansionParameters(self.parameters, is_concept_queryset).apply(queryset) + return ExpansionParameters.of_version(self.parameters, is_concept_queryset, self.collection_version).apply( + queryset) @property def concepts(self): diff --git a/core/collections/member_versions.py b/core/collections/member_versions.py index a0a367ae3..319c54395 100644 --- a/core/collections/member_versions.py +++ b/core/collections/member_versions.py @@ -636,7 +636,11 @@ def can_be(self, reference, version): def held_at(self, version, candidates): """The candidates (concepts in `version`) it holds there, and those it holds by code (held_by_code). One that - leads back to a value set being evaluated again holds there only its own members in that version""" + leads back to a value set being evaluated again holds there only its own members in that version. Its own rule + on retired concepts (Collection.include_retired) leaves retired candidates out, as its build does""" + from core.collections.models import ExpansionParameters + if ExpansionParameters.leaves_retired_out(self.collection_version): + candidates = ExpansionParameters({}, True, retired_left_out=True).apply(candidates) replaying = self.member_versions.replaying if self.collection_version.id in replaying: held = concepts_q([self.members_at(version)]) diff --git a/core/collections/migrations/0081_value_set_compose_details.py b/core/collections/migrations/0081_value_set_compose_details.py new file mode 100644 index 000000000..3962472a1 --- /dev/null +++ b/core/collections/migrations/0081_value_set_compose_details.py @@ -0,0 +1,35 @@ +""" +Adds what a ValueSet written through FHIR says beyond its references: collections.include_retired, the value set's own +rule on retired (inactive) concepts, and collection_references.concept_details, a listed code's designations and +extensions. Both columns are nullable with no default, which PostgreSQL adds by updating the catalog only: no existing +row is read or rewritten. + +Its lock waits are bounded (LOCK_TIMEOUT), as phase C's storage migrations' are: behind a long transaction on a table it +alters (collection_references, collections), it fails in seconds and changes nothing, instead of holding its locks, +and every query queued behind them, until that transaction ends. Run it again once that transaction is over. +""" +from django.db import migrations, models + +LOCK_TIMEOUT = "SET LOCAL lock_timeout = '5s'" # within the migration's own transaction + + +class Migration(migrations.Migration): + + dependencies = [ + ('collections', '0080_expansion_reserved_codes'), + ] + + operations = [ + migrations.RunSQL(LOCK_TIMEOUT, reverse_sql=migrations.RunSQL.noop), # first, applied + migrations.AddField( + model_name='collection', + name='include_retired', + field=models.BooleanField(blank=True, default=None, null=True), + ), + migrations.AddField( + model_name='collectionreference', + name='concept_details', + field=models.JSONField(blank=True, null=True), + ), + migrations.RunSQL(migrations.RunSQL.noop, reverse_sql=LOCK_TIMEOUT), # first, reversed + ] diff --git a/core/collections/models.py b/core/collections/models.py index 1efe02fe7..71d67d949 100644 --- a/core/collections/models.py +++ b/core/collections/models.py @@ -131,6 +131,9 @@ class Meta: custom_resources_linked_source = models.TextField(blank=True) immutable = models.BooleanField(null=True, blank=True, default=None) locked_date = models.DateTimeField(null=True, blank=True) + # whether its members include retired concepts (FHIR's compose.inactive): False leaves them out wherever it's + # evaluated, whatever an expansion's activeOnly says (ExpansionParameters); None or True keeps OCL's default + include_retired = models.BooleanField(null=True, blank=True, default=None) # the code system supplements it declares (url or url|version), applied wherever it's evaluated under FHIR's rules # (ExpansionEvaluation.supplements_for): FHIR's valueset-supplement extension. Not in the API's serializers yet declared_supplements = ArrayField(models.TextField(), default=list, null=True, blank=True) @@ -184,6 +187,7 @@ def update_version_data(self, head): self.custom_resources_linked_source = head.custom_resources_linked_source self.immutable = head.immutable self.locked_date = head.locked_date + self.include_retired = head.include_retired self.declared_supplements = list(head.declared_supplements or []) @property @@ -222,7 +226,9 @@ def post_create_actions(self): if self.should_auto_expand: self.cascade_children_to_expansion(index=False) - def validate(self, reference): + def validate(self, reference, by_clause=False): + """by_clause: a reference already there with its expression is the same one only if it's the same clause too + (CollectionReference.clause_key), as add_references(by_clause=True) keeps them apart""" if self.should_auto_expand: reference.full_clean() else: @@ -231,6 +237,9 @@ def validate(self, reference): if reference.expression: same_refs = self.references.filter(expression=reference.expression, include=reference.include) + if by_clause: + same_refs = same_refs.filter(valueset=reference.valueset) if reference.valueset else same_refs.filter( + models.Q(valueset__isnull=True) | models.Q(valueset=[])) if same_refs.exists(): errors = { reference.expression: { @@ -363,7 +372,9 @@ def get_import_loop_errors(self, reference): return None return [REFERENCE_NOT_SAVED_VALUESET_LOOP_FMT.format(self.name, ', '.join(looping))] - def add_references(self, references, user=None, _async=False): + def add_references(self, references, user=None, _async=False, by_clause=False): # pylint: disable=too-many-locals + """by_clause: references that differ only in including or excluding, or in the value sets they intersect with, + are kept apart, not deduplicated by their expression, which doesn't say either (a FHIR compose's clauses)""" errors = {} unapplied_errors = {} added_references = [] @@ -381,13 +392,13 @@ def add_references(self, references, user=None, _async=False): # a cascade-and-transform reference whose value set can't be applied generates nothing: say why unapplied_errors[reference.expression] = [self.get_unapplied_valueset_message(reference)] total_references += generated - total_references = CollectionReference.dedupe_by_expression(total_references) + total_references = CollectionReference.dedupe_by_expression(total_references, by_clause) for reference in total_references: reference.collection = self reference.created_by = user reference._async = _async # pylint: disable=protected-access try: - reference_errors = self.validate(reference) or self.get_import_loop_errors(reference) + reference_errors = self.validate(reference, by_clause) or self.get_import_loop_errors(reference) if reference_errors: errors[reference.expression] = reference_errors continue @@ -905,6 +916,8 @@ class Meta: # FHIR specs filter = models.JSONField(null=True, blank=True) display = models.TextField(null=True, blank=True) + # what a value set lists with its code besides the display: FHIR's designation and extension of include.concept + concept_details = models.JSONField(null=True, blank=True) namespace = models.TextField(null=True, blank=True) code = models.CharField(null=True, blank=True, max_length=255) system = models.TextField(null=True, blank=True) @@ -962,6 +975,7 @@ def clone(self, **kwargs): created_by=self.created_by, filter=self.filter, display=self.display, + concept_details=self.concept_details, namespace=self.namespace, code=self.code, system=self.system, @@ -1162,8 +1176,16 @@ def _update_by_transform_to_latest_version(self, queryset, klass): return queryset @staticmethod - def dedupe_by_expression(references): - return list({reference.expression: reference for reference in references}.values()) + def dedupe_by_expression(references, by_clause=False): + """One of each expression; by_clause, one of each clause_key""" + key = CollectionReference.clause_key if by_clause else (lambda reference: reference.expression) + return list({key(reference): reference for reference in references}.values()) + + @staticmethod + def clause_key(reference): + """What tells a FHIR compose's clauses apart besides their expression: including or excluding, and the value + sets they intersect with""" + return reference.expression, reference.include, tuple(reference.valueset or ()) def __get_repo_and_resource_version(self, resource, is_intensional, is_extensional, locked_version=None): if locked_version: @@ -2703,8 +2725,9 @@ def get_actions(batch_ids): ) def apply_parameters(self, queryset, is_concept_queryset): - parameters = ExpansionParameters(self.parameters, is_concept_queryset) - return parameters.apply(queryset) + """Its parameters, and its collection version's own rule on retired concepts (Collection.include_retired)""" + return ExpansionParameters.of_version(self.parameters, is_concept_queryset, self.collection_version).apply( + queryset) def index_concepts(self, concept_ids=None): should_run = len(concept_ids) > 0 if concept_ids is not None else self.concepts.exists() @@ -4400,12 +4423,28 @@ class ExpansionParameters: # keys only FHIR's rules apply (core.collections.version_rules), so accepted only under them FHIR_RULES_ONLY = (DEFAULT_VALUESET_VERSION, VERSIONS_MATCH) - def __init__(self, parameters, is_concept_queryset=True): + def __init__(self, parameters, is_concept_queryset=True, retired_left_out=False): + """ + retired_left_out: the collection version's own rule (Collection.include_retired False) leaves retired concepts + out as activeOnly does, while the parameters keep the activeOnly they were given + """ self.parameters = parameters or {} self.parameter_classes = {} self.before_filters = {} self.is_concept_queryset = is_concept_queryset self.to_parameter_classes() + if retired_left_out: + self.parameter_classes[self.ACTIVE] = ExpansionActiveParameter(value=True) + + @classmethod + def of_version(cls, parameters, is_concept_queryset, collection_version): + """An expansion's parameters, with its collection version's own rule on retired concepts""" + return cls(parameters, is_concept_queryset, cls.leaves_retired_out(collection_version)) + + @staticmethod + def leaves_retired_out(collection_version): + """Whether a collection version's own rule leaves retired concepts out of what it's evaluated to""" + return get(collection_version, 'include_retired') is False @property def reads_members(self): diff --git a/core/collections/tests/tests_include_retired.py b/core/collections/tests/tests_include_retired.py new file mode 100644 index 000000000..8f6581adf --- /dev/null +++ b/core/collections/tests/tests_include_retired.py @@ -0,0 +1,109 @@ +""" +A collection's own rule on retired concepts (Collection.include_retired, FHIR's compose.inactive): False leaves them out +wherever the collection is evaluated, under either rule set, as an import too, and apart from an expansion's +activeOnly, which keeps the value it was given. The code system is the IG's version case (core.collections.tests +.tests_version_rules): code3, only in 1.2.0, is retired. +""" +import importlib + +from django.db.migrations import RunSQL +from django.test import SimpleTestCase + +from core.collections.models import Collection, CollectionReference +from core.collections.tests.factories import OrganizationCollectionFactory +from core.collections.tests.tests_imports import ImportsTestMixin, VALUE_SET, off, on +from core.collections.tests.tests_member_versions import MemberVersionsTestMixin, ON, VALUE_SET as MEMBER_VALUE_SET +from core.collections.tests.tests_version_rules import CODE_SYSTEM +from core.common.tests import OCLTestCase +from core.concepts.models import Concept + + +class IncludeRetiredTest(ImportsTestMixin, OCLTestCase): + def setUp(self): + super().setUp() + Concept.objects.filter(mnemonic='code3').update(retired=True) + + def leave_retired_out(self, collection, value=False): + collection.include_retired = value + collection.save() + + def test_its_own_expansion_leaves_retired_concepts_out_under_either_rules(self): + self.reference(system=CODE_SYSTEM) + self.assertEqual(self.expand(on()), {'code1', 'code2', 'code3'}) + + self.leave_retired_out(self.collection) + for evaluation in (on(), off()): + self.assertEqual(self.expand(evaluation), {'code1', 'code2'}) + + def test_true_and_none_keep_ocl_s_default(self): + self.reference(system=CODE_SYSTEM) + for value in (True, None): + self.leave_retired_out(self.collection, value) + self.assertEqual(self.expand(on(), activeOnly=False), {'code1', 'code2', 'code3'}) + self.assertEqual(self.expand(on(), activeOnly=True), {'code1', 'code2'}) + + def test_activeOnly_keeps_the_value_it_was_given(self): + self.reference(system=CODE_SYSTEM) + self.leave_retired_out(self.collection) + + self.assertEqual(self.expand(on(), activeOnly=False), {'code1', 'code2'}) + self.assertIs(self.expansion.parameters['activeOnly'], False) + + def test_an_import_evaluated_again_keeps_its_own_rule(self): + """The import's rule, not the importer's: a version parameter has the import evaluated again""" + imported = self.imported(include_retired=False) + self.import_reference() + + self.assertEqual(self.build(on(), **{'system-version': f'{CODE_SYSTEM}|1.2.0'}), {'code1', 'code2'}) + self.leave_retired_out(imported, None) + self.assertEqual( + self.build(on(), **{'system-version': f'{CODE_SYSTEM}|1.2.0'}), {'code1', 'code2', 'code3'}) + + def test_an_importer_s_rule_reaches_what_it_imports(self): + """Its rule is applied to all it includes, what an import gives it included""" + self.value_set(VALUE_SET, [{'system': CODE_SYSTEM}], ['code1', 'code2', 'code3']) + self.import_reference() + self.leave_retired_out(self.collection) + + for evaluation in (on(), off()): + self.assertEqual(self.build(evaluation), {'code1', 'code2'}) + + def test_a_new_version_takes_head_s_rule_and_its_references_details(self): + """A version made as the API makes one, which doesn't say: it takes HEAD's (Collection.update_version_data)""" + details = {'designation': [{'language': 'fr', 'value': 'Code un'}]} + CollectionReference( + collection=self.collection, expression=CODE_SYSTEM, system=CODE_SYSTEM, code='code1', + concept_details=details).save() + self.leave_retired_out(self.collection) + + version = OrganizationCollectionFactory.build( + mnemonic=self.collection.mnemonic, organization=self.collection.organization, version='v1') + self.assertIsNone(version.include_retired) + Collection.persist_new_version(version, self.collection.created_by, sync=True) + + version = Collection.objects.get(mnemonic=self.collection.mnemonic, version='v1') + self.assertIs(version.include_retired, False) + self.assertEqual(version.references.get().concept_details, details) + + +class ImportedRuleAtAnotherVersionTest(MemberVersionsTestMixin, OCLTestCase): + def test_an_import_s_rule_reaches_a_code_it_holds_at_another_version(self): + """Its code2, listed from 1.0.0 where it's active, holds the outer 2.0.0 code2 (tests_member_versions); retired + there, the import's own rule leaves it out, as the import's evaluation at 2.0.0 would""" + Concept.objects.filter(id=self.code2_v2.id).update(retired=True) + imported = self.value_set({'version': '1.0.0', 'code': 'code2'}) + self.reference(version='2.0.0', valueset=[MEMBER_VALUE_SET]) + self.assertEqual(self.members(ON), {('code2', '2.0.0')}) + + Collection.objects.filter(id=imported.id).update(include_retired=False) + self.assertEqual(self.members(ON), set()) + + +class ComposeDetailsMigrationTest(SimpleTestCase): + def test_it_bounds_its_lock_waits_first_both_ways(self): + """Reversed, a migration's operations run last first: the reverse's own timeout is its last operation""" + lock = "SET LOCAL lock_timeout = '5s'" + operations = importlib.import_module( + 'core.collections.migrations.0081_value_set_compose_details').Migration.operations + self.assertEqual((operations[0].sql, operations[0].reverse_sql), (lock, RunSQL.noop)) + self.assertEqual((operations[-1].sql, operations[-1].reverse_sql), (RunSQL.noop, lock)) diff --git a/core/common/models.py b/core/common/models.py index 416c512f2..884346df3 100644 --- a/core/common/models.py +++ b/core/common/models.py @@ -1515,6 +1515,7 @@ def persist_changes(cls, obj, updated_by, original_schema, **kwargs): # pylint: meanwhile, such as publishing its HEAD, isn't published unasked. A source's save, and the cascade of its access and activity to its concepts and mappings, run in one transaction. Outside a caller's transaction, a failed enqueue of the row's search index is raised once the save commits, unless keep_private=True, which only logs it. + revalidates_schema=False: the write can't change the validation schema, so no revalidation is queued. """ keep_private = kwargs.pop('keep_private', False) keep_access = kwargs.pop('keep_access', False) @@ -1533,7 +1534,7 @@ def persist_changes(cls, obj, updated_by, original_schema, **kwargs): # pylint: if not parent_resource: errors['parent'] = SOURCE_PARENT_CANNOT_BE_NONE - queue_schema_update_task = obj.is_validation_necessary() + queue_schema_update_task = kwargs.pop('revalidates_schema', True) and obj.is_validation_necessary() try: with transaction.atomic() if lock or cascade_atomically else nullcontext(): stored_rows = cls.objects.filter(id=obj.id) diff --git a/core/concept_maps/serializers.py b/core/concept_maps/serializers.py index 9c01da91e..81db14e61 100644 --- a/core/concept_maps/serializers.py +++ b/core/concept_maps/serializers.py @@ -159,25 +159,9 @@ def update(self, instance, validated_data): f' {instance.mnemonic}.'}) return instance - source = SourceCreateOrUpdateSerializer().prepare_object(validated_data, instance) - - # Preserve version specific values - source_version = source.version - source_released = source.released - + source, errors = self.update_head(instance, validated_data, SourceCreateOrUpdateSerializer().prepare_object) user = self.context['request'].user - # Update HEAD first - # Determine existing source ID - source_head = source.head - source.id = source_head.id - source.version = HEAD - source.released = False # HEAD must never be released - source.custom_validation_schema = source_head.custom_validation_schema - - # a private HEAD stays private, as in CodeSystemDetailSerializer.update - errors = Source.persist_changes(source, user, None, keep_private=True) - if errors: self._errors.update(errors) return source @@ -205,12 +189,7 @@ def update(self, instance, validated_data): new_mapping_serializer.is_valid(raise_exception=True) Mapping.persist_new(new_mapping_serializer.validated_data, user) - source.id = None - source.version = source_version - source.released = source_released - source.is_latest_version = True - - errors = Source.persist_new_version(source, user) + errors = Source.persist_new_version(self.as_new_version(source, instance, validated_data), user) self._errors.update(errors) return source diff --git a/core/fhir/serializers.py b/core/fhir/serializers.py index adb746bc0..7aff3b675 100644 --- a/core/fhir/serializers.py +++ b/core/fhir/serializers.py @@ -1,6 +1,9 @@ """Shared fields and resource representations for FHIR repository serializers.""" +from django.db import transaction from rest_framework.fields import CharField +from core.common.constants import HEAD + SUBSETTED = {'system': 'http://terminology.hl7.org/CodeSystem/v3-ObservationValue', 'code': 'SUBSETTED'} @@ -68,3 +71,44 @@ def refuses_another_id(self, instance, validated_data): return False self._errors.update({'id': [f'The id must be {instance.mnemonic}, the id of the resource being updated.']}) return True + + def update_head(self, instance, validated_data, prepare_object): + """ + Saves an update onto the HEAD of the repository whose version `instance` the URL resolved, and returns HEAD and + the save's errors. HEAD is the stored HEAD with what the resource says: a field the resource leaves out keeps + HEAD's value, not `instance`'s, so an edit made to HEAD since that version stays. HEAD is read for update in the + transaction that saves it, so an edit committed meanwhile is the one kept. That includes HEAD's access, which a + FHIR resource doesn't carry: a concurrent write that makes HEAD private, or publishes it, isn't undone + (persist_changes keep_private and keep_access). Its validation schema is HEAD's, which a FHIR resource can't + change, so its concepts aren't revalidated. The resource's id never renames HEAD. + """ + klass, head_id = type(instance), instance.head.id + with transaction.atomic(): + head = klass.objects.select_for_update(no_key=True).get(id=head_id) + mnemonic, schema = head.mnemonic, head.custom_validation_schema + repo = prepare_object(validated_data, head) + repo.mnemonic = mnemonic + repo.version = HEAD + repo.released = False # HEAD is never released + return repo, klass.persist_changes( + repo, self.context['request'].user, schema, keep_private=True, keep_access=True, + revalidates_schema=False) + + @staticmethod + def as_new_version(head, instance, validated_data): + """ + HEAD as it's stored once the update has written it, made into the update's new version (unsaved), so the + version says what HEAD says, a concurrent edit since included. Its version label and status (released, retired) + are the resource's, else those of the version the URL resolved (`instance`). It's the latest version, and like + any new version it starts with no background tasks, member counts or record of removed members. + """ + head.refresh_from_db() + head.id = None + head.version = validated_data.get('version', instance.version) + head.released = validated_data.get('released', instance.released) + head.retired = validated_data.get('retired', instance.retired) + head.is_latest_version = True + head._background_process_ids = [] # pylint: disable=protected-access + head.active_concepts = head.active_mappings = None + head.last_child_removal_at = None + return head diff --git a/core/fhir/tests_updates.py b/core/fhir/tests_updates.py new file mode 100644 index 000000000..05025bf1d --- /dev/null +++ b/core/fhir/tests_updates.py @@ -0,0 +1,204 @@ +""" +A FHIR update (PUT) of a CodeSystem, ValueSet or ConceptMap saves onto HEAD and adds a version. HEAD is the stored HEAD +with what the resource says, whichever version the URL resolves, and the new version is made from that HEAD +(FhirRepositorySerializerMixin.update_head and as_new_version). +""" +from unittest.mock import Mock, patch + +from core.collections.tests.factories import OrganizationCollectionFactory +from core.common.constants import HEAD, OPENMRS_VALIDATION_SCHEMA +from core.common.tests import OCLAPITestCase +from core.fhir.serializers import FhirRepositorySerializerMixin +from core.orgs.tests.factories import OrganizationFactory +from core.sources.tests.factories import OrganizationSourceFactory +from core.users.tests.factories import UserProfileFactory + +# what a version takes from its HEAD; website and extras aren't FHIR elements, so a FHIR resource never carries them +METADATA = ('name', 'full_name', 'description', 'website', 'publisher', 'purpose', 'canonical_url', 'extras') +RELEASED = { + 'description': 'As released', 'website': 'https://released.example', 'publisher': 'Released', + 'purpose': 'As released', 'extras': {'state': 'released'} +} +EDITED = { + 'description': 'Edited through the API', 'website': 'https://edited.example', 'publisher': 'Edited', + 'purpose': 'Edited through the API', 'extras': {'state': 'edited'} +} + + +class FhirUpdateOntoHeadTest(OCLAPITestCase): + def setUp(self): + super().setUp() + self.user = UserProfileFactory() + self.org = OrganizationFactory() + self.org.members.add(self.user) + for task in ('index_source_concepts', 'index_source_mappings'): + patcher = patch(f'core.sources.models.{task}', Mock(__name__=task)) + patcher.start() + self.addCleanup(patcher.stop) + + @staticmethod + def resource_types(): + """Each resource type, its repositories' factory and kind in the API, and what its resource must say""" + return ( + ('CodeSystem', OrganizationSourceFactory, 'sources', {'content': 'fragment'}), + ('ValueSet', OrganizationCollectionFactory, 'collections', {}), + ('ConceptMap', OrganizationSourceFactory, 'sources', {}), + ) + + def request(self, method, url, data): + return getattr(self.client, method)( + url, data, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + + def released_then_edited(self, factory, kind): + """ + A repository released as version 1, then its HEAD edited through the API (description, website, publisher, + purpose, extras). Its HEAD, as stored. + """ + head = factory(organization=self.org, canonical_url='http://example.org/fhir/edited', **RELEASED) + factory( + organization=self.org, mnemonic=head.mnemonic, canonical_url=head.canonical_url, name=head.name, + full_name=head.full_name, version='1', released=True, **RELEASED) + response = self.request('put', f'{self.org.uri}{kind}/{head.mnemonic}/', EDITED) + self.assertEqual(response.status_code, 200, response.content) + head.refresh_from_db() + self.assertEqual({field: getattr(head, field) for field in EDITED}, EDITED) + return head + + def fhir_update(self, head, resource_type, extra, **resource): + """PUTs a version 2 that says its name, a title and a publisher, and nothing else HEAD has""" + body = { + 'resourceType': resource_type, 'id': head.mnemonic, 'version': '2', 'status': 'active', + 'name': head.name, 'title': 'Retitled', 'publisher': 'Written through FHIR', **extra, **resource + } + return self.request('put', f'{self.org.uri}{resource_type}/{head.mnemonic}/', body) + + def test_an_api_edit_to_head_survives_an_update_that_does_not_mention_it(self): + for resource_type, factory, kind, extra in self.resource_types(): + with self.subTest(resource_type): + head = self.released_then_edited(factory, kind) + + response = self.fhir_update(head, resource_type, extra) + + self.assertEqual(response.status_code, 200, response.content) + head.refresh_from_db() + self.assertEqual( + [head.description, head.website, head.purpose, head.extras], + [EDITED['description'], EDITED['website'], EDITED['purpose'], EDITED['extras']]) + release = head.versions.get(version='1') + self.assertEqual([release.description, release.publisher], ['As released', 'Released']) + + def test_what_the_update_says_wins(self): + for resource_type, factory, kind, extra in self.resource_types(): + with self.subTest(resource_type): + head = self.released_then_edited(factory, kind) + + response = self.fhir_update(head, resource_type, extra, description='Described through FHIR') + + self.assertEqual(response.status_code, 200, response.content) + head.refresh_from_db() + self.assertEqual( + [head.full_name, head.publisher, head.description, head.version, head.released], + ['Retitled', 'Written through FHIR', 'Described through FHIR', HEAD, False]) + + def test_the_new_version_is_made_from_head(self): + for resource_type, factory, kind, extra in self.resource_types(): + with self.subTest(resource_type): + head = self.released_then_edited(factory, kind) + + response = self.fhir_update(head, resource_type, extra) + + self.assertEqual(response.status_code, 200, response.content) + head.refresh_from_db() + version = head.versions.get(version='2') + self.assertEqual( + {field: getattr(version, field) for field in METADATA}, + {field: getattr(head, field) for field in METADATA}) + self.assertEqual([version.released, version.public_access], [True, head.public_access]) + self.assertEqual([version.website, version.extras], [EDITED['website'], EDITED['extras']]) + + def test_the_new_version_is_the_latest_and_takes_none_of_head_s_tasks(self): + """ + HEAD's row state isn't the version's: HEAD is never the latest version (each new version clears the flag on all + its siblings, HEAD included), and HEAD's tasks and member counts are its own. + """ + for resource_type, factory, kind, extra in self.resource_types(): + with self.subTest(resource_type): + head = self.released_then_edited(factory, kind) + type(head).objects.filter(id=head.id).update( + is_latest_version=False, _background_process_ids=['a-task-on-head'], active_concepts=20, + active_mappings=7) + if kind == 'collections': # a version that isn't expanded isn't counted when it's made + type(head).objects.filter(id=head.id).update(autoexpand=False) + + response = self.fhir_update(head, resource_type, extra) + + self.assertEqual(response.status_code, 200, response.content) + version = head.versions.get(version='2') + self.assertTrue(version.is_latest_version) + self.assertNotIn('a-task-on-head', version._background_process_ids or []) # pylint: disable=protected-access + self.assertFalse(head.versions.get(version='1').is_latest_version) + self.assertNotEqual(version.active_concepts, 20) + self.assertNotEqual(version.active_mappings, 7) + + def test_a_supplement_s_concepts_are_written_in_head_s_language_when_it_says_none(self): + """A supplement's display is its name in the code system's language (CodeSystemSupplementConceptSerializer)""" + supplement = {'content_type': 'supplement', 'supplements': 'http://hl7.org/fhir/sid/icd-10'} + head = self.released_then_edited( + lambda **fields: OrganizationSourceFactory(**fields, **supplement, default_locale='en'), 'sources') + type(head).objects.filter(id=head.id).update(default_locale='fr', supported_locales=['fr']) + + response = self.fhir_update( + head, 'CodeSystem', {'content': 'supplement', 'supplements': supplement['supplements']}, + concept=[{'code': 'A00', 'display': 'Choléra'}]) + + self.assertEqual(response.status_code, 200, response.content) + concept = head.get_concepts_queryset().get(mnemonic='A00') + self.assertEqual([(name.locale, name.name) for name in concept.names.all()], [('fr', 'Choléra')]) + + def test_head_s_validation_schema_is_kept_when_the_release_has_another(self): + """HEAD's schema, set since the release, with concepts: the update saves it as an API edit sending none does""" + update_validation_schema = Mock(__name__='update_validation_schema') + patcher = patch('core.common.models.update_validation_schema', update_validation_schema) + patcher.start() + self.addCleanup(patcher.stop) + for resource_type, _, kind, extra in self.resource_types(): + if kind != 'sources': + continue + with self.subTest(resource_type): + update_validation_schema.reset_mock() + head = self.released_then_edited(OrganizationSourceFactory, kind) + type(head).objects.filter(id=head.id).update( + custom_validation_schema=OPENMRS_VALIDATION_SCHEMA, active_concepts=1) + + response = self.fhir_update(head, resource_type, extra) + + self.assertEqual(response.status_code, 200, response.content) + head.refresh_from_db() + self.assertEqual(head.custom_validation_schema, OPENMRS_VALIDATION_SCHEMA) + self.assertEqual(head.versions.get(version='2').custom_validation_schema, OPENMRS_VALIDATION_SCHEMA) + update_validation_schema.apply_async.assert_not_called() # a FHIR update can't change the schema + + @staticmethod + def edited_first(model): + """as_new_version, run after an edit to HEAD commits""" + as_new_version = FhirRepositorySerializerMixin.as_new_version + + def edited(head, instance, validated_data): + model.objects.filter(id=head.id).update(description='Edited meanwhile', purpose='Meanwhile', retired=True) + return as_new_version(head, instance, validated_data) + return edited + + def test_the_new_version_is_made_from_head_as_stored_once_the_update_wrote_it(self): + """An edit to HEAD after the update saved it and before the version is made: the version is HEAD as it is then, + not a mix of the update's values and HEAD's""" + for resource_type, factory, kind, extra in self.resource_types(): + with self.subTest(resource_type): + head = self.released_then_edited(factory, kind) + with patch.object( + FhirRepositorySerializerMixin, 'as_new_version', staticmethod(self.edited_first(type(head)))): + response = self.fhir_update(head, resource_type, extra, description='Described through FHIR') + + self.assertEqual(response.status_code, 200, response.content) + version = head.versions.get(version='2') + self.assertEqual([version.description, version.purpose], ['Edited meanwhile', 'Meanwhile']) + self.assertEqual([version.released, version.retired], [True, False]) # the update's status, active diff --git a/core/integration_tests/tests_value_sets.py b/core/integration_tests/tests_value_sets.py index 40a081ec7..7a99621f9 100644 --- a/core/integration_tests/tests_value_sets.py +++ b/core/integration_tests/tests_value_sets.py @@ -118,7 +118,6 @@ def test_posting_value_sets(self): url = f"/orgs/{self.organization.mnemonic}/CodeSystem/" json_file = self.load_json('code_systems/code_systems_who_core.json') self.remove_duplicate_codes(json_file) - source_version = json_file.get('version') json_response = self.post(url, json_file) source_url = json_response.get('url') @@ -126,9 +125,7 @@ def test_posting_value_sets(self): json_file = self.load_json(test_file) response = self.post(url, json_file) json_response = response.json() - # the code system resolves in the value set owner's namespace, so each include names its version - for include in json_file['compose']['include']: - include['version'] = source_version + # each include is kept as written: one that names no version names none when read back self.ignore_paths(json_file, json_response, ['jurisdiction', 'date', 'copyright', 'purpose', 'identifier', 'meta', 'text', 'revisionDate', 'count', diff --git a/core/sources/models.py b/core/sources/models.py index 82409a9c4..8927e9b1b 100644 --- a/core/sources/models.py +++ b/core/sources/models.py @@ -545,8 +545,8 @@ def clean_supplements(self): def is_stored_supplement_without_supplements(self): """ - Whether the stored row with this id is a supplement without supplements. That's the row itself, not where this - object was loaded from: a FHIR CodeSystem PUT loads the latest release and saves it over HEAD. + Whether the stored row with this id is a supplement without supplements: the row itself, whatever row this + object was loaded from. """ return bool(self.id) and Source.objects.filter( id=self.id, content_type=CONTENT_TYPE_SUPPLEMENT, supplements__isnull=True).exists() diff --git a/core/value_sets/compose.py b/core/value_sets/compose.py new file mode 100644 index 000000000..4d7ef8da1 --- /dev/null +++ b/core/value_sets/compose.py @@ -0,0 +1,90 @@ +""" +A ValueSet's compose as OCL reads it when the value set is written: what makes a compose invalid before anything is +turned into references (compose_errors), and what OCL keeps of each listed code beyond its code and display +(concept_details). +""" +from pydash import get + +# what OCL keeps of a listed code (include.concept) besides its code and display (CollectionReference.concept_details) +CONCEPT_DETAILS = ('designation', 'extension') + + +def compose_errors(compose): + """ + Why a compose can't be used as written, as messages that name where: an element that isn't the object or list + FHIR makes it; a modifier extension, which changes what an element means and which OCL doesn't know (on the + compose, an include or exclude, a listed code, its designations or a filter); a filter with no value; codes or + filters with no code system (FHIR R4's vsd-2: what they select from is undefined); codes and filters together + (vsd-3). + """ + if not isinstance(compose, dict): + return ['compose: it must be an object.'] + errors = modifier_errors('compose', compose) + for element in ('include', 'exclude'): + items = compose.get(element) or [] + if not isinstance(items, list): + errors.append(f'compose.{element}: it must be a list.') + continue + for index, item in enumerate(items): + path = f'compose.{element}[{index}]' + if not isinstance(item, dict): + errors.append(f'{path}: it must be an object.') + continue + errors += modifier_errors(path, item) + shape = shape_errors(path, item) + if shape: + errors += shape + continue + concepts, filters = item.get('concept') or [], item.get('filter') or [] + if (concepts or filters) and not item.get('system'): + errors.append(f'{path}: codes and filters need the code system they come from (system).') + if concepts and filters: # FHIR R4's vsd-3 + errors.append(f'{path}: it lists codes or has filters, not both.') + for position, concept in enumerate(concepts): + errors += modifier_errors(f'{path}.concept[{position}]', concept) + for which, designation in enumerate(concept.get('designation') or []): + errors += modifier_errors(f'{path}.concept[{position}].designation[{which}]', designation) + for position, entry in enumerate(filters): + errors += modifier_errors(f'{path}.filter[{position}]', entry) + if get(entry, 'value') in (None, ''): + errors.append( + f"{path}.filter[{position}]: the filter on '{get(entry, 'property')}' " + f"({get(entry, 'op')}) has no value.") + return errors + + +def shape_errors(path, item): + """An include's or exclude's lists that aren't lists, or whose entries aren't what FHIR makes them""" + errors = [] + for key, entries_are in (('concept', dict), ('filter', dict), ('valueSet', str)): + if key not in item: + continue + entries = item[key] + if not isinstance(entries, list) or not all(isinstance(entry, entries_are) for entry in entries): + errors.append(f"{path}.{key}: it must be a list of {'objects' if entries_are is dict else 'strings'}.") + continue + if key == 'concept': + for position, concept in enumerate(entries): + if not isinstance(concept.get('code'), str) or not concept['code'].strip(): + errors.append(f'{path}.concept[{position}]: a listed code needs its code.') + designations = concept.get('designation') or [] + if not isinstance(designations, list) or not all(isinstance(entry, dict) for entry in designations): + errors.append(f'{path}.concept[{position}].designation: it must be a list of objects.') + return errors + + +def modifier_errors(path, element): + """An element's modifier extensions, each refused; a modifierExtension that isn't a list of objects, refused""" + modifiers = element.get('modifierExtension') if isinstance(element, dict) else None + if modifiers is None: + return [] + if not isinstance(modifiers, list) or not all(isinstance(modifier, dict) for modifier in modifiers): + return [f'{path}.modifierExtension: it must be a list of objects.'] + return [ + f"{path}: the modifier extension '{modifier.get('url')}' isn't supported, so the value set can't be read." + for modifier in modifiers] + + +def concept_details(concept): + """A listed code's designations and extensions as the value set lists them, or None""" + return {key: concept[key] for key in CONCEPT_DETAILS if concept.get(key)} or None diff --git a/core/value_sets/serializers.py b/core/value_sets/serializers.py index dc2517d5a..4d20b3ace 100644 --- a/core/value_sets/serializers.py +++ b/core/value_sets/serializers.py @@ -1,19 +1,23 @@ +import json import logging from django.conf import settings +from django.db import transaction +from pydash import get from rest_framework import serializers from rest_framework.fields import CharField, DateField, SerializerMethodField, ChoiceField, DateTimeField, \ BooleanField, ListField, URLField from core.code_systems.serializers import CodeSystemConceptSerializer, TextField -from core.collections.models import Collection, CollectionReference +from core.collections.models import Collection, CollectionReference, ExpansionParameters from core.collections.evaluation import ExpansionEvaluation from core.collections.parsers import CollectionReferenceParser from core.collections.serializers import CollectionCreateOrUpdateSerializer from core.common.constants import HEAD from core.common.fhir_helpers import delete_empty_fields from core.common.serializers import StatusField, IdentifierSerializer, ReadSerializerMixin -from core.fhir.serializers import CanonicalUrlField, FhirRepositorySerializerMixin, TitleField +from core.fhir.serializers import SUBSETTED, CanonicalUrlField, FhirRepositorySerializerMixin, TitleField +from core.value_sets.compose import compose_errors, concept_details, modifier_errors from core.value_sets.constants import RESOURCE_TYPE logger = logging.getLogger('oclapi') @@ -44,35 +48,27 @@ def to_internal_value(self, data): pass def to_representation(self, instance): - if instance: - include = {} - if instance[0].system: - system = instance[0].system - system = IdentifierSerializer.convert_ocl_uri_to_fhir_url(system, 'ValueSet') - include.update({'system': system}) - if instance[0].version: - include.update({'version': instance[0].version}) - for reference in instance: - if reference.valueset: - include.update({'valueSet': reference.valueset}) - break - if reference.filter: - filters = include.get('filter', None) - if not filters: - filters = [] - include.update({'filter': filters}) - filters.extend(FilterValueSetSerializer(reference.filter, many=True).data) - break - if reference.code: - concepts = include.get('concept', None) - if not concepts: - concepts = [] - include.update({'concept': concepts}) - concepts.append({'code': reference.code, 'display': reference.display}) - - return include - - return [] + """One include or exclude: the references of one clause of a compose (ComposeValueSetField.clause_of)""" + if not instance: + return [] + first, include = instance[0], {} + if first.system: + include['system'] = IdentifierSerializer.convert_ocl_uri_to_fhir_url(first.system, 'ValueSet') + if first.version: + include['version'] = first.version + concepts = [{'code': reference.code, 'display': reference.display, **(reference.concept_details or {})} + for reference in instance if reference.code] + if concepts: + include['concept'] = concepts + if first.filter: + include['filter'] = FilterValueSetSerializer(first.filter, many=True).data + if first.valueset: + include['valueSet'] = first.valueset + return include + + +# a compose include's or exclude's elements OCL reads into references +INCLUDE_ELEMENTS = ('system', 'version', 'concept', 'filter', 'valueSet') class ComposeValueSetField(serializers.Field): @@ -82,21 +78,55 @@ class ComposeValueSetField(serializers.Field): exclude = ValueSetComposeIncludeField(required=False) def to_internal_value(self, data): + """ + Each include and exclude as written, made into references with no transform: a listed code keeps the version + its include names, or none, so OCL's version rules pick one wherever the value set is evaluated, and keeps its + designations and extensions (CollectionReference.concept_details). Only FHIR's elements are read + (INCLUDE_ELEMENTS): an OCL expression's other keys, such as cascade or transform, aren't part of a FHIR + resource. compose.inactive is the collection's own rule (Collection.include_retired). What can't be used as + written is refused, not saved to add nothing: what compose_errors finds, and a filter OCL can't apply, as the + API refuses it when the reference is added (Collection.get_reference_filter_errors). + """ + errors = compose_errors(data) + if errors: + raise serializers.ValidationError(errors) references = [] evaluation = ExpansionEvaluation() # one default for all of them, so OCL's toggle is read once - for include in data.get('include', []): - include.update({'transform': 'resourceversions'}) - references += self.transform_to_ref(include, evaluation) - for exclude in data.get('exclude', []): - exclude.update({'transform': 'resourceversions'}) - exclude.update({'include': False}) - references += self.transform_to_ref(exclude, evaluation) + head = get(self.parent, 'instance.head') # an update's filters are checked in its HEAD's namespace + for element, include in (('include', True), ('exclude', False)): + for index, item in enumerate(data.get(element) or []): + expression = {key: item[key] for key in INCLUDE_ELEMENTS if item.get(key) is not None} + if expression.get('concept'): # a listed code's code and display; its details are kept apart + expression['concept'] = [ + {'code': concept['code'], 'display': concept.get('display')} + for concept in expression['concept']] + expression['include'] = include + errors += [ + f'compose.{element}[{index}].filter: {error}' + for reference_errors in Collection.get_reference_filter_errors( + expression, get(self.context, 'request.user'), collection=head).values() + for error in reference_errors['filter']] + if not errors: + references += self.references_of(expression, item, evaluation) + if errors: + raise serializers.ValidationError(errors) + result = {'include_retired': data.get('inactive')} # a compose given is the rule: none when it gives none if references: - res = {'references': references} + result['references'] = references if 'lockedDate' in data: - res['locked_date'] = data['lockedDate'] - return res - return {} + result['locked_date'] = data['lockedDate'] + return result + + @classmethod + def references_of(cls, expression, item, evaluation): + """An include's or exclude's references, each listed code's with its designations and extensions""" + details = {} + for concept in item.get('concept') or []: + details.setdefault(concept['code'], concept_details(concept)) + references = cls.transform_to_ref(expression, evaluation) + for reference in references: + reference.concept_details = details.get(reference.code) if reference.code else None + return references @staticmethod def transform_to_ref(include, evaluation=None): @@ -108,6 +138,15 @@ def transform_to_ref(include, evaluation=None): ref.expression = ref.build_expression() return refs + @staticmethod + def clause_of(reference): + """ + The compose clause a reference is read back in: listed codes of one code system version share one; a filter, + an import, or a whole code system is one of its own, so neither takes the place of the other + """ + return (reference.include, reference.system, reference.version, tuple(reference.valueset or ()), + json.dumps(reference.filter, sort_keys=True) if reference.filter else None, bool(reference.code)) + def to_representation(self, value): include = [] exclude = [] @@ -117,11 +156,7 @@ def to_representation(self, value): self.subsetted = len(references) > limit grouped_references = {} for reference in references[:limit]: - ref_list = grouped_references.get((reference.include, reference.system, reference.version), None) - if not ref_list: - ref_list = [] - grouped_references.update({(reference.include, reference.system, reference.version): ref_list}) - ref_list.append(reference) + grouped_references.setdefault(self.clause_of(reference), []).append(reference) for group, ref_list in grouped_references.items(): if group[0]: @@ -137,13 +172,30 @@ def to_representation(self, value): if result: result.update({'lockedDate': self.lockedDate.to_representation(value.locked_date)}) + if value.include_retired is not None: + result['inactive'] = value.include_retired return result return None +class ReferencesRefused(Exception): + """An update's references refused, after removing those it left out: raised so the removal is rolled back""" + def __init__(self, errors): + super().__init__(errors) + self.errors = errors + + +def evaluated_alike(stored, reference): + """Whether a stored reference is evaluated as an update's reference of the same clause would be: no cascade or + pinned concept version a compose can't show, and the same transform""" + return not stored.cascade and not stored.resource_version and (stored.transform or None) == ( + reference.transform or None) + + class ValueSetDetailSerializer(FhirRepositorySerializerMixin, serializers.ModelSerializer): content_field = 'compose' + left_out_before = False # an update's HEAD's rule on retired concepts, as read for update (prepare_object) resourceType = SerializerMethodField(method_name='get_resource_type') id = CharField(source='mnemonic') url = CanonicalUrlField(source='canonical_url', required=False) @@ -161,10 +213,23 @@ class Meta: 'jurisdiction', 'name', 'description', 'publisher', 'purpose', 'copyright', 'experimental', 'immutable', 'text', 'compose') + def prepare_object(self, validated_data, instance=None): + """ + A collection as the API prepares one (CollectionCreateOrUpdateSerializer.prepare_object), with the value set's + own rule on retired concepts when its compose gives one (compose.inactive). Given HEAD as an update reads it + for update (update_head), it notes whether HEAD's rule left retired concepts out before. + """ + if instance is not None and instance.is_head: + self.left_out_before = ExpansionParameters.leaves_retired_out(instance) + collection = CollectionCreateOrUpdateSerializer().prepare_object(validated_data, instance) + if 'include_retired' in validated_data: + collection.include_retired = validated_data['include_retired'] + return collection + def create(self, validated_data): uri = '/'.join([self.context['request'].path.rstrip('/'), validated_data['mnemonic']]) ident = IdentifierSerializer.include_ocl_identifier(uri, RESOURCE_TYPE, validated_data) - collection = CollectionCreateOrUpdateSerializer().prepare_object(validated_data) + collection = self.prepare_object(validated_data) collection_version = collection.version if collection.version != HEAD else '0.1' collection.version = HEAD collection.collection_type = 'ValueSet' @@ -181,7 +246,7 @@ def create(self, validated_data): if references: # atomic, so a version created meanwhile doesn't see the references without their expansion members with CollectionReference.atomic_when_locked(): - _, errors = collection.add_references(references, user) + _, errors = collection.add_references(references, user, by_clause=True) if errors: self._errors.update(errors) return collection @@ -196,8 +261,6 @@ def create(self, validated_data): return collection def update(self, instance, validated_data): - # Find HEAD first - head_collection = instance.head new_version = validated_data.get('version') if instance.active_versions.filter(version=new_version): @@ -205,47 +268,23 @@ def update(self, instance, validated_data): f' {instance.mnemonic}.'}) return instance - collection = CollectionCreateOrUpdateSerializer().prepare_object(validated_data, instance) - - # Preserve version specific values - collection_version = collection.version - collection_released = collection.released - - # Update HEAD first - collection.id = head_collection.id - collection.version = HEAD - collection.released = False # HEAD must never be released - collection.expansion_uri = head_collection.expansion_uri - user = self.context['request'].user - # a private HEAD stays private, as in CodeSystemDetailSerializer.update - errors = Collection.persist_changes(collection, user, None, keep_private=True) - - if errors: - self._errors.update(errors) - return collection - - # Update references - new_references = validated_data.get('references', []) - existing_references = [] - for reference in collection.references.all(): - for new_reference in new_references: - if reference.expression == new_reference.expression: - existing_references.append(new_reference) - - new_references = [reference for reference in new_references if reference not in existing_references] - - if new_references: - with CollectionReference.atomic_when_locked(): - _, errors = collection.add_references(new_references, user) - if errors: - self._errors.update(errors) - return collection + try: + # HEAD's save and its references in one transaction, under HEAD's lock: a refusal leaves both as they were + with transaction.atomic(): + collection, errors = self.update_head(instance, validated_data, self.prepare_object) + if errors: + self._errors.update(errors) + return collection + rebuild = ExpansionParameters.leaves_retired_out(collection) != self.left_out_before + rebuild = self.replace_references(collection, validated_data.get('references'), user) or rebuild + except ReferencesRefused as ex: + self._errors.update(ex.errors) + return instance + if rebuild: + self.rebuild_expansion(collection) - # Create new version - collection.version = collection_version - collection.released = collection_released - collection.id = None + collection = self.as_new_version(collection, instance, validated_data) collection.expansion_uri = None # Persist synchronously in order to include complete results in the response errors = Collection.persist_new_version(collection, user, sync=True) @@ -253,6 +292,62 @@ def update(self, instance, validated_data): return collection + @classmethod + def replace_references(cls, head, references, user): + """ + When the update gives a compose (`references` isn't None), HEAD's references become what it says, all of it or + nothing (its caller's transaction rolls back on ReferencesRefused): references it leaves out are removed, new + ones added. Whether a reference was removed: a removal takes away members that kept references have too, and + keeps what it excluded, so HEAD's expansion is rebuilt. + """ + if references is None: + return False + new_references, left_out = cls.update_references(head, references) + if left_out: # first, so a clause re-added differently doesn't meet the one it replaces + head.remove_references(head.references.filter(id__in=left_out)) + if new_references: + _, errors = head.add_references(new_references, user, by_clause=True) + if errors: + raise ReferencesRefused(errors) + return bool(left_out) + + @staticmethod + def update_references(head, references): + """ + (references to add, ids of references to remove) to make HEAD's what an update's compose says, a clause at a + time (CollectionReference.clause_key). One HEAD has that's evaluated alike (evaluated_alike) takes the update's + display, designations and extensions; one evaluated otherwise (a cascade, a pinned concept version, another + transform) is replaced. Only references a compose can show (to concepts) are removed. + """ + stored = {} + for reference in head.references.filter(reference_type='concepts').order_by('id'): + stored.setdefault(CollectionReference.clause_key(reference), []).append(reference) + new_references, kept = [], set() + for reference in references: + existing = next((stored_ for stored_ in stored.get(CollectionReference.clause_key(reference)) or [] + if evaluated_alike(stored_, reference)), None) + if existing is None: + new_references.append(reference) + continue + kept.add(existing.id) + if (existing.display, existing.concept_details) != (reference.display, reference.concept_details): + existing.display, existing.concept_details = reference.display, reference.concept_details + existing.save(update_fields=['display', 'concept_details', 'updated_at']) + return new_references, [ + reference.id for references_ in stored.values() for reference in references_ if reference.id not in kept] + + @staticmethod + def rebuild_expansion(head): + """ + HEAD's default expansion rebuilt with its version locks, as when its rules change (Expansion.add_references), + after an update changed its own rule on retired concepts or took references away: its members were evaluated + before. A member that leaves moves HEAD's export key, as any removal from an expansion does. + """ + expansion = head.expansion if head.expansion_uri else None + if expansion is not None: + expansion.seed_children(index=True, force_reevaluate=True, keep_locks=True) + expansion.update_health() + def to_representation(self, instance): try: rep = super().to_representation(instance) @@ -279,6 +374,24 @@ def get_resource_type(_): def get_meta(obj): return {'lastUpdated': obj.updated_at} + def to_internal_value(self, data): + """ + A modifier extension on the ValueSet itself changes what it means, and OCL knows none: refused. So is a read + marked SUBSETTED (its compose cut at the read's limit) written back with its compose, which would replace the + value set's with the part it shows. + """ + errors = modifier_errors('ValueSet', data) + if errors: + raise serializers.ValidationError({'modifierExtension': errors}) + tags = get(data, 'meta.tag') if isinstance(data, dict) else None + subsetted = isinstance(tags, list) and any( + isinstance(tag, dict) and (tag.get('system'), tag.get('code')) == (SUBSETTED['system'], SUBSETTED['code']) + for tag in tags) + if subsetted and data.get('compose') is not None: + raise serializers.ValidationError({'compose': [ + "It's marked SUBSETTED: its compose is only part of the value set's, so it can't replace it."]}) + return super().to_internal_value(data) + class ValueSetExpansionSerializer(ValueSetDetailSerializer): """A value set version as $expand answers it: the read's ValueSet without compose. The view adds the expansion.""" diff --git a/core/value_sets/tests.py b/core/value_sets/tests.py index d0cbd4559..072686124 100644 --- a/core/value_sets/tests.py +++ b/core/value_sets/tests.py @@ -2,6 +2,7 @@ from django.test import tag from core.collections.models import CollectionReference, Collection, Expansion +from core.collections.tests.tests_filters import set_fhir_rules from core.collections.tests.factories import OrganizationCollectionFactory, ExpansionFactory, UserCollectionFactory from core.common.constants import ACCESS_TYPE_NONE from core.common.tests import OCLAPITestCase @@ -13,7 +14,9 @@ from core.sources.tests.factories import OrganizationSourceFactory, UserSourceFactory from core.url_registry.tests_resolution import set_registry_toggle from core.users.models import UserProfile +from core.url_registry.factories import OrganizationURLRegistryFactory from core.users.tests.factories import UserProfileFactory +from core.fhir.serializers import SUBSETTED from core.value_sets.serializers import ValueSetDetailSerializer @@ -211,6 +214,8 @@ def test_create_with_filter_and_system(self): self.assertIsNone(resource['compose']['include'][0].get('concept')) def test_create_with_is_a_filter_and_system(self): + """Under FHIR's expansion rules, which apply is-a (without them it's refused, as the API refuses it)""" + set_fhir_rules(True) ConceptDocument().update(self.org_source_v2.head.concepts_set.all()) response = self.client.post( @@ -294,9 +299,8 @@ def test_create_with_is_a_filter_and_system(self): }] ) - def test_create_with_a_filter_it_cant_apply_resolves_to_nothing(self): - ConceptDocument().update(self.org_source_v2.head.concepts_set.all()) - + def test_create_with_a_filter_it_cant_apply_is_refused(self): + """Not saved to add nothing: refused, as adding the reference through the API refuses it""" response = self.client.post( f'/users/{self.user.username}/ValueSet/', HTTP_AUTHORIZATION='Token ' + self.user_token, @@ -316,21 +320,9 @@ def test_create_with_a_filter_it_cant_apply_resolves_to_nothing(self): format='json' ) - self.assertEqual(response.status_code, 201, response.data) - head = Collection.objects.get(user=self.user, mnemonic='c2', version='HEAD') - reference = head.references.get() - self.assertEqual(reference.filter, [{'property': 'concept', 'op': 'is-a', 'value': self.concept_1.mnemonic}]) - self.assertIsNone(reference.last_resolved_at) - self.assertEqual(reference.concepts.count(), 0) - for version in head.versions: - if version.expansion_uri: - self.assertEqual(version.expansion.concepts.count(), 0, version.version) - # recorded as a filter OCL couldn't apply, not as one that matched nothing - self.assertIn( - {'url': reference.expression, 'namespace': reference.namespace, 'type': 'reference.filter', - 'include': True, 'reason': 'filter_not_applied', - 'filter': [{'property': 'concept', 'op': 'is-a'}]}, - head.expansion.unresolved_repo_versions) + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("Filter op 'is-a' is not supported", str(response.data)) + self.assertFalse(Collection.objects.filter(user=self.user, mnemonic='c2').exists()) def test_create_with_filter_and_system_and_no_filter(self): ConceptDocument().update(self.org_source_v2.head.concepts_set.all()) @@ -466,14 +458,16 @@ def test_update_with_compose(self): format='json' ) + # the update's compose is what the value set says now: the reference it leaves out goes resource = response.data self.assertEqual(resource['version'], 'v2') self.assertEqual(resource['identifier'][0]['value'], f'/orgs/{self.org.mnemonic}/ValueSet/c1/') - self.assertEqual(len(resource['compose']['include']), 2) - self.assertEqual(resource['compose']['include'][1]['system'], 'http://some/url') - self.assertEqual(resource['compose']['include'][1]['version'], self.org_source_v2.version) - self.assertEqual(len(resource['compose']['include'][1]['concept']), 1) - self.assertEqual(resource['compose']['include'][1]['concept'][0]['code'], self.concept_2.mnemonic) + self.assertEqual(len(resource['compose']['include']), 1) + self.assertEqual(resource['compose']['include'][0]['system'], 'http://some/url') + self.assertEqual(resource['compose']['include'][0]['version'], self.org_source_v2.version) + self.assertEqual(len(resource['compose']['include'][0]['concept']), 1) + self.assertEqual(resource['compose']['include'][0]['concept'][0]['code'], self.concept_2.mnemonic) + self.assertFalse(self.collection.references.filter(code=self.concept_1.mnemonic).exists()) def release_system(self): """FHIR shows code systems with a release: the org source's v2 is one.""" @@ -794,3 +788,374 @@ def test_unable_to_represent_as_fhir(self): self.assertDictEqual(serialized, { 'resourceType': 'OperationOutcome', 'issue': [{'severity': 'error', 'details': 'Failed to represent "/invalid/uri" as ValueSet'}]}) + + +class ValueSetComposeWriteTest(OCLAPITestCase): + """A ValueSet written through FHIR keeps what its compose says: each include and exclude as written""" + @patch('core.sources.models.index_source_concepts', Mock(__name__='index_source_concepts')) + @patch('core.sources.models.index_source_mappings', Mock(__name__='index_source_mappings')) + def setUp(self): + set_registry_toggle(False) + super().setUp() + self.user = UserProfileFactory() + self.source = OrganizationSourceFactory(canonical_url='http://example.org/cs') + self.concept = ConceptFactory(parent=self.source, mnemonic='A') + ConceptFactory(parent=self.source, mnemonic='R', retired=True) + for version in ('1', '2'): # the concept, unchanged, is in both + Source.persist_new_version( + OrganizationSourceFactory.build( + version=version, mnemonic=self.source.mnemonic, organization=self.source.organization, + released=True), + self.source.created_by) + + def write(self, compose): + return self.client.post( + f'/users/{self.user.mnemonic}/ValueSet/', { + 'resourceType': 'ValueSet', 'id': 'vs', 'url': 'http://example.org/vs', 'version': '1', + 'status': 'active', 'name': 'vs', 'compose': compose + }, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + + def head(self): + return Collection.objects.get(user=self.user, mnemonic='vs', version='HEAD') + + def test_a_listed_code_keeps_the_version_its_include_names_or_none(self): + """Not the newest version holding the same concept version, as a transform would make it: with none, OCL's + version rules pick one wherever it's evaluated, not one fixed when it was written""" + for version in ('1', None): + with self.subTest(version=version): + include = {'system': self.source.canonical_url, 'concept': [{'code': 'A'}]} + response = self.write({'include': [{**include, 'version': version} if version else include]}) + + self.assertEqual(response.status_code, 201, response.data) + reference = self.head().references.get() + self.assertEqual( + [reference.version, reference.resource_version, reference.transform], [version, None, None]) + self.assertEqual(response.data['compose']['include'][0].get('version'), version) + Collection.objects.filter(user=self.user, mnemonic='vs').delete() + + def test_an_exclude_is_kept_as_written_too(self): + response = self.write({ + 'include': [{'system': self.source.canonical_url}], + 'exclude': [{'system': self.source.canonical_url, 'version': '1', 'concept': [{'code': 'A'}]}]}) + + self.assertEqual(response.status_code, 201, response.data) + exclusion = self.head().references.get(include=False) + self.assertEqual( + [exclusion.version, exclusion.code, exclusion.resource_version, exclusion.transform], + ['1', 'A', None, None]) + + def test_only_fhir_s_elements_of_an_include_are_read(self): + """An OCL expression's own keys (cascade, transform; a listed code's resource_version, a pinned concept + version) aren't elements of a FHIR include""" + response = self.write({'include': [{ + 'system': self.source.canonical_url, 'concept': [{'code': 'A', 'resource_version': '123'}], + 'transform': 'resourceversions', 'cascade': 'sourcemappings'}]}) + + self.assertEqual(response.status_code, 201, response.data) + reference = self.head().references.get() + self.assertEqual( + [reference.transform, reference.cascade, reference.version, reference.resource_version], + [None, None, None, None]) + + def test_a_filter_ocl_cant_apply_is_refused(self): + """As adding the reference through the API refuses it: nothing is saved""" + response = self.write({'include': [ + {'system': self.source.canonical_url, 'concept': [{'code': 'A'}]}, + {'system': self.source.canonical_url, 'filter': [{'property': 'no-such-property', 'op': '=', 'value': 'x'}]} + ]}) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn('include[1].filter', str(response.data)) + self.assertIn('no-such-property', str(response.data)) + self.assertFalse(Collection.objects.filter(user=self.user, mnemonic='vs').exists()) + + def version(self): + return Collection.objects.get(user=self.user, mnemonic='vs', version='1') + + def members(self, collection): + return set(collection.expansion.concepts.values_list('mnemonic', flat=True)) + + def test_compose_inactive_false_is_the_value_set_s_own_rule(self): + """Its expansions leave retired concepts out, while their activeOnly stays as given""" + response = self.write({'inactive': False, 'include': [{'system': self.source.canonical_url}]}) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual([self.head().include_retired, self.version().include_retired], [False, False]) + self.assertEqual(self.members(self.version()), {'A'}) + self.assertFalse(self.version().expansion.parameters.get('activeOnly')) # not set by the rule + self.assertIs(response.data['compose']['inactive'], False) + + def test_without_compose_inactive_retired_concepts_stay(self): + response = self.write({'include': [{'system': self.source.canonical_url}]}) + + self.assertEqual(response.status_code, 201, response.data) + self.assertIsNone(self.version().include_retired) + self.assertEqual(self.members(self.version()), {'A', 'R'}) + self.assertNotIn('inactive', response.data['compose']) + + def test_a_listed_code_keeps_its_designations_and_extensions(self): + concept = { + 'code': 'A', 'display': 'Alpha', + 'designation': [{'language': 'fr', 'value': 'Alpha (fr)', 'use': {'system': 'http://snomed.info/sct', + 'code': '900000000000013009'}}], + 'extension': [{'url': 'http://hl7.org/fhir/StructureDefinition/valueset-deprecated', 'valueBoolean': True}] + } + response = self.write({'include': [{'system': self.source.canonical_url, 'concept': [concept]}]}) + + self.assertEqual(response.status_code, 201, response.data) + details = {key: concept[key] for key in ('designation', 'extension')} + self.assertEqual(self.head().references.get().concept_details, details) + self.assertEqual(self.version().references.get().concept_details, details) + self.assertEqual(response.data['compose']['include'][0]['concept'], [concept]) + + def test_a_modifier_extension_is_refused_wherever_it_is(self): + """It changes what its element means, and OCL knows none, so the value set can't be read as written""" + modifier = [{'url': 'http://example.org/modifier', 'valueBoolean': True}] + include = {'system': self.source.canonical_url, 'concept': [{'code': 'A'}], + 'filter': [{'property': 'concept_class', 'op': '=', 'value': 'Misc'}]} + for path, compose in ( + ('compose', {'modifierExtension': modifier, 'include': [include]}), + ('compose.include[0]', {'include': [{**include, 'modifierExtension': modifier}]}), + ('compose.exclude[0]', {'include': [include], 'exclude': [{**include, 'modifierExtension': modifier}]}), + ('compose.include[0].concept[0]', { + 'include': [{**include, 'concept': [{'code': 'A', 'modifierExtension': modifier}]}]}), + ('compose.include[0].filter[0]', { + 'include': [{**include, 'filter': [{**include['filter'][0], 'modifierExtension': modifier}]}]}), + ('compose.include[0].concept[0].designation[0]', {'include': [{**include, 'concept': [ + {'code': 'A', 'designation': [{'value': 'Alpha', 'modifierExtension': modifier}]}]}]}), + ): + with self.subTest(path): + response = self.write(compose) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn(f"{path}: the modifier extension 'http://example.org/modifier'", str(response.data)) + self.assertFalse(Collection.objects.filter(user=self.user, mnemonic='vs').exists()) + + def test_a_filter_with_no_value_or_codes_with_no_system_are_refused(self): + for message, include in ( + ("compose.include[0].filter[0]: the filter on 'concept_class' (=) has no value", + {'system': self.source.canonical_url, 'filter': [{'property': 'concept_class', 'op': '='}]}), + ('compose.include[0]: codes and filters need the code system', + {'valueSet': ['http://example.org/other'], 'concept': [{'code': 'A'}]}), + ('compose.include[0].filter: it must be a list of objects', {'system': 'http://x.org', 'filter': 7}), + ('compose.include[0].concept[0].designation: it must be a list of objects', + {'system': 'http://x.org', 'concept': [{'code': 'A', 'designation': 'Alpha'}]}), + ('compose.include[0].modifierExtension: it must be a list of objects', + {'system': 'http://x.org', 'modifierExtension': 7}), + ('compose.include[0]: it lists codes or has filters, not both', { + 'system': 'http://x.org', 'concept': [{'code': 'A'}], + 'filter': [{'property': 'concept_class', 'op': '=', 'value': 'Misc'}]}), + ('compose.exclude[0].concept[0]: a listed code needs its code', { + 'system': 'http://x.org', 'concept': [{'display': 'Alpha'}]}), + ('compose.include[0].concept: it must be a list of objects', + {'system': 'http://x.org', 'concept': None}), + ): + with self.subTest(message): + exclusion = message.startswith('compose.exclude') + response = self.write({'include': [{'system': self.source.canonical_url}], 'exclude': [include]} + if exclusion else {'include': [include]}) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn(message, str(response.data)) + self.assertFalse(Collection.objects.filter(user=self.user, mnemonic='vs').exists()) + + def update(self, compose, version='2', path=None): + return self.client.put( + path or f'/users/{self.user.mnemonic}/ValueSet/vs/', { + 'resourceType': 'ValueSet', 'id': 'vs', 'url': 'http://example.org/vs', 'version': version, + 'status': 'active', 'name': 'vs', 'compose': compose + }, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + + def test_an_update_changes_a_listed_code_s_display_designations_and_extensions(self): + system = self.source.canonical_url + designation = [{'language': 'fr', 'value': 'Alpha (fr)'}] + self.assertEqual(self.write({'include': [{'system': system, 'concept': [ + {'code': 'A', 'display': 'Alpha', 'designation': designation}]}]}).status_code, 201) + + corrected = [{'language': 'fr', 'value': 'Alpha, corrigé'}] + response = self.update({'include': [{'system': system, 'concept': [ + {'code': 'A', 'display': 'Alpha!', 'designation': corrected}]}]}) + self.assertEqual(response.status_code, 200, response.data) + for version in ('HEAD', '2'): + reference = Collection.objects.get(user=self.user, mnemonic='vs', version=version).references.get() + self.assertEqual([reference.display, reference.concept_details], ['Alpha!', {'designation': corrected}]) + + response = self.update({'include': [{'system': system, 'concept': [{'code': 'A'}]}]}, version='3') + self.assertEqual(response.status_code, 200, response.data) + reference = Collection.objects.get(user=self.user, mnemonic='vs', version='3').references.get() + self.assertEqual([reference.display, reference.concept_details], [None, None]) + + def test_each_clause_is_read_back_as_its_own_include(self): + """A whole code system, a filter and listed codes of the same code system version stay apart""" + set_fhir_rules(True) # filters in the database, as FHIR's rules apply them + system = self.source.canonical_url + includes = [ + {'system': system}, + {'system': system, 'filter': [{'property': 'concept_class', 'op': '=', 'value': 'Misc'}]}, + {'system': system, 'concept': [{'code': 'A', 'designation': [{'language': 'fr', 'value': 'Alpha'}]}]}, + ] + response = self.write({'include': includes}) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self.client.get(f'/users/{self.user.mnemonic}/ValueSet/vs/').data['compose']['include'], + includes) + + def test_an_update_that_changes_compose_inactive_rebuilds_head_s_expansion(self): + """Its members were evaluated under the old rule; an import that reads HEAD's stored expansion reads them""" + whole = {'include': [{'system': self.source.canonical_url}]} + self.assertEqual(self.write(whole).status_code, 201) + self.assertEqual(self.members(self.head()), {'A', 'R'}) + removal_before = self.head().last_child_removal_at + + response = self.update({**whole, 'inactive': False}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self.members(self.head()), {'A'}) + self.assertEqual( + self.members(Collection.objects.get(user=self.user, mnemonic='vs', version='2')), {'A'}) + # its export, which lists R, is no longer current + self.assertNotEqual(self.head().last_child_removal_at, removal_before) + + def test_an_update_s_filters_are_checked_in_its_head_s_namespace(self): + """As adding a reference through the API checks them in the collection's: the code system its owner's URL + registry names declares the property""" + set_fhir_rules(True) + set_registry_toggle(True) + org = OrganizationFactory() + org.members.add(self.user) + url = 'http://example.org/CodeSystem/units' + declared = OrganizationSourceFactory( + organization=org, canonical_url=url, properties=[{'code': 'units', 'type': 'string'}]) + OrganizationSourceFactory( + organization=org, mnemonic=declared.mnemonic, canonical_url=url, version='1', released=True, + properties=declared.properties) + OrganizationURLRegistryFactory(organization=org, url=url, namespace=org.uri) + path = f'/orgs/{org.mnemonic}/ValueSet/' + response = self.client.post(path, { + 'resourceType': 'ValueSet', 'id': 'vs', 'url': 'http://example.org/vs', 'version': '1', 'status': 'active', + 'name': 'vs', 'compose': {'include': [{'system': url}]} + }, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + self.assertEqual(response.status_code, 201, response.data) + + response = self.update( + {'include': [{'system': url, 'filter': [{'property': 'units', 'op': '=', 'value': 'mg'}]}]}, + path=f'{path}vs/') + + self.assertEqual(response.status_code, 200, response.data) + + def test_a_modifier_extension_on_the_value_set_itself_is_refused(self): + response = self.client.post( + f'/users/{self.user.mnemonic}/ValueSet/', { + 'resourceType': 'ValueSet', 'id': 'vs', 'url': 'http://example.org/vs', 'version': '1', + 'status': 'active', 'name': 'vs', 'compose': {'include': [{'system': self.source.canonical_url}]}, + 'modifierExtension': [{'url': 'http://example.org/modifier', 'valueBoolean': True}] + }, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("ValueSet: the modifier extension 'http://example.org/modifier'", str(response.data)) + self.assertFalse(Collection.objects.filter(user=self.user, mnemonic='vs').exists()) + + def test_clauses_that_share_an_expression_are_kept_apart(self): + """All of a code system but what a value set holds: the include and the exclude both say the code system""" + system, imported = self.source.canonical_url, 'http://example.org/ValueSet/other' + compose = {'include': [{'system': system}], 'exclude': [{'system': system, 'valueSet': [imported]}]} + response = self.write(compose) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self.head().references.count(), 2) + self.assertEqual( + {key: value for key, value in response.data['compose'].items() if key in ('include', 'exclude')}, compose) + + def test_an_update_s_compose_replaces_head_s(self): + """What it leaves out goes, from HEAD and the new version: a code listed from another version is not kept""" + system = self.source.canonical_url + self.assertEqual(self.write({'include': [ + {'system': system, 'version': '1', 'concept': [{'code': 'A'}]}]}).status_code, 201) + + response = self.update({'include': [{'system': system, 'version': '2', 'concept': [{'code': 'A'}]}]}) + + self.assertEqual(response.status_code, 200, response.data) + for version in ('HEAD', '2'): + references = Collection.objects.get(user=self.user, mnemonic='vs', version=version).references + self.assertEqual(list(references.values_list('version', 'code')), [('2', 'A')], version) + self.assertEqual(response.data['compose']['include'], [{'system': system, 'version': '2', 'concept': [ + {'code': 'A'}]}]) + self.assertEqual(self.members(self.head()), {'A'}) + + def test_two_includes_that_share_an_expression_are_both_kept(self): + """All of a code system, and what of it a value set holds: both include, and both say the code system""" + system = self.source.canonical_url + compose = {'include': [{'system': system}, {'system': system, 'valueSet': ['http://example.org/ValueSet/v']}]} + response = self.write(compose) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self.head().references.count(), 2) + self.assertEqual(response.data['compose']['include'], compose['include']) + + def test_a_refused_update_leaves_head_as_it_was(self): + """Its compose would import the value set itself, a loop: refused, after it would have removed HEAD's + references and cleared its rule on retired concepts (no inactive given): HEAD keeps both""" + set_fhir_rules(True) + self.assertEqual(self.write({'inactive': False, 'include': [ + {'system': self.source.canonical_url}]}).status_code, 201) + before = list(self.head().references.values_list('id', flat=True)) + + response = self.update({'include': [{'valueSet': ['http://example.org/vs|HEAD']}]}) + + self.assertEqual(response.status_code, 400, response.data) + self.assertEqual(list(self.head().references.values_list('id', flat=True)), before) + self.assertIs(self.head().include_retired, False) + self.assertEqual(self.members(self.head()), {'A'}) + + def test_a_subsetted_read_can_t_replace_the_compose(self): + self.assertEqual(self.write({'include': [{'system': self.source.canonical_url}]}).status_code, 201) + + response = self.client.put( + f'/users/{self.user.mnemonic}/ValueSet/vs/', { + 'resourceType': 'ValueSet', 'id': 'vs', 'url': 'http://example.org/vs', 'version': '2', + 'status': 'active', 'name': 'vs', 'meta': {'tag': [SUBSETTED]}, + 'compose': {'include': [{'system': self.source.canonical_url, 'concept': [{'code': 'A'}]}]} + }, HTTP_AUTHORIZATION='Token ' + self.user.get_token(), format='json') + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn('SUBSETTED', str(response.data)) + self.assertEqual(self.head().references.get().code, None) + + def test_a_compose_given_without_inactive_clears_the_rule(self): + """An update's compose is the value set's: one that gives no inactive keeps OCL's default""" + whole = {'include': [{'system': self.source.canonical_url}]} + self.assertEqual(self.write({**whole, 'inactive': False}).status_code, 201) + + self.assertEqual(self.update(whole).status_code, 200) + + version = Collection.objects.get(user=self.user, mnemonic='vs', version='2') + self.assertEqual([self.head().include_retired, version.include_retired], [None, None]) + self.assertEqual(self.members(version), {'A', 'R'}) + + def test_an_update_replaces_a_reference_its_compose_shows_but_that_s_evaluated_otherwise(self): + """One the API added with a cascade, which a compose can't show: the update's listed code replaces it""" + self.assertEqual(self.write({'include': [{'system': self.source.canonical_url}]}).status_code, 201) + head = self.head() + head.references.all().delete() + reference = CollectionReference( + collection=head, system=self.source.canonical_url, code='A', cascade='sourcetoconcepts') + reference.expression = reference.build_expression() + reference.save() + + response = self.update({'include': [{'system': self.source.canonical_url, 'concept': [{'code': 'A'}]}]}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(list(self.head().references.values_list('code', 'cascade')), [('A', None)]) + + def test_a_clause_listing_no_code_takes_the_concepts_of_the_release_it_s_evaluated_in(self): + """A is active in the releases and retired in HEAD since: the filter, unversioned, is evaluated in the latest + release, and the value set's own rule leaves out what's retired there, not in HEAD (the concepts are the + release's, with INTENSIONAL_REFERENCE_RESOURCE_VERSIONS_TOGGLE on, as it is everywhere)""" + set_fhir_rules(True) + Concept.objects.filter(id=self.concept.id).update(retired=True) # A's HEAD row + + response = self.write({'inactive': False, 'include': [{'system': self.source.canonical_url, 'filter': [ + {'property': 'concept_class', 'op': '=', 'value': self.concept.concept_class}]}]}) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self.members(self.version()), {'A'})