How to use test_selectors_register_should_work_with_path method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_queryselector.py

Source: test_queryselector.py Github

copy
1import pytest
2
3from playwright.async_api import Error, Page
4
5
6async def test_selectors_register_should_work(selectors, browser):
7    tag_selector = """
8        {
9            create(root, target) {
10                return target.nodeName;
11            },
12            query(root, selector) {
13                return root.querySelector(selector);
14            },
15            queryAll(root, selector) {
16                return Array.from(root.querySelectorAll(selector));
17            }
18        }"""
19
20    # Register one engine before creating context.
21    await selectors.register("tag", tag_selector)
22
23    context = await browser.new_context()
24    # Register another engine after creating context.
25    await selectors.register("tag2", tag_selector)
26
27    page = await context.new_page()
28    await page.set_content("<div><span></span></div><div></div>")
29
30    assert await page.eval_on_selector("tag=DIV", "e => e.nodeName") == "DIV"
31    assert await page.eval_on_selector("tag=SPAN", "e => e.nodeName") == "SPAN"
32    assert await page.eval_on_selector_all("tag=DIV", "es => es.length") == 2
33
34    assert await page.eval_on_selector("tag2=DIV", "e => e.nodeName") == "DIV"
35    assert await page.eval_on_selector("tag2=SPAN", "e => e.nodeName") == "SPAN"
36    assert await page.eval_on_selector_all("tag2=DIV", "es => es.length") == 2
37
38    # Selector names are case-sensitive.
39    with pytest.raises(Error) as exc:
40        await page.query_selector("tAG=DIV")
41    assert 'Unknown engine "tAG" while parsing selector tAG=DIV' in exc.value.message
42
43    await context.close()
44
45
46async def test_selectors_register_should_work_with_path(
47    selectors, page: Page, utils, assetdir
48):
49    await utils.register_selector_engine(
50        selectors, "foo", path=assetdir / "sectionselectorengine.js"
51    )
52    await page.set_content("<section></section>")
53    assert await page.eval_on_selector("foo=whatever", "e => e.nodeName") == "SECTION"
54
55
56async def test_selectors_register_should_work_in_main_and_isolated_world(
57    selectors, page: Page, utils
58):
59    dummy_selector_script = """{
60      create(root, target) { },
61      query(root, selector) {
62        return window.__answer;
63      },
64      queryAll(root, selector) {
65        return window['__answer'] ? [window['__answer'], document.body, document.documentElement] : [];
66      }
67    }"""
68
69    await utils.register_selector_engine(selectors, "main", dummy_selector_script)
70    await utils.register_selector_engine(
71        selectors, "isolated", dummy_selector_script, content_script=True
72    )
73    await page.set_content("<div><span><section></section></span></div>")
74    await page.evaluate('() => window.__answer = document.querySelector("span")')
75    # Works in main if asked.
76    assert await page.eval_on_selector("main=ignored", "e => e.nodeName") == "SPAN"
77    assert (
78        await page.eval_on_selector("css=div >> main=ignored", "e => e.nodeName")
79        == "SPAN"
80    )
81    assert await page.eval_on_selector_all(
82        "main=ignored", "es => window.__answer !== undefined"
83    )
84    assert (
85        await page.eval_on_selector_all(
86            "main=ignored", "es => es.filter(e => e).length"
87        )
88        == 3
89    )
90    # Works in isolated by default.
91    assert await page.query_selector("isolated=ignored") is None
92    assert await page.query_selector("css=div >> isolated=ignored") is None
93    # $$eval always works in main, to avoid adopting nodes one by one.
94    assert await page.eval_on_selector_all(
95        "isolated=ignored", "es => window.__answer !== undefined"
96    )
97    assert (
98        await page.eval_on_selector_all(
99            "isolated=ignored", "es => es.filter(e => e).length"
100        )
101        == 3
102    )
103    # At least one engine in main forces all to be in main.
104    assert (
105        await page.eval_on_selector(
106            "main=ignored >> isolated=ignored", "e => e.nodeName"
107        )
108        == "SPAN"
109    )
110    assert (
111        await page.eval_on_selector(
112            "isolated=ignored >> main=ignored", "e => e.nodeName"
113        )
114        == "SPAN"
115    )
116    # Can be chained to css.
117    assert (
118        await page.eval_on_selector("main=ignored >> css=section", "e => e.nodeName")
119        == "SECTION"
120    )
121
122
123async def test_selectors_register_should_handle_errors(selectors, page: Page, utils):
124    with pytest.raises(Error) as exc:
125        await page.query_selector("neverregister=ignored")
126    assert (
127        'Unknown engine "neverregister" while parsing selector neverregister=ignored'
128        in exc.value.message
129    )
130
131    dummy_selector_engine_script = """{
132      create(root, target) {
133        return target.nodeName;
134      },
135      query(root, selector) {
136        return root.querySelector('dummy');
137      },
138      queryAll(root, selector) {
139        return Array.from(root.query_selector_all('dummy'));
140      }
141    }"""
142
143    with pytest.raises(Error) as exc:
144        await selectors.register("$", dummy_selector_engine_script)
145    assert (
146        exc.value.message
147        == "Selector engine name may only contain [a-zA-Z0-9_] characters"
148    )
149
150    # Selector names are case-sensitive.
151    await utils.register_selector_engine(
152        selectors, "dummy", dummy_selector_engine_script
153    )
154    await utils.register_selector_engine(
155        selectors, "duMMy", dummy_selector_engine_script
156    )
157
158    with pytest.raises(Error) as exc:
159        await selectors.register("dummy", dummy_selector_engine_script)
160    assert exc.value.message == '"dummy" selector engine has been already registered'
161
162    with pytest.raises(Error) as exc:
163        await selectors.register("css", dummy_selector_engine_script)
164    assert exc.value.message == '"css" is a predefined selector engine'
165
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)