Example #1
0
    def test_p3(self):
        print 'get a community name from the mapper classes'
        mapper = site_mappers.get_current_mapper()
        community = mapper.map_area
        print 'No. of SURVEY = ' + str(Survey.objects.all().count())
        plot = PlotFactory(community=community, household_count=1, status='residential_habitable')
        print 'No. of HOUSEHOLDS = ' + str(Household.objects.all().count())
        Household.objects.get(plot=plot)
        self.assertEquals(HouseholdStructure.objects.all().count(), 3)
        self.assertEquals(Survey.objects.all().count(), 3)
        household_structure = HouseholdStructure.objects.get(survey=Survey.objects.all()[0])
        RepresentativeEligibilityFactory(household_structure=household_structure)
        household_member = HouseholdMemberFactory(household_structure=household_structure)
        enrollment_checklist = EnrollmentChecklistFactory(household_member=household_member, initials=household_member.initials, has_identity='Yes', dob=date(1989, 01, 01))
        study_site = StudySite.objects.all()[0]
        subject_consent = SubjectConsentFactory(study_site=study_site, household_member=household_member, registered_subject=household_member.registered_subject,
                                                dob=enrollment_checklist.dob, initials=enrollment_checklist.initials)
        print subject_consent.subject_identifier
        print 'get registered subject'
        registered_subject = RegisteredSubject.objects.get(subject_identifier=subject_consent.subject_identifier)
        instances = []
        instances.append(subject_consent)
        instances.append(registered_subject)

        print 'test natural key / get_by_natural_key on subject_visit'
        print 'No. of ENTRIES = ' + str(Entry.objects.all().count())
#         content_type = ContentType.objects.get(app_label='bcpp_subject', model='subjectvisit')
#         content_type_map = ContentTypeMap.objects.get(content_type=content_type)
        self.assertEqual(VisitDefinition.objects.all().count(), 2)
        visit_definition = VisitDefinition.objects.get(code='T0')
        print 'No. of Appointments = ' + str(Appointment.objects.all().count())
        appointment = Appointment.objects.get(visit_definition=visit_definition)
        # print 'No. of ScheduledEntryMetaData before Visit = '+str(ScheduledEntryMetaData.objects.all().count())
        subject_visit = SubjectVisitFactory(appointment=appointment, household_member=household_member)
        signals.post_save.disconnect(entry_meta_data_on_post_save, weak=False, dispatch_uid="entry_meta_data_on_post_save")

        aliquot_type = AliquotType.objects.all()[0]
        site = StudySite.objects.all()[0]
        microtube_panel = Panel.objects.get(name='Microtube')
        requisition1 = SubjectRequisitionFactory(subject_visit=subject_visit, panel=microtube_panel, aliquot_type=aliquot_type, site=site)
