[Python] How to assert an http.client.HTTPSConnection.request

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    My code tries to make HTTP requests to Gitlab API to make different actions such as create projects, branches, milestones etc. I'm not using external modules like requests because I want to keep my project free of dependencies and I haven't found the need to import any so far. That said I'm trying to assert what my HTTPS Connection requests with a mock in my tests in this way:

    gitlab_requests_tests.py

    def test_project_creation(self):
    connection = http.client.HTTPSConnection("gitlab.com")
    r = urllib.request.Request(
    method="POST",
    url="https://gitlab.com/api/v4/projects",
    headers={
    "PRIVATE-TOKEN": os.environ.get("ACCESS_TOKEN"),
    "name": Path.cwd().name
    },
    )
    glab_requests.create_project(connection)
    with patch("http.client.HTTPSConnection.request") as https_mock:
    https_mock.assert_called_with(r)


    Which tests this code:

    gitlab_requests.py

    def create_project(connection: http.client.HTTPSConnection):
    header={
    "PRIVATE-TOKEN": os.getenv("ACCESS_TOKEN", default="*"),
    "name": Path.cwd().name
    }
    if re.search(r"[^\w-]", os.getenv("ACCESS_TOKEN", default="*")):
    raise GlabRequestException("Invalid Access token format")
    connection.request("POST", "/api/v4/projects", headers=header)


    I know that I asserting my request with url.request.Request isn't the right way to do because it creates a different request object to the one I'm calling from my source code.

    How can I assert my request? What am I missing/doing wrong?

    Continue reading...

Compartilhe esta Página