Esempio n. 1
0
 def test_staff_access(self):
     staff = self.add_user('*****@*****.**')
     self.promote_user(role_name=ROLE.PATIENT.value)
     self.promote_user(staff, role_name=ROLE.STAFF.value)
     self.shallow_org_tree()
     org = Organization.query.filter(Organization.id > 0).first()
     staff = db.session.merge(staff)
     staff.organizations.append(org)
     self.test_user = db.session.merge(self.test_user)
     self.test_user.organizations.append(org)
     audit = Audit(
         user_id=TEST_USER_ID, subject_id=TEST_USER_ID,
         comment='just test data')
     consent = UserConsent(user_id=TEST_USER_ID, organization_id=org.id,
                           audit=audit, agreement_url='http://fake.org')
     with SessionScope(db):
         db.session.add(audit)
         db.session.add(consent)
         db.session.commit()
     staff = db.session.merge(staff)
     self.login(staff.id)
     response = self.client.get('/api/user/{}/audit'.format(TEST_USER_ID))
     assert response.status_code == 200
     assert 1 == len(response.json['audits'])
     assert (response.json['audits'][0]['by']['reference'] ==
             Reference.patient(TEST_USER_ID).as_fhir()['reference'])
     assert (response.json['audits'][0]['on'] ==
             Reference.patient(TEST_USER_ID).as_fhir())
     assert response.json['audits'][0]['context'] == 'other'
     assert response.json['audits'][0]['comment'] == 'just test data'
Esempio n. 2
0
 def test_staff_access(self):
     staff = self.add_user('*****@*****.**')
     self.promote_user(role_name=ROLE.PATIENT)
     self.promote_user(staff, role_name=ROLE.STAFF)
     self.shallow_org_tree()
     org = Organization.query.filter(Organization.id > 0).first()
     staff.organizations.append(org)
     self.test_user.organizations.append(org)
     audit = Audit(user_id=TEST_USER_ID,
                   subject_id=TEST_USER_ID,
                   comment='just test data')
     consent = UserConsent(user_id=TEST_USER_ID,
                           organization_id=org.id,
                           audit=audit,
                           agreement_url='http://fake.org')
     with SessionScope(db):
         db.session.add(audit)
         db.session.add(consent)
         db.session.commit()
     staff = db.session.merge(staff)
     self.login(staff.id)
     rv = self.client.get('/api/user/{}/audit'.format(TEST_USER_ID))
     self.assert200(rv)
     self.assertEquals(1, len(rv.json['audits']))
     self.assertEquals(
         rv.json['audits'][0]['by']['reference'],
         Reference.patient(TEST_USER_ID).as_fhir()['reference'])
     self.assertEquals(rv.json['audits'][0]['on'],
                       Reference.patient(TEST_USER_ID).as_fhir())
     self.assertEquals(rv.json['audits'][0]['context'], 'other')
     self.assertEquals(rv.json['audits'][0]['comment'], 'just test data')
Esempio n. 3
0
    def test_procedureGET(self):
        self.add_procedure()
        self.login()
        rv = self.client.get('/api/patient/%s/procedure' % TEST_USER_ID)

        data = json.loads(rv.data)
        self.assertEquals(
            '367336001',
            data['entry'][0]['resource']['code']['coding'][0]['code'])
        self.assertEquals(
            'Chemotherapy',
            data['entry'][0]['resource']['code']['coding'][0]['display'])
        self.assertEquals(
            Reference.patient(TEST_USER_ID).as_fhir()['reference'],
            data['entry'][0]['resource']['meta']['by']['reference'])
        last_updated = FHIR_datetime.parse(
            data['entry'][0]['resource']['meta']['lastUpdated'])
        self.assertAlmostEquals(datetime.utcnow(),
                                last_updated,
                                delta=timedelta(seconds=5))
        start_time = FHIR_datetime.parse(
            data['entry'][0]['resource']['performedPeriod']['start'])
        self.assertAlmostEquals(datetime.utcnow(),
                                start_time,
                                delta=timedelta(seconds=5))
        self.assertEquals(current_app.config.metadata.version,
                          data['entry'][0]['resource']['meta']['version'])
Esempio n. 4
0
    def test_clinicalPOST(self):
        data = {
            "resourceType": "Observation",
            "code": {
                "coding": [{
                    "system":
                    "http://loinc.org",
                    "code":
                    "28540-3",
                    "display":
                    "Erythrocyte mean corpuscular hemoglobin concentration [Mass/volume]"
                }]
            },
            "valueQuantity": {
                "value": 18.7,
                "units": "g/dl",
                "system": "http://unitsofmeasure.org",
                "code": "g/dl"
            },
            "status": "final",
            "issued": "2015-08-04T13:27:00+01:00",
            "performer": Reference.patient(TEST_USER_ID).as_fhir()
        }

        self.login()
        rv = self.client.post('/api/patient/%s/clinical' % TEST_USER_ID,
                              content_type='application/json',
                              data=json.dumps(data))
        self.assert200(rv)
        fhir = json.loads(rv.data)
        self.assertIn('28540-3', fhir['message'])
        self.assertEquals(self.test_user.observations.count(), 1)
        uo = UserObservation.query.filter_by(user_id=TEST_USER_ID).one()
        self.assertEquals(uo.encounter.auth_method, 'password_authenticated')