#         print requisition1.aliquot_type.numeric_code
        elisa_panel = Panel.objects.get(name='ELISA')
        requisition2 = SubjectRequisitionFactory(subject_visit=subject_visit, panel=elisa_panel, aliquot_type=aliquot_type, site=site)
        signals.post_save.connect(entry_meta_data_on_post_save, weak=False, dispatch_uid="entry_meta_data_on_post_save")
        subject_locator = SubjectLocatorFactory(subject_visit=subject_visit, registered_subject=registered_subject)
        year_1_survey = Survey.objects.get(survey_slug='bcpp-year-1')
        call_list = CallListFactory(household_member=household_member, label='call_label_1')
        call_log = CallLogFactory(household_member=household_member, survey=year_1_survey, label='call_label_1')
        call_log2 = CallLogFactory(household_member=household_member, survey=year_1_survey, label='call_label_2')
        call_log_entry = CallLogEntryFactory(call_log=call_log, survey=year_1_survey, call_datetime=datetime.now())
        call_log_entry2 = CallLogEntryFactory(call_log=call_log, survey=year_1_survey, call_datetime=datetime.now() + timedelta(minutes=3))
        instances.append(subject_locator)
        instances.append(requisition1)
        instances.append(requisition2)
        instances.append(call_log)
        instances.append(call_log2)
        instances.append(call_log_entry)
        instances.append(call_log_entry2)
        instances.append(call_list)

        print 'INSTANCE: ' + str(instances)
        for obj in instances:
            print 'test natural key on {0}'.format(obj._meta.object_name)
            natural_key = obj.natural_key()
            get_obj = obj.__class__.objects.get_by_natural_key(*natural_key)
            self.assertEqual(obj.pk, get_obj.pk)
        # pp = pprint.PrettyPrinter(indent=4)
        for obj in instances:
            print 'test serializing/deserializing {0}'.format(obj._meta.object_name)
            outgoing_transaction = SerializeToTransaction().serialize(obj.__class__, obj, False, True, 'default')
            # pp.pprint(FieldCryptor('aes', 'local').decrypt(outgoing_transaction.tx))
            for transaction in serializers.deserialize("json", FieldCryptor('aes', 'local').decrypt(outgoing_transaction.tx)):
                self.assertEqual(transaction.object.pk, obj.pk)
    def test_p1(self):
        self.assertTrue(Household.objects.all().count() == 0)
        self.assertTrue(HouseholdStructure.objects.all().count() == 0)
        self.assertTrue(HouseholdMember.objects.all().count() == 0)
        site_lab_tracker.autodiscover()
        study_specific = StudySpecificFactory()
        StudySiteFactory()

        content_type_map_helper = ContentTypeMapHelper()
        content_type_map_helper.populate()
        content_type_map_helper.sync()
        ContentTypeMap.objects.get(
            model__iexact=SubjectConsent._meta.object_name)

        setup_dashboard(
            self)  # creates 3 surveys a plot and two HH which -> 6 HHS

        print 'initialize the HH dashboard which will create HHS'
        print 'assert no survey for today\'s date'
        self.survey1.datetime_end = datetime.today() + relativedelta(days=-5)
        self.survey1.save()
        self.assertRaises(TypeError, HouseholdDashboard, self.dashboard_type,
                          self.dashboard_id, self.dashboard_model)
        self.assertEquals(HouseholdStructure.objects.all().count(), 6)
        print 'update survey1 to include today'
        self.survey1.datetime_end = datetime.today() + relativedelta(days=+5)
        self.survey1.save()
        print 'try again, initialize the HH dashboard which will create HHS'
        self.household_dashboard = HouseholdDashboard(self.dashboard_type,
                                                      self.dashboard_id,
                                                      self.dashboard_model)
        print 'assert household structure exists for this HH and the three surveys'
        self.assertEquals(
            HouseholdStructure.objects.filter(
                household=self.household1).count(), 3)
        self.household_structure = self.household_dashboard.get_household_structure(
        )
        print 'create another new HH in community {0}.'.format(self.community)
        self.assertEquals(
            HouseholdStructure.objects.filter(
                household=self.household2).count(), 3)
        print 'assert no additional hh structure created'
        self.assertEquals(HouseholdStructure.objects.all().count(),
                          6)  # 2 surveys for each HH = 2 x 3 = 6
        print 'create HH members for this survey and HH {0}'.format(
            self.household1)
        self.household_member1 = HouseholdMemberFactory(
            household_structure=self.household_structure)
        print 'household_member1.registered_subject.pk = {0}'.format(
            self.household_member1.registered_subject.pk)
        print 'household_member1.survey = {0}'.format(
            self.household_member1.survey)
        self.household_member2 = HouseholdMemberFactory(
            household_structure=self.household_structure)
        print self.household_member2.registered_subject.pk
        self.household_member3 = HouseholdMemberFactory(
            household_structure=self.household_structure)
        print self.household_member3.registered_subject.pk
        self.household_member4 = HouseholdMemberFactory(
            household_structure=self.household_structure)
        print self.household_member4.registered_subject.pk

        # this consent has a fk to registered subject
        # confirm that the signals do not create more than one registered
        # subject or anything like that. consent.rs must equal household_member.rs, etc

        self.assertEqual(Survey.objects.all().count(), 3)
        print 'assert one RS per HM'
        self.assertEqual(HouseholdMember.objects.all().count(),
                         RegisteredSubject.objects.all().count())
        print 'assert HM1.registered_subject.subject_identifier is a pk (not consented yet)'
        self.assertRegexpMatches(
            HouseholdMember.objects.get(pk=self.household_member1.pk).
            registered_subject.subject_identifier, self.re_pk)
        print 'consent household_member1'
        consent1 = SubjectConsentFactory(
            household_member=self.household_member1)
        self.assertEqual(Survey.objects.all().count(), 3)
        print consent1.subject_identifier
        print HouseholdMember.objects.get(
            pk=self.household_member1.pk).registered_subject.subject_identifier
        print 'assert consent1 household member is household_member1'
        print self.assertEqual(consent1.household_member.pk,
                               self.household_member1.pk)
        print 'assert still one RS per HM'
        self.assertEqual(HouseholdMember.objects.all().count(),
                         RegisteredSubject.objects.all().count())
        print 'assert subject identifier on consent1 == subject identifier in registered_subject'
        self.assertEqual(
            consent1.subject_identifier,
            RegisteredSubject.objects.get(
                subject_identifier=consent1.subject_identifier).
            subject_identifier)
        print 'assert consent1 registered subject pk = household_member1 registered subject pk'
        self.assertEqual(
            consent1.registered_subject.pk,
            HouseholdMember.objects.get(
                pk=self.household_member1.pk).registered_subject.pk)
        print 'assert consent1 registered subject subject identifier = household_member1 registered subject subject_identifier'
        self.assertEqual(
            consent1.registered_subject.subject_identifier,
            HouseholdMember.objects.get(pk=self.household_member1.pk).
            registered_subject.subject_identifier)
        print 'assert cannot create a second consent for consented household_member1 {0}'.format(
            self.household_member1.survey)
        self.assertRaises(IdentifierError,
                          SubjectConsentFactory,
                          household_member=self.household_member1)

        # repeat for year 2, make a household_structure, members and consent, etc.
        # verify FK constraints do not prevent member, consent data
        # verify that subsequent surveys refer to the same registered subject
        # that being the one created from the first year

        print 'repeat for YEAR 2 for household1'
        print 'assert still have only 3 surveys'
        self.assertEqual(Survey.objects.all().count(), 3)
        print 'assert have 4 HHMs for household1 (from survey1'
        self.assertEqual(HouseholdMember.objects.all().count(), 4)
        print 'get a household dashboard for survey2 using HH2'
        self.dashboard_type = 'household'
        self.dashboard_model = 'household'
        self.dashboard_id = self.household1.pk
        print 'instantiate hHH dashboard with household'
        household_dashboard_survey2 = HouseholdDashboard(self.dashboard_type,
                                                         self.dashboard_id,
                                                         self.dashboard_model,
                                                         survey=self.survey2)
        print household_dashboard_survey2
        self.assertEqual(Survey.objects.all().count(), 3)
        print 'assert defaults to survey1, HHS for survey1'
        self.assertEqual(household_dashboard_survey2.get_survey(),
                         self.survey1)
        self.assertEqual(
            household_dashboard_survey2.get_household_structure().survey,
            self.survey1)
        print 'get a household dashboard for survey2 using HH2'
        self.household_structure2 = HouseholdStructure.objects.get(
            household=self.household1, survey=self.survey2)
        self.dashboard_type = 'household'
        self.dashboard_model = 'household_structure'
        self.dashboard_id = self.household_structure2.pk
        household_dashboard_survey2 = HouseholdDashboard(self.dashboard_type,
                                                         self.dashboard_id,
                                                         self.dashboard_model,
                                                         survey=self.survey2)
        household_dashboard_survey2
        print 'confirm uses HHS2 and survey2'
        self.assertEqual(household_dashboard_survey2.get_survey(),
                         self.survey2)
        self.assertEqual(
            household_dashboard_survey2.get_household_structure().survey,
            self.survey2)
        household_structure = household_dashboard_survey2.get_household_structure(
        )
        self.assertEqual(Survey.objects.all().count(), 3)
        print 'assert household dashboard returns correct household structure if given survey2'
        self.assertEqual(household_structure.survey.pk, self.survey2.pk)
        print 'assert household dashboard returns correct household structure if given HH1'
        self.assertEqual(household_structure.household.pk, self.household1.pk)
        print 'household_structure={0}, plot={1}'.format(
            household_structure, household_structure.plot)
        print 'assert have 4 HHMs imported from first survey after instantiating dashboard'
        household_dashboard_survey2.get_context()
        self.assertEqual(
            HouseholdMember.objects.filter(
                household_structure=household_structure).count(), 4)
        print 'assert cannot create a household_member for this survey for known household members (because the dashboard created them)'
        self.assertRaises(
            IntegrityError,
            HouseholdMemberFactory,
            household_structure=household_structure,
            survey=self.survey2,
            registered_subject=self.household_member1.registered_subject)
        self.assertRaises(
            IntegrityError,
            HouseholdMemberFactory,
            household_structure=household_structure,
            survey=self.survey2,
            registered_subject=self.household_member2.registered_subject)
        self.assertRaises(
            IntegrityError,
            HouseholdMemberFactory,
            household_structure=household_structure,
            survey=self.survey2,
            registered_subject=self.household_member3.registered_subject)
        self.assertRaises(
            IntegrityError,
            HouseholdMemberFactory,
            household_structure=household_structure,
            survey=self.survey2,
            registered_subject=self.household_member4.registered_subject)

        # in BCPP, subject consent has a key to registered subject as does
        # household member. ensure both are pointing to the same registered_subject
        # not only for this survey but always. a household_member is created anew
        # for each survey but still refers to a common registered subject. the same
        # for the consent, a new consent for each survey but pointing to the same
        # registered_subject. household_member uses the registered_subject internal
        # identifier field to figure out which registered subject to use when
        # setting the attribute for subsequent surveys.

        print 'get a list of household members for the survey2 household dashboard'
        household_members = household_dashboard_survey2.get_household_members_as_list(
        )
        household_member1 = household_members[0]
        print 'assert 8 household members'
        self.assertEqual(HouseholdMember.objects.all().count(), 8)
        print '... 4 for survey 1 and 4 for survey 2'
        self.assertEqual(
            HouseholdMember.objects.filter(survey=self.survey1).count(), 4)
        self.assertEqual(
            HouseholdMember.objects.filter(survey=self.survey2).count(), 4)
        print 'assert still 4 registered subjects'
        self.assertEqual(RegisteredSubject.objects.all().count(), 4)
        print 'assert one RS per 2 HM'
        self.assertEqual(HouseholdMember.objects.all().count(),
                         RegisteredSubject.objects.all().count() * 2)
        print 'assert HM1.registered_subject.subject_identifier is a subject identifier (was consented in previous survey)'
        print HouseholdMember.objects.get(
            pk=household_member1.pk).registered_subject.subject_identifier
        print HouseholdMember.objects.get(
            pk=household_member1.pk
        ).registered_subject.subject_identifier_as_pk
        self.assertTrue(
            HouseholdMember.objects.get(pk=household_member1.pk).
            registered_subject.subject_identifier.startswith('066'))
        print 'consent household_member1 (it should find the existing registered subject and subject identifier)'
        consent1 = SubjectConsentFactory(household_member=household_member1)
        print consent1.subject_identifier
        print HouseholdMember.objects.get(
            pk=household_member1.pk).registered_subject.subject_identifier
        print 'assert consent1 household member is household_member1'
        print self.assertEqual(consent1.household_member.pk,
                               household_member1.pk)
        print 'assert still one RS per HM'
        self.assertEqual(HouseholdMember.objects.all().count(),
                         RegisteredSubject.objects.all().count() * 2)
        print 'assert subject identifier on consent1 == subject identifier in registered_subject'
        self.assertEqual(
            consent1.subject_identifier,
            RegisteredSubject.objects.get(
                subject_identifier=consent1.subject_identifier).
            subject_identifier)
        print 'assert consent1 registered subject pk = household_member1 registered subject pk'
        self.assertEqual(
            consent1.registered_subject.pk,
            HouseholdMember.objects.get(
                pk=household_member1.pk).registered_subject.pk)
        print 'assert consent1 registered subject subject identifier = household_member1 registered subject subject_identifier'
        self.assertEqual(
            consent1.registered_subject.subject_identifier,
            HouseholdMember.objects.get(
                pk=household_member1.pk).registered_subject.subject_identifier)
        print 'assert consent1 registered subject pk = household_member1 registered subject pk for previous survey'
        self.assertEqual(
            consent1.registered_subject.pk,
            HouseholdMember.objects.get(
                pk=self.household_member1.pk).registered_subject.pk)
