コード例 #1
0
ファイル: middleware.py プロジェクト: pyhealth-dev/hyperfhir
    def error_response(scope: Scope, errors) -> Response:
        default = MIME_FHIR_VERSION_MAP[DEFAULT_FHIR_VERSION]
        klass = lookup_fhir_class("OperationOutcome", fhir_release=default)
        issues = list()

        for error in errors:
            issue = {
                "severity":
                "fatal",
                "code":
                "value",
                "details": {
                    "coding": [{
                        "system":
                        "http://terminology.hl7.org/CodeSystem/operation-outcome",
                        "code": "MSG_BAD_FORMAT",
                        "display": error["msg"],
                    }]
                },
                "diagnostics":
                f"Request loc: {error['loc']}, Original Value: {error['original']}",
            }
            issues.append(issue)

        outcome = klass(**{
            "id": str(scope["FHIR_REQUEST_ID"]),
            "issue": issues
        })

        return FHIRHttpJsonResponse(outcome,
                                    status_code=422,
                                    fhir_version=default,
                                    locked=True)
コード例 #2
0
def make_outcome(request: Request, exc: RequestValidationError):
    """
    https://terminology.hl7.org/2.0.0/CodeSystem-operation-outcome.html
    :param exc:
    :param status_code:
    :return:
    """
    klass = lookup_fhir_class(
        "OperationOutcome", fhir_release=request.scope["FHIR_VERSION"]
    )
    issues = list()
    for error in exc.errors():
        issue = {
            "severity": "error",
            "code": exc.code,
            "details": {
                "coding": [
                    {
                        "system": "http://terminology.hl7.org/CodeSystem/operation-outcome",
                        "code": exc.system_code,
                        "display": exc.body,
                    }
                ]
            },
            "diagnostics": f"loc: {error['loc']}, message: {error['msg']}",
        }
        issues.append(issue)

    outcome = klass(**{"id": str(request.scope["FHIR_REQUEST_ID"]), "issue": issues})
    return outcome
コード例 #3
0
ファイル: test_fhirpath.py プロジェクト: nazrulworld/fhirpath
def test_fhirpath_list_type_info():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Patient.json"), "r") as fp:
        data = fp.read()
        obj = lookup_fhir_class("Patient", FHIR_VERSION.R4).parse_raw(data)
    fpath = fhirpath.FHIRPath(obj)
    assert isinstance(fpath.address.get_type(), fhirpath.ListTypeInfo)
    assert fpath.address.get_type().elementType == "FHIR.Address"
    assert isinstance(
        fhirpath.FHIRPath.__storage__[fpath.address.get_type().elementType],
        fhirpath.ClassInfo,
    )
    with pytest.raises(ValueError) as exc_info:
        fhirpath.FHIRPath(["mu", "mn"])
        assert "root fhirpath cannot be initialized" in exc_info.value.args[0]

    obj.address = None
    fpath = fhirpath.FHIRPath(obj)
    assert isinstance(fpath.address.get_type(), fhirpath.ListTypeInfo)

    obj.address = []
    fpath = fhirpath.FHIRPath(obj)
    assert isinstance(fpath.address.get_type(), fhirpath.ListTypeInfo)
    assert isinstance(fpath.extension.get_type(), fhirpath.ListTypeInfo)
    assert fpath.extension() is None
コード例 #4
0
ファイル: test_fhirpath.py プロジェクト: nazrulworld/fhirpath
def test_fhirpath_tuple_type_info():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Patient.json"), "r") as fp:
        data = fp.read()
        obj = lookup_fhir_class("Patient", FHIR_VERSION.R4).parse_raw(data)
    fpath = fhirpath.FHIRPath(obj)
    assert isinstance(fpath.contact[0].get_type(), fhirpath.TupleTypeInfo)
    assert len(fpath.contact[0].get_type().get_elements()) == 10
コード例 #5
0
ファイル: test_fhirpath.py プロジェクト: nazrulworld/fhirpath
def test_existence_5_1_1_empty():
    """ """
    obj = lookup_fhir_class("Patient", FHIR_VERSION.R4).parse_file(
        FHIR_EXAMPLE_RESOURCES / "Patient.json")
    f_path = fhirpath.FHIRPath(obj)
    assert f_path.name.empty() is False
    assert f_path.name.count() == 2
    assert f_path.extension.empty() is True
    assert f_path.extension.count() == 0