Esempio n. 5
0
 def prep_db_for_clinical(self):
     # First push some clinical data into the db for the test user
     with SessionScope(db):
         audit = Audit(user_id=TEST_USER_ID, subject_id=TEST_USER_ID)
         observation = Observation()
         coding = Coding(system='SNOMED-CT',
                         code='372278000',
                         display='Gleason score')
         cc = CodeableConcept(codings=[
             coding,
         ])
         observation.codeable_concept = cc
         observation.value_quantity = ValueQuantity(value=2)
         performer = Performer(reference_txt=json.dumps(
             Reference.patient(TEST_USER_ID).as_fhir()))
         observation.performers.append(performer)
         db.session.add(observation)
         enc = Encounter(status='planned',
                         auth_method='url_authenticated',
                         user_id=TEST_USER_ID,
                         start_time=datetime.utcnow())
         db.session.add(enc)
         db.session.flush()
         db.session.add(
             UserObservation(user_id=int(TEST_USER_ID),
                             observation_id=observation.id,
                             encounter_id=enc.id,
                             audit=audit))
         db.session.commit()
Esempio n. 6
0
    def test_deleted_search(self):
        second = self.add_user(username='******')
        second_id = second.id
        self.promote_user(user=second, role_name=ROLE.PATIENT.value)
        ident = Identifier(system='http://example.com', value='testy')
        ui = UserIdentifier(identifier=ident, user_id=TEST_USER_ID)
        ui2 = UserIdentifier(identifier=ident, user_id=second_id)
        with SessionScope(db):
            db.session.add(ident)
            db.session.add(ui)
            db.session.add(ui2)
            db.session.commit()
        self.promote_user(role_name=ROLE.PATIENT.value)
        self.promote_user(role_name=ROLE.ADMIN.value)  # skip org/staff steps

        # Mark second user as deleted - should therefore be excluded
        second = db.session.merge(second)
        second.deleted = Audit(
            user_id=second_id, subject_id=second_id, comment='deleted')
        with SessionScope(db):
            db.session.commit()

        self.login()
        ident = db.session.merge(ident)
        response = self.client.get('/api/patient/', query_string={
            'identifier': '{}|{}'.format(ident.system, ident.value),
            'patch_dstu2': True},
            follow_redirects=True)
        assert response.status_code == 200
        assert response.json['resourceType'] == 'Bundle'
        assert response.json['total'] == 1
        assert response.json['type'] == 'searchset'
        assert (
            response.json['entry'][0]['resource'] ==
            Reference.patient(TEST_USER_ID).as_fhir())
    def test_clinicalPOST(self):
        data = {
            "resourceType": "Observation",
            "code": {
                "coding": [{
                    "system": "http://loinc.org",
                    "code": "28540-3",
                    "display": ("Erythrocyte mean corpuscular hemoglobin "
                                "concentration [Mass/volume]")
                }]},
            "valueQuantity": {
                "value": 18.7,
                "units": "g/dl",
                "system": "http://unitsofmeasure.org",
                "code": "g/dl"
            },
            "status": "final",
            "issued": "2015-08-04T13:27:00+01:00",
            "performer": Reference.patient(TEST_USER_ID).as_fhir()
        }

        self.login()
        response = self.client.post(
            '/api/patient/%s/clinical' % TEST_USER_ID,
            content_type='application/json', data=json.dumps(data))
        assert response.status_code == 200
        fhir = response.json
        assert '28540-3' in fhir['message']
        assert self.test_user.observations.count() == 1
        uo = UserObservation.query.filter_by(user_id=TEST_USER_ID).one()
        assert uo.encounter.auth_method == 'password_authenticated'
 def test_questionnaire_parse(self):
     q = self.add_questionnaire('epiclife')
     ref = {
         'reference':
             'api/questionnaire/{0.value}?system={0.system}'.format(
                 q.identifiers[0])}
     parsed = Reference.parse(ref)
     assert q == parsed
