Example #1
0
    def test_treatment_table_entry_treatment_relationship(self):
        entry1 = TreatmentTableEntry()
        entry2 = TreatmentTableEntry()

        treatment1 = Treatment(name='Treatment 1')
        treatment2 = Treatment(name='Treatment 2')

        # before connecting
        self.assertEqual(len(treatment1.treatment_table_entries.all()), 0)
        self.assertEqual(len(treatment2.treatment_table_entries.all()), 0)

        # after connecting
        entry1.treatment = treatment1
        entry2.treatment = treatment1

        self.assertEqual(len(treatment1.treatment_table_entries.all()), 2)
        self.assertEqual(treatment1, entry1.treatment)
        self.assertEqual(treatment1, entry2.treatment)
        self.assertTrue(entry1 in treatment1.treatment_table_entries.all())
        self.assertTrue(entry2 in treatment1.treatment_table_entries.all())

        self.assertEqual(len(treatment2.treatment_table_entries.all()), 0)
        self.assertNotEqual(treatment2, entry1.treatment)
        self.assertNotEqual(treatment2, entry2.treatment)
        self.assertFalse(entry1 in treatment2.treatment_table_entries.all())
        self.assertFalse(entry2 in treatment2.treatment_table_entries.all())
Example #2
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        self.client = self.app.test_client(use_cookies=True)

        hospital = Hospital(name='Hospital')
        user = User(first_name='userone',
                    last_name='userone',
                    username='******',
                    email='*****@*****.**',
                    password='******')
        user.hospital = hospital
        patient = Patient('Patient', '100', '*****@*****.**')
        user.patients.append(patient)
        treatment = Treatment(name='Treatment 1')
        treatment.hospital = hospital
        table1 = TreatmentTable(patient=patient, name='Table 1')
        entry1 = TreatmentTableEntry(amount='Entry1Amount',
                                     note='Entry1Note',
                                     treatment=treatment,
                                     treatment_table=table1)
        db.session.add_all(
            [hospital, user, patient, treatment, table1, entry1])
        db.session.commit()
Example #3
0
    def test_treatments_list(self):
        # create model instances
        hospital1 = Hospital(name='hospital1')
        hospital2 = Hospital(name='hospital2')

        user1 = User(first_name='one',
                     last_name='one',
                     username='******',
                     email='*****@*****.**',
                     password='******')
        user2 = User(first_name='two',
                     last_name='two',
                     username='******',
                     email='*****@*****.**',
                     password='******')

        treatment1 = Treatment(name='treatment1')
        treatment2 = Treatment(name='treatment2')

        hospital1.treatments.append(treatment1)
        hospital1.treatments.append(treatment2)

        user1.hospital = hospital1
        user2.hospital = hospital2

        db.session.add_all(
            [hospital1, hospital2, user1, user2, treatment1, treatment2])
        db.session.commit()

        # test for user1
        with self.client:
            self.client.post(url_for('auth.login'),
                             data={
                                 'email': '*****@*****.**',
                                 'password': '******'
                             })
            response = self.client.get(url_for('treatments.list'))
            data = response.get_data(as_text=True)
            self.assertTrue('treatment1' in data)
            self.assertTrue('treatment2' in data)

        # test for user2
        with self.client:
            self.client.post(url_for('auth.login'),
                             data={
                                 'email': '*****@*****.**',
                                 'password': '******'
                             })
            response = self.client.get(url_for('treatments.list'))
            data = response.get_data(as_text=True)
            self.assertFalse('treatment1' in data)
            self.assertFalse('treatment2' in data)
Example #4
0
def add():
    form = TreatmentAddForm()

    if form.validate_on_submit():
        hospital = current_user.hospital

        # create new treatment
        treatment = Treatment(name=form.name.data)
        treatment.hospital = hospital

        db.session.add(treatment)
        db.session.commit()

        flash('Treatment Successfully Added')
        return redirect(url_for('treatments.list'))

    return render_template('treatments/add.html', form=form)
