Example #1
0
    def test_success(self, req, db_session, check_csrf_token):
        """
        It should allow removal of entities from a visit.
        """
        from datetime import date, timedelta
        from pyramid.httpexceptions import HTTPOk
        from occams_datastore import models as datastore
        from occams_studies import models

        cycle = models.Cycle(name='week-1', title=u'', week=1)

        schema = datastore.Schema(name=u'sample',
                                  title=u'',
                                  publish_date=date.today())

        study = models.Study(name=u'somestudy',
                             title=u'Some Study',
                             short_title=u'sstudy',
                             code=u'000',
                             consent_date=date.today(),
                             cycles=[cycle],
                             schemata=set([schema]))

        site = models.Site(name=u'ucsd', title=u'UCSD')

        default_state = (db_session.query(
            datastore.State).filter_by(name=u'pending-entry').one())

        t_a = date.today() + timedelta(days=5)
        patient_a = models.Patient(site=site, pid=u'12345')
        visit_a = models.Visit(patient=patient_a,
                               cycles=[cycle],
                               visit_date=t_a)
        entity_a_1 = datastore.Entity(schema=schema,
                                      collect_date=t_a,
                                      state=default_state)
        entity_a_2 = datastore.Entity(schema=schema,
                                      collect_date=t_a,
                                      state=default_state)
        entity_a_3 = datastore.Entity(schema=schema,
                                      collect_date=t_a,
                                      state=default_state)
        list(map(visit_a.entities.add, [entity_a_1, entity_a_2, entity_a_3]))

        db_session.add_all([visit_a, study])
        db_session.flush()

        req.json_body = {'forms': [entity_a_2.id, entity_a_3.id]}

        res = self._call_fut(visit_a['forms'], req)

        # refresh the session so we can get a correct listing
        db_session.expunge_all()
        visit_a = db_session.query(models.Visit).get(visit_a.id)

        assert isinstance(res, HTTPOk)
        assert sorted([e.id for e in [entity_a_1]]) == \
            sorted([e.id for e in visit_a.entities])
Example #2
0
def test_validator_max_constraint(db_session):
    """
    It should validate string/number value min/max
    """
    from datetime import date
    from occams_datastore import models
    from occams_datastore.exc import ConstraintError

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    models.Attribute(
        schema=schema,
        parent_attribute=s1,
        name=u'test',
        title=u'',
        type=u'string',
        is_required=False,
        value_max=3,
        order=0)
    db_session.add(schema)
    db_session.flush()

    entity = models.Entity(schema=schema)
    db_session.add(entity)

    entity['test'] = None

    with pytest.raises(ConstraintError):
        entity['test'] = u'foobar'

    entity['test'] = u'foo'
    db_session.flush()
    assert 'foo' == entity['test']
Example #3
0
def check_value_max_constraint(db_session, type_, limit, below, equal, over):
    """
    It should validate against maximum constraints
    """
    from datetime import date
    from occams_datastore import models
    from occams_datastore.exc import ConstraintError

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    entity = models.Entity(schema=schema)
    db_session.add(entity)
    db_session.flush()

    models.Attribute(
        schema=schema, parent_attribute=s1,
        name=type_, title=u'', type=type_, is_required=False,
        value_max=limit, order=0)

    entity[type_] = None
    entity[type_] = below
    entity[type_] = equal

    with pytest.raises(ConstraintError):
        entity[type_] = over

    models.Attribute(
        schema=schema, parent_attribute=s1,
        name=u'boolean', title=u'', type=u'boolean', value_max=10, order=1)
    with pytest.raises(NotImplementedError):
        entity['boolean'] = True
Example #4
0
def preview(context, request):
    """
    Preview form for test-drivining.
    """
    db_session = request.db_session
    form_class = make_form(db_session, context, show_metadata=False)
    form = form_class(request.POST)
    form_id = 'form-preview'
    entity = None

    if request.method == 'POST' and form.validate():
        upload_path = tempfile.mkdtemp()
        entity = datastore.Entity(schema=context)
        try:
            apply_data(db_session, entity, form.patch_data, upload_path)
        finally:
            shutil.rmtree(upload_path)

        # Remove from session so entity or attributes don't persist in db
        db_session.expunge(entity)

    return {
        'entity': entity,
        'form_id': form_id,
        'form_content': render_form(
            form,
            cancel_url=request.current_route_path(),
            attr={
                'id': form_id,
                'method': 'POST',
                'action': request.current_route_path(_query={}),
                'role': 'form'
                })
        }