Esempio n. 9
0
 def test_questionnaire_parse(self):
     q = self.add_questionnaire('epiclife')
     ref = {
         'reference':
         'api/questionnaire/{0.value}?system={0.system}'.format(
             q.identifiers[0])
     }
     parsed = Reference.parse(ref)
     assert q == parsed
 def test_user_org_get(self):
     self.bless_with_basics()
     self.test_user = db.session.merge(self.test_user)
     expected = [
         Reference.organization(o.id).as_fhir()
         for o in self.test_user.organizations]
     self.login()
     response = self.client.get('/api/user/{}/organization'.format(
         TEST_USER_ID))
     assert response.status_code == 200
     assert response.json['organizations'] == expected
Esempio n. 11
0
 def test_user_org_get(self):
     self.bless_with_basics()
     self.test_user = db.session.merge(self.test_user)
     expected = [
         Reference.organization(o.id).as_fhir()
         for o in self.test_user.organizations
     ]
     self.login()
     response = self.client.get(
         '/api/user/{}/organization'.format(TEST_USER_ID))
     assert response.status_code == 200
     assert response.json['organizations'] == expected
Esempio n. 12
0
    def test_get(self):
        audit = Audit(
            user_id=TEST_USER_ID, subject_id=TEST_USER_ID,
            comment='just test data')
        with SessionScope(db):
            db.session.add(audit)
            db.session.commit()

        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()
        response = self.client.get('/api/user/{}/audit'.format(TEST_USER_ID))
        assert response.status_code == 200
        assert 1 == len(response.json['audits'])
        assert (response.json['audits'][0]['by']['reference'] ==
                Reference.patient(TEST_USER_ID).as_fhir()['reference'])
        assert (response.json['audits'][0]['by']['display'] ==
                ' '.join((FIRST_NAME, LAST_NAME)))
        assert (response.json['audits'][0]['on'] ==
                Reference.patient(TEST_USER_ID).as_fhir())
        assert response.json['audits'][0]['context'] == 'other'
        assert response.json['audits'][0]['comment'] == 'just test data'
Esempio n. 13
0
    def test_get(self):
        audit = Audit(user_id=TEST_USER_ID,
                      subject_id=TEST_USER_ID,
                      comment='just test data')
        with SessionScope(db):
            db.session.add(audit)
            db.session.commit()

        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()
        response = self.client.get('/api/user/{}/audit'.format(TEST_USER_ID))
        assert response.status_code == 200
        assert 1 == len(response.json['audits'])
        assert (response.json['audits'][0]['by']['reference'] ==
                Reference.patient(TEST_USER_ID).as_fhir()['reference'])
        assert (response.json['audits'][0]['by']['display'] == ' '.join(
            (FIRST_NAME, LAST_NAME)))
        assert (response.json['audits'][0]['on'] == Reference.patient(
            TEST_USER_ID).as_fhir())
        assert response.json['audits'][0]['context'] == 'other'
        assert response.json['audits'][0]['comment'] == 'just test data'
Esempio n. 14
0
    def test_get(self):
        audit = Audit(user_id=TEST_USER_ID,
                      subject_id=TEST_USER_ID,
                      comment='just test data')
        with SessionScope(db):
            db.session.add(audit)
            db.session.commit()

        self.promote_user(role_name=ROLE.ADMIN)
        self.login()
        rv = self.client.get('/api/user/{}/audit'.format(TEST_USER_ID))
        self.assert200(rv)
        self.assertEquals(1, len(rv.json['audits']))
        self.assertEquals(
            rv.json['audits'][0]['by']['reference'],
            Reference.patient(TEST_USER_ID).as_fhir()['reference'])
        self.assertEquals(rv.json['audits'][0]['by']['display'], 'First Last')
        self.assertEquals(rv.json['audits'][0]['on'],
                          Reference.patient(TEST_USER_ID).as_fhir())
        self.assertEquals(rv.json['audits'][0]['context'], 'other')
        self.assertEquals(rv.json['audits'][0]['comment'], 'just test data')
Esempio n. 15
0
 def test_email_search(self):
     self.promote_user(role_name=ROLE.PATIENT.value)
     self.login()
     response = self.client.get(
         '/api/patient/', follow_redirects=True,
         query_string={'email': TEST_USERNAME, 'patch_dstu2': True})
     # Known patient should return bundle of one
     assert response.status_code == 200
     assert response.json['resourceType'] == 'Bundle'
     assert response.json['total'] == 1
     assert (
         response.json['entry'][0]['resource'] ==
         Reference.patient(TEST_USER_ID).as_fhir())
Esempio n. 16
0
 def test_email_search(self):
     self.promote_user(role_name=ROLE.PATIENT.value)
     self.login()
     response = self.client.get('/api/patient/',
                                follow_redirects=True,
                                query_string={
                                    'email': TEST_USERNAME,
                                    'patch_dstu2': True
                                })
     # Known patient should return bundle of one
     assert response.status_code == 200
     assert response.json['resourceType'] == 'Bundle'
     assert response.json['total'] == 1
     assert (response.json['entry'][0]['resource'] == Reference.patient(
         TEST_USER_ID).as_fhir())