Example #5
0
    def test_treatments_delete(self):
        hospital1 = Hospital(name='hospital1')

        user = User(first_name='one',
                    last_name='one',
                    username='******',
                    email='*****@*****.**',
                    password='******')
        user.hospital = hospital1
        treatment = Treatment(name='treatment')
        treatment.hospital = hospital1

        treatment2 = Treatment(name='not part of hospital1')

        db.session.add_all([user, hospital1, treatment, treatment2])
        db.session.commit()

        with self.client:
            self.client.post(url_for('auth.login'),
                             data={
                                 'email': '*****@*****.**',
                                 'password': '******'
                             })

            # treatment id does not exist
            response = self.client.get(url_for('treatments.delete', id=100))
            self.assertEqual(response.status_code, 404)

            # user not validated
            response = self.client.get(url_for('treatments.delete', id=2))
            self.assertEqual(response.status_code, 403)

            # successful deletion
            self.assertEqual(len(current_user.hospital.treatments.all()), 1)
            response = self.client.get(url_for('treatments.delete', id=1),
                                       follow_redirects=True)
            data = response.get_data(as_text=True)
            self.assertEqual(response.status_code, 200)
            self.assertTrue('Treatment Successfully Deleted' in data)
            self.assertEqual(len(current_user.hospital.treatments.all()), 0)
Example #6
0
    def test_treatment_hospital_relationship(self):
        hospital1 = Hospital('hospital1')
        hospital2 = Hospital('hospital2')

        treatment1 = Treatment('treatment1')
        treatment2 = Treatment('treatment2')

        # before connecting
        self.assertEqual(len(hospital1.treatments.all()), 0)
        self.assertEqual(len(hospital2.treatments.all()), 0)

        # after connecting
        treatment1.hospital = hospital1
        treatment2.hospital = hospital1
        self.assertEqual(len(hospital1.treatments.all()), 2)
        self.assertEqual(hospital1, treatment1.hospital)
        self.assertEqual(hospital1, treatment2.hospital)
        self.assertTrue(treatment1 in hospital1.treatments.all())
        self.assertTrue(treatment2 in hospital1.treatments.all())

        self.assertEqual(len(hospital2.treatments.all()), 0)
        self.assertNotEqual(hospital2, treatment1.hospital)
        self.assertNotEqual(hospital2, treatment2.hospital)
        self.assertFalse(treatment1 in hospital2.treatments.all())
        self.assertFalse(treatment2 in hospital2.treatments.all())
Example #7
0
    def test_appointments_relationship(self):
        start = datetime.utcnow()
        end = datetime.utcnow() + timedelta(days=1)
        appointment1 = Appointment(title='title1',
                                   description='description1',
                                   date_start=start,
                                   date_end=end)
        appointment2 = Appointment(title='title2',
                                   description='description2',
                                   date_start=start,
                                   date_end=end)
        patient = Patient(first_name='John',
                          last_name='Elliot',
                          email="*****@*****.**")
        user = User(first_name='John',
                    last_name='Elliot',
                    username='******',
                    email="*****@*****.**",
                    password='******')
        treatment = Treatment(name='Tylenol')

        # before connecting
        self.assertEqual(len(patient.appointments.all()), 0)
        self.assertEqual(len(user.appointments.all()), 0)
        self.assertEqual(len(treatment.appointments.all()), 0)

        # after connecting appointment1
        appointment1.patient = patient
        appointment1.user = user
        appointment1.treatment = treatment

        db.session.add_all(
            [patient, user, treatment, appointment1, appointment2])
        db.session.commit()

        self.assertEqual(len(patient.appointments.all()), 1)
        self.assertTrue(appointment1 in patient.appointments.all())
        self.assertEqual(appointment1.patient_id, patient.id)
        self.assertFalse(appointment2 in patient.appointments.all())
        self.assertNotEqual(appointment2.patient_id, patient.id)

        self.assertEqual(len(user.appointments.all()), 1)
        self.assertTrue(appointment1 in user.appointments.all())
        self.assertEqual(appointment1.user_id, user.id)
        self.assertFalse(appointment2 in user.appointments.all())
        self.assertNotEqual(appointment2.user_id, user.id)

        self.assertEqual(len(treatment.appointments.all()), 1)
        self.assertTrue(appointment1 in treatment.appointments.all())
        self.assertEqual(appointment1.treatment_id, treatment.id)
        self.assertFalse(appointment2 in treatment.appointments.all())
        self.assertNotEqual(appointment2.treatment_id, treatment.id)
