lundberg / respx

Mock HTTPX with awesome request patterns and response side effects 🦋
https://lundberg.github.io/respx
BSD 3-Clause "New" or "Revised" License
581 stars 38 forks source link

Feature request: easily mock cookies #249

Closed phha closed 3 months ago

phha commented 6 months ago

It would be super nice if we could do something like this:

respx.get("example.com").respond(cookies={"foo": "bar"})

cookies = httpx.Cookies()
respx.get("example.com").respond(cookies=cookies)
lundberg commented 6 months ago

Sounds like a reasonable feature .. we'll need to dig in httpx to figure out how to best construct a response with the cookies, e.g. Set-Cookie headers or other way

phha commented 5 months ago

I've followed the trail a bit and it seems like we'd have to set the headers.

Response.cookies is a read-only property

@property
def cookies(self) -> "Cookies":
    if not hasattr(self, "_cookies"):
        self._cookies = Cookies()
        self._cookies.extract_cookies(self)
    return self._cookies

Where

def extract_cookies(self, response: Response) -> None:
    """
    Loads any cookies based on the response `Set-Cookie` headers.
    """

Which leads to the question whether headers= or cookies= should take precedence in case of collisions. My gut feeling is that cookies should override headers. Essentially, cookies= is a special case of headers=, and the more specific case should take precedence over the general case.

lundberg commented 4 months ago

@phha I finally got around and implemented a feature for this 😅. Please try the PR out locally, if possible, to rule out any bugs.