Beispiel #1
0
async def test_http_methods(client):
    async with respx.mock:
        url = "https://foo.bar"
        route = respx.get(url, path="/") % 404
        respx.post(url, path="/").respond(200)
        respx.post(url, path="/").respond(201)
        respx.put(url, path="/").respond(202)
        respx.patch(url, path="/").respond(500)
        respx.delete(url, path="/").respond(204)
        respx.head(url, path="/").respond(405)
        respx.options(url, path="/").respond(status_code=501)
        respx.request("GET", url, path="/baz/").respond(status_code=204)
        url += "/"

        response = httpx.get(url)
        assert response.status_code == 404
        response = await client.get(url)
        assert response.status_code == 404

        response = httpx.get(url + "baz/")
        assert response.status_code == 204
        response = await client.get(url + "baz/")
        assert response.status_code == 204

        response = httpx.post(url)
        assert response.status_code == 201
        response = await client.post(url)
        assert response.status_code == 201

        response = httpx.put(url)
        assert response.status_code == 202
        response = await client.put(url)
        assert response.status_code == 202

        response = httpx.patch(url)
        assert response.status_code == 500
        response = await client.patch(url)
        assert response.status_code == 500

        response = httpx.delete(url)
        assert response.status_code == 204
        response = await client.delete(url)
        assert response.status_code == 204

        response = httpx.head(url)
        assert response.status_code == 405
        response = await client.head(url)
        assert response.status_code == 405

        response = httpx.options(url)
        assert response.status_code == 501
        response = await client.options(url)
        assert response.status_code == 501

        assert route.called is True
        assert respx.calls.call_count == 8 * 2
Beispiel #2
0
def update_device(mac_address: str,
                  is_operation_confirmed: bool = False) -> None:
    username, header = get_auth_header_and_username()
    if not username:
        return
    url = get_url("/devices/{mac_address}")
    body = pydantic_to_prompt(model=UpdateDeviceModel)
    if not is_operation_confirmed and not is_operation_confirm():
        return
    response = httpx.patch(url=url, json=body.dict(), headers=header)
    response_handler(response=response, return_model=DeviceModel)
Beispiel #3
0
def update_run_metrics(*, client: Client, project_key: str, run_key: int, metrics: Dict[str, Any]) -> None:

    url = "{}/projects/{projectKey}/runs/{runKey}/metrics".format(
        client.base_url, projectKey=project_key, runKey=run_key
    )

    headers: Dict[str, Any] = client.get_headers()
    headers["content-type"] = content_type_merge_patch

    response = httpx.patch(url=url, headers=headers, json=metrics)

    assert_response_status(response)
Beispiel #4
0
def update_repo(repo: Optional[str], is_operation_confirmed: Optional[bool] = False):
    username, headers = get_auth_header_and_username()
    if not username:
        return
    if not repo:
        repo = select_from_available_repo(subject=username)
    body = pydantic_to_prompt(model=RepoUpdateBodyModel)
    if not is_operation_confirmed and not is_operation_confirm():
        return
    url: str = get_url(f"/repos/{username}/{repo}")
    response = httpx.patch(url=url, json=body.dict(), headers=headers)
    response_handler(response=response)
Beispiel #5
0
def remove_scope(users_username: str):
    username, headers = get_auth_header_and_username()
    if not username:
        exit(1)
    scopes = get_valid_scopes()
    if not scopes:
        print_error("No Scope has been selected!")
        exit(1)
    url = get_url(f"/v1/authorization/user/{users_username}/scopes")
    body = DeleteScopeBodyModel(scopes=scopes)
    response = httpx.patch(url=url, headers=headers, json=body.dict())
    response_handler(response=response,
                     return_model=UserScopeDeleteResponseModel)
Beispiel #6
0
def sync_detailed(
    *,
    client: Client,
    json_body: UserPreference,
) -> Response[None]:
    kwargs = _get_kwargs(
        client=client,
        json_body=json_body,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #7
0
def update_set(
    json_body: UpdateSetAutoTestData,
    *,
    client: "AuthenticatedClient",
    auto_test_id: "int",
    auto_test_set_id: "int",
    extra_parameters: Mapping[str, str] = None,
) -> Union[AutoTestSetAsJSON, ]:
    """Update the given <span data-role=\"class\">.models.AutoTestSet</span>."""
    url = "{}/api/v1/auto_tests/{autoTestId}/sets/{autoTestSetId}".format(
        client.base_url,
        autoTestId=auto_test_id,
        autoTestSetId=auto_test_set_id)

    headers: Dict[str, Any] = client.get_headers()

    params: Dict[str, Any] = {
        "no_course_in_assignment": "true",
        "no_role_name": "true",
        "no_assignment_in_case": "true",
        "extended": "true",
    }

    if extra_parameters:
        params.update(extra_parameters)

    json_json_body = maybe_to_dict(json_body)

    response = httpx.patch(
        url=url,
        headers=headers,
        json=json_json_body,
        params=params,
    )

    if response_code_matches(response.status_code, 200):
        return AutoTestSetAsJSON.from_dict(
            cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 400):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 409):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 401):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 403):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, "5XX"):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    else:
        raise ApiResponseError(response=response)