Esempio n. 17
0
    def test_dstu2GET(self):
        self.prep_db_for_clinical()
        self.login()
        response = self.client.get(
            '/api/patient/%s/clinical' % TEST_USER_ID,
            query_string={'patch_dstu2': True})

        clinical_data = response.json
        assert len(clinical_data['entry']) == 1
        assert 'resource' in clinical_data['entry'][0]
        assert ('Gleason score' ==
                clinical_data['entry'][0]['resource']['code']['coding'][0][
                   'display'])
        assert ('2' == clinical_data['entry'][0][
            'resource']['valueQuantity']['value'])
        assert (json.dumps(Reference.patient(TEST_USER_ID).as_fhir())
                == clinical_data['entry'][0]['resource']['performer'][0])
Esempio n. 18
0
    def test_clinicalGET(self):
        self.prep_db_for_clinical()
        self.login()
        response = self.client.get('/api/patient/%s/clinical' % TEST_USER_ID)

        clinical_data = response.json
        assert ('Gleason score' ==
                clinical_data['entry'][0]['content']['code']['coding'][0][
                   'display'])
        assert ('2' ==
                clinical_data['entry'][0]['content']['valueQuantity']['value'])
        assert (json.dumps(Reference.patient(TEST_USER_ID).as_fhir())
                == clinical_data['entry'][0]['content']['performer'][0])
        found = parser.parse(clinical_data['entry'][0]['updated'])
        found = found.replace(tzinfo=None)
        self.assertAlmostEqual(datetime.utcnow(), found,
                               delta=timedelta(seconds=5))
Esempio n. 19
0
    def test_clinicalGET(self):
        self.prep_db_for_clinical()
        self.login()
        response = self.client.get('/api/patient/%s/clinical' % TEST_USER_ID)

        clinical_data = response.json
        assert \
            'Gleason score' == \
            clinical_data\
                ['entry'][0]['content']['code']['coding'][0]['display']
        assert '2' == \
               clinical_data['entry'][0]['content']['valueQuantity']['value']
        assert json.dumps(Reference.patient(TEST_USER_ID).as_fhir())\
            == clinical_data['entry'][0]['content']['performer'][0]
        found = parser.parse(clinical_data['entry'][0]['updated'])
        found = found.replace(tzinfo=None)
        self.assertAlmostEqual(datetime.utcnow(),
                               found,
                               delta=timedelta(seconds=5))
Esempio n. 20
0
 def test_ident_pipe_search(self):
     ident = Identifier(system='http://example.com', value='testy')
     ui = UserIdentifier(identifier=ident, user_id=TEST_USER_ID)
     with SessionScope(db):
         db.session.add(ident)
         db.session.add(ui)
         db.session.commit()
     self.promote_user(role_name=ROLE.PATIENT.value)
     self.login()
     ident = db.session.merge(ident)
     response = self.client.get('/api/patient/', query_string={
         'identifier': '{}|{}'.format(ident.system, ident.value),
         'patch_dstu2': True},
         follow_redirects=True)
     assert response.status_code == 200
     assert response.json['resourceType'] == 'Bundle'
     assert response.json['total'] == 1
     assert (
         response.json['entry'][0]['resource'] ==
         Reference.patient(TEST_USER_ID).as_fhir())
Esempio n. 21
0
    def test_deleted_search(self):
        second = self.add_user(username='******')
        second_id = second.id
        self.promote_user(user=second, role_name=ROLE.PATIENT.value)
        ident = Identifier(system='http://example.com', value='testy')
        ui = UserIdentifier(identifier=ident, user_id=TEST_USER_ID)
        ui2 = UserIdentifier(identifier=ident, user_id=second_id)
        with SessionScope(db):
            db.session.add(ident)
            db.session.add(ui)
            db.session.add(ui2)
            db.session.commit()
        self.promote_user(role_name=ROLE.PATIENT.value)
        self.promote_user(role_name=ROLE.ADMIN.value)  # skip org/staff steps

        # Mark second user as deleted - should therefore be excluded
        second = db.session.merge(second)
        second.deleted = Audit(user_id=second_id,
                               subject_id=second_id,
                               comment='deleted')
        with SessionScope(db):
            db.session.commit()

        self.login()
        ident = db.session.merge(ident)
        response = self.client.get('/api/patient/',
                                   query_string={
                                       'identifier':
                                       '{}|{}'.format(ident.system,
                                                      ident.value),
                                       'patch_dstu2':
                                       True
                                   },
                                   follow_redirects=True)
        assert response.status_code == 200
        assert response.json['resourceType'] == 'Bundle'
        assert response.json['total'] == 1
        assert response.json['type'] == 'searchset'
        assert (response.json['entry'][0]['resource'] == Reference.patient(
            TEST_USER_ID).as_fhir())
