How to use test_accessibility_should_work 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_accessibility.py

Source: test_accessibility.py Github

copy
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
15import pytest
16
17
18async def test_accessibility_should_work(page, is_firefox, is_chromium):
19    await page.set_content(
20        """<head>
21      <title>Accessibility Test</title>
22    </head>
23    <body>
24      <h1>Inputs</h1>
25      <input placeholder="Empty input" autofocus />
26      <input placeholder="readonly input" readonly />
27      <input placeholder="disabled input" disabled />
28      <input aria-label="Input with whitespace" value="  " />
29      <input value="value only" />
30      <input aria-placeholder="placeholder" value="and a value" />
31      <div aria-hidden="true" id="desc">This is a description!</div>
32      <input aria-placeholder="placeholder" value="and a value" aria-describedby="desc" />
33    </body>"""
34    )
35    # autofocus happens after a delay in chrome these days
36    await page.wait_for_function("document.activeElement.hasAttribute('autofocus')")
37
38    if is_firefox:
39        golden = {
40            "role": "document",
41            "name": "Accessibility Test",
42            "children": [
43                {"role": "heading", "name": "Inputs", "level": 1},
44                {"role": "textbox", "name": "Empty input", "focused": True},
45                {"role": "textbox", "name": "readonly input", "readonly": True},
46                {"role": "textbox", "name": "disabled input", "disabled": True},
47                {"role": "textbox", "name": "Input with whitespace", "value": "  "},
48                {"role": "textbox", "name": "", "value": "value only"},
49                {
50                    "role": "textbox",
51                    "name": "",
52                    "value": "and a value",
53                },  # firefox doesn't use aria-placeholder for the name
54                {
55                    "role": "textbox",
56                    "name": "",
57                    "value": "and a value",
58                    "description": "This is a description!",
59                },  # and here
60            ],
61        }
62    elif is_chromium:
63        golden = {
64            "role": "WebArea",
65            "name": "Accessibility Test",
66            "children": [
67                {"role": "heading", "name": "Inputs", "level": 1},
68                {"role": "textbox", "name": "Empty input", "focused": True},
69                {"role": "textbox", "name": "readonly input", "readonly": True},
70                {"role": "textbox", "name": "disabled input", "disabled": True},
71                {"role": "textbox", "name": "Input with whitespace", "value": "  "},
72                {"role": "textbox", "name": "", "value": "value only"},
73                {"role": "textbox", "name": "placeholder", "value": "and a value"},
74                {
75                    "role": "textbox",
76                    "name": "placeholder",
77                    "value": "and a value",
78                    "description": "This is a description!",
79                },
80            ],
81        }
82    else:
83        golden = {
84            "role": "WebArea",
85            "name": "Accessibility Test",
86            "children": [
87                {"role": "heading", "name": "Inputs", "level": 1},
88                {"role": "textbox", "name": "Empty input", "focused": True},
89                {"role": "textbox", "name": "readonly input", "readonly": True},
90                {"role": "textbox", "name": "disabled input", "disabled": True},
91                {"role": "textbox", "name": "Input with whitespace", "value": "  "},
92                {"role": "textbox", "name": "", "value": "value only"},
93                {"role": "textbox", "name": "placeholder", "value": "and a value"},
94                {
95                    "role": "textbox",
96                    "name": "This is a description!",
97                    "value": "and a value",
98                },  # webkit uses the description over placeholder for the name
99            ],
100        }
101    assert await page.accessibility.snapshot() == golden
102
103
104async def test_accessibility_should_work_with_regular_text(page, is_firefox):
105    await page.set_content("<div>Hello World</div>")
106    snapshot = await page.accessibility.snapshot()
107    assert snapshot["children"][0] == {
108        "role": "text leaf" if is_firefox else "text",
109        "name": "Hello World",
110    }
111
112
113async def test_accessibility_roledescription(page):
114    await page.set_content('<div tabIndex=-1 aria-roledescription="foo">Hi</div>')
115    snapshot = await page.accessibility.snapshot()
116    assert snapshot["children"][0]["roledescription"] == "foo"
117
118
119async def test_accessibility_orientation(page):
120    await page.set_content(
121        '<a href="" role="slider" aria-orientation="vertical">11</a>'
122    )
123    snapshot = await page.accessibility.snapshot()
124    assert snapshot["children"][0]["orientation"] == "vertical"
125
126
127async def test_accessibility_autocomplete(page):
128    await page.set_content('<div role="textbox" aria-autocomplete="list">hi</div>')
129    snapshot = await page.accessibility.snapshot()
130    assert snapshot["children"][0]["autocomplete"] == "list"
131
132
133async def test_accessibility_multiselectable(page):
134    await page.set_content(
135        '<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>'
136    )
137    snapshot = await page.accessibility.snapshot()
138    assert snapshot["children"][0]["multiselectable"]
139
140
141async def test_accessibility_keyshortcuts(page):
142    await page.set_content(
143        '<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>'
144    )
145    snapshot = await page.accessibility.snapshot()
146    assert snapshot["children"][0]["keyshortcuts"] == "foo"
147
148
149async def test_accessibility_filtering_children_of_leaf_nodes_should_not_report_text_nodes_inside_controls(
150    page, is_firefox
151):
152    await page.set_content(
153        """
154    <div role="tablist">
155    <div role="tab" aria-selected="true"><b>Tab1</b></div>
156    <div role="tab">Tab2</div>
157    </div>"""
158    )
159    golden = {
160        "role": "document" if is_firefox else "WebArea",
161        "name": "",
162        "children": [
163            {"role": "tab", "name": "Tab1", "selected": True},
164            {"role": "tab", "name": "Tab2"},
165        ],
166    }
167    assert await page.accessibility.snapshot() == golden
168
169
170# WebKit rich text accessibility is iffy
171@pytest.mark.skip_browser("webkit")
172async def test_accessibility_filtering_children_of_leaf_nodes_rich_text_editable_fields_should_have_children(
173    page, is_firefox
174):
175    await page.set_content(
176        """
177    <div contenteditable="true">
178    Edit this image: <img src="fakeimage.png" alt="my fake image">
179    </div>"""
180    )
181    golden = (
182        {
183            "role": "section",
184            "name": "",
185            "children": [
186                {"role": "text leaf", "name": "Edit this image: "},
187                {"role": "text", "name": "my fake image"},
188            ],
189        }
190        if is_firefox
191        else {
192            "role": "generic",
193            "name": "",
194            "value": "Edit this image: ",
195            "children": [
196                {"role": "text", "name": "Edit this image:"},
197                {"role": "img", "name": "my fake image"},
198            ],
199        }
200    )
201    snapshot = await page.accessibility.snapshot()
202    assert snapshot["children"][0] == golden
203
204
205# WebKit rich text accessibility is iffy
206@pytest.mark.skip_browser("webkit")
207async def test_accessibility_filtering_children_of_leaf_nodes_rich_text_editable_fields_with_role_should_have_children(
208    page,
209    is_firefox,
210):
211    await page.set_content(
212        """
213    <div contenteditable="true" role='textbox'>
214    Edit this image: <img src="fakeimage.png" alt="my fake image">
215    </div>"""
216    )
217    if is_firefox:
218        golden = {
219            "role": "textbox",
220            "name": "",
221            "value": "Edit this image: my fake image",
222            "children": [{"role": "text", "name": "my fake image"}],
223        }
224    else:
225        golden = {
226            "role": "textbox",
227            "name": "",
228            "value": "Edit this image: ",
229            "children": [
230                {"role": "text", "name": "Edit this image:"},
231                {"role": "img", "name": "my fake image"},
232            ],
233        }
234    snapshot = await page.accessibility.snapshot()
235    assert snapshot["children"][0] == golden
236
237
238# Firefox does not support contenteditable="plaintext-only".
239# WebKit rich text accessibility is iffy
240@pytest.mark.only_browser("chromium")
241async def test_accessibility_plain_text_field_with_role_should_not_have_children(page):
242    await page.set_content(
243        """
244    <div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>"""
245    )
246    snapshot = await page.accessibility.snapshot()
247    assert snapshot["children"][0] == {
248        "role": "textbox",
249        "name": "",
250        "value": "Edit this image:",
251    }
252
253
254@pytest.mark.only_browser("chromium")
255async def test_accessibility_plain_text_field_without_role_should_not_have_content(
256    page,
257):
258    await page.set_content(
259        """
260    <div contenteditable="plaintext-only">Edit this image:<img src="fakeimage.png" alt="my fake image"></div>"""
261    )
262    snapshot = await page.accessibility.snapshot()
263    assert snapshot["children"][0] == {"role": "generic", "name": ""}
264
265
266@pytest.mark.only_browser("chromium")
267async def test_accessibility_plain_text_field_with_tabindex_and_without_role_should_not_have_content(
268    page,
269):
270    await page.set_content(
271        """
272    <div contenteditable="plaintext-only" tabIndex=0>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>"""
273    )
274    snapshot = await page.accessibility.snapshot()
275    assert snapshot["children"][0] == {"role": "generic", "name": ""}
276
277
278async def test_accessibility_non_editable_textbox_with_role_and_tabIndex_and_label_should_not_have_children(
279    page, is_chromium, is_firefox
280):
281    await page.set_content(
282        """
283      <div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox">
284        this is the inner content
285        <img alt="yo" src="fakeimg.png">
286      </div>"""
287    )
288    if is_firefox:
289        golden = {
290            "role": "textbox",
291            "name": "my favorite textbox",
292            "value": "this is the inner content yo",
293        }
294    elif is_chromium:
295        golden = {
296            "role": "textbox",
297            "name": "my favorite textbox",
298            "value": "this is the inner content ",
299        }
300    else:
301        golden = {
302            "role": "textbox",
303            "name": "my favorite textbox",
304            "value": "this is the inner content  ",
305        }
306    snapshot = await page.accessibility.snapshot()
307    assert snapshot["children"][0] == golden
308
309
310async def test_accessibility_checkbox_with_and_tabIndex_and_label_should_not_have_children(
311    page,
312):
313    await page.set_content(
314        """
315    <div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox">
316    this is the inner content
317    <img alt="yo" src="fakeimg.png">
318    </div>"""
319    )
320    golden = {"role": "checkbox", "name": "my favorite checkbox", "checked": True}
321    snapshot = await page.accessibility.snapshot()
322    assert snapshot["children"][0] == golden
323
324
325async def test_accessibility_checkbox_without_label_should_not_have_children(
326    page, is_firefox
327):
328    await page.set_content(
329        """
330      <div role="checkbox" aria-checked="true">
331        this is the inner content
332        <img alt="yo" src="fakeimg.png">
333    </div>"""
334    )
335    golden = {
336        "role": "checkbox",
337        "name": "this is the inner content yo",
338        "checked": True,
339    }
340    snapshot = await page.accessibility.snapshot()
341    assert snapshot["children"][0] == golden
342
343
344async def test_accessibility_should_work_a_button(page):
345    await page.set_content("<button>My Button</button>")
346
347    button = await page.query_selector("button")
348    assert await page.accessibility.snapshot(root=button) == {
349        "role": "button",
350        "name": "My Button",
351    }
352
353
354async def test_accessibility_should_work_an_input(page):
355    await page.set_content('<input title="My Input" value="My Value">')
356
357    input = await page.query_selector("input")
358    assert await page.accessibility.snapshot(root=input) == {
359        "role": "textbox",
360        "name": "My Input",
361        "value": "My Value",
362    }
363
364
365async def test_accessibility_should_work_on_a_menu(page, is_webkit):
366    await page.set_content(
367        """
368        <div role="menu" title="My Menu">
369        <div role="menuitem">First Item</div>
370        <div role="menuitem">Second Item</div>
371        <div role="menuitem">Third Item</div>
372        </div>
373    """
374    )
375
376    menu = await page.query_selector('div[role="menu"]')
377    golden = {
378        "role": "menu",
379        "name": "My Menu",
380        "children": [
381            {"role": "menuitem", "name": "First Item"},
382            {"role": "menuitem", "name": "Second Item"},
383            {"role": "menuitem", "name": "Third Item"},
384        ],
385    }
386    if is_webkit:
387        golden["orientation"] = "vertical"
388    assert await page.accessibility.snapshot(root=menu) == golden
389
390
391async def test_accessibility_should_return_null_when_the_element_is_no_longer_in_DOM(
392    page,
393):
394    await page.set_content("<button>My Button</button>")
395    button = await page.query_selector("button")
396    await page.eval_on_selector("button", "button => button.remove()")
397    assert await page.accessibility.snapshot(root=button) is None
398
399
400async def test_accessibility_should_show_uninteresting_nodes(page):
401    await page.set_content(
402        """
403        <div id="root" role="textbox">
404        <div>
405            hello
406            <div>
407            world
408            </div>
409        </div>
410        </div>
411    """
412    )
413
414    root = await page.query_selector("#root")
415    snapshot = await page.accessibility.snapshot(root=root, interesting_only=False)
416    assert snapshot["role"] == "textbox"
417    assert "hello" in snapshot["value"]
418    assert "world" in snapshot["value"]
419    assert snapshot["children"]
420
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)