コード例 #6
0
async def fhir_resource_from_request(request: Request, resource_type: str) -> BaseModel:
    """
    :param request:
    :param resource_type:
    :return:
    """
    raw = await request.body()
    klass = lookup_fhir_class(resource_type, request.scope["FHIR_VERSION"])
    obj = klass.parse_raw(raw)
    return obj
コード例 #7
0
 def test_bundle_response_as_dict(self):
     """ """
     self.load_contents()
     context = self.get_context("Task", True)
     result = zcatalog_fhir_search(context,
                                   bundle_response=True,
                                   bundle_as_dict=True)
     self.assertIsInstance(result, dict)
     try:
         bundle = lookup_fhir_class("Bundle",
                                    FHIR_VERSION.STU3).parse_obj(result)
         self.assertEqual(len(bundle.entry), len(result["entry"]))
     except Exception:
         raise AssertionError("Code should not come here.")
コード例 #8
0
ファイル: test_fhirpath.py プロジェクト: nazrulworld/fhirpath
def test_fhirpath_class_type_info():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Patient.json"), "r") as fp:
        data = fp.read()

        obj = lookup_fhir_class("Patient", FHIR_VERSION.R4).parse_raw(data)

    fpath = fhirpath.FHIRPath(obj)
    assert isinstance(fpath.get_type(), fhirpath.ClassInfo)
    # Patient has 26 elements
    assert len(fpath.get_type().element) == 26
    assert fpath.get_type().name == "Patient"
    assert fpath.get_type().baseType == "FHIR.DomainResource"
    # Test Element from Base
    assert fpath.meta.get_type().name == "Meta"
コード例 #9
0
def test_fhir_field_value_pickling():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Organization.json"), "r") as fp:
        fhir_json = json.load(fp)

    model = implementer(IFhirResource)(lookup_fhir_class(
        fhir_json["resourceType"]))
    fhir_resource = model(fhir_json)
    fhir_resource_value = FhirFieldValue(obj=fhir_resource)

    serialized = pickle.dumps(fhir_resource_value)
    deserialized = pickle.loads(serialized)

    assert len(deserialized.stringify()) == len(
        fhir_resource_value.stringify())
コード例 #10
0
ファイル: test_fhirpath.py プロジェクト: nazrulworld/fhirpath
def test_fhirpath_simple_type_info():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Patient.json"), "r") as fp:
        data = fp.read()
        obj = lookup_fhir_class("Patient", FHIR_VERSION.R4).parse_raw(data)
    fpath = fhirpath.FHIRPath(obj)
    assert fpath.gender.get_type().name == "code"
    assert fpath.gender.get_type().baseType == "FHIR.Primitive"
    assert fpath.active.get_type().name == "boolean"

    assert fpath.identifier[0].type.text.get_type().name == "string"
    obj.gender = None
    obj.active = None
    fpath = fhirpath.FHIRPath(obj)
    assert fpath.gender.get_type().name == "code"
    assert fpath.active.get_type().name == "boolean"
コード例 #11
0
async def test_fhir_field_value_serializer(dummy_request):
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Organization.json"), "r") as fp:
        fhir_json = json.load(fp)

    model = implementer(IFhirResource)(lookup_fhir_class(
        fhir_json["resourceType"]))
    fhir_resource = model(fhir_json)
    value = FhirFieldValue(obj=fhir_resource)

    serialized = query_adapter(value, IValueToJson)
    assert serialized == value.as_json()

    serialized = query_adapter(FhirFieldValue(), IValueToJson)

    assert serialized is None
コード例 #12
0
    def _from_dict(self, dict_value):
        """ """
        self._pre_value_validate(dict_value)
        klass = self._resource_class

        if klass is None:
            # relay on json value for resource type
            klass = implementer(IFhirResource)(
                lookup_fhir_class(dict_value["resourceType"])
            )

        # check constraint
        if klass.resource_type != dict_value.get("resourceType"):
            raise ConstraintNotSatisfied(
                "Fhir Resource mismatched with provided resource type!\n"
                "`{0}` resource type is permitted but got `{1}`".format(
                    klass.resource_type, dict_value.get("resourceType")
                ),
                field_name=self.getName(),
            )

        value = FhirFieldValue(obj=klass(dict_value))

        return value