Esempio n. 22
0
 def prep_db_for_clinical(self):
     # First push some clinical data into the db for the test user
     with SessionScope(db):
         audit = Audit(user_id=TEST_USER_ID, subject_id=TEST_USER_ID)
         observation = Observation()
         coding = Coding(system='SNOMED-CT', code='372278000',
                         display='Gleason score')
         self.gleason_concept = CodeableConcept(codings=[coding, ])
         observation.codeable_concept = self.gleason_concept
         observation.value_quantity = ValueQuantity(value=2)
         performer = Performer(reference_txt=json.dumps(
             Reference.patient(TEST_USER_ID).as_fhir()))
         observation.performers.append(performer)
         db.session.add(observation)
         enc = Encounter(status='planned', auth_method='url_authenticated',
                         user_id=TEST_USER_ID, start_time=datetime.utcnow())
         db.session.add(enc)
         db.session.flush()
         db.session.add(UserObservation(user_id=int(TEST_USER_ID),
                                        observation_id=observation.id,
                                        encounter_id=enc.id, audit=audit))
         db.session.commit()
Esempio n. 23
0
    def test_procedureGET(self):
        self.add_procedure()
        self.login()
        response = self.client.get('/api/patient/%s/procedure' % TEST_USER_ID)

        data = response.json
        assert ('367336001'
                == data['entry'][0]['resource']['code']['coding'][0]['code'])
        assert ('Chemotherapy' ==
                data['entry'][0]['resource']['code']['coding'][0]['display'])
        assert (Reference.patient(TEST_USER_ID).as_fhir()['reference']
                == data['entry'][0]['resource']['meta']['by']['reference'])
        last_updated = FHIR_datetime.parse(
            data['entry'][0]['resource']['meta']['lastUpdated'])
        self.assertAlmostEqual(
            datetime.utcnow(), last_updated, delta=timedelta(seconds=5))
        start_time = FHIR_datetime.parse(
            data['entry'][0]['resource']['performedPeriod']['start'])
        self.assertAlmostEqual(
            datetime.utcnow(), start_time, delta=timedelta(seconds=5))
        assert (current_app.config.metadata['version']
                == data['entry'][0]['resource']['meta']['version'])
Esempio n. 24
0
 def test_ident_search(self):
     ident = Identifier(system='http://example.com', value='testy')
     ui = UserIdentifier(identifier=ident, user_id=TEST_USER_ID)
     with SessionScope(db):
         db.session.add(ident)
         db.session.add(ui)
         db.session.commit()
     self.promote_user(role_name=ROLE.PATIENT.value)
     self.login()
     ident = db.session.merge(ident)
     response = self.client.get('/api/patient/',
                                follow_redirects=True,
                                query_string={
                                    'identifier':
                                    json.dumps(ident.as_fhir()),
                                    'patch_dstu2': True
                                })
     assert response.status_code == 200
     assert response.json['resourceType'] == 'Bundle'
     assert response.json['total'] == 1
     assert (response.json['entry'][0]['resource'] == Reference.patient(
         TEST_USER_ID).as_fhir())
Esempio n. 25
0
 def test_patient(self):
     patient = Reference.patient(TEST_USER_ID)
     self.assertEquals(patient.as_fhir()['display'],
                       self.test_user.display_name)
Esempio n. 26
0
 def test_questionnaire_bank(self):
     q = QuestionnaireBank(name='testy')
     q_ref = Reference.questionnaire_bank(q.name)
     self.assertEquals(q_ref.as_fhir()['display'], 'testy')
Esempio n. 27
0
 def test_questionnaire(self):
     q = self.add_questionnaire('epic1000')
     q_ref = Reference.questionnaire(q.name)
     assert q_ref.as_fhir()['display'] == 'epic1000'
Esempio n. 28
0
 def test_org_w_identifier(self):
     o = self.prep_org_w_identifier()
     o_ref = Reference.organization(o.id)
     assert o_ref.as_fhir()['display'] == 'test org'
     assert (o_ref.as_fhir()['reference']
             == 'api/organization/{}'.format(o.id))
Esempio n. 29
0
 def test_patient(self):
     patient = Reference.patient(TEST_USER_ID)
     assert patient.as_fhir()['display'] == self.test_user.display_name
Esempio n. 30
0
 def test_intervention_parse(self):
     ref = {'reference': 'api/intervention/self_management'}
     i = Reference.parse(ref)
     self.assertEqual(i.name, 'self_management')
Esempio n. 31
0
 def test_practitioner_parse(self):
     p = self.add_practitioner()
     ref = {'reference': 'api/practitioner/12345?system={}'.format(US_NPI)}
     parsed = Reference.parse(ref)
     assert p == parsed
