_selectors.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. from pathlib import Path
  16. from typing import Any, Dict, List, Optional, Set, Union
  17. from playwright._impl._browser_context import BrowserContext
  18. from playwright._impl._errors import Error
  19. from playwright._impl._helper import async_readfile
  20. from playwright._impl._locator import set_test_id_attribute_name
  21. class Selectors:
  22. def __init__(self, loop: asyncio.AbstractEventLoop, dispatcher_fiber: Any) -> None:
  23. self._loop = loop
  24. self._contexts_for_selectors: Set[BrowserContext] = set()
  25. self._selector_engines: List[Dict] = []
  26. self._dispatcher_fiber = dispatcher_fiber
  27. self._test_id_attribute_name: Optional[str] = None
  28. async def register(
  29. self,
  30. name: str,
  31. script: str = None,
  32. path: Union[str, Path] = None,
  33. contentScript: bool = None,
  34. ) -> None:
  35. if any(engine for engine in self._selector_engines if engine["name"] == name):
  36. raise Error(
  37. f'Selectors.register: "{name}" selector engine has been already registered'
  38. )
  39. if not script and not path:
  40. raise Error("Either source or path should be specified")
  41. if path:
  42. script = (await async_readfile(path)).decode()
  43. engine: Dict[str, Any] = dict(name=name, source=script)
  44. if contentScript:
  45. engine["contentScript"] = contentScript
  46. for context in self._contexts_for_selectors:
  47. await context._channel.send(
  48. "registerSelectorEngine",
  49. None,
  50. {"selectorEngine": engine},
  51. )
  52. self._selector_engines.append(engine)
  53. def set_test_id_attribute(self, attributeName: str) -> None:
  54. set_test_id_attribute_name(attributeName)
  55. self._test_id_attribute_name = attributeName
  56. for context in self._contexts_for_selectors:
  57. context._channel.send_no_reply(
  58. "setTestIdAttributeName",
  59. None,
  60. {"testIdAttributeName": attributeName},
  61. )