def test_off_study_date_before_subject_visit(self): """Assert cannot enter off study if visits already exist after offstudy date. """ for appointment in Appointment.objects.exclude( subject_identifier=self.subject_identifier).order_by('appt_datetime'): SubjectVisit.objects.create( appointment=appointment, visit_schedule_name=appointment.visit_schedule_name, schedule_name=appointment.schedule_name, visit_code=appointment.visit_code, report_datetime=appointment.appt_datetime, study_status=SCHEDULED) for appointment in Appointment.objects.filter(subject_identifier=self.subject_identifier): SubjectVisit.objects.create( appointment=appointment, visit_schedule_name=appointment.visit_schedule_name, schedule_name=appointment.schedule_name, visit_code=appointment.visit_code, report_datetime=get_utcnow(), study_status=SCHEDULED) appointment = Appointment.objects.filter( subject_identifier=self.subject_identifier).first() self.subject_visit = SubjectVisit.objects.get(appointment=appointment) self.assertRaises( OffstudyError, SubjectOffstudy.objects.create, subject_identifier=self.subject_consent.subject_identifier, offstudy_datetime=get_utcnow() - relativedelta(weeks=3), offstudy_reason=DEAD)
def setUp(self): self.visit_schedule_name = 'visit_schedule' self.schedule_name = 'schedule' site_visit_schedules._registry = {} site_visit_schedules.loaded = False site_visit_schedules.register(visit_schedule) site_visit_schedules.register(visit_schedule2) self.subject_identifier = '111111111' self.subject_identifiers = [ self.subject_identifier, '222222222', '333333333', '444444444'] self.consent_datetime = get_utcnow() - relativedelta(weeks=4) for subject_identifier in self.subject_identifiers: subject_consent = SubjectConsent.objects.create( subject_identifier=subject_identifier, identity=subject_identifier, confirm_identity=subject_identifier, consent_datetime=self.consent_datetime, dob=get_utcnow() - relativedelta(years=25)) Enrollment.objects.create( subject_identifier=subject_consent.subject_identifier, schedule_name=self.schedule_name, report_datetime=self.consent_datetime, facility_name='default') self.subject_consent = SubjectConsent.objects.get( subject_identifier=self.subject_identifier, dob=get_utcnow() - relativedelta(years=25)) enrollment = Enrollment.objects.get( subject_identifier=self.subject_identifier) self.schedule = enrollment.schedule
def to_outgoing_transaction(self, using, created=None, deleted=None): """ Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model. """ OutgoingTransaction = django_apps.get_model( 'edc_sync', 'OutgoingTransaction') created = True if created is None else created action = INSERT if created else UPDATE timestamp_datetime = self.instance.created if created else self.instance.modified if not timestamp_datetime: timestamp_datetime = get_utcnow() if deleted: timestamp_datetime = get_utcnow() action = DELETE outgoing_transaction = None if self.is_serialized: hostname = socket.gethostname() outgoing_transaction = OutgoingTransaction.objects.using(using).create( tx_name=self.instance._meta.label_lower, tx_pk=getattr(self.instance, self.primary_key_field.name), tx=self.encrypted_json(), timestamp=timestamp_datetime.strftime('%Y%m%d%H%M%S%f'), producer=f'{hostname}-{using}', action=action, using=using) return outgoing_transaction
def test_cannot_create_offschedule_before_onschedule(self): OnSchedule.objects.create( subject_identifier=self.subject_identifier, onschedule_datetime=get_utcnow() - relativedelta(months=1)) self.assertRaises( InvalidOffscheduleDate, OffSchedule.objects.create, subject_identifier=self.subject_identifier, offschedule_datetime=get_utcnow() - relativedelta(months=2))
def test_can_create_offschedule_with_onschedule(self): # signal puts on schedule OnSchedule.objects.create( subject_identifier=self.subject_identifier, onschedule_datetime=get_utcnow()) try: OffSchedule.objects.create( subject_identifier=self.subject_identifier, offschedule_datetime=get_utcnow()) except Exception as e: self.fail(f'Exception unexpectedly raised. Got {e}.')
def test_updates_registered_subject(self): SubjectModelOne.objects.create( screening_identifier='12345', dob=get_utcnow() - relativedelta(years=5)) new_dob = get_utcnow().date() obj = SubjectModelOne.objects.get(screening_identifier='12345') obj.dob = new_dob obj.save() rs = RegisteredSubject.objects.get( registration_identifier=obj.to_string(obj.registration_identifier)) self.assertEqual(rs.dob, new_dob)
def test_non_crf_modelform_mixin_not_ok(self): """Asserts that Offstudy class is called. Other tests above apply. """ SubjectOffstudy.objects.create( offstudy_datetime=get_utcnow() - relativedelta(days=1), subject_identifier=self.subject_identifier) data = dict( subject_identifier=self.subject_identifier, report_datetime=get_utcnow()) form = NonCrfOneForm(data=data) form.is_valid() self.assertIn('report_datetime', form.errors)
def test_updates_registered_subject_overridden2(self): """Assert updates RegisteredSubject with registration_unique_field overridden. """ SubjectModelThree.objects.create( subject_identifier='12345', dob=get_utcnow() - relativedelta(years=5)) new_dob = get_utcnow().date() obj = SubjectModelThree.objects.get(subject_identifier='12345') obj.dob = new_dob obj.save() rs = RegisteredSubject.objects.get( subject_identifier=obj.subject_identifier) self.assertEqual(rs.dob, new_dob)
def test_modelform_mixin_ok(self): data = dict( subject_identifier=self.subject_identifier, offstudy_datetime=get_utcnow(), offstudy_reason=DEAD) form = SubjectOffstudyForm(data=data) self.assertTrue(form.is_valid())
def setUp(self): import_holidays() self.options = {'consent_datetime': get_utcnow(), 'version': '2'} self.screening_preg = mommy.make_recipe( 'flourish_caregiver.screeningpregwomen', ) self.preg_subject_consent = mommy.make_recipe( 'flourish_caregiver.subjectconsent', screening_identifier=self.screening_preg.screening_identifier, breastfeed_intent=YES, **self.options) self.preg_caregiver_child_consent_obj = mommy.make_recipe( 'flourish_caregiver.caregiverchildconsent', subject_consent=self.preg_subject_consent, gender=None, first_name=None, last_name=None, identity=None, confirm_identity=None, study_child_identifier=None, child_dob=None, version='2') self.preg_subject_identifier = self.preg_subject_consent.subject_identifier
def test_off_study_date_after_subject_visit(self): """Assert can enter off study if visits do not exist after off-study date. """ for appointment in Appointment.objects.exclude( subject_identifier=self.subject_identifier).order_by('appt_datetime'): SubjectVisit.objects.create( appointment=appointment, visit_schedule_name=appointment.visit_schedule_name, schedule_name=appointment.schedule_name, visit_code=appointment.visit_code, report_datetime=appointment.appt_datetime, study_status=SCHEDULED) for appointment in Appointment.objects.filter( subject_identifier=self.subject_identifier).order_by('appt_datetime')[0:2]: SubjectVisit.objects.create( appointment=appointment, visit_schedule_name=appointment.visit_schedule_name, schedule_name=appointment.schedule_name, visit_code=appointment.visit_code, report_datetime=appointment.appt_datetime, study_status=SCHEDULED) try: SubjectOffstudy.objects.create( subject_identifier=self.subject_consent.subject_identifier, offstudy_datetime=get_utcnow(), offstudy_reason=DEAD) except OffstudyError: self.fail('OffstudyError unexpectedly raised')
def status(self, reference_datetime=None): reference_datetime = reference_datetime or get_utcnow() if self.closing_datetime < reference_datetime: status = CLOSED else: status = OPEN return status
def test_first_appointment_with_visit_schedule(self): """Asserts first appointment correctly selected if just visit_schedule_name provided. """ subject_consent = SubjectConsent.objects.create( subject_identifier=self.subject_identifier, consent_datetime=get_utcnow()) OnScheduleTwo.objects.create( subject_identifier=self.subject_identifier, onschedule_datetime=subject_consent.consent_datetime) OnScheduleOne.objects.create( subject_identifier=self.subject_identifier, onschedule_datetime=( subject_consent.report_datetime + relativedelta(months=1))) first_appointment = Appointment.objects.first_appointment( subject_identifier=self.subject_identifier, visit_schedule_name='visit_schedule2') self.assertEqual(first_appointment.schedule_name, 'schedule2') self.assertEqual( Appointment.objects.filter( subject_identifier=self.subject_identifier, visit_schedule_name='visit_schedule2').order_by('appt_datetime')[0], first_appointment)
def test_appointments_dates_mo(self): """Test appointment datetimes are chronological. """ for index in range(0, 7): SubjectConsent.objects.create( subject_identifier=f'{self.subject_identifier}-{index}', consent_datetime=get_utcnow()) for day in [MO, TU, WE, TH, FR, SA, SU]: subject_consent = SubjectConsent.objects.all()[day.weekday] OnScheduleOne.objects.create( subject_identifier=subject_consent.subject_identifier, onschedule_datetime=(subject_consent.consent_datetime + relativedelta(weeks=2) + relativedelta(weekday=day(-1)))) appt_datetimes = [ obj.appt_datetime for obj in Appointment.objects.filter( subject_identifier=subject_consent.subject_identifier).order_by( 'appt_datetime')] last = None self.assertGreater(len(appt_datetimes), 0) for appt_datetime in appt_datetimes: if not last: last = appt_datetime else: self.assertGreater(appt_datetime, last) last = appt_datetime
def setUp(self): site_sync_models.registry = {} site_sync_models.loaded = False sync_models = ['edc_sync.testmodeldates'] site_sync_models.register(sync_models, wrapper_cls=SyncModel) self.export_path = os.path.join(tempfile.gettempdir(), 'export') if not os.path.exists(self.export_path): os.mkdir(self.export_path) self.import_path = self.export_path IncomingTransaction.objects.all().delete() OutgoingTransaction.objects.using('client').all().delete() TestModelDates.objects.all().delete() TestModelDates.objects.using('client').all().delete() self.date = get_utcnow() TestModelDates.objects.using('client').create(f2=self.date.date()) tx_exporter = TransactionExporter( export_path=self.export_path, using='client') batch = tx_exporter.export_batch() tx_importer = TransactionImporter(import_path=self.import_path) self.batch = tx_importer.import_batch(filename=batch.filename) datetime_format = '%Y-%m-%dT%H:%M:%S.%fZ' self.obj = IncomingTransaction.objects.all()[0] bad_date = self.date.strftime(datetime_format) json_text = self.obj.aes_decrypt(self.obj.tx) json_obj = json.loads(json_text) json_obj[0]['fields']['f2'] = bad_date json_text = json.dumps(json_obj) self.obj.tx = self.obj.aes_encrypt(json_text) self.obj.save() self.obj = IncomingTransaction.objects.get(id=self.obj.id) self.app_config = copy(django_apps.get_app_config('edc_sync'))
def test_live_births_one_still_births_invalid(self): cleaned_data = { 'report_datetime': get_utcnow(), 'subject_identifier': self.subject_consent.subject_identifier, 'arv_initiation_date': get_utcnow().date(), 'valid_regiment_duration': YES, 'delivery_datetime': get_utcnow() + relativedelta(weeks=5), 'still_births': 1, 'live_infants_to_register': 1 } maternal_status = MaternalStatusHelper(status=POS) MaternalDeliveryFormValidator.maternal_status_helper = maternal_status form_validator = MaternalDeliveryFormValidator( cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('still_births', form_validator._errors)
def test_still_births_one_live_births_zero_valid(self): cleaned_data = { 'report_datetime': get_utcnow(), 'subject_identifier': self.subject_consent.subject_identifier, 'arv_initiation_date': get_utcnow().date(), 'valid_regiment_duration': YES, 'delivery_datetime': get_utcnow() + relativedelta(weeks=5), 'still_births': 1, 'live_infants_to_register': 0 } form_validator = MaternalDeliveryFormValidator( cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_delivery_date_more_than_4wks_arv_init_date_valid(self): cleaned_data = { 'report_datetime': get_utcnow(), 'subject_identifier': self.subject_consent.subject_identifier, 'valid_regiment_duration': YES, 'arv_initiation_date': get_utcnow().date(), 'delivery_datetime': get_utcnow() + relativedelta(weeks=5) } maternal_status = MaternalStatusHelper(status=POS) MaternalDeliveryFormValidator.maternal_status_helper = maternal_status form_validator = MaternalDeliveryFormValidator( cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def add_plot_log_entry(self, plot, log_status=None, **options): """Returns a plot log entry instance that defaults to an accessible plot. """ log_status = log_status or ACCESSIBLE plot_log = PlotLog.objects.get(plot=plot) options['report_datetime'] = options.get('report_datetime', get_utcnow()) try: PlotLogEntry.objects.filter( plot_log=plot_log, report_datetime=options.get('report_datetime')).order_by( 'report_datetime').last() except PlotLogEntry.DoesNotExist: pass else: options['report_datetime'] = options.get( 'report_datetime') + relativedelta(days=1) opts = {} for field in PlotLogEntry._meta.get_fields(): if field.name in options: opts.update({field.name: options.get(field.name)}) return mommy.make_recipe('plot.plotlogentry', plot_log=plot_log, log_status=log_status, **opts)
def onschedule_or_raise(self, subject_identifier=None, report_datetime=None, compare_as_datetimes=None): try: history_obj = self.history_model_cls.objects.get( subject_identifier=subject_identifier, visit_schedule_name=self.visit_schedule_name, schedule_name=self.schedule_name) except ObjectDoesNotExist: raise NotOnScheduleError( f'Subject is not been put on schedule {self.schedule_name}. ' f'Got {subject_identifier}.') offschedule_datetime = history_obj.offschedule_datetime or get_utcnow() if compare_as_datetimes: in_date_range = (history_obj.onschedule_datetime <= report_datetime <= offschedule_datetime) else: in_date_range = (history_obj.onschedule_datetime.date() <= report_datetime.date() <= offschedule_datetime.date()) if not in_date_range: formatted_date = report_datetime.strftime( convert_php_dateformat(settings.SHORT_DATE_FORMAT)) raise NotOnScheduleForDateError( f'Subject not on schedule {self.schedule_name} on ' f'{formatted_date}. Got {subject_identifier}.')
def setUp(self): site_sync_models.registry = {} site_sync_models.loaded = False sync_models = ['edc_sync.testmodeldates'] site_sync_models.register(sync_models, wrapper_cls=SyncModel) self.export_path = os.path.join(tempfile.gettempdir(), 'export') if not os.path.exists(self.export_path): os.mkdir(self.export_path) self.import_path = self.export_path IncomingTransaction.objects.all().delete() OutgoingTransaction.objects.using('client').all().delete() TestModelDates.objects.all().delete() TestModelDates.objects.using('client').all().delete() self.date = get_utcnow() TestModelDates.objects.using('client').create(f2=self.date.date()) tx_exporter = TransactionExporter(export_path=self.export_path, using='client') batch = tx_exporter.export_batch() tx_importer = TransactionImporter(import_path=self.import_path) self.batch = tx_importer.import_batch(filename=batch.filename) datetime_format = '%Y-%m-%dT%H:%M:%S.%fZ' self.obj = IncomingTransaction.objects.all()[0] bad_date = self.date.strftime(datetime_format) json_text = self.obj.aes_decrypt(self.obj.tx) json_obj = json.loads(json_text) json_obj[0]['fields']['f2'] = bad_date json_text = json.dumps(json_obj) self.obj.tx = self.obj.aes_encrypt(json_text) self.obj.save() self.obj = IncomingTransaction.objects.get(id=self.obj.id) self.app_config = copy(django_apps.get_app_config('edc_sync'))
def setUp(self): import_holidays() self.visit_schedule = VisitSchedule( name='visit_schedule', verbose_name='Visit Schedule', offstudy_model='edc_visit_schedule.subjectoffstudy', death_report_model='edc_visit_schedule.deathreport') self.schedule = Schedule( name='schedule', onschedule_model='edc_visit_schedule.onschedule', offschedule_model='edc_visit_schedule.offschedule', appointment_model='edc_appointment.appointment', consent_model='edc_visit_schedule.subjectconsent') visit = Visit( code='1000', rbase=relativedelta(days=0), rlower=relativedelta(days=0), rupper=relativedelta(days=6), facility_name='default') self.schedule.add_visit(visit) self.visit_schedule.add_schedule(self.schedule) site_visit_schedules._registry = {} site_visit_schedules.register(self.visit_schedule) self.subject_consent = SubjectConsent.objects.create( subject_identifier='12345', consent_datetime=get_utcnow() - relativedelta(seconds=1), dob=date(1995, 1, 1), identity='11111', confirm_identity='11111') self.subject_identifier = self.subject_consent.subject_identifier
def test_srh_required(self): self.create_mother(self.hiv_pos_mother_options()) mommy.make_recipe( 'td_maternal.maternallabourdel', subject_identifier=self.subject_consent.subject_identifier, report_datetime=get_utcnow()) mommy.make_recipe( 'td_maternal.karabosubjectscreening', subject_identifier=self.subject_consent.subject_identifier, willing_to_consent=NO, report_datetime=get_utcnow()) for x in Appointment.objects.all().order_by('timepoint'): if x.visit_code not in ['1000M', '1010M']: visit = mommy.make_recipe( 'td_maternal.maternalvisit', subject_identifier=self.subject_consent.subject_identifier, report_datetime=get_utcnow(), appointment=x) if x.visit_code == '2120M': mommy.make_recipe( 'td_maternal.maternalcontraception', maternal_visit=visit, report_datetime=get_utcnow(), srh_referral=YES) self.assertEqual( CrfMetadata.objects.get( model='td_maternal.maternalsrh', subject_identifier=self.subject_consent.subject_identifier, visit_code='2240M').entry_status, REQUIRED) visit_2240 = MaternalVisit.objects.get(visit_code='2240M') mommy.make_recipe('td_maternal.maternalsrh', maternal_visit=visit_2240, report_datetime=get_utcnow()) visit_2300M = MaternalVisit.objects.get(visit_code='2300M') visit_2300M.save() self.assertEqual( CrfMetadata.objects.get( model='td_maternal.maternalsrh', subject_identifier=self.subject_consent.subject_identifier, visit_code='2300M').entry_status, NOT_REQUIRED)
def test_cohort_c_onschedule_valid(self): """Assert that a 10 year old participant's mother who is on the PI regimen from Mpepu study is put on cohort c. """ self.subject_identifier = self.subject_identifier[:-1] + '4' self.maternal_dataset_options['protocol'] = 'Tshipidi' self.maternal_dataset_options['delivdt'] = self.year_3_age(11, 1) self.maternal_dataset_options['preg_pi'] = 1 self.child_dataset_options['infant_hiv_exposed'] = 'Unexposed' self.options['subject_identifier'] = self.subject_identifier mommy.make_recipe('flourish_child.childdataset', subject_identifier=self.subject_identifier + '10', dob=self.year_3_age(11, 1), **self.child_dataset_options) maternal_dataset_obj = mommy.make_recipe( 'flourish_caregiver.maternaldataset', subject_identifier=self.subject_identifier, **self.maternal_dataset_options) sh = SubjectHelperMixin() subject_identifier = sh.enroll_prior_participant_assent( maternal_dataset_obj.screening_identifier, study_child_identifier=self. child_dataset_options['study_child_identifier']) self.assertEqual( OnScheduleCohortCEnrollment.objects.filter( subject_identifier=subject_identifier, schedule_name='c_enrol1_schedule1').count(), 1) self.assertEqual( OnScheduleCohortCQuarterly.objects.filter( subject_identifier=subject_identifier, schedule_name='c_quarterly1_schedule1').count(), 0) mommy.make_recipe('flourish_caregiver.maternalvisit', appointment=Appointment.objects.get( visit_code='2000M', subject_identifier=subject_identifier), report_datetime=get_utcnow(), reason=SCHEDULED) self.assertEqual( OnScheduleCohortCQuarterly.objects.filter( subject_identifier=subject_identifier, schedule_name='c_quarterly1_schedule1').count(), 1) # self.assertEqual(OnScheduleCohortCFU.objects.filter( # subject_identifier=subject_identifier, # schedule_name='c_fu1_schedule1').count(), 1) self.assertNotEqual( Appointment.objects.filter( subject_identifier=subject_identifier).count(), 0)
def enroll_prior_participant_assent(self, screening_identifier, study_child_identifier, consent_datetime=None, hiv_status=None): try: maternal_dataset_obj = MaternalDataset.objects.get( screening_identifier=screening_identifier) except MaternalDataset.DoesNotExist: pass else: self.options = { 'consent_datetime': consent_datetime or get_utcnow(), 'version': '1' } mommy.make_recipe( 'flourish_caregiver.screeningpriorbhpparticipants', screening_identifier=maternal_dataset_obj.screening_identifier, study_maternal_identifier=maternal_dataset_obj. study_maternal_identifier) subject_consent = mommy.make_recipe( 'flourish_caregiver.subjectconsent', screening_identifier=maternal_dataset_obj.screening_identifier, breastfeed_intent=NOT_APPLICABLE, **self.options) caregiver_child_consent_obj = mommy.make_recipe( 'flourish_caregiver.caregiverchildconsent', subject_consent=subject_consent, study_child_identifier=study_child_identifier, child_dob=maternal_dataset_obj.delivdt, ) mommy.make_recipe( 'flourish_child.childassent', subject_identifier=caregiver_child_consent_obj. subject_identifier, first_name=caregiver_child_consent_obj.first_name, last_name=caregiver_child_consent_obj.last_name, dob=caregiver_child_consent_obj.child_dob, identity=caregiver_child_consent_obj.identity, confirm_identity=caregiver_child_consent_obj.identity, remain_in_study=YES, version=subject_consent.version) if hiv_status: mommy.make_recipe( 'flourish_caregiver.caregiverpreviouslyenrolled', subject_identifier=subject_consent.subject_identifier, current_hiv_status=hiv_status) else: mommy.make_recipe( 'flourish_caregiver.caregiverpreviouslyenrolled', subject_identifier=subject_consent.subject_identifier) return subject_consent.subject_identifier
def _data(self): return { '_created': get_utcnow(), 'best_prev_result_date': self.best_prev_result_date, 'documented_pos': self.documented_pos, 'documented_pos_date': self.documented_pos_date, 'final_arv_status': self.final_arv_status, 'final_arv_status_baseline': self.final_arv_status_baseline, 'final_hiv_status': self.final_hiv_status, 'final_hiv_status_date': self.final_hiv_status_date, 'has_tested': self.has_tested, 'indeterminate': self.indeterminate, 'known_positive': self.known_positive, 'naive_at_baseline': self.naive_at_baseline, 'newly_diagnosed': self.newly_diagnosed, 'prev_result': self.prev_result, 'prev_result_date': self.prev_result_date, 'prev_result_known': self.prev_result_known, 'prev_results_discordant': self.prev_results_discordant, 'subject_identifier': self.subject_identifier, 'source_object_name': self.source_object_name, 'today_hiv_result': self.current.today_hiv_result, 'baseline_hiv_result': self.baseline.today_hiv_result, 'current_hiv_result': self.current.today_hiv_result, 'self_reported_result': self.current.self_reported_result, 'current_arv_evidence': self.current.arv_evidence, 'declined': self.declined, 'defaulter_at_baseline': self.defaulter_at_baseline, 'visit_code': self.subject_visit.visit_code, 'visit_date': Arrow.fromdatetime(self.subject_visit.report_datetime).date(), }
def test_consent_date_more_than_report_date_invalid(self): '''Asserts raises exception if subject received antiretrovirals during a prior pregnancy and date first started given but does not state if the date is estimated or not.''' self.maternal_visit.report_datetime = get_utcnow() - relativedelta( days=30) cleaned_data = { 'maternal_visit': self.maternal_visit, 'art_start_date': get_utcnow().date(), 'is_date_estimated': NO, 'report_datetime': get_utcnow() - relativedelta(days=30) } form_validator = ArvsPrePregnancyFormValidator( cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('report_datetime', form_validator._errors)
def test_repr(self): creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=get_utcnow()) self.assertTrue(creator)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update( MALE=MALE, reference_datetime=get_utcnow()) context.update( {k: v for k, v in self.url_names('anonymous_listboard_url_name')}) return context
def save(self, *args, **kwargs): if not self.using: raise ValueError( 'Value for \'{}.using\' cannot be None.'.format( self._meta.model_name)) if self.is_consumed_server and not self.consumed_datetime: self.consumed_datetime = get_utcnow() super().save(*args, **kwargs)
def test_yes_blood_culture_performed_with_blood_culture_results(self): data = {'subject_visit': self.subject_visit, 'blood_culture_performed': YES, 'blood_taken_date': get_utcnow().date(), 'blood_culture_results': 'no_growth'} form = MicrobiologyForm(initial=data) form.is_valid()
def test_delivery_c_section_valid(self): cleaned_data = { 'report_datetime': get_utcnow(), 'subject_identifier': self.subject_consent.subject_identifier, 'arv_initiation_date': get_utcnow().date(), 'delivery_datetime': get_utcnow() + relativedelta(weeks=5), 'valid_regiment_duration': YES, 'mode_delivery': 'elective c-section', 'csection_reason': 'blahblah' } maternal_status = MaternalStatusHelper(status=POS) MaternalLabDelFormValidator.maternal_status_helper = maternal_status form_validator = MaternalLabDelFormValidator(cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_validate_negative_no_cd4_not(self): '''Assert raises exception if sero_posetive is yes and perinataly_infected, know_hiv_status, lowest_cd4_known are given ''' maternal_status = MaternalStatusHelper(status=NEG) MaternalMedicalHistoryFormValidator.maternal_status_helper = maternal_status self.cleaned_data.update( sero_posetive=YES, cd4_date=get_utcnow().date() + relativedelta(years=1), cd4_count=20, is_date_estimated=get_utcnow().date() + relativedelta(years=2), lowest_cd4_known=NOT_APPLICABLE ) form_validator = MaternalMedicalHistoryFormValidator( cleaned_data=self.cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('sero_posetive', form_validator._errors)
def test_hip_circ_required_invalid(self): appointment = Appointment.objects.create( subject_identifier=self.subject_consent.subject_identifier, appt_datetime=get_utcnow(), visit_code='2000D') self.maternal_visit = MaternalVisit.objects.create( appointment=appointment, subject_identifier=self.subject_consent.subject_identifier, report_datetime=get_utcnow()) cleaned_data = {'maternal_visit': self.maternal_visit, 'hip_circ': 15} form_validator = CaregiverClinicalMeasurementsFormValidator( cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('hip_circ', form_validator._errors)
def setUp(self): self.subject_consent = SubjectConsent.objects.create( subject_identifier='11111111', gender='M', dob=(get_utcnow() - relativedelta(years=25)).date(), consent_datetime=get_utcnow()) appointment = Appointment.objects.create( subject_identifier=self.subject_consent.subject_identifier, appt_datetime=get_utcnow(), visit_code='1000') self.maternal_visit = MaternalVisit.objects.create( appointment=appointment) self.maternal_ultrasound = MaternalUltraSoundInitial.objects.create( maternal_visit=self.maternal_visit, ga_confirmed=20) self.maternal_ultrasound_model = 'td_maternal_validators.maternalultrasoundinitial' MaternalObstericalHistoryFormValidator.maternal_ultrasound_init_model = \ self.maternal_ultrasound_model
def test_form_report_datetime1(self): data = { 'household_log': self.household_structure.householdlog.id, 'report_datetime': get_utcnow() } form = HouseholdLogEntryForm(data=data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors.get('report_datetime'), None)
def test_infant_subject_identifier_2_children(self): self.study_maternal_identifier = '981232' self.maternal_dataset_options['protocol'] = 'Mpepu' self.maternal_dataset_options['delivdt'] = get_utcnow( ) - relativedelta(years=4, months=9) maternal_dataset_obj = mommy.make_recipe( 'flourish_caregiver.maternaldataset', preg_efv=1, **self.maternal_dataset_options) mommy.make_recipe('flourish_child.childdataset', dob=get_utcnow() - relativedelta(years=4, months=9), **self.child_dataset_options) self.child_dataset_options['study_child_identifier'] = '1235' mommy.make_recipe('flourish_child.childdataset', dob=get_utcnow() - relativedelta(years=5, months=9), **self.child_dataset_options) mommy.make_recipe( 'flourish_caregiver.screeningpriorbhpparticipants', screening_identifier=maternal_dataset_obj.screening_identifier, ) subject_consent = mommy.make_recipe( 'flourish_caregiver.subjectconsent', screening_identifier=maternal_dataset_obj.screening_identifier, breastfeed_intent=NOT_APPLICABLE, **self.options) first_child = mommy.make_recipe( 'flourish_caregiver.caregiverchildconsent', subject_consent=subject_consent, child_dob=(get_utcnow() - relativedelta(years=4, months=9)).date(), ) second_child = mommy.make_recipe( 'flourish_caregiver.caregiverchildconsent', subject_consent=subject_consent, identity='234513181', confirm_identity='234513181', child_dob=(get_utcnow() - relativedelta(years=5, months=9)).date(), ) self.assertTrue(first_child.subject_identifier.endswith('10')) self.assertTrue(second_child.subject_identifier.endswith('60'))
def test_study_covid_visit_valid(self): cleaned_data = { 'report_datetime': get_utcnow(), 'survival_status': ALIVE, 'last_alive_date': get_utcnow().date(), 'study_status': ON_STUDY, 'appointment': self.appointment, 'covid_visit': YES, 'is_present': NO } form_validator = MaternalVisitFormValidator(cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_recruitment_clinic_not_OTHER_recruitment_clinic_other_valid(self): cleaned_data = { 'screening_identifier': self.screening_identifier, 'consent_datetime': get_utcnow(), 'dob': (get_utcnow() - relativedelta(years=22)).date(), 'recruitment_clinic': 'G.West Clinic', 'recruitment_clinic_other': None, 'first_name': 'TEST ONE', 'last_name': 'TEST', 'initials': 'TOT', 'citizen': YES } form_validator = SubjectConsentFormValidator(cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_knows_appointment(self): appointment = Appointment.objects.create( subject_identifier=self.subject_identifier, appt_datetime=get_utcnow(), appt_reason='scheduled') subject_visit = SubjectVisit.objects.create(appointment=appointment) wrapper = MySubjectVisitModelWrapper(model_obj=subject_visit) self.assertEqual(str(appointment.id), wrapper.appointment)
def test_prev_preg_art_yes_start_date_provided(self): '''Tests validates cleaned data given or fails the tests if validation error raised unexpectedly.''' cleaned_data = { 'maternal_visit': self.maternal_visit, 'prev_preg_art': YES, 'art_start_date': get_utcnow().date(), 'is_date_estimated': 'no', 'report_datetime': get_utcnow() } form_validator = ArvsPrePregnancyFormValidator( cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_LMP_more_than_28wks_of_report_datetime_invalid(self): '''Asserts if an exception is raised if last period date is more than 28 weeks of the report datetime.''' cleaned_data = { 'subject_identifier': self.subject_identifier, 'report_datetime': get_utcnow(), 'last_period_date': get_utcnow().date() - relativedelta(weeks=29), 'rapid_test_done': YES, 'rapid_test_result': NEG, 'rapid_test_date': get_utcnow().date(), 'current_hiv_status': NEG } form_validator = AntenatalEnrollmentFormValidator( cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('last_period_date', form_validator._errors)
def test_haart_start_more_than_dob_valid(self): '''Tests validates cleaned data given or fails the tests if validation error raised unexpectedly.''' cleaned_data = { 'maternal_visit': self.maternal_visit, 'haart_start_date': get_utcnow().date(), 'is_date_estimated': NO, 'maternal_visit': self.maternal_visit, 'report_datetime': get_utcnow() } form_validator = MaternalLifetimeArvHistoryFormValidator( cleaned_data=cleaned_data) try: form_validator.validate() except ValidationError as e: self.fail(f'ValidationError unexpectedly raised. Got{e}')
def test_preg_on_art_yes_preg_prior_invalid(self): '''Asserts raises exception if subject was still on triple antiretrovirals at the time she became pregnant but prior to pregnancy value is stopped.''' cleaned_data = { 'maternal_visit': self.maternal_visit, 'preg_on_art': YES, 'prior_preg': STOPPED, 'art_start_date': get_utcnow().date(), 'is_date_estimated': 'yes', 'report_datetime': get_utcnow() + relativedelta(days=30) } form_validator = ArvsPrePregnancyFormValidator( cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('prior_preg', form_validator._errors)
def handle(self, *args, **kwargs): already_exists = 0 created = 0 file_path = kwargs['file_path'] data = self.data(file_path=file_path) for data_item in data: options = {} for field_name in self.all_model_fields: options[field_name] = data_item.get(field_name) # Convert date to date objects try: report_datetime = get_utcnow() # report_datetime = make_aware(report_datetime, pytz.timezone(settings.TIME_ZONE)) except parser.ParserError: options.update(report_datetime=None) else: options.update(report_datetime=report_datetime) try: locator_date = parser.parse(options.get('locator_date')).date() except parser.ParserError: options.update(locator_date=None) else: options.update(locator_date=locator_date) locator = None try: locator = CaregiverLocator.objects.get( study_maternal_identifier=data_item.get( 'study_maternal_identifier')) except CaregiverLocator.DoesNotExist: options.update(user_created='imosweu') locator = CaregiverLocator.objects.create(**options) created += 1 else: for (key, value) in options.items(): setattr(locator, key, value) locator.save() already_exists += 1 try: dataset = MaternalDataset.objects.get( study_maternal_identifier=data_item.get( 'study_maternal_identifier')) except MaternalDataset.DoesNotExist: pass else: screening_identifier = getattr(dataset, 'screening_identifier') setattr(locator, 'screening_identifier', screening_identifier) locator.save() self.stdout.write( self.style.SUCCESS(f'A total of {created} have been created')) self.stdout.write( self.style.WARNING( f'Total items {already_exists} already existed'))
def test_hiv_rapid_test_required(self): self.maternal_dataset_options = { 'delivdt': get_utcnow() - relativedelta(years=8), 'mom_enrolldate': get_utcnow(), 'mom_hivstatus': 'HIV-uninfected', 'study_maternal_identifier': '11123', 'protocol': 'Mpepu', 'preg_pi': 0 } self.child_dataset_options = { 'infant_hiv_exposed': '', 'infant_enrolldate': get_utcnow(), 'study_maternal_identifier': '11123', 'study_child_identifier': '1234', 'dob': get_utcnow() - relativedelta(years=8) } mommy.make_recipe('flourish_child.childdataset', **self.child_dataset_options) maternal_dataset_obj = mommy.make_recipe( 'flourish_caregiver.maternaldataset', **self.maternal_dataset_options) sh = SubjectHelperMixin() subject_identifier = sh.enroll_prior_participant_assent( maternal_dataset_obj.screening_identifier, self.child_dataset_options.get('study_child_identifier'), hiv_status=NEG) mommy.make_recipe('flourish_caregiver.maternalvisit', appointment=Appointment.objects.get( visit_code='2000M', subject_identifier=subject_identifier), report_datetime=get_utcnow(), reason=SCHEDULED) self.assertEqual( CrfMetadata.objects.get( model='flourish_caregiver.hivrapidtestcounseling', subject_identifier=subject_identifier, visit_code='2000M').entry_status, REQUIRED)
def test_offstudy_cls_consented(self): try: Offstudy( subject_identifier=self.subject_identifier, offstudy_datetime=get_utcnow(), consent_model='edc_offstudy.subjectconsent', label_lower='edc_offstudy.subjectoffstudy') except OffstudyError: self.fail('OffstudyError unexpectedly raised.')
def test_cannot_put_on_schedule_if_visit_schedule_not_consented(self): _, schedule = site_visit_schedules.get_by_onschedule_model( 'edc_visit_schedule.onschedule') SubjectConsent.objects.all().delete() self.assertRaises( NotConsentedError, schedule.put_on_schedule, subject_identifier=self.subject_identifier, onschedule_datetime=get_utcnow())
def test_creates_appointments_starting_with_onschedule_datetime(self): _, schedule = site_visit_schedules.get_by_onschedule_model( 'edc_visit_schedule.onschedule') onschedule_datetime = get_utcnow() - relativedelta(months=1) schedule.put_on_schedule( subject_identifier=self.subject_identifier, onschedule_datetime=onschedule_datetime) appointment = Appointment.objects.all().order_by('appt_datetime').first() self.assertEqual(appointment.appt_datetime, onschedule_datetime)
def test_cannot_put_on_schedule_if_visit_schedule_not_registered_subject(self): _, schedule = site_visit_schedules.get_by_onschedule_model( 'edc_visit_schedule.onschedule') RegisteredSubject.objects.all().delete() self.assertRaises( UnknownSubjectError, schedule.put_on_schedule, subject_identifier=self.subject_identifier, onschedule_datetime=get_utcnow())
def test_off_study_date_before_consent(self): """Assert cannot go off study a week before consent. """ self.assertRaises( OffstudyError, SubjectOffstudy.objects.create, subject_identifier=self.subject_consent.subject_identifier, offstudy_datetime=get_utcnow() - relativedelta(weeks=5), offstudy_reason=DEAD)
def test_ga_ultrasound_wks_invalid(self): cleaned_data = { 'maternal_visit': self.maternal_visit, 'ga_by_ultrasound_wks': 50, 'report_datetime': get_utcnow(), } form_validator = UltrasoundFormValidator(cleaned_data=cleaned_data) self.assertRaises(ValidationError, form_validator.validate) self.assertIn('ga_by_ultrasound_wks', form_validator._errors)
def test_appointments_creation2(self): """Asserts first appointment correctly selected if both visit_schedule_name and schedule_name provided. """ self.helper.consent_and_put_on_schedule() OnScheduleTwo.objects.create( subject_identifier=self.subject_identifier, onschedule_datetime=get_utcnow()) self.assertEqual(Appointment.objects.all().count(), 8)
def update_verified(self): if self.status in [OPEN, VERIFIED]: if self.is_verified: self.verified = 1 self.status = VERIFIED self.verified_datetime = get_utcnow() else: self.verified = 0 self.verified_datetime = None self.status = OPEN
def report_datetime(self): report_datetime = None try: report_datetime = self.appointment.visit.report_datetime except AttributeError: try: report_datetime = self.appointment.appt_datetime except AttributeError: pass return report_datetime or get_utcnow()
def test_off_study_date_after_consent(self): """Assert can go off study a week after consent. """ try: SubjectOffstudy.objects.create( subject_identifier=self.subject_consent.subject_identifier, offstudy_datetime=get_utcnow() - relativedelta(weeks=3), offstudy_reason=DEAD) except OffstudyError: self.fail('OffstudyError unexpectedly raised.')
def consent_and_put_on_schedule(self, subject_identifier=None): subject_identifier = subject_identifier or self.subject_identifier subject_consent = SubjectConsent.objects.create( subject_identifier=subject_identifier, consent_datetime=get_utcnow()) _, schedule = site_visit_schedules.get_by_onschedule_model( 'edc_visit_tracking.onscheduleone') schedule.put_on_schedule( subject_identifier=subject_consent.subject_identifier, onschedule_datetime=subject_consent.consent_datetime)
def post_identifier(self): """Creates a registered subject instance for this subject identifier. """ model = django_apps.get_app_config('edc_registration').model model.objects.create( subject_identifier=self.identifier, site=self.site, subject_type=self.identifier_type, last_name=self.last_name, registration_datetime=get_utcnow())
def test_listboard_filter_view(self): class SubjectVisitModelWrapper(ModelWrapper): model = 'edc_dashboard.subjectvisit' next_url_name = 'thenexturl' class MyListboardViewFilters(ListboardViewFilters): all = ListboardFilter( name='all', label='All', lookup={}) scheduled = ListboardFilter( label='Scheduled', lookup={'reason': 'scheduled'}) not_scheduled = ListboardFilter( label='Not Scheduled', exclude_filter=True, lookup={'reason': 'scheduled'}) class MyView(ListboardFilterViewMixin, ListboardView): model = 'edc_dashboard.subjectvisit' listboard_url = 'listboard_url' listboard_template = 'listboard_template' listboard_filter_url = 'listboard_url' model_wrapper_cls = SubjectVisitModelWrapper listboard_view_filters = MyListboardViewFilters() start = datetime(2013, 5, 1, 12, 30) end = datetime(2013, 5, 10, 17, 15) for r in arrow.Arrow.range('day', start, end): SubjectVisit.objects.create( subject_identifier='1234', report_datetime=r.datetime, reason='missed') subject_visit = SubjectVisit.objects.create( subject_identifier='1234', report_datetime=get_utcnow(), reason='scheduled') request = RequestFactory().get('/?scheduled=scheduled') request.user = '******' request.site = Site.objects.get_current() request.url_name_data = {'listboard_url': 'listboard_url'} request.template_data = {'listboard_template': 'listboard.html'} template_response = MyView.as_view()(request=request) object_list = template_response.__dict__.get( 'context_data').get('object_list') self.assertEqual( [wrapper.object.reason for wrapper in object_list if wrapper.object.pk == subject_visit.pk], [subject_visit.reason])
def test_modelform_mixin_not_ok(self): """Asserts that Offstudy class is called. Other tests above apply. """ data = dict( subject_identifier='12345', offstudy_datetime=get_utcnow(), offstudy_reason=DEAD) form = SubjectOffstudyForm(data=data) form.is_valid() self.assertIn('Unknown subject. Got 12345.', form.errors.get('__all__'))