def test_duplicate_identifier(self):
        swagger_spec = swagger(self.app)
        identifier = Identifier(system='https://unique.org', value='abc123')
        data = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data['identifier'] = identifier.as_fhir()

        self.promote_user(role_name=ROLE.PATIENT.value)
        self.login()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data)
        assert response.status_code == 200

        # Submit a second, with the same identifier, expect error
        data2 = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data2['identifier'] = identifier.as_fhir()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data2)
        assert response.status_code == 409
        self.test_user = db.session.merge(self.test_user)
        assert self.test_user.questionnaire_responses.count() == 1

        # And a third, with just the id.value changed
        data3 = swagger_spec['definitions']['QuestionnaireResponse']['example']
        identifier.value = 'do-over'
        data3['identifier'] = identifier.as_fhir()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data3)
        assert response.status_code == 200
        self.test_user = db.session.merge(self.test_user)
        assert self.test_user.questionnaire_responses.count() == 2
    def test_organization_identifiers_update(self):
        with open(os.path.join(
            os.path.dirname(__file__),
            'organization-example-gastro.json'), 'r'
        ) as fhir_data:
            data = json.load(fhir_data)
        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()
        before = Organization.query.count()
        response = self.client.post(
            '/api/organization', content_type='application/json',
            data=json.dumps(data))
        assert response.status_code == 200
        assert Organization.query.count() == before + 1

        # the gastro file contains a single identifier - add
        # a second one and PUT, expecting we get two total

        alias = Identifier(system=SHORTCUT_ALIAS, value='foobar',
                           use='secondary')
        org = Organization.query.filter_by(name='Gastroenterology').one()
        data['identifier'].append(alias.as_fhir())
        response = self.client.put(
            '/api/organization/{}'.format(org.id),
            content_type='application/json', data=json.dumps(data))
        assert response.status_code == 200

        # obtain the org from the db, check the identifiers
        org = Organization.query.filter_by(name='Gastroenterology').one()
        assert 2 == org.identifiers.count()
Example #3
0
 def test_questionnaire_serialize(self):
     q1 = self.add_questionnaire(name='q1')
     data = q1.as_fhir()
     assert data['resourceType'] == "Questionnaire"
     expected = Identifier(system=TRUENTH_QUESTIONNAIRE_CODE_SYSTEM,
                           value='q1')
     assert Identifier.from_fhir(data['identifier'][0]) == expected
    def test_organization_identifiers_update(self):
        with open(
                os.path.join(os.path.dirname(__file__),
                             'organization-example-gastro.json'),
                'r') as fhir_data:
            data = json.load(fhir_data)
        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()
        before = Organization.query.count()
        response = self.client.post('/api/organization',
                                    content_type='application/json',
                                    data=json.dumps(data))
        assert response.status_code == 200
        assert Organization.query.count() == before + 1

        # the gastro file contains a single identifier - add
        # a second one and PUT, expecting we get two total

        alias = Identifier(system=SHORTCUT_ALIAS,
                           value='foobar',
                           use='secondary')
        org = Organization.query.filter_by(name='Gastroenterology').one()
        data['identifier'].append(alias.as_fhir())
        response = self.client.put('/api/organization/{}'.format(org.id),
                                   content_type='application/json',
                                   data=json.dumps(data))
        assert response.status_code == 200

        # obtain the org from the db, check the identifiers
        org = Organization.query.filter_by(name='Gastroenterology').one()
        assert 2 == org.identifiers.count()
    def test_invalid_identifier(self):
        swagger_spec = swagger(self.app)
        identifier = Identifier(system=None, value='abc-123')
        data = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data['identifier'] = identifier.as_fhir()

        self.promote_user(role_name=ROLE.PATIENT.value)
        self.login()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data)
        assert response.status_code == 400