Example #8
0
    def test_attributes_assignment(self):
        date = datetime.utcnow()
        amount = "1 mg Dose"
        note = "Additional Note"
        treatment = Treatment(name='Treatment 1')
        patient = Patient(first_name='John',
                          last_name='Doe',
                          email='*****@*****.**')
        table = TreatmentTable(name='Table 1', patient=patient)

        entry = TreatmentTableEntry(timestamp=date,
                                    amount=amount,
                                    note=note,
                                    treatment=treatment,
                                    treatment_table=table)

        self.assertEqual(entry.timestamp, date)
        self.assertEqual(entry.amount, '1 mg Dose')
        self.assertEqual(entry.note, "Additional Note")
        self.assertEqual(entry.treatment, treatment)
        self.assertEqual(entry.treatment_table, table)
Example #9
0
def submit_new(data):
    import datetime

    version = {
        'checked': True,
        'checked_count': 1,
        'statuses': Status.query.filter_by(status_name="Green").first()
    }

    if data["population_database_id"] == "XXX" or data[
            "population_database_id"] == "X.X.X":
        version = {
            'checked': False,
            'checked_count': 0,
            'statuses': Status.query.filter_by(status_name="Pending").first()
        }

    # When checking for null data later, these need to be excluded, as they will always have a value
    ignore_keys = ['version_ok', 'version_latest', 'version_original']
    ''' DigitizationProtocol '''

    #    digitization_protocol = DigitizationProtocol.query.filter_by(field_name=data["digitization_protocol"]).first()

    #   if digitization_protocol == None:
    #           ac_dict = {'protocol_id' : protocol.id,
    #           'field_name' : data['field_name'],
    #           'name_in_csv' : data["name_in_csv"],
    #           'database_model' : data["database_model"],
    #           'field_description' : data["field_description"],
    #           'field_short_description' : data["field_short_description"]
    #           }

    #           ac_cleaned = data_clean(ac_dict)
    #           digitization_protocol = Protocol(**ac_cleaned["kwargs"])

    #           db.session.add(digitization_protocol)
    #           db.session.commit()
    ''' Publication '''

    publications_protocol = PublicationsProtocol.query.filter_by(
        protocol_number=data["publications_protocol_id"]).first()

    if data["publication_DOI_ISBN"] == None:
        publication = Publication.query.filter_by(
            authors=data["publication_authors"]
        ).filter_by(year=data["publication_year"]).filter_by(
            journal_name=data["publication_journal_name"]).filter_by(
                additional_source_string=data[
                    "publication_additional_source_string"]).filter_by(
                        study_notes=data["publication_study_notes"]).first()
    else:
        publication = Publication.query.filter_by(
            DOI_ISBN=data["publication_DOI_ISBN"]).first()

    if publication == None:
        purposes = {
            "Comparative Demography":
            data["publication_purpose_comparative_demography"],
            "Spatial Demography":
            data["publication_purpose_spatial_demography"],
            "Abiotic Impacts":
            data["publication_purpose_abiotic"],
            "PVA":
            data["publication_purpose_pva"],
            "Species Dynamics Description":
            data["publication_purpose_species_dynamics_description"],
            "Interspecific Interactions":
            data["publication_purpose_interspecific_interactions"],
            "Management Evaluation":
            data["publication_purpose_management_evaluation"],
            "Methodological Advancement":
            data["publication_purpose_methodological_advancement"]
        }

        queryset = [
            Purpose.query.filter(Purpose.purpose_name == key).first()
            for key, val in purposes.items() if val == '1'
        ]

        if data['publication_missing_data'] != 'NDY' and data[
                'publication_missing_data']:
            missing_data_unicode = data['publication_missing_data'].replace(
                " ", "").split(';')
            missing_data = [
                MissingData.query.filter_by(missing_code=key).first()
                for key in missing_data_unicode
                if MissingData.query.filter_by(missing_code=key).first()
            ]
        else:
            missing_data = 'NDY'

        pub_dict = {
            'authors':
            data["publication_authors"],
            'year':
            data["publication_year"],
            'publications_protocol':
            publications_protocol,
            'DOI_ISBN':
            data["publication_DOI_ISBN"],
            'additional_source_string':
            data["publication_additional_source_string"],
            'journal_name':
            data["publication_journal_name"],
            'date_digitised':
            datetime.datetime.strptime(data['publication_date_digitization'],
                                       "%d/%m/%Y").strftime("%Y-%m-%d")
            if data['publication_date_digitization'] else None,
            'purposes':
            queryset,
            'study_notes':
            data["publication_study_notes"]
        }

        pub_cleaned = data_clean(pub_dict)

        # if not all(value == None for key, value in pub_cleaned["kwargs"].items() if key not in ignore_keys) and study_present:
        publication = Publication(**pub_cleaned["kwargs"])
        db.session.add(publication)
        db.session.commit()

        publication.missing_data = missing_data if type(
            missing_data) == list else []

        db.session.add(publication)
        db.session.commit()
        ''' Publication Version '''
        #version = version_data(pub_cleaned)
        publication_version = Version(**version)
        publication_version.publication = publication
        publication.colour = gen_hex_code()

        possible_user = User.query.filter_by(
            name=data["publication_student"]).first()
        na_user = User.query.filter_by(name="N/A").first()
        if possible_user == None:
            possible_user = na_user

        publication_version.entered_by_id = possible_user.id if possible_user else None,
        publication_version.checked_by_id = na_user.id if na_user else None,

        db.session.add(publication_version)
        db.session.commit()
        publication_version.original_version_id = publication_version.id
        db.session.add(publication_version)
        db.session.commit()
        ''' Author contact '''

        author_contacts = AuthorContact.query.filter_by(
            corresponding_author=data["publication_corresponding_author"]
        ).filter_by(
            corresponding_author_email=data["publication_corresponding_email"]
        ).first()

        if author_contacts == None:
            ac_dict = {
                'publication_id':
                publication.id,
                'date_contacted':
                datetime.datetime.strptime(data['date_author_contacted'],
                                           "%d/%m/%Y").strftime("%Y-%m-%d")
                if data['date_author_contacted'] else None,
                'date_contacted_again':
                datetime.datetime.strptime(data['date_author_contacted_again'],
                                           "%d/%m/%Y").strftime("%Y-%m-%d")
                if data['date_author_contacted_again'] else None,
                'extra_content_email':
                data["correspondence_email_content"],
                'author_reply':
                data["correspondence_author_reply"],
                'corresponding_author':
                data["publication_corresponding_author"],
                'corresponding_author_email':
                data["publication_corresponding_email"],
                'correspondence_email_content':
                data["correspondence_email_content"],
                'extra_content_email':
                data["extra_content_email"],
                'contacting_user_id':
                possible_user.id if possible_user else None
            }

            ac_cleaned = data_clean(ac_dict)
            author_contact = AuthorContact(**ac_cleaned["kwargs"])

            db.session.add(author_contact)
            db.session.commit()
            ''' Author Contact Version '''
            #version = version_data(ac_cleaned)
            author_contact_version = Version(**version)
            author_contact_version.author_contact = author_contact
            db.session.add(author_contact_version)
            db.session.commit()
            author_contact_version.original_version_id = author_contact_version.id
            db.session.add(author_contact_version)
            db.session.commit()
    ''' Species '''
    species = Species.query.filter_by(
        species_accepted=data["species_accepted"]).first()
    iucn = IUCNStatus.query.filter_by(
        status_code=data["species_iucn_status_id"]).first()

    if species == None:
        species_dict = {
            'gbif_taxon_key': data["species_gbif_taxon_key"],
            'species_iucn_taxonid': data["species_iucn_taxonid"],
            'species_accepted': data["species_accepted"],
            'species_common': data["species_common"],
            'iucn_status_id': iucn.id if iucn else None,
            'image_path': data["image_path"],
            'image_path2': data["image_path2"]
        }

        species_cleaned = data_clean(species_dict)
        species = Species(**species_cleaned["kwargs"])

        db.session.add(species)
        db.session.commit()
        ''' Species Version '''
        #version = version_data(species_cleaned)
        species_version = Version(**version)
        species_version.species = species
        db.session.add(species_version)
        db.session.commit()
        species_version.original_version_id = species_version.id
        db.session.add(species_version)
        db.session.commit()
    ''' Trait '''
    spand_ex_growth_type = SpandExGrowthType.query.filter_by(
        type_name=data["trait_spand_ex_growth_type_id"]).first()
    dicot_monoc = DicotMonoc.query.filter_by(
        dicot_monoc_name=data["trait_dicot_monoc_id"]).first()
    growth_form_raunkiaer = GrowthFormRaunkiaer.query.filter_by(
        form_name=data["trait_growth_form_raunkiaer_id"]).first()
    organism_type = OrganismType.query.filter_by(
        type_name=data["trait_organism_type_id"]).first()
    angio_gymno = AngioGymno.query.filter_by(
        angio_gymno_name=data["trait_angio_gymno_id"]).first()

    trait = Trait.query.filter_by(species_id=species.id).first()

    if trait == None:
        trait_dict = {
            'species_id':
            species.id,
            'organism_type':
            organism_type,
            'dicot_monoc':
            dicot_monoc,
            'angio_gymno':
            angio_gymno,
            'species_seedbank':
            coerce_boolean(data["species_seedbank"]),
            'species_gisd_status':
            coerce_boolean(data["species_gisd_status"]),
            'species_clonality':
            coerce_boolean(data["species_clonality"]),
            'spand_ex_growth_type_id':
            spand_ex_growth_type.id if spand_ex_growth_type else None,
            'growth_form_raunkiaer_id':
            growth_form_raunkiaer.id if growth_form_raunkiaer else None
        }

        trait_cleaned = data_clean(trait_dict)
        trait = Trait(**trait_cleaned["kwargs"])

        db.session.add(trait)
        db.session.commit()
        ''' Trait Version '''
        #version = version_data(trait_cleaned)
        trait_version = Version(**version)
        trait_version.trait = trait
        db.session.add(trait_version)
        db.session.commit()
        trait_version.original_version_id = trait_version.id
        db.session.add(trait_version)
        db.session.commit()
    ''' Taxonomy '''
    tax = Taxonomy.query.filter_by(species_id=species.id).first()
    if tax == None:
        tax_dict = {
            'authority':
            None,
            'tpl_version':
            None,
            'infraspecies_accepted':
            None,
            'species_epithet_accepted':
            None,
            'genus_accepted':
            data["taxonomy_genus_accepted"],
            'genus':
            data["taxonomy_genus"],
            'family':
            data["taxonomy_family"],
            'tax_order':
            data["taxonomy_order"],
            'tax_class':
            data["taxonomy_class"],
            'phylum':
            data["taxonomy_phylum"],
            'kingdom':
            data["taxonomy_kingdom"],
            'col_check_date':
            datetime.datetime.strptime(data["taxonomy_col_check_date"],
                                       "%d/%m/%Y").strftime("%Y-%m-%d")
            if data['taxonomy_col_check_date'] else None,
            'col_check_ok':
            coerce_boolean(data["taxonomy_col_check_ok"])
        }

        tax_cleaned = data_clean(tax_dict)

        # if not all(value == None for key, value in tax_cleaned["kwargs"].items() if key not in ignore_keys):
        tax = Taxonomy(**tax_cleaned["kwargs"])
        db.session.add(tax)
        db.session.commit()
        tax.species = species
        db.session.add(tax)
        db.session.commit()
        ''' Taxonomy Version '''
        #version = version_data(tax_cleaned)
        taxonomy_version = Version(**version)
        taxonomy_version.version_number = 1
        taxonomy_version.taxonomy = tax
        db.session.add(taxonomy_version)
        db.session.commit()
        taxonomy_version.original_version_id = taxonomy_version.id
        db.session.add(taxonomy_version)
        db.session.commit()
    ''' Study '''
    # What if all none? Will they be grouped together?
    #    study = Study.query.filter_by(publication_id=publication.id, study_start=data["study_start"], study_end=data["study_end"]).first()
    #    if study == None:
    #        purpose_endangered = PurposeEndangered.query.filter_by(purpose_name=data["study_purpose_endangered_id"]).first() if data["study_purpose_endangered_id"] else data["study_purpose_endangered_id"]
    #
    #        purpose_weed = PurposeWeed.query.filter_by(purpose_name="study_purpose_weed_id").first() if data["study_purpose_weed_id"] else data["study_purpose_weed_id"]
    #        database_source = Institute.query.filter_by(institution_name=data["study_database_source"]).first()# if data["study_purpose_weed_id"] else data["study_purpose_endangered_id"]
    #
    #        study_dict = {'study_duration' : data["study_duration"],
    #        'study_start' : data["study_start"],
    #        'study_end' :  data["study_end"],
    #        'number_populations' : data["study_number_populations"],
    #        'purpose_endangered_id' : purpose_endangered.id if purpose_endangered else None,
    #        'purpose_weed_id' : purpose_weed.id if purpose_weed else None,
    #        'database_source' : database_source}
    #
    #        study_cleaned = data_clean(study_dict)
    #
    #        # if not all(value == None for key, value in study_cleaned["kwargs"].items() if key not in ignore_keys) and population_present:
    #        study = Study(**study_cleaned["kwargs"])
    #        db.session.add(study)
    #        db.session.commit()
    #
    #        study.publication_id = publication.id
    #        study.species_id = species.id
    #        db.session.add(study)
    #        db.session.commit()
    #
    #
    #        ''' Study Version '''
    #        version = version_data(study_cleaned)
    #        study_version = Version(**version)
    #        study_version.version_number = 1
    #        study_version.study = study
    #        db.session.add(study_version)
    #        db.session.commit()
    #        study_version.original_version_id = study_version.id
    #        db.session.add(study_version)
    #        db.session.commit()
    ''' Protocol '''

    #    digitization_protocol = DigitizationProtocol.query.filter_by(field_name=data["digitization_protocol_id"]).first()
    #    commonterm = CommonTerm.query.filter_by(common_value_name=data["commonterm_id"]).first()

    #    protocol = Protocol.query.filter_by(protocol_id=protocol.id).first()

    #    if protocol == None:
    #        protocol_dict = {'protocol_id' : protocol.id,
    #        'digitization_protocol_id' : digitization_protocol.id if digitization_protocol else None,
    #        'commonterm_id' : commonterm.id if commonterm else None}

    #        protocol_cleaned = data_clean(protocol_dict)
    #        protocol = Protocol(**protocol_cleaned["kwargs"])

    #        db.session.add(protocol)
    #        db.session.commit()
    ''' Population '''
    '''            '''
    invasive_status_study = InvasiveStatusStudy.query.filter_by(
        status_name=data["population_invasive_status_study_id"]).first()
    invasive_status_elsewhere = InvasiveStatusStudy.query.filter_by(
        status_name=data["population_invasive_status_elsewhere_id"]).first()
    ecoregion = Ecoregion.query.filter_by(
        ecoregion_code=data["population_ecoregion_id"]).first()
    continent = Continent.query.filter_by(
        continent_name=data["population_continent_id"]).first()
    ###Danny trying add database meta-table in correct location
    database = Database.query.filter_by(
        database_master_version=data["population_database_id"]).first()

    purpose_endangered = PurposeEndangered.query.filter_by(
        purpose_name=data["study_purpose_endangered_id"]).first(
        ) if data["study_purpose_endangered_id"] else data[
            "study_purpose_endangered_id"]

    purpose_weed = PurposeWeed.query.filter_by(
        purpose_name="study_purpose_weed_id").first(
        ) if data["study_purpose_weed_id"] else data["study_purpose_weed_id"]
    database_source = Institute.query.filter_by(
        institution_name=data["study_database_source_id"]).first()

    pop = Population.query.filter_by(population_name=data["population_name"],
                                     publication_id=publication.id,
                                     species_id=species.id).first()

    if pop == None:
        pop_dict = {
            'population_name':
            data["population_name"],
            'latitude':
            data["population_latitude"],
            'lat_ns':
            data["lat_ns"],
            'lat_deg':
            data["lat_deg"],
            'lat_min':
            data["lat_min"],
            'lat_sec':
            data["lat_sec"],
            'longitude':
            data["population_longitude"],
            'lon_ew':
            data["lon_ew"],
            'lon_deg':
            data["lon_deg"],
            'lon_min':
            data["lon_min"],
            'lon_sec':
            data["lon_sec"],
            'altitude':
            data["population_altitude"],
            #'pop_size' : data["population_pop_size"],
            'country':
            data["population_country"],
            'invasive_status_study_id':
            invasive_status_study.id if invasive_status_study else None,
            'invasive_status_elsewhere_id':
            invasive_status_elsewhere.id
            if invasive_status_elsewhere else None,
            'ecoregion':
            ecoregion,
            'continent':
            continent,
            'database':
            database,
            'within_site_replication':
            data['population_within_site_replication'],
            'study_duration':
            data["study_duration"],
            'study_start':
            data["study_start"],
            'study_end':
            data["study_end"],
            'number_populations':
            data["study_number_populations"],
            'purpose_endangered_id':
            purpose_endangered.id if purpose_endangered else None,
            'purpose_weed_id':
            purpose_weed.id if purpose_weed else None,
            'database_source':
            database_source
        }

        pop_cleaned = data_clean(pop_dict)

        # if not all(value == None for key, value in pop_cleaned["kwargs"].items() if key not in ignore_keys) and matrix_present:
        pop = Population(**pop_cleaned["kwargs"])

        db.session.add(pop)
        db.session.commit()

        pop.species_author = data["species_author"]
        pop.publication_id = publication.id
        pop.species_id = species.id

        db.session.add(pop)
        db.session.commit()
        ''' Population Version '''
        #version = version_data(pop_cleaned)
        population_version = Version(**version)
        population_version.version_number = 1
        population_version.population = pop
        db.session.add(population_version)
        db.session.commit()
        population_version.original_version_id = population_version.id
        db.session.add(population_version)
        db.session.commit()
    ''' Matrix '''
    treatment_string = data["matrix_treatment_id"]

    if treatment_string == 'NDY':
        treatment = 'NDY'
    elif treatment_string == None:
        treatment = None
    else:
        treatment = Treatment.query.filter_by(
            treatment_name=data["matrix_treatment_id"]
        ).first() if Treatment.query.filter_by(
            treatment_name=data["matrix_treatment_id"]).first() else Treatment(
                treatment_name=data["matrix_treatment_id"])
        db.session.add(treatment)
        db.session.commit()

    matrix_dict = {
        'treatment':
        treatment,
        'matrix_split':
        coerce_boolean(data["matrix_split"]),
        'matrix_composition':
        MatrixComposition.query.filter_by(
            comp_name=data["matrix_composition_id"]).first(),
        'matrix_criteria_size':
        data["matrix_criteria_size"],
        'matrix_criteria_ontogeny':
        coerce_boolean(data["matrix_criteria_ontogeny"]),
        'matrix_criteria_age':
        coerce_boolean(data["matrix_criteria_age"]),
        'matrix_start_month':
        data["matrix_start_month"],
        'matrix_end_month':
        data["matrix_end_month"],
        'matrix_start_year':
        data["matrix_start_year"],
        'matrix_end_year':
        data["matrix_end_year"],
        'studied_sex':
        StudiedSex.query.filter_by(
            sex_code=data["matrix_studied_sex_id"]).first(),
        'start_season':
        StartSeason.query.filter_by(
            season_id=data["matrix_start_season_id"]).first()
        if data["matrix_start_season_id"] else None,
        'end_season':
        EndSeason.query.filter_by(
            season_id=data["matrix_end_season_id"]).first()
        if data["matrix_end_season_id"] else None,
        'matrix_fec':
        coerce_boolean(data["matrix_fec"]),
        'matrix_a_string':
        data["matrix_a_string"],
        'matrix_f_string':
        data["matrix_f_string"],
        'matrix_u_string':
        data["matrix_u_string"],
        'matrix_c_string':
        data["matrix_c_string"],
        'non_independence':
        data["matrix_non_independence"],
        'matrix_dimension':
        data["matrix_dimension"],
        'non_independence_author':
        data["matrix_non_independence_author"],
        'matrix_complete':
        coerce_boolean(data["matrix_complete"]),
        'class_number':
        data["matrix_class_number"],
        'observations':
        data["matrix_observations"],
        'captivities':
        Captivity.query.filter_by(
            cap_code=data["matrix_captivity_id"]).first(),
        'class_author':
        data["matrix_class_author"],
        'class_organized':
        data["matrix_class_organized"],
        'matrix_difficulty':
        data["matrix_difficulty"],
        'seasonal':
        coerce_boolean(data["matrix_seasonal"]),
        'survival_issue':
        calc_surv_issue(data["matrix_u_string"]),
        'periodicity':
        data["matrix_periodicity"],
        'matrix_irreducible':
        is_matrix_irreducible(data["matrix_a_string"]),
        'matrix_primitive':
        is_matrix_primitive(data["matrix_a_string"]),
        'matrix_ergodic':
        is_matrix_ergodic(data["matrix_a_string"]),
        'matrix_lambda':
        calc_lambda(data["matrix_a_string"])
    }

    matrix_cleaned = data_clean(matrix_dict)

    # if not all(value == None for key, value in matrix_cleaned["kwargs"].items() if key not in ignore_keys):
    matrix = Matrix(**matrix_cleaned["kwargs"])

    db.session.add(matrix)
    db.session.commit()

    matrix.population_id = pop.id

    db.session.add(matrix)
    db.session.commit()
    ''' matrix Version '''
    #version = version_data(matrix_cleaned)
    matrix_version = Version(**version)
    matrix_version.version_number = 1
    matrix_version.matrix = matrix
    db.session.add(matrix_version)
    db.session.commit()
    matrix_version.original_version_id = matrix_version.id
    db.session.add(matrix_version)
    db.session.commit()
    ''' Fixed '''

    fixed = Fixed.query.filter_by(matrix=matrix).first()

    if fixed == None:
        fixed_dict = {
            'matrix':
            matrix,
            'census_timings':
            CensusTiming.query.filter_by(
                census_name=data["fixed_census_timing_id"]).first(),
            'seed_stage_error':
            coerce_boolean(data["fixed_seed_stage_error"]),
            'smalls':
            Small.query.filter_by(small_name=data["fixed_small_id"]).first(),
            'vector_str':
            data["matrix_vectors_includes_na"]
        }

        fixed_cleaned = data_clean(fixed_dict)
        fixed = Fixed(**fixed_cleaned["kwargs"])

        db.session.add(fixed)
        db.session.commit()
        ''' fixed Version '''
        #version = version_data(fixed_cleaned)
        fixed_version = Version(**version)
        fixed_version.version_number = 1
        fixed_version.fixed = fixed
        db.session.add(fixed_version)
        db.session.commit()
        fixed_version.original_version_id = fixed_version.id
        db.session.add(fixed_version)
        db.session.commit()