Example #3
0
    def setUp(self):
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        BcppAppConfiguration().prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')

        survey = Survey.objects.all().order_by('datetime_start')[0]

        self.study_site = StudySite.objects.get(site_code='14')

        self.household_structure = HouseholdStructure.objects.get(
            household__plot=plot, survey=survey)
        RepresentativeEligibilityFactory(
            household_structure=self.household_structure)
        HouseholdMemberFactory(household_structure=self.household_structure)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_initials = "EW"
        female_dob = date.today() - relativedelta(years=35)
        female_age_in_years = 35
        female_first_name = 'ERIKA'
        female_initials = "EW"

        self.household_member_female_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure,
            gender='F',
            age_in_years=female_age_in_years,
            first_name=female_first_name,
            initials=female_initials)
        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure,
            gender='M',
            age_in_years=self.male_age_in_years,
            first_name=self.male_first_name,
            initials=self.male_initials)

        EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes')

        EnrollmentChecklistFactory(
            household_member=self.household_member_female_T0,
            gender='F',
            citizen='Yes',
            dob=female_dob,
            guardian='No',
            initials=self.household_member_female_T0.initials,
            part_time_resident='Yes')

        subject_consent_female = SubjectConsentFactory(
            household_member=self.household_member_female_T0,
            study_site=self.study_site,
            gender='F',
            dob=female_dob,
            first_name=female_first_name,
            initials=female_initials)
        self.subject_consent_male = SubjectConsentFactory(
            household_member=self.household_member_male_T0,
            study_site=self.study_site,
            gender='M',
            dob=self.male_dob,
            first_name=self.male_first_name,
            initials=self.male_initials)

        self.registered_subject_male = RegisteredSubject.objects.get(
            subject_identifier=self.subject_consent_male.subject_identifier)
        self.registered_subject_female = RegisteredSubject.objects.get(
            subject_identifier=subject_consent_female.subject_identifier)

        self.appointment_male_T0 = Appointment.objects.get(
            registered_subject=self.registered_subject_male,
            visit_definition__code='T0')
        self.appointment_female_T0 = Appointment.objects.get(
            registered_subject=self.registered_subject_female,
            visit_definition__code='T0')

        self.subject_visit_male_T0 = SubjectVisitFactory(
            appointment=self.appointment_male_T0,
            household_member=self.household_member_male_T0)
        self.subject_visit_female_T0 = SubjectVisitFactory(
            appointment=self.appointment_female_T0,
            household_member=self.household_member_female_T0)

        Quota.objects.create(app_label='bcpp_subject',
                             model_name='PimaVl',
                             target=1,
                             expires_datetime=timezone.now() +
                             timedelta(days=1))
        self.assertEqual(1, Quota.objects.all().count())