Beispiel #8
0
def partial_update_run(*, client: Client, project_key: str, run_key: int, run: RunDto) -> None:

    url = "{}/projects/{projectKey}/runs/{runKey}".format(
        client.base_url, projectKey=project_key, runKey=run_key
    )

    headers: Dict[str, Any] = client.get_headers()
    headers["content-type"] = content_type_merge_patch

    json_body = run.to_dict_without_none_values()

    response = httpx.patch(url=url, headers=headers, json=json_body)

    assert_response_status(response)
Beispiel #9
0
def sync_detailed(
    *,
    client: AuthenticatedClient,
    id: int,
    json_body: PatchedPipelineInvocation,
) -> Response[PipelineInvocation]:
    kwargs = _get_kwargs(
        client=client,
        id=id,
        json_body=json_body,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #10
0
def sync_detailed(
    *,
    client: AuthenticatedClient,
    name: str,
    json_body: UpdateDatasetRequest,
) -> Response[Union[Dataset, ErrorMessage, ErrorMessage, HTTPValidationError]]:
    kwargs = _get_kwargs(
        client=client,
        name=name,
        json_body=json_body,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #11
0
def sync_detailed(
    *,
    client: AuthenticatedClient,
    id: int,
    json_body: PatchedStepType,
) -> Response[StepType]:
    kwargs = _get_kwargs(
        client=client,
        id=id,
        json_body=json_body,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #12
0
def sync_detailed(
    typ: str,
    id: str,
    *,
    client: Client,
) -> Response[Any]:
    kwargs = _get_kwargs(
        typ=typ,
        id=id,
        client=client,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #13
0
async def test_http_methods(client):
    async with respx.HTTPXMock() as httpx_mock:
        url = "https://foo.bar/"
        m = httpx_mock.get(url, status_code=404)
        httpx_mock.post(url, status_code=201)
        httpx_mock.put(url, status_code=202)
        httpx_mock.patch(url, status_code=500)
        httpx_mock.delete(url, status_code=204)
        httpx_mock.head(url, status_code=405)
        httpx_mock.options(url, status_code=501)

        response = httpx.get(url)
        assert response.status_code == 404
        response = await client.get(url)
        assert response.status_code == 404

        response = httpx.post(url)
        assert response.status_code == 201
        response = await client.post(url)
        assert response.status_code == 201

        response = httpx.put(url)
        assert response.status_code == 202
        response = await client.put(url)
        assert response.status_code == 202

        response = httpx.patch(url)
        assert response.status_code == 500
        response = await client.patch(url)
        assert response.status_code == 500

        response = httpx.delete(url)
        assert response.status_code == 204
        response = await client.delete(url)
        assert response.status_code == 204

        response = httpx.head(url)
        assert response.status_code == 405
        response = await client.head(url)
        assert response.status_code == 405

        response = httpx.options(url)
        assert response.status_code == 501
        response = await client.options(url)
        assert response.status_code == 501

        assert m.called is True
        assert httpx_mock.stats.call_count == 7 * 2
Beispiel #14
0
def patch(
    json_body: PatchCourseData,
    *,
    client: "AuthenticatedClient",
    course_id: "int",
    extra_parameters: Mapping[str, str] = None,
) -> Union[CourseAsExtendedJSON, ]:
    """Update the given <span data-role=\"class\">.models.Course</span> with new values."""
    url = "{}/api/v1/courses/{courseId}".format(client.base_url,
                                                courseId=course_id)

    headers: Dict[str, Any] = client.get_headers()

    params: Dict[str, Any] = {
        "no_course_in_assignment": "true",
        "no_role_name": "true",
        "no_assignment_in_case": "true",
        "extended": "true",
    }

    if extra_parameters:
        params.update(extra_parameters)

    json_json_body = maybe_to_dict(json_body)

    response = httpx.patch(
        url=url,
        headers=headers,
        json=json_json_body,
        params=params,
    )

    if response_code_matches(response.status_code, 200):
        return CourseAsExtendedJSON.from_dict(
            cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 400):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 409):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 401):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 403):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, "5XX"):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    else:
        raise ApiResponseError(response=response)