Example #5
0
def test_entity_force_date(db_session):
    """
    It should maintain a date object for date types.
    (Sometimes applications will blindly assign datetimes...)
    """
    from datetime import date, datetime
    from occams_datastore import models

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    entity = models.Entity(schema=schema)

    # Do simple values
    simpleName = 'choicesimple'
    schema.attributes[simpleName] = models.Attribute(
        schema=schema,
        parent_attribute=s1,
        title=u'', type='date', is_required=False, order=1)

    now = datetime.now()
    today = now.date()

    entity[simpleName] = now
    db_session.flush()
    assert isinstance(entity[simpleName], date)
    assert today == entity[simpleName]
Example #6
0
    def test_file_is_deleted(self, db_session):
        """
        Test file is deleted on the system after a non-FieldStorage
        object is passed to apply_data
        """

        import os
        from datetime import date

        from occams_datastore import models as datastore

        from mock import Mock

        schema = datastore.Schema(
            name=u'test', title=u'', publish_date=date.today(),
            attributes={
                'q1': datastore.Attribute(
                    name=u'q1',
                    title=u'',
                    type='blob',
                    order=0
                )
            })

        entity = datastore.Entity(schema=schema)

        formdata = {'q1': u''}

        with open(os.path.join(self.tmpdir, 'test.txt'), 'w'):
            fullpath = os.path.join(self.tmpdir, 'test.txt')

        entity['q1'] = Mock(path=fullpath)

        self._call_fut(db_session, entity, formdata, self.tmpdir)
        assert not os.path.exists(fullpath)
Example #7
0
    def test_one_record_exists_db_after_update(self, db_session):
        """
        Test if one updated record exists in value_blob tbl
        after FieldStorage object passed to apply_data
        """

        import os
        import cgi
        from datetime import date

        from occams_datastore import models as datastore

        from mock import Mock

        schema = datastore.Schema(
            name=u'test', title=u'', publish_date=date.today(),
            attributes={
                'q1': datastore.Attribute(
                    name=u'q1',
                    title=u'',
                    type='blob',
                    order=0
                )
            })

        entity = datastore.Entity(schema=schema)

        form = cgi.FieldStorage()
        form.filename = u'test.txt'
        form.file = form.make_file()
        form.file.write(u'test_content')
        form.file.seek(0)

        formdata = {'q1': form}

        with open(os.path.join(self.tmpdir, 'test.txt'), 'w'):
            fullpath = os.path.join(self.tmpdir, 'test.txt')

        entity['q1'] = Mock(path=fullpath)

        self._call_fut(db_session, entity, formdata, self.tmpdir)

        blob = db_session.query(datastore.ValueBlob).one()
        entity_id = blob.entity.id

        form_update = cgi.FieldStorage()
        form_update.filename = u'test2.txt'
        form_update.file = form.make_file()
        form_update.file.write(u'test_content')
        form_update.file.seek(0)

        formdata2 = {'q1': form_update}
        self._call_fut(db_session, entity, formdata2, self.tmpdir)

        blob = db_session.query(datastore.ValueBlob).filter_by(
            file_name=u'test2.txt').first()
        entity_id_after_update = blob.entity_id
        assert entity_id == entity_id_after_update