class TestSubjectConsentForm(TestCase):

    app_label = 'bcpp_subject'
    community = 'test_community'

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def setUp(self):
        site_mappers.autodiscover()
        from bhp066.apps.bcpp_subject.visit_schedule import BcppSubjectVisitSchedule
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        self.app_config = BcppAppConfiguration()
        self.app_config.prepare()
        self.app_config.prep_survey_for_tests()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')

        self.survey_bhs = Survey.objects.get(survey_slug='bcpp-year-1')

        self.survey_ahs = Survey.objects.get(survey_slug='bcpp-year-2')

        self.study_site = StudySite.objects.get(site_code='01')

        self.household_structure_bhs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_bhs)
        self.household_structure_ahs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_ahs)
        self.create_household_log_entry(self.household_structure_bhs)

        RepresentativeEligibilityFactory(
            household_structure=self.household_structure_bhs)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_last_name = 'HIEWAI'
        self.male_initials = "EW"

        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure_bhs,
            gender='M',
            age_in_years=self.male_age_in_years,
            first_name=self.male_first_name,
            initials=self.male_initials)
        HeadHouseholdEligibilityFactory(
            household_member=self.household_member_male_T0,
            household_structure=self.household_structure_bhs)
        self.household_member_male_T0.eligible_hoh = True
        self.household_member_male_T0.save()

        HouseholdInfoFactory(household_member=self.household_member_male_T0,
                             household_structure=self.household_structure_bhs,
                             registered_subject=self.household_member_male_T0.
                             registered_subject)

        self.enrollment = EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes')
        self.subject_consent_male = SubjectConsentFactory(
            household_member=self.household_member_male_T0,
            confirm_identity='101119811',
            identity='101119811',
            study_site=self.study_site,
            gender='M',
            dob=self.male_dob,
            first_name=self.male_first_name,
            initials=self.male_initials)
        self.data = {
            'last_name':
            'WIZZY',
            'is_minor':
            'No',
            'witness_name':
            None,
            'is_literate':
            'Yes',
            'subject_type':
            'subject',
            'consent_copy':
            'Yes',
            'is_verified':
            False,
            'consent_signature':
            None,
            'first_name':
            'ERIK',
            'dm_comment':
            None,
            'is_dob_estimated':
            None,
            'verified_by':
            None,
            'user_modified':
            u'',
            'is_signed':
            True,
            'is_verified_datetime':
            None,
            'subject_identifier_aka':
            None,
            'version':
            u'4',
            'citizen':
            'Yes',
            'legal_marriage':
            u'N/A',
            'assessment_score':
            'Yes',
            'is_incarcerated':
            'No',
            'consent_reviewed':
            'Yes',
            'study_questions':
            'Yes',
            'sid':
            None,
            'study_site_id':
            self.study_site.id,
            'may_store_samples':
            YES,
            'consent_version_recent':
            None,
            'subject_identifier':
            self.household_member_male_T0.registered_subject.
            subject_identifier,
            'subject_identifier_as_pk':
            self.household_member_male_T0.registered_subject.id,
            'community':
            u'test_community',
            'using':
            'default',
            'marriage_certificate_no':
            None,
            'identity':
            '317918515',
            'confirm_identity':
            '317918515',
            'registered_subject_id':
            self.household_member_male_T0.registered_subject.id,
            'identity_type':
            'OMANG',
            'language':
            u'not specified',
            'guardian_name':
            None,
            'gender':
            'M',
            'household_member':
            self.household_member_male_T0.id,
            'marriage_certificate':
            u'N/A',
            'dob':
            self.male_dob,
            'study_site':
            self.study_site.id,
            'initials':
            'EW',
            'language':
            'en',
            'is_dob_estimated':
            '-',
            'consent_signature':
            YES,
            'consent_datetime':
            datetime.today(),
            'version':
            1
        }

    def create_household_log_entry(self, household_structure):
        household_log = HouseholdLog.objects.filter(
            household_structure=household_structure).last()
        HouseholdLogEntry.objects.all().delete()
        HouseholdLogEntryFactory(household_log=household_log)

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_consent_age_above_64_at_bhs(self):
        """ For all participants who are above 64 at bhs are not eligible."""
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm
        self.male_dob = date.today() - relativedelta(years=65)
        self.data['dob'] = self.male_dob
        self.data['household_member'] = self.household_member_male_T0.id
        consent_form = SubjectConsentForm(data=self.data)
        self.assertIn(
            u"Subject's age is 65y. Subject is not eligible for consent.",
            consent_form.errors.get("__all__"))

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_consent_age_within_65_at_bhs(self):
        """ For all participants within 65 at bhs are eligible."""
        self.app_config.prep_survey_for_tests()
        self.subject_consent_male.version = 2
        self.subject_consent_male.save_base()
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm
        dob = date.today() - relativedelta(years=64)
        self.household_member_male_T0.age_in_years = 64
        self.household_member_male_T0.save()
        self.enrollment.dob = dob
        self.enrollment.save_base()
        self.data['dob'] = dob
        self.data['identity'] = '317918514'
        self.data['confirm_identity'] = '317918514'
        consent_form = SubjectConsentForm(data=self.data)
        print consent_form.errors
        consent_form.save()
        self.assertEqual(
            RegisteredSubject.objects.filter(
                identity=self.data['identity']).count(), 1)

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_consent_age_above_64_at_ahs(self):
        """ Test identity on
        """

        dob = date.today() - relativedelta(years=65)
        self.household_member_male_T0.age_in_years = 65
        self.household_member_male_T0.save_base()
        self.subject_consent_male.dob = dob
        self.enrollment.dob = dob
        self.enrollment.save_base()
        self.subject_consent_male.save_base()

        self.app_config.prep_survey_for_tests()
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm

        enumeration_helper = EnumerationHelper(
            self.household_structure_ahs.household, self.survey_bhs,
            self.survey_ahs)
        enumeration_helper.add_members_from_survey()
        self.household_member = HouseholdMember.objects.get(
            registered_subject__identity='101119811',
            household_structure__survey=self.survey_ahs,
        )
        dob = date.today() - relativedelta(years=65)
        self.household_member.age_in_years = 65
        self.household_member.save_base()

        HeadHouseholdEligibilityFactory(
            household_member=self.household_member,
            household_structure=self.household_member.household_structure)
        self.enrollment.dob = dob
        self.enrollment.save_base()

        self.subject_consent = SubjectConsent.objects.get(
            household_member=self.household_member_male_T0)
        self.subject_consent.version = 2
        self.subject_consent.save_base()

        self.create_household_log_entry(self.household_structure_ahs)

        self.data['dob'] = dob
        self.data['household_member'] = self.household_member.id
        self.data['identity'] = '101119811'
        self.data['confirm_identity'] = '101119811'
        consent_form = SubjectConsentForm(data=self.data)
        print consent_form.errors
        self.assertTrue(consent_form.is_valid())

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_consent_age_within_65_at_ahs(self):
        """ Test identity on
        """
        self.app_config.prep_survey_for_tests()
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm

        enumeration_helper = EnumerationHelper(
            self.household_structure_ahs.household, self.survey_bhs,
            self.survey_ahs)
        enumeration_helper.add_members_from_survey()
        self.household_member = HouseholdMember.objects.get(
            registered_subject__identity='101119811',
            household_structure__survey=self.survey_ahs)
        HeadHouseholdEligibilityFactory(
            household_member=self.household_member,
            household_structure=self.household_member.household_structure)
        self.subject_consent = SubjectConsent.objects.get(
            household_member=self.household_member_male_T0)
        self.subject_consent.version = 2
        self.subject_consent.save_base()

        self.data['household_member'] = self.household_member.id
        self.data['identity'] = '101119811'
        self.data['confirm_identity'] = '101119811'

        self.create_household_log_entry(self.household_structure_ahs)

        consent_form = SubjectConsentForm(data=self.data)
        self.assertTrue(consent_form.is_valid())

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_surname_marrige_at_ahs(self):
        """ Test identity on
        """
        self.app_config.prep_survey_for_tests()
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm
        enumeration_helper = EnumerationHelper(
            self.household_structure_ahs.household, self.survey_bhs,
            self.survey_ahs)
        enumeration_helper.add_members_from_survey()
        self.household_member = HouseholdMember.objects.get(
            registered_subject__identity='101119811',
            household_structure__survey=self.survey_ahs)
        self.household_member.personal_details_changed = YES
        self.household_member.details_change_reason = 'married'
        self.household_member.last_name = 'SETSIBA'
        self.household_member.initials = 'ES'
        self.household_member.save()

        self.create_household_log_entry(self.household_structure_ahs)

        HeadHouseholdEligibilityFactory(
            household_member=self.household_member,
            household_structure=self.household_member.household_structure)

        self.subject_consent = SubjectConsent.objects.get(
            household_member=self.household_member_male_T0)
        self.subject_consent.version = 2
        self.subject_consent.save_base()
        self.data['household_member'] = self.household_member.id
        self.data['identity'] = '101119811'
        self.data['confirm_identity'] = '101119811'
        self.data['last_name'] = 'SETSIBA'
        self.data['initials'] = 'ES'
        consent_form = SubjectConsentForm(data=self.data)
        self.assertTrue(consent_form.is_valid())
        consent_form.save()
        consent = SubjectConsent.objects.get(
            household_member=self.household_member)
        consent_form = SubjectConsentForm(data=self.data, instance=consent)
        consent_form.save()

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_validate_legal_marriage_at_bhs(self):
        self.data['citizen'] = NO
        self.data['identity'] = '101119811'
        self.data['confirm_identity'] = '101119811'
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm
        self.data['legal_marriage'] = YES
        self.data['marriage_certificate'] = YES
        self.data['marriage_certificate_no'] = '12421'
        self.enrollment.citizen = NO
        self.enrollment.save_base()
        consent_form = SubjectConsentForm(data=self.data)
        print consent_form.errors
        self.assertTrue(consent_form.is_valid())

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_validate_legal_marriage_at_bhs_not_valid(self):
        self.data['citizen'] = NO
        self.data['identity'] = '101119811'
        self.data['confirm_identity'] = '101119811'
        from bhp066.apps.bcpp_subject.forms.subject_consent_form import SubjectConsentForm
        self.data['legal_marriage'] = YES
        self.data['marriage_certificate'] = YES
        self.enrollment.citizen = NO
        self.enrollment.save_base()
        consent_form = SubjectConsentForm(data=self.data)
        self.assertIn(
            u'You wrote subject is NOT a citizen and has marriage certificate. Please provide certificate number.',
            consent_form.errors.get("__all__"))
        self.assertFalse(consent_form.is_valid())
    def setUp(self):
        site_mappers.autodiscover()
        from bhp066.apps.bcpp_subject.visit_schedule import BcppSubjectVisitSchedule
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        self.app_config = BcppAppConfiguration()
        self.app_config.prepare()
        self.app_config.prep_survey_for_tests()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')

        self.survey_bhs = Survey.objects.get(survey_slug='bcpp-year-1')

        self.survey_ahs = Survey.objects.get(survey_slug='bcpp-year-2')

        self.study_site = StudySite.objects.get(site_code='01')

        self.household_structure_bhs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_bhs)
        self.household_structure_ahs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_ahs)
        self.create_household_log_entry(self.household_structure_bhs)

        RepresentativeEligibilityFactory(
            household_structure=self.household_structure_bhs)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_last_name = 'HIEWAI'
        self.male_initials = "EW"

        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure_bhs,
            gender='M',
            age_in_years=self.male_age_in_years,
            first_name=self.male_first_name,
            initials=self.male_initials)
        HeadHouseholdEligibilityFactory(
            household_member=self.household_member_male_T0,
            household_structure=self.household_structure_bhs)
        self.household_member_male_T0.eligible_hoh = True
        self.household_member_male_T0.save()

        HouseholdInfoFactory(household_member=self.household_member_male_T0,
                             household_structure=self.household_structure_bhs,
                             registered_subject=self.household_member_male_T0.
                             registered_subject)

        self.enrollment = EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes')
        self.subject_consent_male = SubjectConsentFactory(
            household_member=self.household_member_male_T0,
            confirm_identity='101119811',
            identity='101119811',
            study_site=self.study_site,
            gender='M',
            dob=self.male_dob,
            first_name=self.male_first_name,
            initials=self.male_initials)
        self.data = {
            'last_name':
            'WIZZY',
            'is_minor':
            'No',
            'witness_name':
            None,
            'is_literate':
            'Yes',
            'subject_type':
            'subject',
            'consent_copy':
            'Yes',
            'is_verified':
            False,
            'consent_signature':
            None,
            'first_name':
            'ERIK',
            'dm_comment':
            None,
            'is_dob_estimated':
            None,
            'verified_by':
            None,
            'user_modified':
            u'',
            'is_signed':
            True,
            'is_verified_datetime':
            None,
            'subject_identifier_aka':
            None,
            'version':
            u'4',
            'citizen':
            'Yes',
            'legal_marriage':
            u'N/A',
            'assessment_score':
            'Yes',
            'is_incarcerated':
            'No',
            'consent_reviewed':
            'Yes',
            'study_questions':
            'Yes',
            'sid':
            None,
            'study_site_id':
            self.study_site.id,
            'may_store_samples':
            YES,
            'consent_version_recent':
            None,
            'subject_identifier':
            self.household_member_male_T0.registered_subject.
            subject_identifier,
            'subject_identifier_as_pk':
            self.household_member_male_T0.registered_subject.id,
            'community':
            u'test_community',
            'using':
            'default',
            'marriage_certificate_no':
            None,
            'identity':
            '317918515',
            'confirm_identity':
            '317918515',
            'registered_subject_id':
            self.household_member_male_T0.registered_subject.id,
            'identity_type':
            'OMANG',
            'language':
            u'not specified',
            'guardian_name':
            None,
            'gender':
            'M',
            'household_member':
            self.household_member_male_T0.id,
            'marriage_certificate':
            u'N/A',
            'dob':
            self.male_dob,
            'study_site':
            self.study_site.id,
            'initials':
            'EW',
            'language':
            'en',
            'is_dob_estimated':
            '-',
            'consent_signature':
            YES,
            'consent_datetime':
            datetime.today(),
            'version':
            1
        }