Beispiel #15
0
    def send(self):
        try:
            if self.variable_id:
                response = httpx.patch(self.url,
                                       json=self.payload(),
                                       headers=HEADERS)
            else:
                response = httpx.post(self.url,
                                      json=self.payload(),
                                      headers=HEADERS)
            response.raise_for_status()
        except httpx.HTTPError as e:
            logger.error(
                f"({conf.TF_IAM_USERNAME}) Error rotating credential: {self.id}/{self.key} -- {e}"
            )  # noqa

        return response
Beispiel #16
0
def sync_detailed(
    organization_name: str,
    data_set_name: str,
    *,
    client: Client,
    json_body: DatasetUpdateJsonBody,
) -> Response[Any]:
    kwargs = _get_kwargs(
        organization_name=organization_name,
        data_set_name=data_set_name,
        client=client,
        json_body=json_body,
    )

    response = httpx.patch(**kwargs, )

    return _build_response(response=response)
Beispiel #17
0
def patch(
    multipart_data: PatchAutoTestData,
    *,
    client: "AuthenticatedClient",
    auto_test_id: "int",
    extra_parameters: Mapping[str, str] = None,
) -> Union[AutoTestAsJSON, ]:
    """Update the settings of an AutoTest configuration."""
    url = "{}/api/v1/auto_tests/{autoTestId}".format(client.base_url,
                                                     autoTestId=auto_test_id)

    headers: Dict[str, Any] = client.get_headers()

    params: Dict[str, Any] = {
        "no_course_in_assignment": "true",
        "no_role_name": "true",
        "no_assignment_in_case": "true",
        "extended": "true",
    }

    if extra_parameters:
        params.update(extra_parameters)

    response = httpx.patch(
        url=url,
        headers=headers,
        files=to_multipart(multipart_data.to_dict()),
        params=params,
    )

    if response_code_matches(response.status_code, 200):
        return AutoTestAsJSON.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 400):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 409):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 401):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 403):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, "5XX"):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    else:
        raise ApiResponseError(response=response)
Beispiel #18
0
def patch(
    json_body: PatchSitesettingsData, *, client: "AuthenticatedClient", extra_parameters: Mapping[str, str] = None,
) -> Union[
    Union[OptFrontendOptsAsJSON, OptAllOptsAsJSON],
]:

    """Get the settings for this CodeGrade instance."""
    url = "{}/api/v1/site_settings/".format(client.base_url)

    headers: Dict[str, Any] = client.get_headers()

    params: Dict[str, Any] = {
        "no_course_in_assignment": "true",
        "no_role_name": "true",
        "no_assignment_in_case": "true",
        "extended": "true",
    }

    if extra_parameters:
        params.update(extra_parameters)

    json_json_body = maybe_to_dict(json_body)

    response = httpx.patch(url=url, headers=headers, json=json_json_body, params=params,)

    if response_code_matches(response.status_code, 200):
        return try_any(
            [
                lambda: OptFrontendOptsAsJSON.from_dict(cast(Dict[str, Any], response.json())),
                lambda: OptAllOptsAsJSON.from_dict(cast(Dict[str, Any], response.json())),
            ]
        )
    if response_code_matches(response.status_code, 400):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 409):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 401):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 403):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, "5XX"):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    else:
        raise ApiResponseError(response=response)
Beispiel #19
0
def patch_notification_setting(
    json_body: PatchNotificationSettingUserSettingData,
    *,
    client: "Client",
    extra_parameters: Mapping[str, str] = None,
) -> Union[None, ]:
    """Update preferences for notifications."""
    url = "{}/api/v1/settings/notification_settings/".format(client.base_url)

    headers: Dict[str, Any] = client.get_headers()

    params: Dict[str, Any] = {
        "no_course_in_assignment": "true",
        "no_role_name": "true",
        "no_assignment_in_case": "true",
        "extended": "true",
    }

    if extra_parameters:
        params.update(extra_parameters)

    json_json_body = maybe_to_dict(json_body)

    response = httpx.patch(
        url=url,
        headers=headers,
        json=json_json_body,
        params=params,
    )

    if response_code_matches(response.status_code, 204):
        return None
    if response_code_matches(response.status_code, 400):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 409):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 401):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, 403):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    if response_code_matches(response.status_code, "5XX"):
        raise BaseError.from_dict(cast(Dict[str, Any], response.json()))
    else:
        raise ApiResponseError(response=response)
Beispiel #20
0
def update_package(
    repo: Optional[str],
    package: Optional[str],
    is_operation_confirmed: Optional[bool] = False,
):
    username, headers = get_auth_header_and_username()
    if not username:
        exit(1)
    if not repo:
        repo = repositories_core.select_from_available_repo(subject=username)
    if not package:
        package = select_from_available_packages(subject=username, repo=repo)
    body = pydantic_to_prompt(PackageUpdateBodyModel)
    if not is_operation_confirmed and not is_operation_confirm():
        exit(1)

    url = get_url(f"/packages/{username}/{repo}/{package}")
    response = httpx.patch(url=url, json=body.dict(), headers=headers)
    response_handler(response=response)