コード例 #13
0
    def _init(
        self, resource_class, resource_interface, resource_type, fhir_release, **kw
    ):
        """ """
        if "default" in kw:

            if (
                isinstance(kw["default"], (str, dict)) or kw["default"] is None
            ) is False:
                msg = (
                    "Only dict or string or None is accepted as "
                    "default value but got {0}".format(type(kw["default"]))
                )

                raise Invalid(msg)

        field_attributes = get_fields(IFhirField)

        attribute = field_attributes["resource_class"].bind(self)
        if resource_class is None:
            attribute.validate(resource_class)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_class)
        attribute.set(self, attribute_val)

        attribute = field_attributes["resource_interface"].bind(self)
        if resource_interface is None:
            attribute.validate(resource_interface)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_interface)
        attribute.set(self, attribute_val)

        attribute = field_attributes["resource_type"].bind(self)
        if resource_type is None:
            attribute.validate(resource_type)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_type)
        attribute.set(self, attribute_val)

        attribute = field_attributes["fhir_release"].bind(self)
        if fhir_release is None:
            attribute.validate(fhir_release)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(fhir_release)
            # just for ensure correct value
            FHIR_VERSION[attribute_val]
        attribute.set(self, attribute_val)

        if self.resource_type and self.resource_class is not None:
            raise Invalid(
                "Either `resource_class` or `resource_type` value is acceptable! "
                "you cannot provide both!"
            )

        if self.resource_class:
            try:
                klass = import_string(self.resource_class)
                self.ensure_fhir_abstract(klass)

            except ImportError:
                msg = (
                    "Invalid FHIR Resource class `{0}`! "
                    "Please check the module or class name."
                ).format(self.resource_class)

                return reraise(Invalid, msg)

            if not IFhirResource.implementedBy(klass):

                raise Invalid(
                    "{0!r} must be valid resource class from fhir.resources".format(
                        klass
                    )
                )
            self._resource_class = klass

        if self.resource_type:

            try:
                self._resource_class = implementer(IFhirResource)(
                    lookup_fhir_class(self.resource_type)
                )
            except ImportError:
                msg = "{0} is not valid fhir resource type!".format(self.resource_type)
                return reraise(Invalid, msg)

        if self.resource_interface:
            try:
                klass = implementer(IFhirResource)(
                    import_string(self.resource_interface)
                )
            except ImportError:
                msg = (
                    "Invalid FHIR Resource Interface`{0}`! "
                    "Please check the module or class name."
                ).format(self.resource_interface)
                return reraise(Invalid, msg)

            if not IInterface.providedBy(klass):
                raise WrongType("An interface is required", klass, self.__name__)

            if klass is not IFhirResource and not issubclass(klass, IFhirResource):
                msg = "`{0!r}` must be derived from {1}".format(
                    klass,
                    IFhirResource.__module__ + "." + IFhirResource.__class__.__name__,
                )

                raise Invalid(msg)

            self._resource_interface_class = klass