Example #6
0
    def test_invalid_identifier(self):
        swagger_spec = swagger(self.app)
        identifier = Identifier(system=None, value='abc-123')
        data = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data['identifier'] = identifier.as_fhir()

        self.promote_user(role_name=ROLE.PATIENT.value)
        self.login()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data)
        assert response.status_code == 400
 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)
     self.login()
     ident = db.session.merge(ident)
     rv = self.client.get('/api/patient?identifier={}'.format(
         json.dumps(ident.as_fhir())),
                          follow_redirects=True)
     self.assert200(rv)
 def test_ident_nomatch_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)
     self.login()
     ident = db.session.merge(ident)
     # modify the system to mis match
     id_str = json.dumps(ident.as_fhir()).replace("example.com",
                                                  "wrong-system.com")
     rv = self.client.get('/api/patient?identifier={}'.format(id_str),
                          follow_redirects=True)
     self.assert404(rv)
Example #9
0
 def test_multimatch_search_old_format(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
     self.login()
     ident = db.session.merge(ident)
     response = self.client.get('/api/patient/',
                                query_string={
                                    'identifier':
                                    '{}|{}'.format(ident.system,
                                                   ident.value)
                                },
                                follow_redirects=True)
     # Multi not supported in old format
     assert response.status_code == 400
Example #10
0
 def test_multimatch_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
     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'] == 2
     assert response.json['type'] == 'searchset'
    def test_identifier_lookup(self):
        # setup a minimal communication request
        from tests.test_communication import mock_communication_request
        from tests.test_assessment_status import mock_tnth_questionnairebanks
        from portal.system_uri import TRUENTH_CR_NAME
        from portal.models.identifier import Identifier
        mock_tnth_questionnairebanks()
        cr = mock_communication_request(
            'symptom_tracker_recurring', '{"days": 14}')
        cr.identifiers.append(
            Identifier(value='2 week ST', system=TRUENTH_CR_NAME))
        with SessionScope(db):
            db.session.add(cr)
            db.session.commit()
        cr = db.session.merge(cr)
        assert cr.identifiers.count() == 1

        data = cr.as_fhir()
        mp = ModelPersistence(
            CommunicationRequest,
            sequence_name='communication_requests_id_seq',
            lookup_field='identifier')
        new_obj = CommunicationRequest.from_fhir(data)
        match, field_description = mp.lookup_existing(
            new_obj=new_obj, new_data=data)
        assert match.name == cr.name
    def test_organization_get_by_identifier(self):
        org_id_system = "http://test/system"
        org_id_value = "testval"
        self.login()
        org = Organization(name='test', id=999)
        ident = Identifier(id=99, system=org_id_system, value=org_id_value)
        org_ident = OrganizationIdentifier(organization_id=999,
                                           identifier_id=99)
        with SessionScope(db):
            db.session.add(org)
            db.session.add(ident)
            db.session.commit()
            db.session.add(org_ident)
            db.session.commit()

        # use api to obtain FHIR
        response = self.client.get(
            '/api/organization?system={system}&value={value}'.format(
                system=quote_plus(org_id_system), value=org_id_value))
        assert response.status_code == 200
        assert response.json['total'] == 1
        assert response.json['entry'][0]['id'] == 999

        # use alternative API to obtain organization
        response = self.client.get(
            '/api/organization/{value}?system={system}'.format(
                system=quote_plus(org_id_system), value=org_id_value))
        assert response.status_code == 200
        fetched = Organization.from_fhir(response.json)
        org = db.session.merge(org)
        assert org.id == fetched.id
        assert org.name == fetched.name
    def test_organization_inheritence_search(self):
        # Region at top should apply to leaves
        self.deepen_org_tree()
        count = Organization.query.count()
        assert count > 3

        # add region to one mid-level parent org with two children,
        # we should get only those three
        region = Identifier(value='state:NY', system=PRACTICE_REGION)
        with SessionScope(db):
            db.session.add(region)
            db.session.commit()
        region = db.session.merge(region)
        oi = OrganizationIdentifier(organization_id=1002,
                                    identifier_id=region.id)
        with SessionScope(db):
            db.session.add(oi)
            db.session.commit()

        # use api to obtain FHIR bundle
        self.login()
        response = self.client.get('/api/organization?state=NY')
        assert response.status_code == 200
        bundle = response.json
        assert bundle['resourceType'] == 'Bundle'
        assert len(bundle['entry']) == 3

        # add filter to restrict to just the leaves
        response = self.client.get('/api/organization?state=NY&filter=leaves')
        assert response.status_code == 200
        bundle = response.json
        assert bundle['resourceType'] == 'Bundle'
        assert len(bundle['entry']) == 2
 def test_questionnaire_serialize(self):
     q1 = self.add_questionnaire(name='q1')
     data = q1.as_fhir()
     assert data['resourceType'] == "Questionnaire"
     expected = Identifier(
         system=TRUENTH_QUESTIONNAIRE_CODE_SYSTEM, value='q1')
     assert Identifier.from_fhir(data['identifier'][0]) == expected
    def test_organization_extension_update(self):
        # confirm clearing one of several extensions works
        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()

        en_AU = LocaleConstants().AustralianEnglish

        # Populate db with complete org, and set many fields
        org = Organization(name='test',
                           phone='800-800-5665',
                           timezone='US/Pacific')
        org.identifiers.append(
            Identifier(value='state:NY', system=PRACTICE_REGION))
        org.locales.append(en_AU)
        org.default_locale = 'en_AU'
        rp = ResearchProtocol(name='rp1')

        with SessionScope(db):
            db.session.add(rp)
            db.session.add(org)
            db.session.commit()
        org, rp = map(db.session.merge, (org, rp))
        org_id, rp_id = org.id, rp.id
        org.research_protocols.append(rp)
        data = org.as_fhir()
        input = {
            k: v
            for k, v in data.items() if k in ('name', 'resourceType')
        }

        # Replace locale extension with null value, copy
        # over others.
        input['extension'] = [
            e for e in data['extension']
            if e['url'] != LocaleExtension.extension_url
        ]
        input['extension'].append({'url': LocaleExtension.extension_url})

        response = self.client.put('/api/organization/{}'.format(org_id),
                                   content_type='application/json',
                                   data=json.dumps(input))
        assert response.status_code == 200

        # Pull the updated db entry
        org = Organization.query.get(org_id)
        en_AU = db.session.merge(en_AU)

        # Confirm all the unmentioned entries survived
        assert org.phone == '800-800-5665'
        assert org.default_locale == 'en_AU'
        assert org.locales.count() == 0
        assert org.timezone == 'US/Pacific'
        assert org.research_protocol(as_of_date=datetime.utcnow()).id == rp_id

        # Confirm empty extension isn't included in result
        results = response.json
        for e in results['extension']:
            assert 'url' in e
            assert len(e.keys()) > 1
Example #16
0
 def prep_org_w_identifier(self):
     o = Organization(name='test org')
     i = Identifier(system=US_NPI, value='123-45')
     o.identifiers.append(i)
     with SessionScope(db):
         db.session.add(o)
         db.session.commit()
     o = db.session.merge(o)
     return o
Example #17
0
 def add_questionnaire(name):
     q = Questionnaire()
     i = Identifier(
         system=TRUENTH_QUESTIONNAIRE_CODE_SYSTEM, value=name)
     q.identifiers.append(i)
     with SessionScope(db):
         db.session.add(q)
         db.session.commit()
     return db.session.merge(q)
    def test_organization_identifiers(self):
        alias = Identifier(use='official',
                           system='http://www.zorgkaartnederland.nl/',
                           value='my official alias',
                           assigner='Organization/1')
        shortcut = Identifier(use='secondary',
                              system=SHORTCUT_ALIAS,
                              value='shortcut')

        self.shallow_org_tree()
        org = Organization.query.filter(Organization.id > 0).first()
        before = org.identifiers.count()
        org.identifiers.append(alias)
        org.identifiers.append(shortcut)
        with SessionScope(db):
            db.session.commit()
        org = db.session.merge(org)
        assert org.identifiers.count() == before + 2
    def test_site_ids(self):
        # bless org w/ expected identifier type
        wanted_system = 'http://pcctc.org/'
        unwanted_system = 'http://other.org/'
        self.app.config['REPORTING_IDENTIFIER_SYSTEMS'] = [wanted_system]
        id_value = '146-11'
        org = Organization.query.filter(
            Organization.name == 'metastatic').one()
        id1 = Identifier(
            system=wanted_system, use='secondary', value=id_value)
        id2 = Identifier(
            system=unwanted_system, use='secondary', value=id_value)
        org.identifiers.append(id1)
        org.identifiers.append(id2)

        with SessionScope(db):
            db.session.commit()

        nineback, nowish = associative_backdate(
            now=now, backdate=relativedelta(months=9, hours=1))
        self.bless_with_basics(
            setdate=nineback, local_metastatic='metastatic')
        instrument_id = 'eortc'
        mock_qr(instrument_id=instrument_id)

        # add staff user w/ same org association for bundle creation

        staff = self.add_user(username='******')
        staff.organizations.append(Organization.query.filter(
                Organization.name == 'metastatic').one())
        self.promote_user(staff, role_name=ROLE.STAFF.value)
        staff = db.session.merge(staff)
        bundle = aggregate_responses(
            instrument_ids=[instrument_id], current_user=staff)
        id1 = db.session.merge(id1)
        assert 1 == len(bundle['entry'])
        assert (1 ==
                len(bundle['entry'][0]['subject']['careProvider']))
        assert (1 ==
                len(bundle['entry'][0]['subject']['careProvider'][0]
                    ['identifier']))
        assert (id1.as_fhir() ==
                bundle['entry'][0]['subject']['careProvider'][0]
                ['identifier'][0])
Example #20
0
    def test_site_ids(self):
        # bless org w/ expected identifier type
        wanted_system = 'http://pcctc.org/'
        unwanted_system = 'http://other.org/'
        self.app.config['REPORTING_IDENTIFIER_SYSTEMS'] = [wanted_system]
        id_value = '146-11'
        org = Organization.query.filter(
            Organization.name == 'metastatic').one()
        id1 = Identifier(
            system=wanted_system, use='secondary', value=id_value)
        id2 = Identifier(
            system=unwanted_system, use='secondary', value=id_value)
        org.identifiers.append(id1)
        org.identifiers.append(id2)

        with SessionScope(db):
            db.session.commit()

        nineback, nowish = associative_backdate(
            now=now, backdate=relativedelta(months=9, hours=1))
        self.bless_with_basics(
            setdate=nineback, local_metastatic='metastatic')
        instrument_id = 'eortc'
        mock_qr(instrument_id=instrument_id)

        # add staff user w/ same org association for bundle creation

        staff = self.add_user(username='******')
        staff.organizations.append(Organization.query.filter(
                Organization.name == 'metastatic').one())
        self.promote_user(staff, role_name=ROLE.STAFF.value)
        staff = db.session.merge(staff)
        bundle = aggregate_responses(
            instrument_ids=[instrument_id], current_user=staff)
        id1 = db.session.merge(id1)
        assert 1 == len(bundle['entry'])
        assert (1 ==
                len(bundle['entry'][0]['subject']['careProvider']))
        assert (1 ==
                len(bundle['entry'][0]['subject']['careProvider'][0]
                    ['identifier']))
        assert (id1.as_fhir() ==
                bundle['entry'][0]['subject']['careProvider'][0]
                ['identifier'][0])
Example #21
0
 def add_practitioner(
         first_name='first', last_name='last', id_value='12345'):
     p = Practitioner(first_name=first_name, last_name=last_name)
     i = Identifier(system=US_NPI, value=id_value)
     p.identifiers.append(i)
     with SessionScope(db):
         db.session.add(p)
         db.session.commit()
     p = db.session.merge(p)
     return p
    def test_delete_identifier(self):
        # orgs losing identifiers should delete the orphans
        from portal.system_uri import SHORTCUT_ALIAS, TRUENTH_CR_NAME
        from portal.models.identifier import Identifier

        org = Organization(name='testy')
        org.identifiers.append(Identifier(
            value='2 week ST', system=TRUENTH_CR_NAME))
        org.identifiers.append(Identifier(
            value='ohsu', system=SHORTCUT_ALIAS))
        with SessionScope(db):
            db.session.add(org)
            db.session.commit()
        mp = ModelPersistence(
            Organization, lookup_field='id',
            sequence_name='organizations_id_seq',
            target_dir=self.tmpdir)
        mp.export()

        # Reduce identifiers to one - make sure the other identifier goes away
        with open(
                os.path.join(self.tmpdir, 'Organization.json'), 'r') as pfile:
            data = json.load(pfile)

        for i, entry in enumerate(data['entry']):
            identifiers = entry['identifier']
            keepers = [
                identifier for identifier in identifiers
                if identifier['system'] == SHORTCUT_ALIAS]
            data['entry'][i]['identifier'] = keepers

        with open(
                os.path.join(self.tmpdir, 'Organization.json'), 'w') as pfile:
            pfile.write(json.dumps(data))

        mp.import_(keep_unmentioned=False)
        org = Organization.query.filter(Organization.name == 'testy').one()
        assert org.identifiers.count() == 1

        # Make sure we cleared out the orphan
        with pytest.raises(NoResultFound):
            Identifier.query.filter_by(
                value='2 week ST', system=TRUENTH_CR_NAME).one()
 def testPOST(self):
     """Add an existing and fresh identifier - confirm it sticks"""
     expected = len(self.test_user.identifiers) + 2
     existing = Identifier(system='http://notreal.com', value='unique')
     with SessionScope(db):
         db.session.add(existing)
         db.session.commit()
     existing = db.session.merge(existing)
     fresh = Identifier(system='http://another.com', value='unique')
     data = {'identifier': [i.as_fhir() for i in (existing, fresh)]}
     self.login()
     response = self.client.post(
         '/api/user/{}/identifier'.format(TEST_USER_ID),
         content_type='application/json',
         data=json.dumps(data))
     assert response.status_code == 200
     assert len(response.json['identifier']) == expected
     user = User.query.get(TEST_USER_ID)
     assert len(user.identifiers) == expected
 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())