Esempio n. 32
0
 def test_intervention_parse(self):
     ref = {'reference': 'api/intervention/self_management'}
     i = Reference.parse(ref)
     assert i.name == 'self_management'
Esempio n. 33
0
 def test_questionnaire_bank(self):
     q = QuestionnaireBank(name='testy')
     q_ref = Reference.questionnaire_bank(q.name)
     assert q_ref.as_fhir()['display'] == 'testy'
Esempio n. 34
0
 def test_patient(self):
     patient = Reference.patient(TEST_USER_ID)
     assert patient.as_fhir()['display'] == self.test_user.display_name
Esempio n. 35
0
    def test_demographicsPUT(self):
        # race / ethnicity require the SLOW addition of concepts to db
        self.add_concepts()

        # clinic reference requires pre-existing organization
        self.shallow_org_tree()
        (org_id, org_name), (org2_id, org2_name) = [
            (org.id, org.name)
            for org in Organization.query.filter(Organization.id > 0).limit(2)
        ]

        pract = self.add_practitioner(first_name='Indiana', last_name='Jones')
        pract_id = pract.id

        family = 'User'
        given = 'Test'
        dob = '1999-01-31'
        dod = '2027-12-31T09:10:00+00:00'
        gender = 'Male'
        phone = "867-5309"
        alt_phone = "555-5555"
        data = {
            "name": {
                "family": family,
                "given": given
            },
            "resourceType":
            "Patient",
            "birthDate":
            dob,
            "deceasedDateTime":
            dod,
            "gender":
            gender,
            "telecom": [{
                "system": "phone",
                "use": "mobile",
                "value": phone,
            }, {
                "system": "phone",
                "use": "home",
                "value": alt_phone,
            }, {
                "system": 'email',
                'value': '__no_email__'
            }],
            "extension": [{
                "url": "http://hl7.org/fhir/StructureDefinition/us-core-race",
                "valueCodeableConcept": {
                    "coding": [{
                        "system": "http://hl7.org/fhir/v3/Race",
                        "code": "1096-7"
                    }]
                }
            }, {
                "url":
                "http://hl7.org/fhir/StructureDefinition/us-core-"
                "ethnicity",
                "valueCodeableConcept": {
                    "coding": [{
                        "system": "http://hl7.org/fhir/v3/Ethnicity",
                        "code": "2162-6"
                    }]
                }
            }],
            "careProvider": [
                {
                    "reference": "Organization/{}".format(org_id)
                },
                {
                    "reference": "api/organization/{}".format(org2_id)
                },
                {
                    "reference": "Practitioner/{}".format(pract_id)
                },
            ]
        }

        self.login()
        response = self.client.put('/api/demographics/%s' % TEST_USER_ID,
                                   content_type='application/json',
                                   data=json.dumps(data))

        assert response.status_code == 200
        fhir = response.json
        for item in fhir['telecom']:
            if item['system'] == 'phone':
                if item['use'] == 'home':
                    assert alt_phone == item['value']
                elif item['use'] == 'mobile':
                    assert phone == item['value']
                else:
                    self.fail('unexpected telecom use: {}'.format(item['use']))
            else:
                self.fail('unexpected telecom system: {}'.format(
                    item['system']))
        assert fhir['birthDate'] == dob
        assert fhir['deceasedDateTime'] == dod
        assert fhir['gender'] == gender.lower()
        assert fhir['name']['family'] == family
        assert fhir['name']['given'] == given
        # ignore added timezone and empty extensions
        assert 2 == len([
            ext for ext in fhir['extension'] if 'valueCodeableConcept' in ext
        ])
        assert 3 == len(fhir['careProvider'])
        assert (Reference.practitioner(pract_id).as_fhir()
                in fhir['careProvider'])

        user = db.session.merge(self.test_user)
        assert user._email.startswith('__no_email__')
        assert user.email is None
        assert user.first_name == given
        assert user.last_name == family
        assert ['2162-6'] == [c.code for c in user.ethnicities]
        assert ['1096-7'] == [c.code for c in user.races]
        assert len(user.organizations) == 2
        assert user.organizations[0].name == org_name
        assert user.organizations[1].name == org2_name
        assert user.practitioner_id == pract_id
