def test_get(self): partner = PartnerFactory() agreement = AgreementFactory(partner=partner) intervention_1 = InterventionFactory(agreement=agreement) intervention_2 = InterventionFactory(agreement=agreement) intervention_3 = InterventionFactory() res = tags.get_interventions(partner.pk) self.assertIn(intervention_1.number, res) self.assertIn(intervention_2.number, res) self.assertNotIn(intervention_3.number, res)
def test_notify_interventions_ending_soon_with_some_interventions( self, mock_notification_objects, mock_db_connection, mock_logger): '''Exercise _notify_interventions_ending_soon() when there are interventions for it to work on. That task specifically works on interventions that will end in 15 and 30 days. ''' today = datetime.date.today() # Create some interventions to work with. Interventions sort by oldest last, so I make sure my list here is # ordered in the same way as they'll be pulled out of the database. interventions = [] for delta in partners.tasks._INTERVENTION_ENDING_SOON_DELTAS: end_on = datetime.date.today() + datetime.timedelta(days=delta) interventions += [InterventionFactory(status=Intervention.ACTIVE, end=end_on, created=_make_past_datetime(i + delta)) for i in range(3)] # Create a few items that should be ignored. If they're not ignored, this test will fail. # Should be ignored because of status InterventionFactory(status=Intervention.DRAFT, end=end_on) InterventionFactory(status=Intervention.IMPLEMENTED, end=end_on) InterventionFactory(status=Intervention.TERMINATED, end=end_on) # All of these should be ignored because of end date for delta in range(max(partners.tasks._INTERVENTION_ENDING_SOON_DELTAS) + 5): if delta not in partners.tasks._INTERVENTION_ENDING_SOON_DELTAS: InterventionFactory(status=Intervention.ACTIVE, end=today + datetime.timedelta(days=delta)) # Mock Notifications.objects.create() to return a Mock. In order to *truly* mimic create(), my # mock_notification_objects.create() should return a new (mock) object every time, but the lazy way or # returning the same object is good enough and still allows me to count calls to .send_notification(). mock_notification = mock.Mock(spec=['send_notification']) mock_notification_objects.create = mock.Mock(return_value=mock_notification) # I'm done mocking, it's time to call the function. partners.tasks._notify_interventions_ending_soon(self.country_name) # Verify that Notification.objects.create() was called as expected. expected_call_args = [] for intervention in interventions: template_data = partners.tasks.get_intervention_context(intervention) template_data['days'] = str((intervention.end - today).days) expected_call_args.append(((), {'sender': intervention, 'recipients': [], 'template_name': 'partners/partnership/ending', 'template_data': template_data })) self._assertCalls(mock_notification_objects.create, expected_call_args) # Verify that each created notification object had send_notification() called. expected_call_args = [((), {}) for intervention in interventions] self._assertCalls(mock_notification.send_notification, expected_call_args)
def test_notify_of_ended_interventions_with_some_interventions( self, mock_notification_objects, mock_db_connection, mock_logger): '''Exercise _notify_of_ended_interventions_with_mismatched_frs() when it has some interventions to work on''' # Create some interventions to work with. Interventions sort by oldest last, so I make sure my list here is # ordered in the same way as they'll be pulled out of the database. interventions = [InterventionFactory(status=Intervention.ENDED, created=_make_past_datetime(i)) for i in range(3)] # Add mismatched funds values to each intervention. for intervention in interventions: for i in range(3): FundsReservationHeaderFactory(intervention=intervention, actual_amt_local=_make_decimal(i + 1), total_amt_local=_make_decimal(i)) # Create a few items that should be ignored. If they're not ignored, this test will fail. # Should be ignored because of status even though FRS values are mismatched intervention = InterventionFactory(status=Intervention.DRAFT) for i in range(3): FundsReservationHeaderFactory(intervention=intervention, actual_amt_local=_make_decimal(i + 1), total_amt_local=_make_decimal(i)) # Should be ignored because FRS values are not mismatched intervention = InterventionFactory(status=Intervention.ENDED) for i in range(3): FundsReservationHeaderFactory(intervention=intervention, actual_amt_local=_make_decimal(i), total_amt_local=_make_decimal(i)) # Mock Notifications.objects.create() to return a Mock. In order to *truly* mimic create(), my # mock_notification_objects.create() should return a new (mock) object every time, but the lazy way or # returning the same object is good enough and still allows me to count calls to .send_notification(). mock_notification = mock.Mock(spec=['send_notification']) mock_notification_objects.create = mock.Mock(return_value=mock_notification) # I'm done mocking, it's time to call the function. partners.tasks._notify_of_ended_interventions_with_mismatched_frs(self.country_name) # Verify that Notification.objects.create() was called as expected. expected_call_args = [((), {'sender': intervention_, 'recipients': [], 'template_name': 'partners/partnership/ended/frs/outstanding', 'template_data': partners.tasks.get_intervention_context(intervention_) }) for intervention_ in interventions] self._assertCalls(mock_notification_objects.create, expected_call_args) # Verify that each created notification object had send_notification() called. expected_call_args = [((), {})] * len(interventions) self._assertCalls(mock_notification.send_notification, expected_call_args)
def test_intervention_terminable_statuses(self): """Interventions in amendment cannot be terminated""" terminable_statuses = [Intervention.SIGNED, Intervention.ACTIVE] for terminable_status in terminable_statuses: intervention = InterventionFactory( status=terminable_status, ) self.assertTrue(transition_to_terminated(intervention)) intervention.in_amendment = True with self.assertRaises(TransitionError): transition_to_terminated(intervention)
def setUpTestData(cls): cls.file_type_partner = AttachmentFileTypeFactory( code="partners_partner_assessment") cls.file_type_agreement = AttachmentFileTypeFactory( code="partners_agreement") cls.file_type_assessment = AttachmentFileTypeFactory( code="partners_assessment_report") cls.file_type_agreement_amendment = AttachmentFileTypeFactory( code="partners_agreement_amendment") cls.file_type_intervention_prc_review = AttachmentFileTypeFactory( code="partners_intervention_prc_review") cls.file_type_intervention_signed_pd = AttachmentFileTypeFactory( code="partners_intervention_signed_pd") cls.file_type_intervention_amendment = AttachmentFileTypeFactory( code="partners_intervention_amendment_signed") cls.file_type_intervention_attachment = AttachmentFileTypeFactory( code="partners_intervention_attachment") cls.partner = PartnerFactory(core_values_assessment="sample.pdf") cls.agreement = AgreementFactory(attached_agreement="sample.pdf") cls.assessment = AssessmentFactory(report="sample.pdf") cls.agreement_amendment = AgreementAmendmentFactory( signed_amendment="sample.pdf") cls.intervention = InterventionFactory( prc_review_document="prc_sample.pdf", signed_pd_document="pd_sample.pdf") cls.intervention_amendment = InterventionAmendmentFactory( signed_amendment="sample.pdf") cls.intervention_attachment = InterventionAttachmentFactory( attachment="sample.pdf")
def test_issue_found(self): """Check that is country programme for intervention does not match result country programme then issue is created""" qs_issue = FlaggedIssue.objects.filter(issue_id="pd_outputs_wrong") start_date = datetime.date(2001, 1, 1) end_date = datetime.date(2001, 12, 31) country = CountryProgrammeFactory( from_date=start_date, to_date=end_date, ) intervention = InterventionFactory( country_programme=country, start=start_date, ) result = ResultFactory(country_programme=CountryProgrammeFactory()) InterventionResultLink.objects.create( intervention=intervention, cp_output=result, ) self.assertNotEqual(intervention.country_programme, result.country_programme) self.assertFalse(qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertTrue(qs_issue.exists()) issue = qs_issue.first() self.assertIn("has wrongly mapped outputs", issue.message)
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) partner = PartnerFactory( partner_type='Government', vendor_number='Vendor No', short_name="Short Name", alternate_name="Alternate Name", shared_with=["DPKO", "ECA"], address="Address 123", phone_number="Phone no 1234567", email="*****@*****.**", rating="High", core_values_assessment_date=datetime.date.today(), total_ct_cp=10000, total_ct_cy=20000, deleted_flag=False, blocked=False, type_of_assessment="Type of Assessment", last_assessment_date=datetime.date.today(), ) partnerstaff = PartnerStaffFactory(partner=partner) agreement = AgreementFactory( partner=partner, country_programme=CountryProgrammeFactory(wbs="random WBS"), attached_agreement="fake_attachment.pdf", start=datetime.date.today(), end=datetime.date.today(), signed_by_unicef_date=datetime.date.today(), signed_by=cls.unicef_staff, signed_by_partner_date=datetime.date.today() ) agreement.authorized_officers.add(partnerstaff) agreement.save() AgreementFactory(signed_by_unicef_date=datetime.date.today()) cls.intervention = InterventionFactory( agreement=agreement, document_type='SHPD', status='draft', start=datetime.date.today(), end=datetime.date.today(), submission_date=datetime.date.today(), submission_date_prc=datetime.date.today(), review_date_prc=datetime.date.today(), signed_by_unicef_date=datetime.date.today(), signed_by_partner_date=datetime.date.today(), unicef_signatory=cls.unicef_staff, population_focus="Population focus", partner_authorized_officer_signatory=partnerstaff, country_programme=agreement.country_programme, ) cls.ib = InterventionBudgetFactory( intervention=cls.intervention, currency="USD" ) cls.planned_visit = InterventionPlannedVisitsFactory( intervention=cls.intervention, ) cls.attachment = InterventionAttachmentFactory( intervention=cls.intervention, )
def test_intervention(self): intervention = InterventionFactory() fields = utils.get_to_many_field_names(intervention.__class__) # check many_to_one field self.assertIn("frs", fields) # check many_to_many field self.assertIn("sections", fields)
def test_prp_api_performance(self): EXPECTED_QUERIES = 23 with self.assertNumQueries(EXPECTED_QUERIES): self.run_prp_v1( user=self.unicef_staff, method='get' ) # make a bunch more stuff, make sure queries don't go up. intervention = InterventionFactory(agreement=self.agreement, title='New Intervention') result = ResultFactory(name='Another Result') result_link = InterventionResultLink.objects.create( intervention=intervention, cp_output=result) lower_result = LowerResult.objects.create(result_link=result_link, name='Lower Result 1') indicator_blueprint = IndicatorBlueprint.objects.create( title='The Blueprint' ) applied_indicator = AppliedIndicator.objects.create( indicator=indicator_blueprint, lower_result=lower_result, ) applied_indicator.locations.add(LocationFactory(name='A Location', gateway=GatewayTypeFactory(name='Another Gateway'), p_code='a-p-code')) applied_indicator.disaggregation.create(name='Another Disaggregation') with self.assertNumQueries(EXPECTED_QUERIES): self.run_prp_v1( user=self.unicef_staff, method='get' )
def test_no_issue(self): """Check that valida interventions results in no issue""" qs_issue = FlaggedIssue.objects.filter(issue_id="pd_outputs_wrong") start_date = datetime.date(2001, 1, 1) end_date = datetime.date(2001, 12, 31) country = CountryProgrammeFactory( from_date=start_date, to_date=end_date, ) intervention = InterventionFactory( country_programme=country, start=start_date, ) result = ResultFactory(country_programme=country) InterventionResultLink.objects.create( intervention=intervention, cp_output=result, ) self.assertEqual(intervention.country_programme, result.country_programme) self.assertFalse(qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertFalse(qs_issue.exists())
def test_no_interventions(self): """If intervention does not fit in with Country Programmes then no issues raised """ qs_issue = FlaggedIssue.objects.filter(issue_id="pd_outputs_wrong") start_date = datetime.date(2001, 1, 1) end_date = datetime.date(2001, 12, 31) country = CountryProgrammeFactory( from_date=start_date, to_date=end_date, ) intervention = InterventionFactory( country_programme=country, start=start_date - datetime.timedelta(days=1), ) result = ResultFactory(country_programme=CountryProgrammeFactory()) InterventionResultLink.objects.create( intervention=intervention, cp_output=result, ) self.assertNotEqual(intervention.country_programme, result.country_programme) self.assertFalse(qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertFalse(qs_issue.exists())
def test_ssfa_invalid(self): """If document type SSFA, and agreement type is SSFA invalid if agreement interventions count is > 1 """ InterventionFactory(agreement=self.agreement) self.assertFalse( ssfa_agreement_has_no_other_intervention(self.intervention) )
def test_str(self): user = UserFactory() intervention = InterventionFactory() activity = ActivityFactory(target=intervention, action=Activity.CREATE, by_user=user) self.assertEqual( six.text_type(activity), "{} {} {}".format(user, Activity.CREATE, intervention))
def test_start_date_after_signed_date(self): """Start date after max signed date is valid""" intervention = InterventionFactory( signed_by_unicef_date=datetime.date(2001, 2, 1), signed_by_partner_date=datetime.date(2001, 3, 1), signed_pd_document="random.pdf", start=datetime.date(2001, 4, 1) ) self.assertTrue(start_date_signed_valid(intervention))
def test_create(self): user = UserFactory() intervention = InterventionFactory() activity = utils.create_snapshot(intervention, {}, user) self.assertEqual(activity.target, intervention) self.assertEqual(activity.action, activity.CREATE) self.assertEqual(activity.by_user, user) self.assertEqual(activity.data["title"], intervention.title) self.assertEqual(activity.change, {})
def setUp(self): super(TestSSFAgreementHasNoOtherIntervention, self).setUp() self.agreement = AgreementFactory( agreement_type=Agreement.SSFA, ) self.intervention = InterventionFactory( document_type=Intervention.SSFA, agreement=self.agreement, )
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) cls.url = reverse("lower-results") cls.intervention = InterventionFactory() cls.result_link = InterventionResultLinkFactory( intervention=cls.intervention, ) cls.lower_result = LowerResultFactory( name="LL Name", result_link=cls.result_link, )
def test_save_model_update(self): self.assertFalse(Activity.objects.exists()) ia = InterventionAdmin(Intervention, self.site) obj = InterventionFactory() title_before = obj.title obj.title = "Title Change" ia.save_model(self.request, obj, {}, True) self.assertTrue( Activity.objects.filter(action=Activity.UPDATE).exists() ) activity = Activity.objects.first() self.assertEqual(activity.target, obj) self.assertEqual(activity.by_user, self.user) self.assertDictEqual(activity.change, { "title": { "before": title_before, "after": "Title Change" } })
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) cls.partnership_manager_user = UserFactory(is_staff=True) cls.partnership_manager_user.groups.add(GroupFactory()) cls.partner1 = PartnerFactory( partner_type=PartnerType.CIVIL_SOCIETY_ORGANIZATION) cls.country_programme = CountryProgrammeFactory() cls.agreement1 = AgreementFactory( partner=cls.partner1, signed_by_unicef_date=datetime.date.today()) cls.intervention = InterventionFactory(agreement=cls.agreement1) cls.intervention_2 = InterventionFactory(agreement=cls.agreement1, document_type=Intervention.PD) cls.amendment = AgreementAmendment.objects.create( agreement=cls.agreement1, types=[AgreementAmendment.IP_NAME, AgreementAmendment.CLAUSE], number="001", signed_amendment="application/pdf", signed_date=datetime.date.today())
def test_no_issue(self): """Check if intervention does not fail validation, no issue is raised """ intervention = InterventionFactory() validator = InterventionValid(intervention, self.master_user) self.assertTrue(validator.is_valid) self.assertFalse(self.qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertFalse(self.qs_issue.exists())
def test_end_after_today(self): """End date cannot be after today's date'""" intervention = InterventionFactory( end=datetime.date.today() + datetime.timedelta(days=2) ) with self.assertRaisesRegexp( TransitionError, "End date is in the future" ): transition_to_closed(intervention) self.assertFundamentals(intervention.total_frs)
def setUp(self): super(TestAmendmentsInvalid, self).setUp() self.intervention = InterventionFactory( status=Intervention.DRAFT, ) self.intervention.old_instance = self.intervention self.amendment = InterventionAmendmentFactory( intervention=self.intervention, signed_date=datetime.date(2001, 1, 1), signed_amendment="random.pdf", )
class TestGetInterventionContext(BaseTenantTestCase): '''Exercise the tasks' helper function get_intervention_context()''' def setUp(self): super(TestGetInterventionContext, self).setUp() self.intervention = InterventionFactory() def test_simple_intervention(self): '''Exercise get_intervention_context() with a very simple intervention''' result = partners.tasks.get_intervention_context(self.intervention) self.assertIsInstance(result, dict) self.assertEqual(sorted(result.keys()), sorted(['number', 'partner', 'start_date', 'url', 'unicef_focal_points'])) self.assertEqual(result['number'], six.text_type(self.intervention)) self.assertEqual(result['partner'], self.intervention.agreement.partner.name) self.assertEqual(result['start_date'], 'None') self.assertEqual(result['url'], 'https://{}/pmp/interventions/{}/details'.format(settings.HOST, self.intervention.id)) self.assertEqual(result['unicef_focal_points'], []) def test_non_trivial_intervention(self): '''Exercise get_intervention_context() with an intervention that has some interesting detail''' focal_point_user = User.objects.all()[0] self.intervention.unicef_focal_points.add(focal_point_user) self.intervention.start = datetime.date(2017, 8, 1) self.intervention.save() result = partners.tasks.get_intervention_context(self.intervention) self.assertIsInstance(result, dict) self.assertEqual(sorted(result.keys()), sorted(['number', 'partner', 'start_date', 'url', 'unicef_focal_points'])) self.assertEqual(result['number'], six.text_type(self.intervention)) self.assertEqual(result['partner'], self.intervention.agreement.partner.name) self.assertEqual(result['start_date'], '2017-08-01') self.assertEqual(result['url'], 'https://{}/pmp/interventions/{}/details'.format(settings.HOST, self.intervention.id)) self.assertEqual(result['unicef_focal_points'], [focal_point_user.email])
def test_no_issue_ssfa(self): """Check that if agreement type PCA and document type SSFA then issue is NOT raised """ agreement = AgreementFactory(agreement_type=Agreement.PCA) InterventionFactory( agreement=agreement, document_type=Intervention.PD, ) self.assertFalse(self.qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertFalse(self.qs_issue.exists())
def test_invalid_intervention(self): """Check if intervention fails validation, issue is raised""" intervention = InterventionFactory( signed_by_unicef_date=datetime.date(2001, 2, 1), signed_by_partner_date=datetime.date(2001, 3, 1), signed_pd_document="random.pdf", start=datetime.date(2001, 1, 1)) validator = InterventionValid(intervention, self.master_user) self.assertFalse(validator.is_valid) self.assertFalse(self.qs_issue.exists()) checks.bootstrap_checks(default_is_active=True) checks.run_all_checks() self.assertTrue(self.qs_issue.exists())
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) cls.intervention = InterventionFactory() cls.result_link = InterventionResultLinkFactory() cls.lower_result = LowerResultFactory( name="LL Name", result_link=cls.result_link, ) cls.indicator = IndicatorBlueprintFactory() cls.applied = AppliedIndicatorFactory(context_code="CC321", indicator=cls.indicator, lower_result=cls.lower_result) cls.url = reverse("applied-indicator")
def setUpTestData(cls): cls.unicef_staff = UserFactory(is_staff=True) cls.intervention = InterventionFactory() cls.intervention.old_instance = cls.intervention cls.validator = InterventionValid( cls.intervention, user=cls.unicef_staff, disable_rigid_check=True, ) cls.validator.permissions = cls.validator.get_permissions( cls.intervention ) cls.future_date = datetime.date.today() + datetime.timedelta(days=2)
def test_start_date_after_signed_date(self): """Start date after agreement start date is invalid If not contingency_pd, and certain document_type """ agreement = AgreementFactory() intervention = InterventionFactory( agreement=agreement, signed_pd_document="random.pdf", start=datetime.date.today() + datetime.timedelta(days=2), contingency_pd=False, document_type=Intervention.PD, ) self.assertTrue(start_date_related_agreement_valid(intervention))
def test_intervention_nonsuspendable_statuses(self): non_suspendable_statuses = [ Intervention.DRAFT, Intervention.ENDED, Intervention.IMPLEMENTED, Intervention.CLOSED, Intervention.TERMINATED, ] for non_suspendable_status in non_suspendable_statuses: intervention = InterventionFactory( status=non_suspendable_status, ) self.assertFalse(transition_to_suspended(intervention))
def test_intervention_nonterminable_statuses(self): non_terminable_statuses = [ Intervention.DRAFT, Intervention.ENDED, Intervention.IMPLEMENTED, Intervention.CLOSED, Intervention.SUSPENDED, ] for non_terminable_status in non_terminable_statuses: intervention = InterventionFactory( status=non_terminable_status, ) self.assertFalse(transition_to_terminated(intervention))