Example #10
0
    def test_database_cascade(self):
        # User and PatientNote
        user = User(first_name='one',
                    last_name='one',
                    username='******',
                    email='*****@*****.**',
                    password='******')
        patient_note = PatientNote(title='title', notes='notes')
        patient_note.user = user
        db.session.add_all([user, patient_note])
        db.session.commit()
        db.session.delete(user)
        db.session.commit()
        self.assertEqual(len(PatientNote.query.all()), 0)

        # User and Appointment
        user = User(first_name='one',
                    last_name='one',
                    username='******',
                    email='*****@*****.**',
                    password='******')
        today = datetime.utcnow()
        appointment = Appointment(title='title',
                                  description='description',
                                  date_start=today,
                                  date_end=today)
        appointment.user = user
        db.session.add_all([user, appointment])
        db.session.commit()
        db.session.delete(user)
        db.session.commit()
        self.assertEqual(len(Appointment.query.all()), 0)

        # Patient and PatientNote
        patient = Patient(first_name='patient1',
                          last_name='patient1',
                          email='*****@*****.**')
        patient_note = PatientNote(title='title', notes='notes')
        patient_note.patient = patient
        db.session.add_all([patient, patient_note])
        db.session.commit()
        db.session.delete(patient)
        db.session.commit()
        self.assertEqual(len(PatientNote.query.all()), 0)

        # Patient and Appointment
        patient = Patient(first_name='patient1',
                          last_name='patient1',
                          email='*****@*****.**')
        appointment = Appointment(title='title',
                                  description='description',
                                  date_start=today,
                                  date_end=today)
        appointment.patient = patient
        db.session.add_all([patient, appointment])
        db.session.commit()
        db.session.delete(patient)
        db.session.commit()
        self.assertEqual(len(Appointment.query.all()), 0)

        # Treatment and Appointment
        treatment = Treatment(name='treatment1')
        appointment = Appointment(title='title',
                                  description='description',
                                  date_start=today,
                                  date_end=today)
        appointment.treatment = treatment
        db.session.add_all([treatment, appointment])
        db.session.commit()
        db.session.delete(treatment)
        db.session.commit()
        self.assertEqual(len(Appointment.query.all()), 0)

        # Hospital and User
        user = User(first_name='one',
                    last_name='one',
                    username='******',
                    email='*****@*****.**',
                    password='******')
        hospital = Hospital(name='hospital')
        user.hospital = hospital
        db.session.add_all([hospital, user])
        db.session.commit()
        db.session.delete(hospital)
        db.session.commit()
        self.assertEqual(len(User.query.all()), 0)

        # Hospital and Treatment
        treatment = Treatment(name='treatment1')
        hospital = Hospital(name='hospital')
        treatment.hospital = hospital
        db.session.add_all([hospital, treatment])
        db.session.commit()
        db.session.delete(hospital)
        db.session.commit()
        self.assertEqual(len(Treatment.query.all()), 0)
Example #11
0
 def test_name_assignment(self):
     treatment = Treatment(name='medicine')
     self.assertEqual(treatment.name, 'medicine')
Example #12
0
 def test_repr(self):
     treatment = Treatment(name='therapy')
     self.assertEqual(treatment.__repr__(), 'therapy')
Example #13
0
 def test_id(self):
     treatment = Treatment(name='medicine')
     db.session.add(treatment)
     db.session.commit()
     self.assertEqual(treatment.id, 1)