Esempio n. 36
0
 def test_intervention(self):
     i = Intervention.query.filter_by(name='self_management').one()
     i_ref = Reference.intervention(i.id)
     assert i_ref.as_fhir()['display'] == 'self_management'
     assert (
         i_ref.as_fhir()['reference'] == 'api/intervention/self_management')
    def test_demographicsPUT(self):
        # race / ethnicity require the SLOW addition of concepts to db
        self.add_concepts()

        # clinic reference requires pre-existing organization
        self.shallow_org_tree()
        (org_id, org_name), (org2_id, org2_name) = [
            (org.id, org.name) for org in Organization.query.filter(
                Organization.id > 0).limit(2)]

        pract = self.add_practitioner(first_name='Indiana', last_name='Jones')
        pract_id = pract.id

        family = 'User'
        given = 'Test'
        dob = '1999-01-31'
        dod = '2027-12-31T09:10:00+00:00'
        gender = 'Male'
        phone = "867-5309"
        alt_phone = "555-5555"
        data = {"name": {"family": family, "given": given},
                "resourceType": "Patient",
                "birthDate": dob,
                "deceasedDateTime": dod,
                "gender": gender,
                "telecom": [
                    {
                        "system": "phone",
                        "use": "mobile",
                        "value": phone,
                    }, {
                        "system": "phone",
                        "use": "home",
                        "value": alt_phone,
                    }, {
                        "system": 'email',
                        'value': '__no_email__'
                    }],
                "extension": [{
                    "url":
                        "http://hl7.org/fhir/StructureDefinition/us-core-race",
                    "valueCodeableConcept": {
                        "coding": [{
                            "system": "http://hl7.org/fhir/v3/Race",
                            "code": "1096-7"}]}},
                    {"url":
                        "http://hl7.org/fhir/StructureDefinition/us-core-"
                        "ethnicity",
                     "valueCodeableConcept": {
                         "coding": [{
                             "system": "http://hl7.org/fhir/v3/Ethnicity",
                             "code": "2162-6"}]}}
                ],
                "careProvider": [
                    {"reference": "Organization/{}".format(org_id)},
                    {"reference": "api/organization/{}".format(org2_id)},
                    {"reference": "Practitioner/{}".format(pract_id)},
                ]
                }

        self.login()
        response = self.client.put(
            '/api/demographics/%s' % TEST_USER_ID,
            content_type='application/json',
            data=json.dumps(data))

        assert response.status_code == 200
        fhir = response.json
        for item in fhir['telecom']:
            if item['system'] == 'phone':
                if item['use'] == 'home':
                    assert alt_phone == item['value']
                elif item['use'] == 'mobile':
                    assert phone == item['value']
                else:
                    self.fail(
                        'unexpected telecom use: {}'.format(item['use']))
            else:
                self.fail(
                    'unexpected telecom system: {}'.format(item['system']))
        assert fhir['birthDate'] == dob
        assert fhir['deceasedDateTime'] == dod
        assert fhir['gender'] == gender.lower()
        assert fhir['name']['family'] == family
        assert fhir['name']['given'] == given
        # ignore added timezone and empty extensions
        assert 2 == len([ext for ext in fhir['extension']
                         if 'valueCodeableConcept' in ext])
        assert 3 == len(fhir['careProvider'])
        assert (
            Reference.practitioner(pract_id).as_fhir() in fhir['careProvider'])

        user = db.session.merge(self.test_user)
        assert user._email.startswith('__no_email__')
        assert user.email is None
        assert user.first_name == given
        assert user.last_name == family
        assert ['2162-6'] == [c.code for c in user.ethnicities]
        assert ['1096-7'] == [c.code for c in user.races]
        assert len(user.organizations) == 2
        assert user.organizations[0].name == org_name
        assert user.organizations[1].name == org2_name
        assert user.practitioner_id == pract_id
Esempio n. 38
0
 def test_intervention_parse(self):
     ref = {'reference': 'api/intervention/self_management'}
     i = Reference.parse(ref)
     assert i.name == 'self_management'
Esempio n. 39
0
 def test_organization(self):
     org = Reference.organization(0)
     assert org.as_fhir()['display'] == 'none of the above'
Esempio n. 40
0
 def test_practioner(self):
     p = self.add_practitioner()
     p_ref = Reference.practitioner(p.id)
     assert p_ref.as_fhir()['display'] == 'first last'
     assert (p_ref.as_fhir()['reference'] ==
             'api/practitioner/12345?system={}'.format(US_NPI))
Esempio n. 41
0
 def test_org_w_identifier_parse(self):
     o = self.prep_org_w_identifier()
     ref = {'reference': 'api/organization/123-45?system={}'.format(US_NPI)}
     parsed = Reference.parse(ref)
     assert o == parsed
Esempio n. 42
0
 def test_practitioner_parse(self):
     p = self.add_practitioner()
     ref = {'reference': 'api/practitioner/12345?system={}'.format(US_NPI)}
     parsed = Reference.parse(ref)
     assert p == parsed
Esempio n. 43
0
 def test_organization(self):
     org = Reference.organization(0)
     assert org.as_fhir()['display'] == 'none of the above'
Esempio n. 44
0
 def test_organization(self):
     org = Reference.organization(0)
     self.assertEquals(org.as_fhir()['display'], 'none of the above')