コード例 #14
0
def test_fhir_field_value():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Organization.json"), "r") as f:
        fhir_json = json.load(f)

    model = implementer(IFhirResource)(lookup_fhir_class(
        fhir_json["resourceType"]))
    fhir_resource = model(fhir_json)
    fhir_resource_value = FhirFieldValue(obj=fhir_resource)

    # __bool__ should be True
    assert bool(fhir_resource_value) is True
    assert IFhirResource.providedBy(
        fhir_resource_value.foreground_origin()) is True
    assert isinstance(fhir_resource_value.stringify(), str) is True

    # Test Patch
    patch_data = {"hello": 123}
    try:
        fhir_resource_value.patch(patch_data)
        raise AssertionError(
            "Code should not come here! because wrong type data is provided for patch!"
        )
    except WrongType:
        pass
    patch_data = [{
        "path": "/text/fake path",
        "value": "patched!",
        "Invalid Option": "replace"
    }]
    # Test getting original error from json patcher
    try:
        fhir_resource_value.patch(patch_data)
        raise AssertionError(
            "Code should not come here! because wrong patch data is"
            " provided for patch and invalid format as well!")
    except Invalid as exc:
        assert "does not contain 'op' member" in str(exc)

    patch_data = [{
        "path": "/text/status",
        "value": "patched!",
        "op": "replace"
    }]
    fhir_resource_value.patch(patch_data)

    assert "patched!" == fhir_resource_value.text.status

    # Make sure string is transformable to fhir resource
    json_str = fhir_resource_value.stringify()
    json_dict = parse_json_str(json_str)

    try:
        model(json_dict).as_json()
    except Exception:
        raise AssertionError("Code should not come here!")

    # Test self representation
    assert fhir_resource_value.__class__.__module__ in repr(
        fhir_resource_value)

    empty_resource = FhirFieldValue()
    # __bool__ should be False
    assert bool(empty_resource) is False

    assert empty_resource.foreground_origin() is None

    # assert (fhir_resource_value == empty_resource) is False
    # assert (empty_resource == fhir_resource_value) is False
    # assert (empty_resource != fhir_resource_value) is True

    # Test Patch with empty value
    try:
        empty_resource.patch(patch_data)
        raise AssertionError(
            "Code should not come here! because empty resource cannot be patched!"
        )
    except Invalid:
        pass

    # Let's try to modify
    fhir_resource_value.identifier[0].use = "no-official"
    # test if it impact
    assert fhir_resource_value.as_json(
    )["identifier"][0]["use"] == "no-official"

    # Let's try to set value on empty value
    try:
        empty_resource.id = "my value"
        raise AssertionError(
            "Code should not come here! because no fhir resource!")
    except AttributeError:
        pass

    assert "NoneType" in repr(empty_resource)
    assert "" == str(empty_resource)

    # Validation Test:: more explict???
    try:
        FhirFieldValue(obj=dict(hello="Ketty"))
        raise AssertionError(
            "Code should not come here, because should raise validation error!"
        )
    except (WrongType, Invalid):
        pass

    @implementer(IFhirResource)
    class TestBrokenInterfaceObject(object):
        def __init__(self):
            pass

    broken_obj = TestBrokenInterfaceObject()
    try:
        fhir_resource_value._validate_object(broken_obj)
        raise AssertionError(
            "Code should not come here! because of validation error")
    except Invalid as exc:
        assert " attribute was not provided" in str(exc)
コード例 #15
0
def test_field_validate():
    """ """
    with open(str(FHIR_EXAMPLE_RESOURCES / "Organization.json"), "r") as f:
        json_dict = json.load(f)

    organization = implementer(IFhirResource)(
        lookup_fhir_class("Organization"))(json_dict)
    fhir_resource_value = FhirFieldValue(obj=organization)

    fhir_field = FhirField(title="Organization resource", fhir_release="R4")

    try:
        fhir_field._validate(fhir_resource_value)
    except Invalid as exc:
        raise AssertionError("Code should not come here!\n{0!s}".format(exc))

    # Test wrong type value!
    try:
        fhir_field._validate(dict(hello="wrong"))
        raise AssertionError(
            "Code should not come here! wrong data type is provide")
    except WrongType as exc:
        assert "fhirpath_guillotina.field.FhirFieldValue" in str(exc)

    type_, address_ = fhir_resource_value.type, fhir_resource_value.address
    fhir_resource_value.type = 390
    fhir_resource_value.address = "i am wrong type"

    try:
        fhir_field._validate(fhir_resource_value)
        raise AssertionError(
            "Code should not come here! wrong element data type is provided")
    except Invalid as exc:
        assert "invalid element inside fhir model object" in str(exc)

    # Restore
    fhir_resource_value.type = type_
    fhir_resource_value.address = address_
    # Test model constraint
    fhir_field = FhirField(
        title="Organization resource",
        resource_class="tests.fixtures.MyTaskResource",
        fhir_release="R4",
    )

    try:
        fhir_field._validate(fhir_resource_value)
        raise AssertionError("Code should not come here! model mismatched!")
    except WrongContainedType as exc:
        assert "Wrong fhir resource value" in str(exc)

    # Test resource type constraint!
    fhir_field = FhirField(title="Organization resource",
                           resource_type="Task",
                           fhir_release="R4")

    try:
        fhir_field._validate(fhir_resource_value)
        raise AssertionError("Code should not come here! model mismatched!")
    except ConstraintNotSatisfied as exc:
        assert "Resource type must be `Task`" in str(exc)

    # Wrong interface attributes
    fhir_field = FhirField(
        title="Organization resource",
        resource_interface="tests.fixtures.IWrongInterface",
        fhir_release="R4",
    )

    try:
        fhir_field._validate(fhir_resource_value)
        raise AssertionError(
            "Code should not come here! interface and object mismatched!")
    except Invalid as exc:

        assert "has failed to implement interface" in str(exc)