_har_router.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import base64
  16. from typing import TYPE_CHECKING, Optional, cast
  17. from playwright._impl._api_structures import HeadersArray
  18. from playwright._impl._helper import (
  19. HarLookupResult,
  20. RouteFromHarNotFoundPolicy,
  21. URLMatch,
  22. )
  23. from playwright._impl._local_utils import LocalUtils
  24. if TYPE_CHECKING: # pragma: no cover
  25. from playwright._impl._browser_context import BrowserContext
  26. from playwright._impl._network import Route
  27. from playwright._impl._page import Page
  28. class HarRouter:
  29. def __init__(
  30. self,
  31. local_utils: LocalUtils,
  32. har_id: str,
  33. not_found_action: RouteFromHarNotFoundPolicy,
  34. url_matcher: Optional[URLMatch] = None,
  35. ) -> None:
  36. self._local_utils: LocalUtils = local_utils
  37. self._har_id: str = har_id
  38. self._not_found_action: RouteFromHarNotFoundPolicy = not_found_action
  39. self._options_url_match: Optional[URLMatch] = url_matcher
  40. @staticmethod
  41. async def create(
  42. local_utils: LocalUtils,
  43. file: str,
  44. not_found_action: RouteFromHarNotFoundPolicy,
  45. url_matcher: Optional[URLMatch] = None,
  46. ) -> "HarRouter":
  47. har_id = await local_utils._channel.send("harOpen", None, {"file": file})
  48. return HarRouter(
  49. local_utils=local_utils,
  50. har_id=har_id,
  51. not_found_action=not_found_action,
  52. url_matcher=url_matcher,
  53. )
  54. async def _handle(self, route: "Route") -> None:
  55. request = route.request
  56. response: HarLookupResult = await self._local_utils.har_lookup(
  57. harId=self._har_id,
  58. url=request.url,
  59. method=request.method,
  60. headers=await request.headers_array(),
  61. postData=request.post_data_buffer,
  62. isNavigationRequest=request.is_navigation_request(),
  63. )
  64. action = response["action"]
  65. if action == "redirect":
  66. redirect_url = response["redirectURL"]
  67. assert redirect_url
  68. await route._redirected_navigation_request(redirect_url)
  69. return
  70. if action == "fulfill":
  71. # If the response status is -1, the request was canceled or stalled, so we just stall it here.
  72. # See https://github.com/microsoft/playwright/issues/29311.
  73. # TODO: it'd be better to abort such requests, but then we likely need to respect the timing,
  74. # because the request might have been stalled for a long time until the very end of the
  75. # test when HAR was recorded but we'd abort it immediately.
  76. if response.get("status") == -1:
  77. return
  78. body = response["body"]
  79. assert body is not None
  80. await route.fulfill(
  81. status=response.get("status"),
  82. headers={
  83. v["name"]: v["value"]
  84. for v in cast(HeadersArray, response.get("headers", []))
  85. },
  86. body=base64.b64decode(body),
  87. )
  88. return
  89. if action == "error":
  90. pass
  91. # Report the error, but fall through to the default handler.
  92. if self._not_found_action == "abort":
  93. await route.abort()
  94. return
  95. await route.fallback()
  96. async def add_context_route(self, context: "BrowserContext") -> None:
  97. await context.route(
  98. url=self._options_url_match or "**/*",
  99. handler=lambda route, _: asyncio.create_task(self._handle(route)),
  100. )
  101. async def add_page_route(self, page: "Page") -> None:
  102. await page.route(
  103. url=self._options_url_match or "**/*",
  104. handler=lambda route, _: asyncio.create_task(self._handle(route)),
  105. )
  106. def dispose(self) -> None:
  107. asyncio.create_task(
  108. self._local_utils._channel.send("harClose", None, {"harId": self._har_id})
  109. )