Esempio n. 45
0
 def test_intervention(self):
     i = Intervention.query.filter_by(name='self_management').one()
     i_ref = Reference.intervention(i.id)
     assert i_ref.as_fhir()['display'] == 'self_management'
     assert (i_ref.as_fhir()['reference']
             == 'api/intervention/self_management')
Esempio n. 46
0
 def test_org_w_identifier(self):
     o = self.prep_org_w_identifier()
     o_ref = Reference.organization(o.id)
     assert o_ref.as_fhir()['display'] == 'test org'
     assert (o_ref.as_fhir()['reference'] == 'api/organization/{}'.format(
         o.id))
Esempio n. 47
0
 def test_practioner(self):
     p = self.add_practitioner()
     p_ref = Reference.practitioner(p.id)
     assert p_ref.as_fhir()['display'] == 'first last'
     assert (p_ref.as_fhir()['reference']
             == 'api/practitioner/12345?system={}'.format(US_NPI))
Esempio n. 48
0
 def test_org_w_identifier_parse(self):
     o = self.prep_org_w_identifier()
     ref = {'reference': 'api/organization/123-45?system={}'.format(US_NPI)}
     parsed = Reference.parse(ref)
     assert o == parsed
Esempio n. 49
0
    def test_permanently_delete_user(self):
        # created acting user and to-be-deleted user
        actor = self.add_user('actor')
        deleted = self.add_user('deleted')
        deleted, actor = map(db.session.merge, (deleted, actor))
        deleted_id, actor_id = deleted.id, actor.id
        deleted_email, actor_email = deleted.email, actor.email
        self.promote_user(user=actor, role_name=ROLE.ADMIN)
        with SessionScope(db):
            db.session.commit()
        deleted = db.session.merge(deleted)

        # create observation and user_observation
        audit = Audit(user_id=TEST_USER_ID, subject_id=TEST_USER_ID)
        observation = Observation()
        coding = Coding(system='SNOMED-CT', code='372278000',
                        display='Gleason score')
        cc = CodeableConcept(codings=[coding, ])
        observation.codeable_concept = cc
        observation.value_quantity = ValueQuantity(value=2)
        performer = Performer(reference_txt=json.dumps(
            Reference.patient(TEST_USER_ID).as_fhir()))
        observation.performers.append(performer)
        enc = Encounter(status='planned', auth_method='url_authenticated',
                        user_id=TEST_USER_ID, start_time=datetime.utcnow())
        with SessionScope(db):
            db.session.add(observation)
            db.session.add(enc)
            db.session.commit()
        observation, enc = map(db.session.merge, (observation, enc))
        observation_id, enc_id = observation.id, enc.id
        user_obs = UserObservation(user_id=deleted_id, audit=audit,
                                   observation_id=observation_id,
                                   encounter_id=enc_id)
        with SessionScope(db):
            db.session.add(user_obs)
            db.session.commit()
        user_obs = db.session.merge(user_obs)
        user_obs_id = user_obs.id

        # create user and subject audits
        subj_audit = Audit(user_id=TEST_USER_ID, subject_id=deleted_id)
        user_audit = Audit(user_id=deleted_id, subject_id=TEST_USER_ID)
        with SessionScope(db):
            db.session.add(subj_audit)
            db.session.add(user_audit)
            db.session.commit()
        subj_audit, user_audit = map(db.session.merge,
                                     (subj_audit, user_audit))
        subj_audit_id, user_audit_id = subj_audit.id, user_audit.id

        # create user_consent and audit
        consent_org = Organization(name='test org')
        consent_audit = Audit(user_id=TEST_USER_ID, subject_id=TEST_USER_ID)
        with SessionScope(db):
            db.session.add(consent_org)
            db.session.add(consent_audit)
            db.session.commit()
            db.session.add(UserConsent(
                                user_id=deleted_id,
                                organization_id=consent_org.id,
                                audit=consent_audit,
                                agreement_url='http://example.org',
                                options=STAFF_EDITABLE_MASK))
            db.session.commit()
        consent_org, consent_audit = map(db.session.merge,
                                         (consent_org, consent_audit))
        co_id, ca_id = consent_org.id, consent_audit.id

        # permanently deleted user, check deletion cascades
        permanently_delete_user(deleted_email, actor=actor_email)
        self.assertFalse(User.query.get(deleted_id))
        self.assertFalse(UserObservation.query.get(user_obs_id))
        self.assertTrue(Observation.query.get(observation_id))
        self.assertFalse(Audit.query.get(subj_audit_id))
        self.assertFalse(Audit.query.get(user_audit_id))
        self.assertFalse(UserConsent.query.get(co_id))
        self.assertFalse(Audit.query.get(ca_id))
Esempio n. 50
0
 def test_questionnaire(self):
     q = self.add_questionnaire('epic1000')
     q_ref = Reference.questionnaire(q.name)
     assert q_ref.as_fhir()['display'] == 'epic1000'