_video.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 pathlib
  15. from typing import TYPE_CHECKING, Union
  16. from playwright._impl._artifact import Artifact
  17. from playwright._impl._helper import Error
  18. if TYPE_CHECKING: # pragma: no cover
  19. from playwright._impl._page import Page
  20. class Video:
  21. def __init__(self, page: "Page") -> None:
  22. self._loop = page._loop
  23. self._dispatcher_fiber = page._dispatcher_fiber
  24. self._page = page
  25. self._artifact_future = page._loop.create_future()
  26. if page.is_closed():
  27. self._page_closed()
  28. else:
  29. page.on("close", lambda page: self._page_closed())
  30. def __repr__(self) -> str:
  31. return f"<Video page={self._page}>"
  32. def _page_closed(self) -> None:
  33. if not self._artifact_future.done():
  34. self._artifact_future.set_exception(Error("Page closed"))
  35. def _artifact_ready(self, artifact: Artifact) -> None:
  36. if not self._artifact_future.done():
  37. self._artifact_future.set_result(artifact)
  38. async def path(self) -> pathlib.Path:
  39. if self._page._connection.is_remote:
  40. raise Error(
  41. "Path is not available when using browserType.connect(). Use save_as() to save a local copy."
  42. )
  43. artifact = await self._artifact_future
  44. if not artifact:
  45. raise Error("Page did not produce any video frames")
  46. return artifact.absolute_path
  47. async def save_as(self, path: Union[str, pathlib.Path]) -> None:
  48. if self._page._connection._is_sync and not self._page._is_closed:
  49. raise Error(
  50. "Page is not yet closed. Close the page prior to calling save_as"
  51. )
  52. artifact = await self._artifact_future
  53. if not artifact:
  54. raise Error("Page did not produce any video frames")
  55. await artifact.save_as(path)
  56. async def delete(self) -> None:
  57. artifact = await self._artifact_future
  58. if not artifact:
  59. raise Error("Page did not produce any video frames")
  60. await artifact.delete()