def test_search_user_by_last_name_big_name(self): user_big_name = baker.make_recipe( 'user.user_recipe', first_name="Ricardo", last_name="Monteiro e Lima", google_drive_spreadsheet_id="00421", ) search_token = "Lima" url_with_parameters = f'{self.endpoint}?search={search_token}' response = self.client.get(url_with_parameters) self.assertEquals(response.status_code, status.HTTP_200_OK) response_content = response.data self.assertEquals(len(response_content), 1) self.assertEquals(response_content[0]['id'], user_big_name.id)
def test_restaurant_update_400(self): random_obj = baker.make_recipe('api.restaurantTemplate') data = { # 'name': fake.text(160), 'description': fake.text(200), 'address': fake.text(35), 'cover': open('test_data/sample.jpg', 'rb') } url = reverse(RESTAURANT_DETAIL_URL, args=(random_obj.pk, )) self.client.force_login(get_user_model().objects.first()) response = self.client.put(url, data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_report_view_last_updated(client, log_output): """ Test that the last updated field (which is fetched on page load and stored on the model) is displayed properly on the report page. """ report = baker.make_recipe("reports.real_report") assert report.last_updated is None # fetch report response = client.get(report.get_absolute_url()) assert response.status_code == 200 report.refresh_from_db() assert report.last_updated is not None assert report.last_updated.strftime("%d %b %Y") in response.rendered_content
def test_ae_initial_creates_action(self): subject_screening = self.get_subject_screening() subject_consent = self.get_subject_consent(subject_screening) ae_initial = baker.make_recipe( "inte_ae.aeinitial", subject_identifier=subject_consent.subject_identifier) try: action_item = ActionItem.objects.get( action_identifier=ae_initial.action_identifier) except ObjectDoesNotExist: self.fail("ObjectDoesNotExist unexpectedly raised.") else: self.assertEqual(action_item.status, CLOSED) self.assertEqual(action_item.subject_identifier, subject_consent.subject_identifier)
def test_invite_new_user(mocker): patched_notification = mocker.patch( "multi_tenant.invite.send_invite_notification") client = baker.make_recipe("multi_tenant.client") assert Invite.objects.count() == 0 invite_user("*****@*****.**", client) invite = Invite.objects.first() assert invite.email == "*****@*****.**" assert invite.primary_client == client assert invite.clients.count() == 1 assert invite.clients.first() == client patched_notification.delay.assert_called_once_with(invite.pk, client.pk)
def test_delete_policy_tasks(self, delete_win_task_schedule): from .tasks import delete_policy_autotask_task policy = baker.make("automation.Policy", active=True) tasks = baker.make("autotasks.AutomatedTask", policy=policy, _quantity=3) site = baker.make("clients.Site") agent = baker.make_recipe("agents.server_agent", site=site, policy=policy) agent.generate_tasks_from_policies() delete_policy_autotask_task(tasks[0].id) delete_win_task_schedule.assert_called_with(agent.autotasks.first().id)
def create_allowed_operation( allowed_groups: QuerySet(MrMapGroup), operations: QuerySet(OGCOperation), root_metadata: Metadata, how_much_allowed_operations: int = 1, allowed_area: MultiPolygon = None, ): return baker.make_recipe( "tests.baker_recipes.service_app.allowed_operation", _quantity=how_much_allowed_operations, root_metadata=root_metadata, allowed_groups=allowed_groups, operations=operations, allowed_area=allowed_area, )
def test_edit_policy(self): url = "/winupdate/editpolicy/" agent = baker.make_recipe("agents.agent") winupdate = baker.make("winupdate.WinUpdate", agent=agent) invalid_data = {"pk": 500, "policy": "inherit"} # test a call where winupdate doesn't exist resp = self.client.patch(url, invalid_data, format="json") self.assertEqual(resp.status_code, 404) data = {"pk": winupdate.pk, "policy": "inherit"} resp = self.client.patch(url, data, format="json") self.assertEqual(resp.status_code, 200) self.check_not_authenticated("patch", url)
def test_does_not_auto_increment_draft_revision_on_save_if_other_states( self): contract = baker.make_recipe("sponsors.tests.empty_contract", revision=10) choices = Contract.STATUS_CHOICES other_status = [c[0] for c in choices if c[0] != Contract.DRAFT] for status in other_status: contract.status = status contract.save() contract.refresh_from_db() self.assertEqual(contract.status, status) self.assertEqual(contract.revision, 10) contract.save() # perform extra save contract.refresh_from_db() self.assertEqual(contract.revision, 10)
def test_task_runner_get(self): from autotasks.serializers import TaskGOGetSerializer r = self.client.get("/api/v3/500/asdf9df9dfdf/taskrunner/") self.assertEqual(r.status_code, 404) # setup data agent = baker.make_recipe("agents.agent") task = baker.make("autotasks.AutomatedTask", agent=agent) url = f"/api/v3/{task.pk}/{agent.agent_id}/taskrunner/" # type: ignore r = self.client.get(url) self.assertEqual(r.status_code, 200) self.assertEqual(TaskGOGetSerializer(task).data, r.data) # type: ignore
def test_cdn_clear_information_field(mocker): patched_tags_call = mocker.patch("election.models.purge_cdn_tags") patched_single_tag_call = mocker.patch("election.models.purge_cdn_tag") information = baker.make_recipe("election.markdown_information") patched_tags_call.assert_called_once_with([ "state", "stateinformationfield", "stateinformationfieldtype", ]) information.text = "New Text" information.save() assert information.state_id == "XX" patched_single_tag_call.assert_called_once_with("XX")
def setUp(self): site_visit_schedules._registry = {} site_visit_schedules.register(visit_schedule) subject_consent = baker.make_recipe( "adverse_event_app.subjectconsent", subject_identifier="1234567" ) self.subject_identifier = subject_consent.subject_identifier # put subject on schedule _, schedule = site_visit_schedules.get_by_onschedule_model( "adverse_event_app.onschedule" ) schedule.put_on_schedule( subject_identifier=subject_consent.subject_identifier, onschedule_datetime=subject_consent.consent_datetime, )
def test_get_winupdates(self): agent = baker.make_recipe("agents.agent") baker.make("winupdate.WinUpdate", agent=agent, _quantity=4) # test a call where agent doesn't exist resp = self.client.get("/winupdate/500/getwinupdates/", format="json") self.assertEqual(resp.status_code, 404) url = f"/winupdate/{agent.pk}/getwinupdates/" resp = self.client.get(url, format="json") serializer = UpdateSerializer(agent) self.assertEqual(resp.status_code, 200) self.assertEqual(len(resp.data["winupdates"]), 4) # type: ignore self.assertEqual(resp.data, serializer.data) # type: ignore self.check_not_authenticated("get", url)
def test_delete_patch_policy(self): # test patch policy doesn't exist resp = self.client.delete("/automation/winupdatepolicy/500/", format="json") self.assertEqual(resp.status_code, 404) winupdate_policy = baker.make_recipe("winupdate.winupdate_policy", policy__name="Test Policy") url = f"/automation/winupdatepolicy/{winupdate_policy.pk}/" resp = self.client.delete(url, format="json") self.assertEqual(resp.status_code, 200) self.assertFalse( WinUpdatePolicy.objects.filter(pk=winupdate_policy.pk).exists()) self.check_not_authenticated("delete", url)
def test_run_autotask(self, run_win_task): # setup data agent = baker.make_recipe("agents.agent", version="1.1.0") task = baker.make("autotasks.AutomatedTask", agent=agent) # test invalid url resp = self.client.get("/tasks/runwintask/500/", format="json") self.assertEqual(resp.status_code, 404) # test run agent task url = f"/tasks/runwintask/{task.id}/" # type: ignore resp = self.client.get(url, format="json") self.assertEqual(resp.status_code, 200) run_win_task.assert_called() self.check_not_authenticated("get", url)
def test_install_program(self, nats_cmd): from .tasks import install_program agent = baker.make_recipe("agents.agent") nats_cmd.return_value = "install of git was successful" _ = install_program(agent.pk, "git", "2.3.4") nats_cmd.assert_called_with( { "func": "installwithchoco", "choco_prog_name": "git", "choco_prog_ver": "2.3.4", }, timeout=915, ) self.assertTrue(ChocoLog.objects.filter(agent=agent, name="git").exists())
def test_dup_lob_letter_status(mocker): ballot_request = baker.make_recipe("absentee.ballot_request") link = Link.objects.create( action=ballot_request.action, external_tool=ExternalToolType.LOB, external_id=LOB_LETTER_STATUS_BODY["body"]["id"], ) process_lob_letter_status(LOB_LETTER_STATUS_BODY["body"]["id"], LOB_LETTER_STATUS_BODY["event_type"]["id"]) process_lob_letter_status(LOB_LETTER_STATUS_BODY["body"]["id"], LOB_LETTER_STATUS_BODY["event_type"]["id"]) events = list(Event.objects.filter(action=ballot_request.action)) assert len(events) == 1 assert events[0].event_type == EventType.LOB_MAILED
def test_generating_agent_policy_checks(self): from .tasks import generate_agent_checks_from_policies_task # setup data policy = baker.make("automation.Policy", active=True) checks = self.create_checks(policy=policy) site = baker.make("clients.Site") agent = baker.make_recipe("agents.agent", site=site, policy=policy) # test policy assigned to agent generate_agent_checks_from_policies_task(policy.id, clear=True) # make sure all checks were created. should be 7 agent_checks = Agent.objects.get(pk=agent.id).agentchecks.all() self.assertEquals(len(agent_checks), 7) # make sure checks were copied correctly for check in agent_checks: self.assertTrue(check.managed_by_policy) if check.check_type == "diskspace": self.assertEqual(check.parent_check, checks[0].id) self.assertEqual(check.disk, checks[0].disk) self.assertEqual(check.threshold, checks[0].threshold) elif check.check_type == "ping": self.assertEqual(check.parent_check, checks[1].id) self.assertEqual(check.ip, checks[1].ip) elif check.check_type == "cpuload": self.assertEqual(check.parent_check, checks[2].id) self.assertEqual(check.threshold, checks[2].threshold) elif check.check_type == "memory": self.assertEqual(check.parent_check, checks[3].id) self.assertEqual(check.threshold, checks[3].threshold) elif check.check_type == "winsvc": self.assertEqual(check.parent_check, checks[4].id) self.assertEqual(check.svc_name, checks[4].svc_name) self.assertEqual(check.svc_display_name, checks[4].svc_display_name) self.assertEqual(check.svc_policy_mode, checks[4].svc_policy_mode) elif check.check_type == "script": self.assertEqual(check.parent_check, checks[5].id) self.assertEqual(check.script, checks[5].script) elif check.check_type == "eventlog": self.assertEqual(check.parent_check, checks[6].id) self.assertEqual(check.event_id, checks[6].event_id) self.assertEqual(check.event_type, checks[6].event_type)
def test_script_arg_replacement_site_custom_fields(self): agent = baker.make_recipe("agents.agent") field = baker.make( "core.CustomField", name="Test Field", model="site", type="text", default_value_string="DEFAULT", ) args = ["-Parameter", "-Another {{site.Test Field}}"] # test default value self.assertEqual( ["-Parameter", "-Another 'DEFAULT'"], Script.parse_script_args(agent=agent, shell="python", args=args), ) # test with set value value = baker.make( "clients.SiteCustomField", field=field, site=agent.site, string_value="CUSTOM VALUE", ) self.assertEqual( ["-Parameter", "-Another 'CUSTOM VALUE'"], Script.parse_script_args(agent=agent, shell="python", args=args), ) # test with set but empty field value value.string_value = "" # type: ignore value.save() # type: ignore self.assertEqual( ["-Parameter", "-Another 'DEFAULT'"], Script.parse_script_args(agent=agent, shell="python", args=args), ) # test blank default and value field.default_value_string = "" # type: ignore field.save() # type: ignore self.assertEqual( ["-Parameter", "-Another ''"], Script.parse_script_args(agent=agent, shell="python", args=args), )
def test_run_autotask(self, nats_cmd): # setup data agent = baker.make_recipe("agents.agent", version="1.1.0") task = baker.make("autotasks.AutomatedTask", agent=agent) # test invalid url resp = self.client.get("/tasks/runwintask/500/", format="json") self.assertEqual(resp.status_code, 404) # test run agent task url = f"/tasks/runwintask/{task.id}/" resp = self.client.get(url, format="json") self.assertEqual(resp.status_code, 200) nats_cmd.assert_called_with({"func": "runtask", "taskpk": task.id}, wait=False) nats_cmd.reset_mock() self.check_not_authenticated("get", url)
def test_sync_salt_modules_task(self, salt_api_cmd): self.agent = baker.make_recipe("agents.agent") salt_api_cmd.return_value = {"return": [{f"{self.agent.salt_id}": []}]} ret = sync_salt_modules_task.s(self.agent.pk).apply() salt_api_cmd.assert_called_with(timeout=35, func="saltutil.sync_modules") self.assertEqual( ret.result, f"Successfully synced salt modules on {self.agent.hostname}" ) self.assertEqual(ret.status, "SUCCESS") salt_api_cmd.return_value = "timeout" ret = sync_salt_modules_task.s(self.agent.pk).apply() self.assertEqual(ret.result, f"Unable to sync modules {self.agent.salt_id}") salt_api_cmd.return_value = "error" ret = sync_salt_modules_task.s(self.agent.pk).apply() self.assertEqual(ret.result, f"Unable to sync modules {self.agent.salt_id}")
def test_agent_pending_actions(self): agent = baker.make_recipe("agents.agent") pending_actions = baker.make( "logs.PendingAction", agent=agent, _quantity=6, ) url = f"/logs/{agent.pk}/pendingactions/" resp = self.client.get(url, format="json") serializer = PendingActionSerializer(pending_actions, many=True) self.assertEqual(resp.status_code, 200) self.assertEqual(len(resp.data), 6) self.assertEqual(resp.data, serializer.data) self.check_not_authenticated("get", url)
def test_update_citycouncil_files(self, mock_save_file): bid = baker.make_recipe("datasets.CityCouncilBid", external_code=214) assert bid.files.count() == 0 record = { "codLic": "214", "arquivos": [{ "codArqLic": "1396", "codLic": "215", "dsArqLic": "publicacao.doc", "caminhoArqLic": "upload/licitacao/publicacao.doc", }], } updated_bid = update_citycouncil_bid(record) assert bid.pk == updated_bid.pk assert bid.files.count() == 1
def test_cancelled_events_shown_in_booking_list(self): """ Test that all future bookings for cancelled events for this user are listed """ ev = baker.make_recipe('booking.future_event', cancelled=True) baker.make(Booking, user=self.student_user, event=ev, status='CANCELLED') # check there are now 4 bookings (2 future, 1 past, 1 cancelled) assert Booking.objects.all().count() == 4 resp = self.client.get(self.url) # booking listing should show this user's future bookings, # including the cancelled one assert resp.context_data['bookings'].count() == 3
def test_create_maximal(basic_state_info, mocker): key = baker.make_recipe("apikey.apikey") mocker.patch("register.external_views.action_check_unfinished") client = APIClient() client.credentials( HTTP_AUTHORIZATION=basicauth(str(key.uuid), key.hashed_secret())) response = client.post(REQUEST_ENDPOINT, MAXIMAL_REGISTRATION) assert response.status_code == 200 registration = Registration.objects.first() assert registration.subscriber == key.subscriber assert registration.gender == RegistrationGender.MALE assert Event.objects.filter( action=registration.action, event_type=EventType.START_ACTION_API).exists()
def test_next_action1(self): ae_initial = baker.make_recipe( "adverse_event_app.aeinitial", subject_identifier=self.subject_identifier ) # action item has no parent, is updated ActionItem.objects.get( parent_action_item=None, action_identifier=ae_initial.action_identifier, reference_model="adverse_event_app.aeinitial", ) # action item a parent, is not updated ActionItem.objects.get( parent_action_item=ae_initial.action_item, related_action_item=ae_initial.action_item, reference_model="adverse_event_app.aefollowup", )
def test_get_services(self, nats_cmd): # test a call where agent doesn't exist resp = self.client.get("/services/500/services/", format="json") self.assertEqual(resp.status_code, 404) agent = baker.make_recipe("agents.agent_with_services") url = f"/services/{agent.pk}/services/" nats_return = [ { "pid": 880, "name": "AeLookupSvc", "status": "stopped", "binpath": "C:\\Windows\\system32\\svchost.exe -k netsvcs", "username": "******", "start_type": "manual", "description": "Processes application compatibility cache requests for applications as they are launched", "display_name": "Application Experience", }, { "pid": 812, "name": "ALG", "status": "stopped", "binpath": "C:\\Windows\\System32\\alg.exe", "username": "******", "start_type": "manual", "description": "Provides support for 3rd party protocol plug-ins for Internet Connection Sharing", "display_name": "Application Layer Gateway Service", }, ] # test failed attempt nats_cmd.return_value = "timeout" resp = self.client.get(url, format="json") self.assertEqual(resp.status_code, 400) nats_cmd.assert_called_with(data={"func": "winservices"}, timeout=10) nats_cmd.reset_mock() # test successful attempt nats_cmd.return_value = nats_return resp = self.client.get(url, format="json") self.assertEqual(resp.status_code, 200) nats_cmd.assert_called_with(data={"func": "winservices"}, timeout=10) self.assertEquals(Agent.objects.get(pk=agent.pk).services, nats_return) self.check_not_authenticated("get", url)
def test_chocos_install(self, install_program): url = "/software/install/" agent = baker.make_recipe("agents.agent") # test a call where agent doesn't exist invalid_data = {"pk": 500, "name": "Test Software", "version": "1.0.0"} resp = self.client.post(url, invalid_data, format="json") self.assertEqual(resp.status_code, 404) data = {"pk": agent.pk, "name": "Test Software", "version": "1.0.0"} resp = self.client.post(url, data, format="json") self.assertEqual(resp.status_code, 200) install_program.assert_called_with(data["pk"], data["name"], data["version"]) self.check_not_authenticated("post", url)
def setUp(self): form_data = self.login_form_data = { "username": "******", "password": "******", } self.user = baker.make_recipe( "sampleapp.account.user", email=form_data["username"], is_superuser=True, is_staff=True, password=make_password(form_data["password"]), ) self.client.login( username=self.login_form_data["username"], password=self.login_form_data["password"], )
def test_custom_partner(submission_task_patch): client = APIClient() second_partner = baker.make_recipe("multi_tenant.client") assert Client.objects.count() == 2 url = f"{REGISTER_API_ENDPOINT}?partner={second_partner.pk}" response = client.post(url, VALID_REGISTRATION) assert response.status_code == 200 assert "uuid" in response.json() registration = Registration.objects.first() assert response.json()["uuid"] == str(registration.uuid) assert registration.partner == second_partner submission_task_patch.delay.assert_called_once_with( registration.uuid, "FOUNDER123", True)