Example #6
0
 def test_updates_household_structure_counts(self):
     """Assert household_member updates household structure member_count and enrolled_member_count."""
     self.assertEquals(self.household_structure.member_count, 0)
     self.assertEquals(self.household_structure.enrolled_member_count, 0)
     household_member = HouseholdMemberFactory(
         household_structure=self.household_structure,
         gender='M',
         age_in_years=25,
         study_resident='Yes',
         initials='EE')
     # who is an eligible subject
     EnrollmentChecklistFactory(household_member=household_member,
                                gender='M',
                                dob=date.today() - relativedelta(years=25),
                                initials=household_member.initials,
                                part_time_resident='Yes')
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).member_count, 1)
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).enrolled_member_count, 0)
     # who is consented
     SubjectConsentFactory(
         household_member=household_member,
         gender='M',
         dob=date.today() - relativedelta(years=25),
         first_name='ERIKFIRST',
         last_name='ERIKLAST',
         initials=household_member.initials,
     )
     self.assertTrue(household_member.is_consented)
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).member_count, 1)
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).enrolled_member_count, 1)
     household_member = HouseholdMemberFactory(
         household_structure=self.household_structure,
         gender='M',
         age_in_years=35,
         study_resident='Yes',
         initials='DD')
     # who is an eligible subject
     EnrollmentChecklistFactory(household_member=household_member,
                                gender='M',
                                dob=date.today() - relativedelta(years=35),
                                initials=household_member.initials,
                                part_time_resident='Yes')
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).member_count, 2)
     # who is consented
     SubjectConsentFactory(
         household_member=household_member,
         gender='M',
         dob=date.today() - relativedelta(years=35),
         first_name='DRIKFIRST',
         last_name='DRIKLAST',
         initials=household_member.initials,
     )
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).member_count, 2)
     self.assertEquals(
         HouseholdStructure.objects.get(
             pk=self.household_structure.pk).enrolled_member_count, 2)
