Python http.HTTPStatus.ACCEPTED Examples

The following are 24 code examples of http.HTTPStatus.ACCEPTED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.HTTPStatus , or try the search function .
Example #1
Source File: requested_task.py    From zimfarm with GNU General Public License v3.0 6 votes vote down vote up
def patch(self, requested_task_id: str, token: AccessToken.Payload):

        requested_task = RequestedTasks().count_documents({"_id": requested_task_id})
        if not requested_task:
            raise TaskNotFound()

        try:
            request_json = UpdateRequestedTaskSchema().load(request.get_json())
        except ValidationError as e:
            raise InvalidRequestJSON(e.messages)

        update = RequestedTasks().update_one(
            {"_id": requested_task_id},
            {"$set": {"priority": request_json.get("priority", 0)}},
        )
        if update.modified_count:
            return Response(status=HTTPStatus.ACCEPTED)
        return Response(status=HTTPStatus.OK) 
Example #2
Source File: rpc.py    From kappa with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def rpc(addr: str, req: Request, pid: Pid, seqno: Seqno):
    """Issues a coordinator call asynchronously.  If the call is blocking, raises WouldBlock."""
    assert addr, "The RPC server address must not be empty."

    with log_duration(pid, seqno, "rpc"):
        conn = http.client.HTTPConnection(addr, timeout=RPC_HTTP_TIMEOUT)  # type: ignore
        # mypy thinks `timeout` has to be an `int`, but passing a `float` doesn't seem to be a problem.

        req_str = str(req)
        log(pid, seqno, f"rpc size: {len(req_str)}")

        conn.request("POST", "", str(req))
        res = conn.getresponse()
        body = res.read()

    if res.status == HTTPStatus.OK:
        return json.loads(body)
    elif res.status == HTTPStatus.ACCEPTED:  # Coordinator call is blocking.
        raise WouldBlock()

    raise RPCError(status=HTTPStatus(res.status).description, message=body.decode("utf-8")) 
Example #3
Source File: jobs.py    From asgard-api with MIT License 6 votes vote down vote up
def _update_job(
    job: ScheduledJob, user: User, account: Account
) -> Response:
    try:
        updated_job = await ScheduledJobsService.update_job(
            job, user, account, ChronosScheduledJobsBackend()
        )
    except NotFoundEntity as e:
        return json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
            status=HTTPStatus.NOT_FOUND,
        )

    return json_response(
        CreateScheduledJobResource(job=updated_job).dict(),
        status=HTTPStatus.ACCEPTED,
    ) 
Example #4
Source File: test_integration_using_async_flow.py    From openbrokerapi with MIT License 6 votes vote down vote up
def check_provision(self, instace_guid, org_guid, space_guid, service_guid, plan_guid):
        response = requests.put(
            "http://localhost:5001/v2/service_instances/{}?accepts_incomplete=true".format(instace_guid),
            data=json.dumps({
                "organization_guid": org_guid,
                "space_guid": space_guid,
                "service_id": service_guid,
                "plan_id": plan_guid,
                # "context": {
                #     "organization_guid": "org-guid-here",
                #     "space_guid": "space-guid-here",
                # }
            }),
            **self.request_ads)
        self.assertEqual(HTTPStatus.ACCEPTED, response.status_code)

        operation = response.json().get('operation')
        self.assertEqual('provision', operation)

        return operation 