Beispiel #21
0
requests.delete('https://gmail.com', timeout=30, verify=False)
requests.patch('https://gmail.com', timeout=30, verify=True)
requests.patch('https://gmail.com', timeout=30, verify=False)
requests.options('https://gmail.com', timeout=30, verify=True)
requests.options('https://gmail.com', timeout=30, verify=False)
requests.head('https://gmail.com', timeout=30, verify=True)
requests.head('https://gmail.com', timeout=30, verify=False)

httpx.request('GET', 'https://gmail.com', verify=True)
httpx.request('GET', 'https://gmail.com', verify=False)
httpx.get('https://gmail.com', verify=True)
httpx.get('https://gmail.com', verify=False)
httpx.options('https://gmail.com', verify=True)
httpx.options('https://gmail.com', verify=False)
httpx.head('https://gmail.com', verify=True)
httpx.head('https://gmail.com', verify=False)
httpx.post('https://gmail.com', verify=True)
httpx.post('https://gmail.com', verify=False)
httpx.put('https://gmail.com', verify=True)
httpx.put('https://gmail.com', verify=False)
httpx.patch('https://gmail.com', verify=True)
httpx.patch('https://gmail.com', verify=False)
httpx.delete('https://gmail.com', verify=True)
httpx.delete('https://gmail.com', verify=False)
httpx.stream('https://gmail.com', verify=True)
httpx.stream('https://gmail.com', verify=False)
httpx.Client()
httpx.Client(verify=False)
httpx.AsyncClient()
httpx.AsyncClient(verify=False)
Beispiel #22
0
 def update_person(self, person_id: str, update: dict, statuscode: int = 204):
     r = httpx.patch(f"{self.api_url}/people/{person_id}", json=update)
     assert r.status_code == statuscode, r.text
     return r
Beispiel #23
0
import httpx
import ssl

httpx.get("url") # $ clientRequestUrlPart="url"
httpx.post("url") # $ clientRequestUrlPart="url"
httpx.patch("url") # $ clientRequestUrlPart="url"
httpx.options("url") # $ clientRequestUrlPart="url"
httpx.request("method", url="url") # $ clientRequestUrlPart="url"
httpx.stream("method", url="url") # $ clientRequestUrlPart="url"

client = httpx.Client()
response = client.get("url") # $ clientRequestUrlPart="url"
response = client.post("url") # $ clientRequestUrlPart="url"
response = client.patch("url") # $ clientRequestUrlPart="url"
response = client.options("url") # $ clientRequestUrlPart="url"
response = client.request("method", url="url") # $ clientRequestUrlPart="url"
response = client.stream("method", url="url") # $ clientRequestUrlPart="url"

async def async_test():
    client = httpx.AsyncClient()
    response = await client.get("url") # $ clientRequestUrlPart="url"
    response = await client.post("url") # $ clientRequestUrlPart="url"
    response = await client.patch("url") # $ clientRequestUrlPart="url"
    response = await client.options("url") # $ clientRequestUrlPart="url"
    response = await client.request("method", url="url") # $ clientRequestUrlPart="url"
    response = await client.stream("method", url="url") # $ clientRequestUrlPart="url"

# ==============================================================================
# Disabling certificate validation
# ==============================================================================
Beispiel #24
0
def test_patch(server):
    response = httpx.patch(server.url, data=b"Hello, world!")
    assert response.status_code == 200
    assert response.reason_phrase == "OK"
Beispiel #25
0
from salesforce_ocapi.auth import CommerceCloudBMSession, EnvParser
import json
import httpx
from salesforce_ocapi.utils import csvopen

with EnvParser(path="examples/.env"):
    session = CommerceCloudBMSession()

INSTANCE = "https://production-eu01-example.demandware.net"
SITE = "sitegenesis"
IDList = csvopen("examples/databreach.csv")
for ID in IDList:
    url = f"{INSTANCE}/s/{sitegenesis}/dw/shop/v20_4/customers/{ID}"
    headers = {
        "Authorization": f"Bearer {session.RawToken}",
        "Content-Type": "application/json"
    }
    payload = {"enabled": False}
    response = httpx.patch(url, headers=headers, json=payload)

    r = response.json()
    # print(r)
    print(r["customer_id"], r["enabled"])
Beispiel #26
0
def patch(ctx, url_suffix, body: dict) -> httpx.Response:
    resp = httpx.patch(url(ctx, url_suffix),
                       json=body,
                       headers=headers(ctx.token))
    resp.raise_for_status()
    return resp
Beispiel #27
0
def test_patch(server):
    response = httpx.patch("http://127.0.0.1:8000/", data=b"Hello, world!")
    assert response.status_code == 200
    assert response.reason_phrase == "OK"