Example #8
0
def test_entity_choices(db_session):
    """
    It should properly handle choices
    """
    from datetime import date
    from occams_datastore import models

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    entity = models.Entity(schema=schema)
    db_session.add(entity)
    db_session.flush()

    # Do simple values
    simpleName = 'choicesimple'
    schema.attributes[simpleName] = models.Attribute(
        schema=schema,
        parent_attribute=s1,
        name=simpleName,
        title=u'', type='choice', is_required=False, order=1,
        choices={
            '001': models.Choice(name=u'001', title=u'Foo', order=1),
            '002': models.Choice(name=u'002', title=u'Bar', order=2),
            '003': models.Choice(name=u'003', title=u'Baz', order=3),
            '004': models.Choice(name=u'004', title=u'Caz', order=4),
            '005': models.Choice(name=u'005', title=u'Jaz', order=5),
            })
    entity[simpleName] = None
    db_session.flush()
    assert entity[simpleName] is None

    entity[simpleName] = u'002'
    db_session.flush()
    assert u'002' == entity[simpleName]

    # Now try collections
    collectionName = 'choicecollection'
    schema.attributes[collectionName] = models.Attribute(
        schema=schema,
        parent_attribute=s1,
        name=collectionName,
        title=u'', type='choice', is_collection=True, order=2,
        choices={
            '001': models.Choice(name=u'001', title=u'Foo', order=1),
            '002': models.Choice(name=u'002', title=u'Bar', order=2),
            '003': models.Choice(name=u'003', title=u'Baz', order=3),
            '004': models.Choice(name=u'004', title=u'Caz', order=4),
            '005': models.Choice(name=u'005', title=u'Jaz', order=5)})
    entity[collectionName] = [u'001', u'002', u'005']
    db_session.flush()
    assert sorted([u'001', u'002', u'005']) == \
        sorted(entity['choicecollection'])