Example #25
0
    def test_duplicate_identifier(self):
        swagger_spec = swagger(self.app)
        identifier = Identifier(system='https://unique.org', value='abc123')
        data = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data['identifier'] = identifier.as_fhir()

        self.promote_user(role_name=ROLE.PATIENT.value)
        self.login()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data)
        assert response.status_code == 200

        # Submit a second, with the same identifier, expect error
        data2 = swagger_spec['definitions']['QuestionnaireResponse']['example']
        data2['identifier'] = identifier.as_fhir()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data2)
        assert response.status_code == 409
        self.test_user = db.session.merge(self.test_user)
        assert self.test_user.questionnaire_responses.count() == 1

        # And a third, with just the id.value changed
        data3 = swagger_spec['definitions']['QuestionnaireResponse']['example']
        identifier.value = 'do-over'
        data3['identifier'] = identifier.as_fhir()
        response = self.client.post(
            '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data3)
        assert response.status_code == 200
        self.test_user = db.session.merge(self.test_user)
        assert self.test_user.questionnaire_responses.count() == 2
    def test_shortname(self):
        shorty = Identifier(system=SHORTNAME_ID, value='shorty')
        self.shallow_org_tree()
        org = Organization.query.filter(Organization.id > 0).first()
        # prior to adding shortname, should just get org name
        assert org.name == org.shortname

        org.identifiers.append(shorty)
        with SessionScope(db):
            db.session.commit()
        org = db.session.merge(org)
        # after, should get the shortname
        assert org.shortname == 'shorty'
    def test_ident_nomatch_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)
        # modify the system to mis match
        id_str = json.dumps(ident.as_fhir()).replace(
            "example.com", "wrong-system.com")
        response = self.client.get('/api/patient/', query_string={
            'identifier': id_str,
            'patch_dstu2': True},
            follow_redirects=True)

        # expect empty bundle
        assert response.status_code == 200
        assert response.json['resourceType'] == 'Bundle'
        assert response.json['total'] == 0