Example #5
Source File: test_jobs.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_job_name_has_namespace_from_another_account(
        self, dev_job_fixture
    ):
        """
        Mesmo que um job tenha o nome começado pelo namespace de outra conta,
        devemos atualizar o job da conta correta, que é a conta do usuário fazendo
        o request
        """
        self.maxDiff = None
        dev_job_fixture["name"] = f"dev-infra-{dev_job_fixture['name']}"
        await _load_jobs_into_chronos(dev_job_fixture)
        asgard_job = ChronosScheduledJobConverter.to_asgard_model(
            ChronosJob(**dev_job_fixture)
        )

        asgard_job.remove_namespace(self.account)
        self.assertEqual(asgard_job.cpus, dev_job_fixture["cpus"])
        self.assertEqual(asgard_job.mem, dev_job_fixture["mem"])

        asgard_job.cpus = 4
        asgard_job.mem = 512

        resp = await self.client.put(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=asgard_job.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)

        updated_job_response = await self.client.get(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_job_data = await updated_job_response.json()
        updated_job_resource = CreateScheduledJobResource(**updated_job_data)
        self.assertEqual(asgard_job.cpus, updated_job_resource.job.cpus)
        self.assertEqual(asgard_job.mem, updated_job_resource.job.mem) 
Example #6
Source File: user_api_steps.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def step_impl(context, a_container_image, analyzer_image):
    payload = {
        'image': a_container_image,
        'analyzer': analyzer_image
    }

    r = requests.post(f'{context.endpoint_url}/analyze', params=payload)

    assert_that(r.status_code, equal_to(HTTPStatus.ACCEPTED))
    assert_that(r.headers['content-type'], equal_to('application/json'))

    response = r.json()
    assert_that(response, not_none)
    context.response = response 
Example #7
Source File: rackspace.py    From cloudstorage with MIT License 5 votes vote down vote up
def disable_container_cdn(self, container: Container) -> bool:
        endpoint_url = (
            self._get_server_public_url("cloudFilesCDN") + "/" + container.name
        )
        headers = {
            "X-Auth-Token": self._token,
            "X-CDN-Enabled": str(False),
        }

        response = requests.put(endpoint_url, headers=headers)
        return response.status_code in (
            HTTPStatus.CREATED,
            HTTPStatus.ACCEPTED,
            HTTPStatus.NO_CONTENT,
        ) 
Example #8
Source File: rackspace.py    From cloudstorage with MIT License 5 votes vote down vote up
def enable_container_cdn(self, container: Container) -> bool:
        endpoint_url = (
            self._get_server_public_url("cloudFilesCDN") + "/" + container.name
        )
        headers = {
            "X-Auth-Token": self._token,
            "X-CDN-Enabled": str(True),
        }

        response = requests.put(endpoint_url, headers=headers)
        return response.status_code in (
            HTTPStatus.CREATED,
            HTTPStatus.ACCEPTED,
            HTTPStatus.NO_CONTENT,
        ) 
Example #9
Source File: test_tasks.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_cancel(self):
        self.client.post.return_value = self.mock_response(
            '/v3/tasks/task_guid/actions/cancel',
            HTTPStatus.ACCEPTED,
            None,
            'v3', 'tasks', 'POST_{id}_actions_cancel_response.json')
        task = self.client.v3.tasks.cancel('task_guid')
        self.client.post.assert_called_with(self.client.post.return_value.url, files=None, json=None)
        self.assertIsNotNone(task) 
Example #10
Source File: test_integration_using_async_flow.py    From openbrokerapi with MIT License 5 votes vote down vote up
def check_deprovision(self, instace_guid, operation):
        response = requests.delete(
            "http://localhost:5001/v2/service_instances/{}".format(instace_guid),
            params={
                'service_id': self.service_guid,
                'plan_id': self.plan_guid,
                'accepts_incomplete': 'true'
            },
            **self.request_ads)
        self.assertEqual(HTTPStatus.ACCEPTED, response.status_code)
        operation = response.json()['operation']
        self.assertEqual('deprovision', operation)
        return operation 
Example #11
Source File: test_integration_using_async_flow.py    From openbrokerapi with MIT License 5 votes vote down vote up
def check_bind(self, binding_guid, instace_guid):
        response = requests.put(
            "http://localhost:5001/v2/service_instances/{}/service_bindings/{}?accepts_incomplete=true".format(
                instace_guid, binding_guid),
            data=json.dumps({
                "service_id": self.service_guid,
                "plan_id": self.plan_guid
            }),
            **self.request_ads
        )
        self.assertEqual(HTTPStatus.ACCEPTED, response.status_code)
        operation = response.json().get('operation')
        self.assertEqual('bind', operation)
        return operation 
Example #12
Source File: test_integration_using_async_flow.py    From openbrokerapi with MIT License 5 votes vote down vote up
def check_unbind(self, binding_guid, instace_guid):
        response = requests.delete(
            "http://localhost:5001/v2/service_instances/{}/service_bindings/{}".format(instace_guid, binding_guid),
            params={
                "service_id": self.service_guid,
                "plan_id": self.plan_guid,
                'accepts_incomplete': 'true'
            },
            **self.request_ads
        )
        self.assertEqual(HTTPStatus.ACCEPTED, response.status_code)
        operation = response.json().get('operation')
        self.assertEqual('unbind', operation)
        return operation 
Example #13
Source File: test_utils.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def test_http_status_to_canonical_code(self):
        for status_code, expected in (
            (HTTPStatus.OK, StatusCanonicalCode.OK),
            (HTTPStatus.ACCEPTED, StatusCanonicalCode.OK),
            (HTTPStatus.IM_USED, StatusCanonicalCode.OK),
            (HTTPStatus.MULTIPLE_CHOICES, StatusCanonicalCode.OK),
            (HTTPStatus.BAD_REQUEST, StatusCanonicalCode.INVALID_ARGUMENT),
            (HTTPStatus.UNAUTHORIZED, StatusCanonicalCode.UNAUTHENTICATED),
            (HTTPStatus.FORBIDDEN, StatusCanonicalCode.PERMISSION_DENIED),
            (HTTPStatus.NOT_FOUND, StatusCanonicalCode.NOT_FOUND),
            (
                HTTPStatus.UNPROCESSABLE_ENTITY,
                StatusCanonicalCode.INVALID_ARGUMENT,
            ),
            (
                HTTPStatus.TOO_MANY_REQUESTS,
                StatusCanonicalCode.RESOURCE_EXHAUSTED,
            ),
            (HTTPStatus.NOT_IMPLEMENTED, StatusCanonicalCode.UNIMPLEMENTED),
            (HTTPStatus.SERVICE_UNAVAILABLE, StatusCanonicalCode.UNAVAILABLE),
            (
                HTTPStatus.GATEWAY_TIMEOUT,
                StatusCanonicalCode.DEADLINE_EXCEEDED,
            ),
            (
                HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
                StatusCanonicalCode.INTERNAL,
            ),
            (600, StatusCanonicalCode.UNKNOWN),
            (99, StatusCanonicalCode.UNKNOWN),
        ):
            with self.subTest(status_code=status_code):
                actual = http_status_to_canonical_code(int(status_code))
                self.assertEqual(actual, expected, status_code) 
Example #14
Source File: test_jobs.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_job_job_exist_put_on_root_endpoint(
        self, dev_job_fixture
    ):
        """
        Confirmamos que é possível fazer um PUT /jobs e atualizar um job
        """
        await _load_jobs_into_chronos(dev_job_fixture)
        asgard_job = ChronosScheduledJobConverter.to_asgard_model(
            ChronosJob(**dev_job_fixture)
        )

        asgard_job.remove_namespace(self.account)
        self.assertEqual(asgard_job.cpus, dev_job_fixture["cpus"])
        self.assertEqual(asgard_job.mem, dev_job_fixture["mem"])

        asgard_job.cpus = 2
        asgard_job.mem = 2048

        resp = await self.client.put(
            f"/jobs",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=asgard_job.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        updated_job_response = await self.client.get(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_job_data = await updated_job_response.json()
        updated_job_resource = CreateScheduledJobResource(**updated_job_data)
        self.assertEqual(asgard_job.cpus, updated_job_resource.job.cpus)
        self.assertEqual(asgard_job.mem, updated_job_resource.job.mem) 
Example #15
Source File: test_jobs.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_job_job_exist(self, dev_job_fixture):
        """
        Conferimos que um job é atualizado corretamente
        """
        await _load_jobs_into_chronos(dev_job_fixture)
        asgard_job = ChronosScheduledJobConverter.to_asgard_model(
            ChronosJob(**dev_job_fixture)
        )

        asgard_job.remove_namespace(self.account)
        self.assertEqual(asgard_job.cpus, dev_job_fixture["cpus"])
        self.assertEqual(asgard_job.mem, dev_job_fixture["mem"])

        asgard_job.cpus = 2
        asgard_job.mem = 2048

        resp = await self.client.put(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=asgard_job.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        updated_job_response = await self.client.get(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_job_data = await updated_job_response.json()
        updated_job_resource = CreateScheduledJobResource(**updated_job_data)
        self.assertEqual(asgard_job.cpus, updated_job_resource.job.cpus)
        self.assertEqual(asgard_job.mem, updated_job_resource.job.mem) 
Example #16
Source File: test_jobs.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_job_on_alternate_account(self, infra_job_fixture):
        """
        Confirmar que podemos fazer PUT /jobs?account_id=<id>
        o job será criado com o namespace da account de id = <id>
        """
        account = Account(**ACCOUNT_INFRA_DICT)
        await _load_jobs_into_chronos(infra_job_fixture)
        asgard_job = ChronosScheduledJobConverter.to_asgard_model(
            ChronosJob(**infra_job_fixture)
        )

        asgard_job.remove_namespace(account)
        self.assertEqual(asgard_job.cpus, infra_job_fixture["cpus"])
        self.assertEqual(asgard_job.mem, infra_job_fixture["mem"])

        asgard_job.cpus = 2
        asgard_job.mem = 2048

        resp = await self.client.put(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            params={"account_id": ACCOUNT_INFRA_ID},
            json=asgard_job.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        updated_job_response = await self.client.get(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            params={"account_id": ACCOUNT_INFRA_ID},
        )
        updated_job_data = await updated_job_response.json()
        updated_job_resource = CreateScheduledJobResource(**updated_job_data)
        self.assertEqual(asgard_job.cpus, updated_job_resource.job.cpus)
        self.assertEqual(asgard_job.mem, updated_job_resource.job.mem) 
Example #17
Source File: test_users.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_user_update_all_fields(self):
        expected_new_name = "Novo Nome"
        expected_new_email = "newemail@server.com"

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_name
        new_user.email = expected_new_email

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        self.assertEqual(UserResource(user=new_user).dict(), user_data)

        resp = await self.client.get(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(UserResource(user=new_user).dict(), updated_user_data) 
Example #18
Source File: test_users.py    From asgard-api with MIT License 5 votes vote down vote up
def test_update_user_update_only_name(self):
        expected_new_name = "Novo Nome"
        new_user_data = {"name": expected_new_name}

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user_data,
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_name
        self.assertEqual(UserResource(user=new_user).dict(), user_data)

        resp = await self.client.get(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(UserResource(user=new_user).dict(), updated_user_data) 
Example #19
Source File: users.py    From asgard-api with MIT License 5 votes vote down vote up
def update_user_partial(user_id: str, wrapper: RequestWrapper):

    try:
        body_data = await wrapper.http_request.json()
    except JSONDecodeError as e:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )

    user = await UsersService.get_user_by_id(int(user_id), UsersBackend())
    status_code = HTTPStatus.ACCEPTED if user else HTTPStatus.NOT_FOUND

    try:
        if user:
            body_user = User(**body_data)
            user.name = body_user.name if body_user.name else user.name
            user.email = body_user.email if body_user.email else user.email
            updated_user = await UsersService.update_user(user, UsersBackend())
    except DuplicateEntity as de:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(de))]).dict(),
            status=status_code,
        )

    return web.json_response(
        UserResource(user=updated_user).dict(), status=status_code
    ) 
Example #20
Source File: webhooks.py    From packit-service with MIT License 5 votes vote down vote up
def post(self):
        """
        A webhook used by Packit-as-a-Service Gitlab hook.
        """
        msg = request.json

        if not msg:
            logger.debug("/webhooks/gitlab: we haven't received any JSON data.")
            return "We haven't received any JSON data.", HTTPStatus.BAD_REQUEST

        if all([msg.get("zen"), msg.get("hook_id"), msg.get("hook")]):
            logger.debug(f"/webhooks/gitlab received ping event: {msg['hook']}")
            return "Pong!", HTTPStatus.OK

        try:
            self.validate_token()
        except ValidationFailed as exc:
            logger.info(f"/webhooks/gitlab {exc}")
            return str(exc), HTTPStatus.UNAUTHORIZED

        if not self.interested():
            return "Thanks but we don't care about this event", HTTPStatus.ACCEPTED

        # TODO: define task names at one place
        celery_app.send_task(
            name="task.steve_jobs.process_message", kwargs={"event": msg}
        )

        return "Webhook accepted. We thank you, Gitlab.", HTTPStatus.ACCEPTED 
Example #21
Source File: webhooks.py    From packit-service with MIT License 5 votes vote down vote up
def post(self):
        """
        A webhook used by Packit-as-a-Service GitHub App.
        """
        msg = request.json

        if not msg:
            logger.debug("/webhooks/github: we haven't received any JSON data.")
            github_webhook_calls.labels(result="no_data").inc()
            return "We haven't received any JSON data.", HTTPStatus.BAD_REQUEST

        if all([msg.get("zen"), msg.get("hook_id"), msg.get("hook")]):
            logger.debug(f"/webhooks/github received ping event: {msg['hook']}")
            github_webhook_calls.labels(result="pong").inc()
            return "Pong!", HTTPStatus.OK

        try:
            self.validate_signature()
        except ValidationFailed as exc:
            logger.info(f"/webhooks/github {exc}")
            github_webhook_calls.labels(result="invalid_signature").inc()
            return str(exc), HTTPStatus.UNAUTHORIZED

        if not self.interested():
            github_webhook_calls.labels(result="not_interested").inc()
            return "Thanks but we don't care about this event", HTTPStatus.ACCEPTED

        # TODO: define task names at one place
        celery_app.send_task(
            name="task.steve_jobs.process_message", kwargs={"event": msg}
        )
        github_webhook_calls.labels(result="accepted").inc()

        return "Webhook accepted. We thank you, Github.", HTTPStatus.ACCEPTED 
Example #22
Source File: jsonapi.py    From safrs with GNU General Public License v3.0 4 votes vote down vote up
def patch(self, **kwargs):
        """
            summary : Update {class_name}
            description: Update {class_name} attributes
            responses:
                200 :
                    description : Request fulfilled, document follows
                202 :
                    description : Accepted
                204 :
                    description : No Content
                403:
                    description : Forbidden
                404 :
                    description : Not Found
                409 :
                    description : Conflict
            ---
            https://jsonapi.org/format/#crud-updating-responses
            Update the object with the specified id
        """
        id = kwargs.get(self._s_object_id, None)

        payload = request.get_jsonapi_payload()
        if not isinstance(payload, dict):
            raise ValidationError("Invalid Object Type")

        data = payload.get("data")
        if id is None and isinstance(data, list):
            # Bulk patch request
            for item in data:
                if not isinstance(item, dict):
                    raise ValidationError("Invalid Data Object")
                instance = self._patch_instance(item)
            response = make_response(jsonify({}), HTTPStatus.ACCEPTED)

        elif not data or not isinstance(data, dict):
            raise ValidationError("Invalid Data Object")
        elif id is None:
            raise ValidationError("Invalid ID")
        else:
            instance = self._patch_instance(data, id)
            # object id is the endpoint parameter, for example "UserId" for a User SAFRSObject
            obj_args = {instance._s_object_id: instance.jsonapi_id}
            # Retrieve the jsonapi encoded object and return it to the client
            obj_data = self.get(**obj_args)
            response = make_response(obj_data, HTTPStatus.OK)
            # Set the Location header to the newly created object
            response.headers["Location"] = url_for(self.endpoint, **obj_args)

        return response 
Example #23
Source File: test_jobs.py    From asgard-api with MIT License 4 votes vote down vote up
def test_update_job_job_exist_add_internal_field_values(
        self, dev_job_fixture
    ):
        """
        Conferimos que quando um job é atualizado, os campos obrigatórios são
        inseridos
        """
        await _load_jobs_into_chronos(dev_job_fixture)
        asgard_job = ChronosScheduledJobConverter.to_asgard_model(
            ChronosJob(**dev_job_fixture)
        )

        expected_fetch_list = asgard_job.fetch + [
            settings.SCHEDULED_JOBS_DEFAULT_FETCH_URIS[0],
            settings.SCHEDULED_JOBS_DEFAULT_FETCH_URIS[1],
        ]
        asgard_job.remove_namespace(self.account)

        resp = await self.client.put(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=asgard_job.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        updated_job_response = await self.client.get(
            f"/jobs/{asgard_job.id}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_job_data = await updated_job_response.json()
        updated_job_resource = CreateScheduledJobResource(**updated_job_data)

        expected_constraints = asgard_job.constraints + [
            f"owner:LIKE:{self.account.owner}"
        ]
        self.assertEqual(
            updated_job_resource.job.constraints, expected_constraints
        )
        self.assertEqual(expected_fetch_list, updated_job_resource.job.fetch) 
Example #24
Source File: test_users.py    From asgard-api with MIT License 4 votes vote down vote up
def test_update_user_cant_update_another_user(self):
        """
        Dado um request 
          PATCH /users/42
          {"id": 50, "name": "Nome", "email": "email"}

        Não podemos, no final das contas ter atualizado o user id=50. Temos que atualizar o user id=42
        """
        expected_new_name = "Novo Nome"
        expected_new_email = "novemail@server.com"

        new_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        new_user.name = expected_new_name
        new_user.email = expected_new_email
        new_user.id = USER_WITH_NO_ACCOUNTS_ID

        resp = await self.client.patch(
            f"/users/{USER_WITH_MULTIPLE_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
            json=new_user.dict(),
        )
        self.assertEqual(HTTPStatus.ACCEPTED, resp.status)
        user_data = await resp.json()

        expected_returned_user = User(**USER_WITH_MULTIPLE_ACCOUNTS_DICT)
        expected_returned_user.name = expected_new_name
        expected_returned_user.email = expected_new_email
        self.assertEqual(
            UserResource(user=expected_returned_user).dict(), user_data
        )

        resp = await self.client.get(
            f"/users/{USER_WITH_NO_ACCOUNTS_ID}",
            headers={
                "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}"
            },
        )
        updated_user_data = await resp.json()
        self.assertEqual(
            UserResource(user=User(**USER_WITH_NO_ACCOUNTS_DICT)).dict(),
            updated_user_data,
        )