def testIsTypedReferenceField_withValidTypedReferenceField_returnsTrue(self): """Test is_typed_reference_field functionality on valid input.""" reference = datatypes_pb2.Reference() practitioner_role_id_field = reference.DESCRIPTOR.fields_by_name[ 'practitioner_role_id'] self.assertTrue( annotation_utils.is_typed_reference_field(practitioner_role_id_field))
def _validate_reference_field(parent: message.Message, field: descriptor.FieldDescriptor): """Ensure that the provided reference field is valid. Args: parent: The containing Message. field: The reference field descriptor. Raises: fhir_errors.InvalidFhirError: In the event of an empty reference (no extensions, no identifier, no display). """ oneof = field.message_type.oneofs[0] # Singular fields have a length of 1 for i in range(proto_utils.field_content_length(parent, field)): reference = proto_utils.get_value_at_field_index(parent, field, i) reference_field_name = reference.WhichOneof(oneof.name) if reference_field_name is None: if not (reference.extension or reference.HasField('identifier') or reference.HasField('display')): raise fhir_errors.InvalidFhirError( f'`{reference.DESCRIPTOR.name}` is an empty reference.') # There's no reference field, but there is other data. This is valid. return field_options = field.GetOptions() if not field_options.Extensions[annotations_pb2.valid_reference_type]: # The reference field does not have restrictions, so any value is fine. return if reference.HasField('uri') or reference.HasField('fragment'): # Uri and Fragment references are untyped. return # There are no reference annotations for DSTU2; skip validation if annotation_utils.get_fhir_version( reference) == annotations_pb2.FhirVersion.DSTU2: return reference_field = reference.DESCRIPTOR.fields_by_name[ reference_field_name] if annotation_utils.is_typed_reference_field(reference_field): # Ensure that the reference type is listed as "valid" reference_type = reference_field.GetOptions().Extensions[ annotations_pb2.referenced_fhir_type] is_allowed = False for valid_type in field_options.Extensions[ annotations_pb2.valid_reference_type]: if valid_type == reference_type or valid_type == 'Resource': is_allowed = True break if not is_allowed: raise fhir_errors.InvalidFhirError( f'Message `{parent.DESCRIPTOR.full_name}` contains an invalid ' f'reference type: `{reference_type}` set at: ' f'`{reference_field_name}`.')
def testIsTypedReferenceField_withInvalidTypedReferenceField_returnsFalse( self): """Test is_typed_reference_field functionality on invalid input.""" reference = datatypes_pb2.Reference() uri_field = reference.DESCRIPTOR.fields_by_name['uri'] self.assertFalse(annotation_utils.is_typed_reference_field(uri_field))