Example #28
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())
 def test_ill_formed_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?identifier=system"http://example.com",value="testy"',
         follow_redirects=True)
     assert response.status_code == 400
Example #30
0
    def test_unique(self):
        """Try adding a non-unique identifier, expect exception"""
        constrained = Identifier(
            system='http://us.truenth.org/identity-codes/external-study-id',
            value='unique-one')
        with SessionScope(db):
            db.session.add(constrained)
        second_user = self.add_user('second')
        constrained = db.session.merge(constrained)
        second_user.add_identifier(constrained)

        user = db.session.merge(self.test_user)
        with pytest.raises(Conflict):
            user.add_identifier(constrained)
Example #31
0
    def test_ident_nomatch_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)
        # modify the system to mis match
        id_str = json.dumps(ident.as_fhir()).replace("example.com",
                                                     "wrong-system.com")
        response = self.client.get('/api/patient/',
                                   query_string={
                                       'identifier': id_str,
                                       'patch_dstu2': True
                                   },
                                   follow_redirects=True)

        # expect empty bundle
        assert response.status_code == 200
        assert response.json['resourceType'] == 'Bundle'
        assert response.json['total'] == 0
Example #32
0
    def test_unique_deleted(self):
        """Try adding a non-unique identifier from deleted user"""
        constrained = Identifier(
            system='http://us.truenth.org/identity-codes/external-study-id',
            value='unique-one')
        with SessionScope(db):
            db.session.add(constrained)
        second_user = self.add_user('second')
        constrained = db.session.merge(constrained)
        second_user.add_identifier(constrained)
        second_user.delete_user(acting_user=self.test_user)

        user = db.session.merge(self.test_user)
        user.add_identifier(constrained)
        assert constrained in user.identifiers