Example #7
0
    def setUp(self):
        site_mappers.autodiscover()

        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        mapper = site_mappers._registry_by_code.get('01')
        mapper.survey_dates = {
            'bcpp-year-1':
            SurveyDatesTuple(name='bhs',
                             start_date=date.today() +
                             relativedelta(years=-1) + relativedelta(days=-89),
                             full_enrollment_date=date.today() +
                             relativedelta(years=-1) + relativedelta(days=60),
                             end_date=date.today() + relativedelta(years=-1) +
                             relativedelta(days=89),
                             smc_start_date=date.today() +
                             relativedelta(years=-1) + relativedelta(days=89)),
            'bcpp-year-2':
            SurveyDatesTuple(name='t1',
                             start_date=date.today() + relativedelta(years=0) +
                             relativedelta(days=-89),
                             full_enrollment_date=date.today() +
                             relativedelta(years=0) + relativedelta(days=60),
                             end_date=date.today() + relativedelta(years=0) +
                             relativedelta(days=89),
                             smc_start_date=date.today() +
                             relativedelta(years=0) + relativedelta(days=89)),
        }

        bcpp_app_configuration.survey_setup = {
            'bcpp-year-1': {
                'survey_name':
                'BCPP Year 1',
                'survey_slug':
                'bcpp-year-1',
                'datetime_start':
                datetime.today() + relativedelta(years=-1) +
                relativedelta(days=-30),
                'datetime_end':
                datetime.today() + relativedelta(years=-1) +
                relativedelta(days=30)
            },
            'bcpp-year-2': {
                'survey_name': 'BCPP Year 2',
                'survey_slug': 'bcpp-year-2',
                'datetime_start': datetime.today() + relativedelta(days=-90),
                'datetime_end': datetime.today() + relativedelta(days=90)
            },
            'bcpp-year-3': {
                'survey_name':
                'BCPP Year 3',
                'survey_slug':
                'bcpp-year-3',
                'datetime_start':
                datetime.today() + relativedelta(years=1) +
                relativedelta(days=-30),
                'datetime_end':
                datetime.today() + relativedelta(years=1) +
                relativedelta(days=30)
            },
        }

        bcpp_app_configuration.prepare()
        site_lab_tracker.autodiscover()
        site_visit_schedules.autodiscover()
        site_visit_schedules.build_all()

        self.survey2 = Survey.objects.current_survey()
        self.survey1 = Survey.objects.previous_survey()
        plot = PlotFactory(community='test_community',
                           household_count=1,
                           status='residential_habitable')
        self.household = Household.objects.get(plot=plot)
        self.source_household_structure = HouseholdStructure.objects.get(
            household=self.household, survey=self.survey1)
        self.target_household_structure = HouseholdStructure.objects.get(
            household=self.household, survey=self.survey2)
        self.representative_eligibility = RepresentativeEligibilityFactory(
            household_structure=self.source_household_structure)
        self.study_site = StudySite.objects.get(
            site_code=site_mappers.get_current_mapper().map_code)
        self.intervention = site_mappers.get_current_mapper().intervention

        # add members to source
        HouseholdMemberFactory(
            household_structure=self.source_household_structure)
        HouseholdMemberFactory(
            household_structure=self.source_household_structure)
        HouseholdMemberFactory(
            household_structure=self.source_household_structure)
        HouseholdMemberFactory(
            household_structure=self.source_household_structure)
        HouseholdMemberFactory(
            household_structure=self.source_household_structure)
    def setUp(self):
        site_mappers.autodiscover()
        from bhp066.apps.bcpp_subject.visit_schedule import BcppSubjectVisitSchedule
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        self.app_config = BcppAppConfiguration()
        self.app_config.prepare()
        self.app_config.prep_survey_for_tests()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')

        self.survey_bhs = Survey.objects.get(survey_slug='bcpp-year-1')

        self.survey_ahs = Survey.objects.get(survey_slug='bcpp-year-2')

        self.study_site = StudySite.objects.get(site_code='01')

        self.household_structure_bhs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_bhs)
        self.household_structure_ahs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_ahs)
        self.create_household_log_entry(self.household_structure_bhs)

        RepresentativeEligibilityFactory(
            household_structure=self.household_structure_bhs)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_last_name = 'HIEWAI'
        self.male_initials = "EW"

        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure_bhs,
            gender='M',
            age_in_years=self.male_age_in_years,
            first_name=self.male_first_name,
            initials=self.male_initials)
        HeadHouseholdEligibilityFactory(
            household_member=self.household_member_male_T0,
            household_structure=self.household_structure_bhs)
        self.household_member_male_T0.eligible_hoh = True
        self.household_member_male_T0.save()

        HouseholdInfoFactory(household_member=self.household_member_male_T0,
                             household_structure=self.household_structure_bhs,
                             registered_subject=self.household_member_male_T0.
                             registered_subject)

        self.enrollment = EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes')
        self.subject_consent_male = SubjectConsentFactory(
            household_member=self.household_member_male_T0,
            confirm_identity='101119811',
            identity='101119811',
            study_site=self.study_site,
            gender='M',
            dob=self.male_dob,
            first_name=self.male_first_name,
            initials=self.male_initials)
        self.appointment = Appointment.objects.get(
            registered_subject=self.household_member_male_T0.
            registered_subject,
            visit_definition__code='T0')

        self.subject_visit = SubjectVisitFactory(
            household_member=self.household_member_male_T0,
            appointment=self.appointment)

        self.registered_subject = RegisteredSubject.objects.get(
            subject_identifier=self.subject_consent_male.subject_identifier)

        self.sexual_data = {
            'subject_visit': self.subject_visit.id,
            'alcohol_sex': 'Myself',
            'report_datetime': datetime.today(),
            'condom': NO,
            'more_sex': NO,
            'ever_sex': YES,
            'first_sex': 20,
            'last_year_partners': None,
            'lifetime_sex_partners': 1,
            'more_sex': None,
            'subject_visit_id': None,
            'user_modified': u'',
        }
        self.data = {
            'subject_visit': self.subject_visit.id,
            'concurrent': NO,
            'first_partner_live': None,
            'first_condom_freq': u'Sometimes',
            'first_disclose': u'Yes',
            'first_exchange': u'30-39',
            'first_first_sex': u'Years',
            'first_first_sex_calc': 3L,
            'first_haart': None,
            'first_partner_arm': None,
            'first_partner_cp': u'No',
            'first_partner_hiv': u'not_sure',
            'first_relationship': u'Long-term partner',
            'first_sex_current': u'Yes',
            'first_sex_freq': None,
            'goods_exchange': u'No',
            'partner_hiv_test': u'not_sure',
            'past_year_sex_freq': u'About once a month',
            'report_datetime': datetime.today(),
            'sex_partner_community': u'N/A',
            'subject_visit_id': None,
            'third_last_sex': u'Days',
            'third_last_sex_calc': 7L,
            'user_modified': u''
        }
