Ejemplo n.º 1
0
async def test_jsoncookie():

    files = {
        f'{json_cookie_path}': cookie_content,
    }

    json_cookie = JsonCookie()

    with mock.patch("builtins.open", get_mock_open(files)) as open_mock:
        try:
            json_cookie.load(json_cookie_path)
            open_mock.assert_called_once_with(json_cookie_path,
                                              "r+",
                                              encoding='utf-8')
        except (IOError, ValueError):
            pytest.fail("Unexpected IOError ..")

    assert json_cookie.filename == json_cookie_path
    assert len(json_cookie.cookiedict) == 1

    cookie_jar: CookieJar = json_cookie.cookiejar(cookie_domain_1)

    assert cookie_jar is not None
    assert cookie_jar.__len__() == 1

    cookies = Cookies()
    cookies.set("secret_cookie", "secret", cookie_domain_1, "/")
    cookies.set("secret_cookie", "secret", cookie_domain_2, "/")

    assert json_cookie.addcookies(cookies) is not False

    cookie_jar = json_cookie.cookiejar(cookie_domain_1)

    assert cookie_jar is not None
    assert cookie_jar.__len__() == 2

    assert json_cookie.delete(cookie_domain_1) is True

    cookie_jar = json_cookie.cookiejar(cookie_domain_1)

    assert cookie_jar is not None
    assert cookie_jar.__len__() == 0

    cookie_jar = json_cookie.cookiejar(cookie_domain_2)

    assert cookie_jar is not None
    assert cookie_jar.__len__() == 1

    with mock.patch("builtins.open", get_mock_open(files)) as open_mock:
        try:
            json_cookie.dump()
            open_mock.assert_called_once_with(json_cookie_path,
                                              "r+",
                                              encoding='utf-8')
        except (IOError, ValueError):
            pytest.fail("Unexpected IOError ..")
Ejemplo n.º 2
0
def test_cookies_update():
    cookies = Cookies()
    more_cookies = Cookies()
    more_cookies.set("name", "value", domain="example.com")

    cookies.update(more_cookies)
    assert dict(cookies) == {"name": "value"}
    assert cookies.get("name", domain="example.com") == "value"
Ejemplo n.º 3
0
def test_cookies_with_domain_and_path():
    cookies = Cookies()
    cookies.set("name", "value", domain="example.com", path="/subpath/1")
    cookies.set("name", "value", domain="example.com", path="/subpath/2")
    cookies.clear(domain="example.com", path="/subpath/1")
    assert len(cookies) == 1
    cookies.delete("name", domain="example.com", path="/subpath/2")
    assert len(cookies) == 0
Ejemplo n.º 4
0
 def __init__(self):
     super().__init__(
         headers={"user-agent": BilibiliConstants.USER_AGENT},
         cookies=Cookies(
             {k: v.value
              for k, v in BilibiliConstants.COOKIES.items()}),
     )
Ejemplo n.º 5
0
 def __init__(self):
     super().__init__(
         headers=NeteaseConstants.DEFAULT_HEADERS,
         cookies=Cookies(
             {k: v.value
              for k, v in NeteaseConstants.COOKIES.items()}),
     )
Ejemplo n.º 6
0
    def _apply_cookies_auth_flow(self, request: httpx.Request) -> None:
        cookies = {
            name: value
            for (name, value) in self.website_cookies.items()
        }

        Cookies(cookies).set_cookie_header(request)
        logger.info("cookies auth flow applied to request")
Ejemplo n.º 7
0
 def __init__(
     self,
     headers: Optional[Dict[str, Any]] = None,
     cookies: Optional[Cookies] = None,
     proxies: Optional[Dict[str, str]] = None,
 ):
     self.headers: Dict[str, Any] = headers or {}
     self.cookies: Cookies = cookies or Cookies()
     self.proxies: Dict[str, str] = proxies or {}
     self.clients: Dict[int, AsyncHTTPClient] = {}
Ejemplo n.º 8
0
def test_cookies():
    cookies = Cookies({"name": "value"})
    assert cookies["name"] == "value"
    assert "name" in cookies
    assert len(cookies) == 1
    assert dict(cookies) == {"name": "value"}
    assert bool(cookies) is True

    del cookies["name"]
    assert "name" not in cookies
    assert len(cookies) == 0
    assert dict(cookies) == {}
    assert bool(cookies) is False
Ejemplo n.º 9
0
async def test_set_cookie_with_cookies_model():
    """
    Send a request including a cookie, using a `Cookies` instance.
    """

    url = "http://example.org/echo_cookies"
    cookies = Cookies()
    cookies["example-name"] = "example-value"

    client = Client(dispatch=MockDispatch())
    response = await client.get(url, cookies=cookies)

    assert response.status_code == 200
    assert response.json() == {"cookies": "example-name=example-value"}
Ejemplo n.º 10
0
def test_cookies_with_domain():
    cookies = Cookies()
    cookies.set("name", "value", domain="example.com")
    cookies.set("name", "value", domain="example.org")

    with pytest.raises(CookieConflict):
        cookies["name"]

    cookies.clear(domain="example.com")
    assert len(cookies) == 1
Ejemplo n.º 11
0
    async def _request(
        self,
        method: str,
        path: str,
        queries: Optional[Params] = None,
        headers: Optional[Headers] = None,
        cookies: Optional[dict[str, str]] = None,
        json: Optional[Mapping] = None,
        files: Optional[Mapping] = None,
        form: Optional[Mapping] = None,
        content: Optional[bytes] = None,
        timeout: Optional[float] = None,
        allow_redirects=True,
    ) -> HttpTestResponse:
        # TODO: max_redirects?
        if isinstance(headers, Mapping):
            ci_headers = MutableHeaders(headers=headers)
        else:
            ci_headers = MutableHeaders(
                raw=[
                    (k.encode("latin-1"), v.encode("latin-1")) for k, v in headers or []
                ]
            )
        if files:
            file_list = [
                RequestField.from_tuples(key, value) for key, value in files.items()
            ]
            data, content_type = encode_multipart_formdata(file_list)
            ci_headers["content-type"] = content_type
        elif form:
            data = form
        else:
            data = content
        timeout = timeout or self.timeout
        if cookies is not None:
            self._client.cookies = Cookies()
        query_params = QueryParams(queries or [])
        if timeout is not None:
            _headers = [(k, v) for k, v in ci_headers.items()]
            async with timeout_ctx(timeout):
                response = await self._client.request(
                    method.upper(),
                    path,
                    headers=_headers,
                    data=data,
                    params=query_params,
                    json=json,
                    cookies=cookies,
                    follow_redirects=False,
                    timeout=timeout,
                )
                if allow_redirects and 300 <= response.status_code < 400:
                    path = response.headers["location"]
                    response = await self._client.request(
                        method.upper(),
                        path,
                        headers=_headers,
                        data=data,
                        params=query_params,
                        json=json,
                        cookies=cookies,
                        follow_redirects=allow_redirects,
                        timeout=timeout,
                    )

        else:
            _headers = [(k, v) for k, v in ci_headers.items()]
            response = await self._client.request(
                method.upper(),
                path,
                headers=_headers,
                data=data,
                params=query_params,
                json=json,
                cookies=cookies,
                follow_redirects=False,
                timeout=timeout,
            )
            if allow_redirects and 300 <= response.status_code < 400:
                path = response.headers["location"]
                response = await self._client.request(
                    method.upper(),
                    path,
                    headers=_headers,
                    data=data,
                    params=query_params,
                    json=json,
                    cookies=cookies,
                    follow_redirects=allow_redirects,
                    timeout=timeout,
                )
        return HttpTestResponse(response)