Example #33
0
    def test_clinc_id(self):
        # Create several orgs with identifier
        org1 = Organization(name='org1')
        org2 = Organization(name='org2')
        org3 = Organization(name='org3')
        identifier = Identifier(value='pick me', system=DECISION_SUPPORT_GROUP)
        for org in (org1, org2, org3):
            org.identifiers.append(identifier)

        # Add access strategy to the care plan intervention
        cp = INTERVENTION.CARE_PLAN
        cp.public_access = False  # turn off public access to force strategy
        cp_id = cp.id

        with SessionScope(db):
            map(db.session.add, (org1, org2, org3))
            db.session.commit()

        org1, org2, org3 = map(db.session.merge, (org1, org2, org3))
        d = {
            'function': 'limit_by_clinic_w_id',
            'kwargs': [{
                'name': 'identifier_value',
                'value': 'pick me'
            }]
        }
        strat = AccessStrategy(name="member of org with identifier",
                               intervention_id=cp_id,
                               function_details=json.dumps(d))

        with SessionScope(db):
            db.session.add(strat)
            db.session.commit()

        cp = INTERVENTION.CARE_PLAN
        user = db.session.merge(self.test_user)

        # Prior to associating user with any orgs, shouldn't have access
        self.assertFalse(cp.display_for_user(user).access)

        # Add association and test again
        user.organizations.append(org3)
        with SessionScope(db):
            db.session.commit()
        user, cp = map(db.session.merge, (user, cp))
        self.assertTrue(cp.display_for_user(user).access)
    def test_organization_get_by_identifier(self):
        org_id_system = "testsystem"
        org_id_value = "testval"
        self.login()
        org = Organization(name='test', id=999)
        ident = Identifier(id=99, system=org_id_system, value=org_id_value)
        org_ident = OrganizationIdentifier(organization_id=999,
                                           identifier_id=99)
        with SessionScope(db):
            db.session.add(org)
            db.session.add(ident)
            db.session.commit()
            db.session.add(org_ident)
            db.session.commit()

        # use api to obtain FHIR
        rv = self.client.get('/api/organization/{}/{}'.format(
            org_id_system, org_id_value))
        self.assert200(rv)
    def test_organization_put_update(self):
        # confirm unmentioned fields persist
        self.promote_user(role_name=ROLE.ADMIN.value)
        self.login()

        en_AU = LocaleConstants().AustralianEnglish

        # Populate db with complet org, and set many fields
        org = Organization(name='test',
                           phone='800-800-5665',
                           timezone='US/Pacific')
        org.identifiers.append(
            Identifier(value='state:NY', system=PRACTICE_REGION))
        org.locales.append(en_AU)
        org.default_locale = 'en_AU'

        with SessionScope(db):
            db.session.add(org)
            db.session.commit()
        org = db.session.merge(org)
        org_id = org.id
        data = org.as_fhir()

        # Now strip down the representation - confirm a post doesn't
        # wipe unmentioned fields
        del data['extension']
        del data['telecom']
        del data['language']

        response = self.client.put('/api/organization/{}'.format(org_id),
                                   content_type='application/json',
                                   data=json.dumps(data))
        assert response.status_code == 200

        # Pull the updated db entry
        org = Organization.query.get(org_id)
        en_AU = db.session.merge(en_AU)

        # Confirm all the unmentioned entries survived
        assert org.phone == '800-800-5665'
        assert org.default_locale == 'en_AU'
        assert org.locales[0] == en_AU
        assert org.timezone == 'US/Pacific'