class TestMostRecentForm(TestCase):

    app_label = 'bcpp_subject'
    community = 'test_community'

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-2',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def setUp(self):
        site_mappers.autodiscover()
        from bhp066.apps.bcpp_subject.visit_schedule import BcppSubjectVisitSchedule
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        self.app_config = BcppAppConfiguration()
        self.app_config.prepare()
        self.app_config.prep_survey_for_tests()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')

        self.survey_bhs = Survey.objects.get(survey_slug='bcpp-year-1')

        self.survey_ahs = Survey.objects.get(survey_slug='bcpp-year-2')

        self.study_site = StudySite.objects.get(site_code='01')

        self.household_structure_bhs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_bhs)
        self.household_structure_ahs = HouseholdStructure.objects.get(
            household__plot=plot, survey=self.survey_ahs)
        self.create_household_log_entry(self.household_structure_bhs)

        RepresentativeEligibilityFactory(
            household_structure=self.household_structure_bhs)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_last_name = 'HIEWAI'
        self.male_initials = "EW"

        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure_bhs,
            gender='M',
            age_in_years=self.male_age_in_years,
            first_name=self.male_first_name,
            initials=self.male_initials)
        HeadHouseholdEligibilityFactory(
            household_member=self.household_member_male_T0,
            household_structure=self.household_structure_bhs)
        self.household_member_male_T0.eligible_hoh = True
        self.household_member_male_T0.save()

        HouseholdInfoFactory(household_member=self.household_member_male_T0,
                             household_structure=self.household_structure_bhs,
                             registered_subject=self.household_member_male_T0.
                             registered_subject)

        self.enrollment = EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes')
        self.subject_consent_male = SubjectConsentFactory(
            household_member=self.household_member_male_T0,
            confirm_identity='101119811',
            identity='101119811',
            study_site=self.study_site,
            gender='M',
            dob=self.male_dob,
            first_name=self.male_first_name,
            initials=self.male_initials)
        self.appointment = Appointment.objects.get(
            registered_subject=self.household_member_male_T0.
            registered_subject,
            visit_definition__code='T0')

        self.subject_visit = SubjectVisitFactory(
            household_member=self.household_member_male_T0,
            appointment=self.appointment)

        self.registered_subject = RegisteredSubject.objects.get(
            subject_identifier=self.subject_consent_male.subject_identifier)

        self.sexual_data = {
            'subject_visit': self.subject_visit.id,
            'alcohol_sex': 'Myself',
            'report_datetime': datetime.today(),
            'condom': NO,
            'more_sex': NO,
            'ever_sex': YES,
            'first_sex': 20,
            'last_year_partners': None,
            'lifetime_sex_partners': 1,
            'more_sex': None,
            'subject_visit_id': None,
            'user_modified': u'',
        }
        self.data = {
            'subject_visit': self.subject_visit.id,
            'concurrent': NO,
            'first_partner_live': None,
            'first_condom_freq': u'Sometimes',
            'first_disclose': u'Yes',
            'first_exchange': u'30-39',
            'first_first_sex': u'Years',
            'first_first_sex_calc': 3L,
            'first_haart': None,
            'first_partner_arm': None,
            'first_partner_cp': u'No',
            'first_partner_hiv': u'not_sure',
            'first_relationship': u'Long-term partner',
            'first_sex_current': u'Yes',
            'first_sex_freq': None,
            'goods_exchange': u'No',
            'partner_hiv_test': u'not_sure',
            'past_year_sex_freq': u'About once a month',
            'report_datetime': datetime.today(),
            'sex_partner_community': u'N/A',
            'subject_visit_id': None,
            'third_last_sex': u'Days',
            'third_last_sex_calc': 7L,
            'user_modified': u''
        }

    def create_household_log_entry(self, household_structure):
        household_log = HouseholdLog.objects.filter(
            household_structure=household_structure).last()
        HouseholdLogEntry.objects.all().delete()
        HouseholdLogEntryFactory(household_log=household_log)

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_recent_form_valid(self):
        """ For all participants who are above 64 at bhs are not eligible."""
        from bhp066.apps.bcpp_subject.forms.months_partner_form import MonthsRecentPartnerForm
        from bhp066.apps.bcpp_subject.forms.sexual_behaviour_form import SexualBehaviourForm
        sexual_behaviour_form = SexualBehaviourForm(data=self.sexual_data)
        sexual_behaviour_form.save()
        self.assertTrue(sexual_behaviour_form.is_valid())
        from bhp066.apps.bcpp_list.models import PartnerResidency
        parnter_residency = PartnerResidency.objects.create(
            name='In this community.')
        self.data['first_partner_live'] = [parnter_residency.id]
        recent_form = MonthsRecentPartnerForm(data=self.data)

        self.assertTrue(recent_form.is_valid())

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_recent_form_valid1(self):
        """ For all participants who are above 64 at bhs are not eligible."""
        from bhp066.apps.bcpp_subject.forms.months_partner_form import MonthsRecentPartnerForm
        from bhp066.apps.bcpp_subject.forms.sexual_behaviour_form import SexualBehaviourForm
        sexual_behaviour_form = SexualBehaviourForm(data=self.sexual_data)
        sexual_behaviour_form.save()
        self.assertTrue(sexual_behaviour_form.is_valid())
        from bhp066.apps.bcpp_list.models import PartnerResidency
        parnter_residency = PartnerResidency.objects.create(
            name='In this community.')
        self.data['first_partner_live'] = [parnter_residency.id]
        self.data['concurrent'] = 'DWTA'
        recent_form = MonthsRecentPartnerForm(data=self.data)

        self.assertTrue(recent_form.is_valid())

    @override_settings(
        SITE_CODE='01',
        CURRENT_COMMUNITY='test_community',
        CURRENT_SURVEY='bcpp-year-1',
        CURRENT_COMMUNITY_CHECK=False,
        LIMIT_EDIT_TO_CURRENT_SURVEY=True,
        LIMIT_EDIT_TO_CURRENT_COMMUNITY=True,
        FILTERED_DEFAULT_SEARCH=True,
    )
    def test_subject_recent_form_not_valid(self):
        """ For all participants who are above 64 at bhs are not eligible."""
        from bhp066.apps.bcpp_subject.forms.months_partner_form import MonthsRecentPartnerForm
        from bhp066.apps.bcpp_subject.forms.sexual_behaviour_form import SexualBehaviourForm
        sexual_behaviour_form = SexualBehaviourForm(data=self.sexual_data)
        sexual_behaviour_form.save()
        print sexual_behaviour_form.errors
        self.assertTrue(sexual_behaviour_form.is_valid())
        from bhp066.apps.bcpp_list.models import PartnerResidency
        parnter_residency = PartnerResidency.objects.create(
            name='In this community.')
        self.data['concurrent'] = YES
        self.data['first_partner_live'] = [parnter_residency.id]
        recent_form = MonthsRecentPartnerForm(data=self.data)
        msg = "Please correct if you have sex with other partners"
        err_msg = u"You wrote that you have only one partner ever in sexual behavior form. {}".format(
            msg)
        #self.assertIn(u"sex", recent_form.errors.get("__all__"))
        self.assertFalse(recent_form.is_valid())
    def test_p3(self):
        instances = []
        plot = PlotFactory(community='test_community6',
                           household_count=1,
                           status='residential_habitable')
        Household.objects.get(plot=plot)
        household_structure = HouseholdStructure.objects.get(
            survey=Survey.objects.all()[0])
        RepresentativeEligibilityFactory(
            household_structure=household_structure)
        household_member = HouseholdMemberFactory(
            household_structure=household_structure)
        enrollment_checklist = EnrollmentChecklistFactory(
            household_member=household_member,
            initials=household_member.initials,
            has_identity='Yes',
            dob=date(1989, 01, 01))
        self.assertTrue(enrollment_checklist.is_eligible)
        instances.append(enrollment_checklist)
        self.assertEqual(RegisteredSubject.objects.all().count(), 1)
        registered_subject = RegisteredSubject.objects.all()[0]
        site = StudySite.objects.all()[0]
        subject_consent = SubjectConsentFactory(
            study_site=site,
            household_member=household_member,
            registered_subject=household_member.registered_subject,
            dob=enrollment_checklist.dob,
            initials=enrollment_checklist.initials)
        instances.append(subject_consent)
        self.assertEqual(Appointment.objects.all().count(), 1)
        appointment = Appointment.objects.get(
            registered_subject=registered_subject)
        subject_visit = SubjectVisitFactory(household_member=household_member,
                                            appointment=appointment)
        instances.append(subject_visit)
        aliquot_type = AliquotType.objects.all()[0]
        panel = Panel.objects.all()[0]
        subjects_requisition = SubjectRequisitionFactory(
            subject_visit=subject_visit,
            panel=panel,
            site=site,
            aliquot_type=aliquot_type,
        )
        self.assertEqual(Aliquot.objects.all().count(), 0)
        subjects_requisition.is_receive = True
        subjects_requisition.is_receive_datetime = datetime.now()
        subjects_requisition.save()
        lab_profile = site_labs.get(subjects_requisition._meta.object_name)
        lab_profile().receive(subjects_requisition)
        receive = Receive.objects.all()[0]
        self.assertEqual(Aliquot.objects.all().count(), 1)
        aliquot = Aliquot.objects.all()[0]
        processing = ProcessingFactory(profile=AliquotProfile.objects.all()[0],
                                       aliquot=aliquot)
        for al in Aliquot.objects.all():
            instances.append(al)
        instances.append(processing)
        instances.append(receive)
        self.assertEqual(PackingListItem.objects.all().count(), 0)
        packing_list = PackingListFactory(
            list_items=aliquot.aliquot_identifier)
        instances.append(packing_list)
        packing_list.list_items = al.aliquot_identifier
        packing_list.save()

        for obj in instances:
            natural_key = obj.natural_key()
            get_obj = obj.__class__.objects.get_by_natural_key(*natural_key)
            self.assertEqual(obj.pk, get_obj.pk)
        for obj in instances:
            outgoing_transaction = SerializeToTransaction().serialize(
                obj.__class__, obj, False, True, 'default')
            for transaction in serializers.deserialize(
                    "json",
                    FieldCryptor('aes',
                                 'local').decrypt(outgoing_transaction.tx)):
                self.assertEqual(transaction.object.pk, obj.pk)