Example #9
0
def edit_json(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    is_new = isinstance(context, models.PatientFactory)
    form = PatientSchema(context, request).from_json(request.json_body)

    if not form.validate():
        raise HTTPBadRequest(json={'errors': wtferrors(form)})

    if is_new:
        # if any errors occurr after this, this PID is essentially wasted
        patient = models.Patient(
            pid=six.text_type(generate(db_session, form.site.data.name)))
        db_session.add(patient)
    else:
        patient = context

    patient.site = form.site.data

    if form.references.data:
        inputs = dict(((r['reference_type'].id, r['reference_number']), r)
                      for r in form.references.data)

        for r in patient.references:
            try:
                # Remove already-existing values from the inputs
                del inputs[(r.reference_type.id, r.reference_number)]
            except KeyError:
                # References not in the inputs indicate they have been removed
                db_session.delete(r)

        for r in six.itervalues(inputs):
            db_session.add(
                models.PatientReference(
                    patient=patient,
                    reference_type=r['reference_type'],
                    reference_number=r['reference_number']))

    # Add the patient forms
    if is_new:
        schemata_query = (db_session.query(datastore.Schema).join(
            models.patient_schema_table))
        pending_entry = (db_session.query(
            datastore.State).filter_by(name=u'pending-entry').one())
        for schema in schemata_query:
            patient.entities.add(
                datastore.Entity(schema=schema, state=pending_entry))

    db_session.flush()
    db_session.refresh(patient)

    return view_json(patient, request)
Example #10
0
def test_entity_add_unpublished_schema(db_session):
    """
    It should not allow adding entities related to unpublished schemata
    """
    from occams_datastore import models
    from occams_datastore.exc import InvalidEntitySchemaError

    schema = models.Schema(name=u'Foo', title=u'')
    entity = models.Entity(schema=schema)
    db_session.add(entity)
    with pytest.raises(InvalidEntitySchemaError):
        db_session.flush()
Example #11
0
    def populate(self, app, db_session):
        import transaction
        from occams_studies import models as studies
        from occams_datastore import models as datastore
        from datetime import date

        # Any view-dependent data goes here
        # Webtests will use a different scope for its transaction
        with transaction.manager:
            user = datastore.User(key=USERID)
            db_session.info['blame'] = user
            db_session.add(user)
            db_session.flush()

            site = studies.Site(name=u'UCSD',
                                title=u'UCSD',
                                description=u'UCSD Campus',
                                create_date=date.today())

            patient = studies.Patient(initials=u'ian',
                                      nurse=u'*****@*****.**',
                                      site=site,
                                      pid=u'123')

            form = datastore.Schema(name=u'test_schema',
                                    title=u'test_title',
                                    publish_date=date(2015, 1, 1))

            study = studies.Study(name=u'test_study',
                                  code=u'test_code',
                                  consent_date=date(2014, 12, 23),
                                  is_randomized=False,
                                  title=u'test_title',
                                  short_title=u'test_short',
                                  schemata=set([form]))

            cycle = studies.Cycle(name=u'TestCycle',
                                  title=u'TestCycle',
                                  week=39,
                                  study=study)

            visit = studies.Visit(patient=patient,
                                  cycles=[cycle],
                                  visit_date='2015-01-01')

            entity = datastore.Entity(schema=form,
                                      collect_date=date(2015, 1, 1))

            db_session.add(study)
            db_session.add(patient)
            db_session.add(visit)
            db_session.add(entity)
            patient.entities.add(entity)
Example #12
0
    def test_old_file_is_deleted_after_update(self, db_session):
        """
        Test if previous file is deleted from the
        system after a new FieldStoarage object
        is passed to apply_data
        """
        import os
        import cgi
        from datetime import date

        from occams_datastore import models as datastore

        from mock import Mock

        schema = datastore.Schema(
            name=u'test', title=u'', publish_date=date.today(),
            attributes={
                'q1': datastore.Attribute(
                    name=u'q1',
                    title=u'',
                    type='blob',
                    order=0
                )
            })

        entity = datastore.Entity(schema=schema)

        form = cgi.FieldStorage()
        form.filename = u'test.txt'
        form.file = form.make_file()
        form.file.write(u'test_content')
        form.file.seek(0)

        formdata = {'q1': form}

        with open(os.path.join(self.tmpdir, 'test.txt'), 'w'):
            fullpath = os.path.join(self.tmpdir, 'test.txt')

        entity['q1'] = Mock(path=fullpath)

        self._call_fut(db_session, entity, formdata, self.tmpdir)

        form_update = cgi.FieldStorage()
        form_update.filename = u'test2.txt'
        form_update.file = form.make_file()
        form_update.file.write(u'test_content')
        form_update.file.seek(0)

        formdata2 = {'q1': form_update}
        self._call_fut(db_session, entity, formdata2, self.tmpdir)

        assert not os.path.exists(fullpath)
Example #13
0
    def test_enrollment(self, db_session):
        """
        It should add enrollment-specific metadata to the report
        """
        from datetime import date, timedelta
        from occams_datastore import models as datastore
        from occams_studies import models
        from occams_studies.exports.schema import SchemaPlan

        schema = datastore.Schema(name=u'termination',
                                  title=u'Termination',
                                  publish_date=date.today(),
                                  attributes={
                                      'foo':
                                      datastore.Attribute(
                                          name='foo',
                                          title=u'',
                                          type='string',
                                          order=0,
                                      )
                                  })
        entity = datastore.Entity(schema=schema, collect_date=date.today())
        patient = models.Patient(site=models.Site(name='ucsd', title=u'UCSD'),
                                 pid=u'12345',
                                 entities=[entity])
        study = models.Study(name=u'cooties',
                             short_title=u'CTY',
                             code=u'999',
                             consent_date=date.today() - timedelta(365),
                             title=u'Cooties')
        enrollment = models.Enrollment(
            patient=patient,
            study=study,
            consent_date=date.today() - timedelta(5),
            latest_consent_date=date.today() - timedelta(3),
            termination_date=date.today(),
            entities=[entity])
        db_session.add_all([schema, entity, patient, study, enrollment])

        plan = SchemaPlan.from_schema(db_session, schema.name)
        codebook = list(plan.codebook())
        query = plan.data()
        codebook_columns = [c['field'] for c in codebook]
        data_columns = [c['name'] for c in query.column_descriptions]
        record = query.one()
        assert sorted(codebook_columns) == sorted(data_columns)
        assert record.site == patient.site.name
        assert record.pid == patient.pid
        assert record.enrollment == enrollment.study.name
        assert record.enrollment_ids == str(enrollment.id)
        assert record.visit_cycles is None
        assert record.collect_date == entity.collect_date
Example #14
0
    def test_old_file_is_deleted_db_after_empty_string_applied(
            self, db_session):
        """
        Test if previous file is deleted from db after
        a non-FieldStoarage is passed to apply_data
        """

        import os
        import cgi
        from datetime import date

        from occams_datastore import models as datastore

        from mock import Mock

        schema = datastore.Schema(
            name=u'test', title=u'', publish_date=date.today(),
            attributes={
                'q1': datastore.Attribute(
                    name=u'q1',
                    title=u'',
                    type='blob',
                    order=0
                )
            })

        entity = datastore.Entity(schema=schema)

        form = cgi.FieldStorage()
        form.filename = u'test.txt'
        form.file = form.make_file()
        form.file.write(u'test_content')
        form.file.seek(0)

        formdata = {'q1': form}

        with open(os.path.join(self.tmpdir, 'test.txt'), 'w'):
            fullpath = os.path.join(self.tmpdir, 'test.txt')

        entity['q1'] = Mock(path=fullpath)

        self._call_fut(db_session, entity, formdata, self.tmpdir)

        formdata = {'q1': u''}
        self._call_fut(db_session, entity, formdata, self.tmpdir)

        blob = db_session.query(datastore.ValueBlob).filter_by(
            file_name=u'test.txt').first()

        assert blob is None
Example #15
0
def test_entity_default_collect_date(db_session):
    """
    It should default to today's date as the collect_date if not is provided
    """
    from datetime import date
    from occams_datastore import models
    # Make sure the system can auto-assign a collect date for the entry

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    entity = models.Entity(schema=schema)
    db_session.add(entity)
    db_session.flush()
    assert date.today() == entity.collect_date

    # If one is supplied by the user, don't do anything
    collect_date = date(2010, 9, 1)
    entity = models.Entity(
        schema=schema,
        collect_date=collect_date)
    db_session.add(entity)
    db_session.flush()
    assert entity.collect_date == collect_date
Example #16
0
 def _make_entity(self):
     from datetime import date
     from occams_datastore import models as datastore
     schema = datastore.Schema(
         name=u'test', title=u'', publish_date=date.today(),
         attributes={
             'q1': datastore.Attribute(
                 name=u'q1',
                 title=u'',
                 type='string',
                 is_required=True,
                 order=0,
             )
         })
     entity = datastore.Entity(schema=schema)
     return entity
Example #17
0
    def populate(self, app, db_session):
        import transaction
        from occams_studies import models as studies
        from occams_datastore import models as datastore
        from datetime import date

        # Any view-dependent data goes here
        # Webtests will use a different scope for its transaction
        with transaction.manager:
            user = datastore.User(key=USERID)
            db_session.info['blame'] = user
            db_session.add(user)
            db_session.flush()
            site = studies.Site(name=u'UCSD',
                                title=u'UCSD',
                                description=u'UCSD Campus',
                                create_date=date.today())

            patient = studies.Patient(initials=u'ian',
                                      nurse=u'*****@*****.**',
                                      site=site,
                                      pid=u'123')

            form = datastore.Schema(name=u'test_schema',
                                    title=u'test_title',
                                    publish_date=date(2015, 1, 1))

            study = studies.Study(name=u'test_study',
                                  code=u'test_code',
                                  consent_date=date(2014, 12, 23),
                                  is_randomized=False,
                                  title=u'test_title',
                                  short_title=u'test_short',
                                  schemata=set([form]))

            state = (db_session.query(
                datastore.State).filter_by(name=u'pending-entry').one())

            db_session.add(
                datastore.Entity(state=state,
                                 schema=form,
                                 collect_date=date(2015, 2, 1)))

            db_session.add(
                studies.Enrollment(patient=patient,
                                   study=study,
                                   consent_date=date(2014, 12, 22)))
Example #18
0
    def test_cascade_forms(self, req, db_session, check_csrf_token):
        """
        It should remove all visit-associated forms.
        """
        from datetime import date
        from occams_datastore import models as datastore
        from occams_studies import models

        schema = datastore.Schema(name=u'sample',
                                  title=u'Some Sample',
                                  publish_date=date.today())

        study = models.Study(name=u'somestudy',
                             title=u'Some Study',
                             short_title=u'sstudy',
                             code=u'000',
                             consent_date=date.today())

        cycle = models.Cycle(name=u'week-10', title=u'Week 10', week=10)

        study.cycles.append(cycle)

        patient = models.Patient(site=models.Site(name=u'ucsd', title=u'UCSD'),
                                 pid=u'12345')

        enrollment = models.Enrollment(study=study,
                                       patient=patient,
                                       consent_date=date.today())

        visit = models.Visit(patient=patient,
                             cycles=[cycle],
                             visit_date=date.today())

        visit.entities.add(
            datastore.Entity(schema=schema, collect_date=date.today()))

        db_session.add_all([patient, enrollment, study, visit])
        db_session.flush()

        visit_id = visit.id

        self._call_fut(visit, req)

        assert db_session.query(models.Visit).get(visit_id) is None
        assert 0 == db_session.query(datastore.Entity).count()
Example #19
0
    def test_file_is_inserted_to_db(self, db_session):
        """
        Test if a new record is inserted to value_blob
        table after a FieldStorage object is passed to apply_data
        """

        import os
        import cgi
        from datetime import date

        from occams_datastore import models as datastore

        from mock import Mock

        schema = datastore.Schema(
            name=u'test', title=u'', publish_date=date.today(),
            attributes={
                'q1': datastore.Attribute(
                    name=u'q1',
                    title=u'',
                    type='blob',
                    order=0
                )
            })

        entity = datastore.Entity(schema=schema)

        form = cgi.FieldStorage()
        form.filename = u'test.txt'
        form.file = form.make_file()
        form.file.write(u'test_content')
        form.file.seek(0)

        formdata = {'q1': form}

        with open(os.path.join(self.tmpdir, 'test.txt'), 'w'):
            fullpath = os.path.join(self.tmpdir, 'test.txt')

        entity['q1'] = Mock(path=fullpath)

        self._call_fut(db_session, entity, formdata, self.tmpdir)

        blob = db_session.query(datastore.ValueBlob).filter_by(
            file_name=u'test.txt').one()
        assert blob.file_name == u'test.txt'
Example #20
0
    def test_add_drsc_entity_already_has_entity(self, db_session):
        """Should not add entity becuase it exists already."""
        from datetime import date

        from occams_studies import models as studies
        from occams_datastore import models as datastore

        patient_site = studies.Site(name=u'test_site', title=u'test_clinic')

        patient = studies.Patient(pid=u'1234', site=patient_site)

        default_state = (db_session.query(
            datastore.State).filter_by(name='complete').one())

        target_schema = datastore.Schema(name=u'Demographics',
                                         title=u'Demographics',
                                         publish_date=date.today(),
                                         attributes={
                                             'yob':
                                             datastore.Attribute(
                                                 name=u'yob',
                                                 title=u'yob',
                                                 type=u'number',
                                                 order=0)
                                         })

        collect_date = date.today()

        entity = datastore.Entity(schema=target_schema,
                                  collect_date=collect_date,
                                  state=default_state)

        patient.entities.add(entity)
        db_session.flush()

        target_schema_name = u'Demographics'

        self._call_fut(db_session, patient, target_schema_name, target_schema,
                       collect_date)

        patient = (db_session.query(
            studies.Patient).filter_by(pid=u'1234').one())

        assert len(patient.entities) == 1
Example #21
0
    def test_skip_validation_if_from_complete(self, db_session):
        from webob.multidict import MultiDict
        from occams_datastore import models as datastore
        from occams_forms.renderers import \
            make_form, states, modes, entity_data

        schema = self._make_schema(db_session)
        entity = datastore.Entity(
            schema=schema,
            state=(
                db_session.query(datastore.State)
                .filter_by(name=states.COMPLETE)
                .one()))
        Form = make_form(
            db_session, schema, entity=entity, transition=modes.ALL)
        formdata = MultiDict({
            'ofworkflow_-state': states.PENDING_CORRECTION,
        })
        form = Form(formdata, data=entity_data(entity))
        assert form.validate(), form.errors
Example #22
0
    def test_patient(self, db_session):
        """
        It should add patient-specific metadata to the report
        """
        from datetime import date
        from occams_datastore import models as datastore
        from occams_studies import models
        from occams_studies.exports.schema import SchemaPlan

        schema = datastore.Schema(name=u'contact',
                                  title=u'Contact Details',
                                  publish_date=date.today(),
                                  attributes={
                                      'foo':
                                      datastore.Attribute(
                                          name='foo',
                                          title=u'',
                                          type='string',
                                          order=0,
                                      )
                                  })
        entity = datastore.Entity(schema=schema, collect_date=date.today())
        patient = models.Patient(site=models.Site(name='ucsd', title=u'UCSD'),
                                 pid=u'12345',
                                 entities=[entity])
        db_session.add_all([schema, entity, patient])
        db_session.flush()

        plan = SchemaPlan.from_schema(db_session, schema.name)
        codebook = list(plan.codebook())
        query = plan.data()
        codebook_columns = [c['field'] for c in codebook]
        data_columns = [c['name'] for c in query.column_descriptions]
        record = query.one()
        assert sorted(codebook_columns) == sorted(data_columns)
        assert record.site == patient.site.name
        assert record.pid == patient.pid
        assert record.enrollment is None
        assert record.visit_cycles is None
        assert record.visit_date is None
        assert record.collect_date == entity.collect_date
Example #23
0
    def test_list_not_include_rand(self, db_session):
        """
        It should not include randomization data if specified.
        """
        from datetime import date, timedelta
        from occams_datastore import models as datastore
        from occams_studies import models
        from occams_studies.exports.schema import SchemaPlan

        schema = datastore.Schema(name=u'vitals',
                                  title=u'Vitals',
                                  publish_date=date.today(),
                                  attributes={
                                      'foo':
                                      datastore.Attribute(
                                          name='foo',
                                          title=u'',
                                          type='string',
                                          order=0,
                                      )
                                  })
        entity = datastore.Entity(collect_date=date.today(), schema=schema)
        study = models.Study(name=u'study1',
                             short_title=u'S1',
                             code=u'001',
                             consent_date=date.today() - timedelta(365),
                             title=u'Study 1')
        armga = models.Arm(name=u'groupa', title=u'GROUP A', study=study)
        stratum = models.Stratum(study=study,
                                 arm=armga,
                                 block_number=12384,
                                 randid=u'8484',
                                 entities=[entity])
        db_session.add_all([schema, entity, stratum])
        db_session.flush()

        plans = SchemaPlan.list_all(db_session, include_private=True)
        assert len(plans) == 1

        plans = SchemaPlan.list_all(db_session, include_rand=False)
        assert len(plans) == 0
Example #24
0
    def _make_form(self, db_session):
        from datetime import date
        from occams_datastore import models as datastore
        from occams_forms.renderers import make_form

        schema = datastore.Schema(name=u'dymmy_schema',
                                  title=u'Dummy Schema',
                                  publish_date=date.today(),
                                  attributes={
                                      'dummy_field':
                                      datastore.Attribute(name=u'dummy_field',
                                                          title=u'Dummy Field',
                                                          type='string',
                                                          order=0)
                                  })

        entity = datastore.Entity(schema=schema)
        db_session.add(entity)
        db_session.flush()

        return make_form(db_session, schema, entity=entity)
Example #25
0
    def test_without_state(self, req, db_session):
        """
        It should generate none if no state data is available
        """
        import mock
        from occams_datastore import models as datastore
        from datetime import date

        myfirst = datastore.Schema(name=u'myfirst',
                                   title=u'My First Schema',
                                   publish_date=date.today())
        mydata = datastore.Entity(schema=myfirst)
        db_session.add(mydata)
        db_session.flush()
        mydata.__parent__ = mock.MagicMock()
        mydata.__parent__.__parent__ = mock.MagicMock()

        req.session.changed = mock.Mock()
        res = self._call_fut(mydata, req)

        assert res['state'] is None
Example #26
0
def test_choice_constraint(db_session):
    """
    It should validate against choice constraints
    """
    from datetime import date
    from occams_datastore import models
    from occams_datastore.exc import ConstraintError

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    models.Attribute(
        schema=schema, parent_attribute=s1,
        name=u'test', title=u'', type=u'choice', is_required=False, order=0,
        choices={
            '001': models.Choice(name=u'001', title=u'Foo', order=0),
            '002': models.Choice(name=u'002', title=u'Bar', order=1),
            '003': models.Choice(name=u'003', title=u'Baz', order=2)})
    db_session.add(schema)
    db_session.flush()

    entity = models.Entity(schema=schema)
    db_session.add(entity)

    entity['test'] = None
    entity['test'] = u'002'
    db_session.flush()

    entry = (
        db_session.query(models.ValueChoice)
        .filter(models.ValueChoice.value.has(name=u'002'))
        .one())
    assert entry.value.name == '002'

    # Should not be able to set it to something outside of the specified
    # choice constraints

    with pytest.raises(ConstraintError):
        entity['test'] = u'999'
Example #27
0
def test_state_entity_relationship(db_session):
    """
    It should implement state/entity relationship
    """
    from datetime import date
    from occams_datastore import models

    schema = models.Schema(name=u'Foo', title=u'Foo',
                           publish_date=date(2000, 1, 1))
    pending_entry = models.State(name=u'pending-entry', title=u'Pending Entry')
    entity = models.Entity(schema=schema)
    db_session.add_all([pending_entry, entity])
    db_session.flush()

    assert entity.state is None
    assert pending_entry.entities.count() == 0

    entity.state = pending_entry
    db_session.flush()

    assert entity.state is not None
    assert pending_entry.entities.count() == 1
Example #28
0
    def test_with_state(self, req, db_session):
        """
        It should generate state data is available
        """
        from datetime import date
        import mock
        from occams_datastore import models as datastore

        myfirst = datastore.Schema(name=u'myfirst',
                                   title=u'My First Schema',
                                   publish_date=date.today())
        mydata = datastore.Entity(
            schema=myfirst,
            state=(db_session.query(
                datastore.State).filter_by(name=u'pending-entry').one()))
        db_session.add(mydata)
        db_session.flush()
        mydata.__parent__ = mock.MagicMock()
        mydata.__parent__.__parent__ = mock.MagicMock()

        req.session.changed = mock.Mock()
        res = self._call_fut(mydata, req)

        assert res['state'] is not None
Example #29
0
def test_entity_blob_type(db_session):
    """
    It should be able to keep track of file uploads (will not be storing in DB)
    """

    from occams_datastore import models
    from datetime import date

    schema = models.Schema(name='HasBlob', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    schema.attributes['theblob'] = models.Attribute(
        parent_attribute=s1,
        name=u'theblob', title=u'', type='blob', order=0)

    entity = models.Entity(schema=schema)
    db_session.add(entity)
    db_session.flush()
    entity_id = entity.id

    # Add value
    entity['theblob'] = models.BlobInfo(file_name=u'foo', path='bar/baz.gif')
    db_session.add(entity)
    db_session.flush()
    entity = db_session.query(models.Entity).get(entity_id)
    blob = entity['theblob']
    assert u'foo' == blob.file_name
    assert 'bar/baz.gif' == blob.path

    # Clear value
    entity['theblob'] = None
    db_session.flush()
    entity = db_session.query(models.Entity).get(entity_id)
    blob = entity['theblob']
    assert blob is None
Example #30
0
def test_validator_pattern_constraint(db_session):
    """
    It should validate against string pattern constraints
    """
    from datetime import date
    from occams_datastore import models
    from occams_datastore.exc import ConstraintError

    schema = models.Schema(name=u'Foo', title=u'',
                           publish_date=date(2000, 1, 1))
    s1 = models.Attribute(
        schema=schema, name='s1', title=u'Section 1', type='section', order=0)
    models.Attribute(
        schema=schema,
        parent_attribute=s1,
        name=u'test',
        title=u'',
        type=u'string',
        is_required=False,
        # Valid US phone number
        pattern=r'\d{3}-\d{3}-\d{4}',
        order=0)
    db_session.add(schema)
    db_session.flush()

    entity = models.Entity(schema=schema)
    db_session.add(entity)

    entity['test'] = None

    with pytest.raises(ConstraintError):
        entity['test'] = u'trollol'

    entity['test'] = u'123-456-7890'
    db_session.flush()
    assert '123-456-7890' == entity['test']