Example #36
0
    def test_unique_api(self):
        constrained = Identifier(
            system='http://us.truenth.org/identity-codes/external-study-id',
            value='unique-one')
        with SessionScope(db):
            db.session.add(constrained)
        second_user = self.add_user('second')
        constrained = db.session.merge(constrained)
        second_user.add_identifier(constrained)

        self.login()
        response = self.client.get('/api/user/{}/unique'.format(TEST_USER_ID),
                                   query_string={
                                       'identifier':
                                       '|'.join((constrained.system,
                                                 constrained.value))
                                   })
        assert response.status_code == 200
        assert response.json['unique'] is False
    def test_demographics_identifier_ref(self):
        # referencing careProvider by (unique) external Identifier

        self.shallow_org_tree()
        org = Organization.query.filter(Organization.id > 0).first()
        org_id, org_name = org.id, org.name

        # create OrganizationIdentifier and add to org
        org_id_system = "testsystem"
        org_id_value = "testval"
        ident = Identifier(id=99, system=org_id_system, value=org_id_value)
        org.identifiers.append(ident)
        with SessionScope(db):
            db.session.commit()

        # create Practitioner and add Identifier
        pract = self.add_practitioner(first_name="Indiana",
                                      last_name="Jones",
                                      id_value='practval')

        data = {
            "careProvider": [{
                "reference":
                "Organization/{}?system={}".format(org_id_value, org_id_system)
            }, {
                "reference":
                "Practitioner/{}?system={}".format('practval', US_NPI)
            }],
            "resourceType":
            "Patient",
        }

        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
        user, pract = map(db.session.merge, (self.test_user, pract))
        assert len(user.organizations) == 1
        assert user.organizations[0].name == org_name
        assert user.practitioner_id == pract.id
 def test_unicode_value(self):
     ex = Identifier(system='http://nonsense.com', value='ascii')
     unicode_string = '__invite__justin.emcee\[email protected]'
     ex.value = unicode_string
     assert ex.value == unicode_string