How to use test_jshandle_evaluate_accept_multiple_nested_handles 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_jshandle.py

Source: test_jshandle.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 json
16import math
17from datetime import datetime
18
19from playwright.async_api import Error
20
21
22async def test_jshandle_evaluate_work(page):
23    window_handle = await page.evaluate_handle("window")
24    assert window_handle
25
26
27async def test_jshandle_evaluate_accept_object_handle_as_argument(page):
28    navigator_handle = await page.evaluate_handle("navigator")
29    text = await page.evaluate("e => e.userAgent", navigator_handle)
30    assert "Mozilla" in text
31
32
33async def test_jshandle_evaluate_accept_handle_to_primitive_types(page):
34    handle = await page.evaluate_handle("5")
35    is_five = await page.evaluate("e => Object.is(e, 5)", handle)
36    assert is_five
37
38
39async def test_jshandle_evaluate_accept_nested_handle(page):
40    foo = await page.evaluate_handle('({ x: 1, y: "foo" })')
41    result = await page.evaluate("({ foo }) => foo", {"foo": foo})
42    assert result == {"x": 1, "y": "foo"}
43
44
45async def test_jshandle_evaluate_accept_nested_window_handle(page):
46    foo = await page.evaluate_handle("window")
47    result = await page.evaluate("({ foo }) => foo === window", {"foo": foo})
48    assert result
49
50
51async def test_jshandle_evaluate_accept_multiple_nested_handles(page):
52    foo = await page.evaluate_handle('({ x: 1, y: "foo" })')
53    bar = await page.evaluate_handle("5")
54    baz = await page.evaluate_handle('["baz"]')
55    result = await page.evaluate(
56        "x => JSON.stringify(x)",
57        {"a1": {"foo": foo}, "a2": {"bar": bar, "arr": [{"baz": baz}]}},
58    )
59    assert json.loads(result) == {
60        "a1": {"foo": {"x": 1, "y": "foo"}},
61        "a2": {"bar": 5, "arr": [{"baz": ["baz"]}]},
62    }
63
64
65async def test_jshandle_evaluate_throw_for_circular_objects(page):
66    a = {"x": 1}
67    a["y"] = a
68    error = None
69    try:
70        await page.evaluate("x => x", a)
71    except Error as e:
72        error = e
73    assert "Maximum argument depth exceeded" in error.message
74
75
76async def test_jshandle_evaluate_accept_same_nested_object_multiple_times(page):
77    foo = {"x": 1}
78    assert await page.evaluate(
79        "x => x", {"foo": foo, "bar": [foo], "baz": {"foo": foo}}
80    ) == {"foo": {"x": 1}, "bar": [{"x": 1}], "baz": {"foo": {"x": 1}}}
81
82
83async def test_jshandle_evaluate_accept_object_handle_to_unserializable_value(page):
84    handle = await page.evaluate_handle("() => Infinity")
85    assert await page.evaluate("e => Object.is(e, Infinity)", handle)
86
87
88async def test_jshandle_evaluate_pass_configurable_args(page):
89    result = await page.evaluate(
90        """arg => {
91            if (arg.foo !== 42)
92            throw new Error('Not a 42');
93            arg.foo = 17;
94            if (arg.foo !== 17)
95            throw new Error('Not 17');
96            delete arg.foo;
97            if (arg.foo === 17)
98            throw new Error('Still 17');
99            return arg;
100        }""",
101        {"foo": 42},
102    )
103    assert result == {}
104
105
106async def test_jshandle_properties_get_property(page):
107    handle1 = await page.evaluate_handle(
108        """() => ({
109            one: 1,
110            two: 2,
111            three: 3
112        })"""
113    )
114    handle2 = await handle1.get_property("two")
115    assert await handle2.json_value() == 2
116
117
118async def test_jshandle_properties_work_with_undefined_null_and_empty(page):
119    handle = await page.evaluate_handle(
120        """() => ({
121            undefined: undefined,
122            null: null,
123        })"""
124    )
125    undefined_handle = await handle.get_property("undefined")
126    assert await undefined_handle.json_value() is None
127    null_handle = await handle.get_property("null")
128    assert await null_handle.json_value() is None
129    empty_handle = await handle.get_property("empty")
130    assert await empty_handle.json_value() is None
131
132
133async def test_jshandle_properties_work_with_unserializable_values(page):
134    handle = await page.evaluate_handle(
135        """() => ({
136            infinity: Infinity,
137            negInfinity: -Infinity,
138            nan: NaN,
139            negZero: -0
140        })"""
141    )
142    infinity_handle = await handle.get_property("infinity")
143    assert await infinity_handle.json_value() == float("inf")
144    neg_infinity_handle = await handle.get_property("negInfinity")
145    assert await neg_infinity_handle.json_value() == float("-inf")
146    nan_handle = await handle.get_property("nan")
147    assert math.isnan(await nan_handle.json_value()) is True
148    neg_zero_handle = await handle.get_property("negZero")
149    assert await neg_zero_handle.json_value() == float("-0")
150
151
152async def test_jshandle_properties_get_properties(page):
153    handle = await page.evaluate_handle('() => ({ foo: "bar" })')
154    properties = await handle.get_properties()
155    assert "foo" in properties
156    foo = properties["foo"]
157    assert await foo.json_value() == "bar"
158
159
160async def test_jshandle_properties_return_empty_map_for_non_objects(page):
161    handle = await page.evaluate_handle("123")
162    properties = await handle.get_properties()
163    assert properties == {}
164
165
166async def test_jshandle_json_value_work(page):
167    handle = await page.evaluate_handle('() => ({foo: "bar"})')
168    json = await handle.json_value()
169    assert json == {"foo": "bar"}
170
171
172async def test_jshandle_json_value_work_with_dates(page):
173    handle = await page.evaluate_handle('() => new Date("2020-05-27T01:31:38.506Z")')
174    json = await handle.json_value()
175    assert json == datetime.fromisoformat("2020-05-27T01:31:38.506")
176
177
178async def test_jshandle_json_value_throw_for_circular_object(page):
179    handle = await page.evaluate_handle("window")
180    error = None
181    try:
182        await handle.json_value()
183    except Error as e:
184        error = e
185    assert "Argument is a circular structure" in error.message
186
187
188async def test_jshandle_as_element_work(page):
189    handle = await page.evaluate_handle("document.body")
190    element = handle.as_element()
191    assert element is not None
192
193
194async def test_jshandle_as_element_return_none_for_non_elements(page):
195    handle = await page.evaluate_handle("2")
196    element = handle.as_element()
197    assert element is None
198
199
200async def test_jshandle_to_string_work_for_primitives(page):
201    number_handle = await page.evaluate_handle("2")
202    assert str(number_handle) == "[email protected]"
203    string_handle = await page.evaluate_handle('"a"')
204    assert str(string_handle) == "[email protected]"
205
206
207async def test_jshandle_to_string_work_for_complicated_objects(page):
208    handle = await page.evaluate_handle("window")
209    assert str(handle) == "[email protected]"
210
211
212async def test_jshandle_to_string_work_for_promises(page):
213    handle = await page.evaluate_handle("({b: Promise.resolve(123)})")
214    b_handle = await handle.get_property("b")
215    assert str(b_handle) == "[email protected]"
216
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)