forked from cztomczak/cefpython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_common.py
More file actions
329 lines (272 loc) · 12.7 KB
/
Copy path_common.py
File metadata and controls
329 lines (272 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# Copyright (c) 2018 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython
from cefpython3 import cefpython as cef
import base64
import os
import platform
import sys
import time
# Platforms
SYSTEM = platform.system().upper()
if SYSTEM == "DARWIN":
SYSTEM = "MAC"
WINDOWS = SYSTEM if SYSTEM == "WINDOWS" else False
LINUX = SYSTEM if SYSTEM == "LINUX" else False
MAC = SYSTEM if SYSTEM == "MAC" else False
# To show the window for an extended period of time increase this number.
MESSAGE_LOOP_RANGE = 200 # each iteration is 0.01 sec
MAIN_BROWSER_ID = 1
POPUP_BROWSER_ID = 2
g_subtests_ran = 0
g_js_code_completed = False
g_on_load_end_callbacks = []
if LINUX:
# Ensure windowless_rendering_enabled=True on Linux so that JS-created
# popup browsers can be configured as off-screen (see LoadHandler.
# OnBeforePopup). Off-screen browsers are destroyed immediately when
# DoClose returns False — no X11/GLib delete_event dispatch is needed,
# avoiding the main browser's GTK window receiving the close notification.
_orig_cef_initialize = cef.Initialize
def _cef_initialize_linux(settings=None, switches=None, **kw):
if settings is None:
settings = {}
settings.setdefault("windowless_rendering_enabled", True)
return _orig_cef_initialize(settings, switches=switches, **kw)
cef.Initialize = _cef_initialize_linux
def init_gtk():
"""Open a GDK/X11 display connection before CEF initialises.
On a desktop GNOME/Wayland session gdk_display_get_default() returns NULL
unless a GTK application has already opened a display. Calling
gtk_init(NULL, NULL) here ensures the display is available so that the
browser window becomes visible. On CI (xvfb) this is a no-op.
GTK is safe to initialise multiple times.
"""
if LINUX:
try:
import ctypes
gtk = ctypes.CDLL("libgtk-3.so.0")
gtk.gtk_init(None, None)
except Exception as e:
print("WARNING: gtk_init failed: %s" % e)
def _linux_needs_no_sandbox():
"""Return True if unprivileged user namespaces are not available.
Chrome's namespace sandbox requires clone(CLONE_NEWUSER). Two sysctls
can block it:
* apparmor_restrict_unprivileged_userns=1 (Ubuntu 23.10+)
* unprivileged_userns_clone=0 (older Debian/Ubuntu)
When namespaces are unavailable and no SUID sandbox binary is present,
Chrome FATALs with "No usable sandbox!" unless --no-sandbox is passed.
Note: do NOT pass --no-sandbox at all. It causes Chrome to skip
GlobalDescriptors key 7 registration while still encoding it in
--pseudonymization-salt-handle, causing a CHECK-crash in subprocesses.
"""
if not LINUX:
return False
try:
with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns") as f:
if f.read().strip() == "1":
return True
except OSError:
pass
try:
with open("/proc/sys/kernel/unprivileged_userns_clone") as f:
if f.read().strip() == "0":
return True
except OSError:
pass
return False
def subtest_message(message):
global g_subtests_ran
g_subtests_ran += 1
print(str(g_subtests_ran) + ". " + message)
sys.stdout.flush()
def show_test_summary(pyfile):
print("\nRan " + str(g_subtests_ran) + " sub-tests in "
+ os.path.basename(pyfile))
def run_message_loop():
# Run message loop for some time.
# noinspection PyTypeChecker
for i in range(MESSAGE_LOOP_RANGE):
cef.MessageLoopWork()
time.sleep(0.01)
subtest_message("cef.MessageLoopWork() ok")
def do_message_loop_work(work_loops):
# noinspection PyTypeChecker
for i in range(work_loops):
cef.MessageLoopWork()
time.sleep(0.01)
def on_load_end(callback, *args):
global g_on_load_end_callbacks
g_on_load_end_callbacks.append([callback, args])
def js_code_completed():
"""Sometimes window.onload can execute before javascript bindings
are ready if the document loads very fast. When setting javascript
bindings it can take some time, because these bindings are sent
via IPC messaging to the Renderer process."""
global g_js_code_completed
assert not g_js_code_completed
g_js_code_completed = True
subtest_message("js_code_completed() ok")
def check_auto_asserts(test_case, objects):
# Check if js code completed
test_case.assertTrue(g_js_code_completed)
# Automatic check of asserts in handlers and in external
for obj in objects:
test_for_True = False # Test whether asserts are working correctly
for key, value in obj.__dict__.items():
if key == "test_for_True":
test_for_True = value
continue
if "_True" in key:
test_case.assertTrue(value, "Check assert: " +
obj.__class__.__name__ + "." + key)
subtest_message(obj.__class__.__name__ + "." +
key.replace("_True", "") +
" ok")
elif "_False" in key:
test_case.assertFalse(value, "Check assert: " +
obj.__class__.__name__ + "." + key)
subtest_message(obj.__class__.__name__ + "." +
key.replace("_False", "") +
" ok")
if "test_for_True" in obj.__dict__.keys():
test_case.assertTrue(test_for_True)
class DisplayHandler(object):
def __init__(self, test_case):
self.test_case = test_case
# Asserts for True/False will be checked just before shutdown
self.test_for_True = True # Test whether asserts are working correctly
self.javascript_errors_False = False
self.OnConsoleMessage_True = False
def OnConsoleMessage(self, message, **_):
if "error" in message.lower() or "uncaught" in message.lower():
self.javascript_errors_False = True
raise Exception("Javascript error: " + message)
else:
# Check whether messages from javascript are coming
self.OnConsoleMessage_True = True
subtest_message(message)
def close_popup(global_handler, browser):
# The popup was created as off-screen on Linux (see LoadHandler.OnBeforePopup).
# For off-screen browsers DoClose returning False causes immediate destruction
# without any GLib/X11 event dispatch, so CloseBrowser(False) works cleanly.
browser.CloseBrowser(False)
global_handler.PopupClosed_True = True
# Test developer tools popup
main_browser = cef.GetBrowserByIdentifier(MAIN_BROWSER_ID)
main_browser.ShowDevTools()
cef.PostDelayedTask(cef.TID_UI, 800, close_devtools, global_handler)
cef.PostDelayedTask(cef.TID_UI, 500, main_browser.SetFocus, True)
def close_devtools(global_handler):
main_browser = cef.GetBrowserByIdentifier(MAIN_BROWSER_ID)
global_handler.HasDevTools_True = main_browser.HasDevTools()
main_browser.CloseDevTools()
subtest_message("DevTools popup ok")
class GlobalHandler(object):
def __init__(self, test_case):
self.test_case = test_case
# Asserts for True/False will be checked just before shutdown
self.test_for_True = True # Test whether asserts are working correctly
self.OnAfterCreatedMain_True = False
if "main_test" in test_case.id():
self.OnAfterCreatedPopup_True = False
self.PopupClosed_True = False
self.HasDevTools_True = False
def _OnAfterCreated(self, browser, **_):
# For asserts that are checked automatically before shutdown its
# values should be set first, so that when other asserts fail
# (the ones called through the test_case member) they are reported
# correctly.
if not self.OnAfterCreatedMain_True:
# First call for main browser.
# browser.GetUrl() returns empty at this moment.
self.OnAfterCreatedMain_True = True
self.test_case.assertEqual(browser.GetIdentifier(),
MAIN_BROWSER_ID)
self.test_case.assertFalse(browser.IsPopup())
else:
# Second call for implicit popup browser opened via js.
# Should execute only for main test.
# Should not execute for DevTools window.
assert "main_test" in self.test_case.id()
assert not self.OnAfterCreatedPopup_True
self.OnAfterCreatedPopup_True = True
self.test_case.assertEqual(browser.GetIdentifier(),
POPUP_BROWSER_ID)
# browser.GetUrl() returns empty at this moment.
self.test_case.assertTrue(browser.IsPopup())
if WINDOWS:
cef.WindowUtils.SetTitle(browser, "Popup test")
# Close the popup browser after 250 ms
cef.PostDelayedTask(cef.TID_UI, 250, close_popup, self, browser)
class LoadHandler(object):
def __init__(self, test_case, datauri):
self.test_case = test_case
self.datauri = datauri
self.frame_source_visitor = None
# Asserts for True/False will be checked just before shutdown
self.test_for_True = True # Test whether asserts are working correctly
self.OnLoadStart_True = False
self.OnLoadEnd_True = False
self.FrameSourceVisitor_True = False
# self.OnLoadingStateChange_Start_True = False # FAILS
self.OnLoadingStateChange_End_True = False
def OnBeforePopup(self, browser, frame, target_url, target_frame_name,
target_disposition, user_gesture, popup_features,
window_info_out, client, browser_settings_out,
no_javascript_access_out, **_):
if LINUX:
# Configure JS-created popups as off-screen so they can be closed
# without GLib/X11 event dispatch. For off-screen browsers CEF
# destroys the browser immediately when DoClose returns False,
# without sending delete_event to any parent GTK window.
winfo = cef.WindowInfo()
winfo.SetAsOffscreen(0)
window_info_out.append(winfo)
return False # Allow the popup
def OnLoadStart(self, browser, frame, **_):
self.test_case.assertFalse(self.OnLoadStart_True)
self.OnLoadStart_True = True
self.test_case.assertEqual(browser.GetUrl(), frame.GetUrl())
self.test_case.assertEqual(browser.GetUrl(), self.datauri)
def OnLoadEnd(self, browser, frame, http_code, **_):
# OnLoadEnd should be called only once
self.test_case.assertFalse(self.OnLoadEnd_True)
self.OnLoadEnd_True = True
self.test_case.assertEqual(http_code, 200)
self.frame_source_visitor = FrameSourceVisitor(self, self.test_case)
frame.GetSource(self.frame_source_visitor)
browser.ExecuteJavascript("print('LoadHandler.OnLoadEnd() ok')")
subtest_message("Executing callbacks registered with on_load_end()")
global g_on_load_end_callbacks
for callback_data in g_on_load_end_callbacks:
callback_data[0](*callback_data[1])
del g_on_load_end_callbacks
def OnLoadingStateChange(self, browser, is_loading, can_go_back,
can_go_forward, **_):
if is_loading:
# TODO: this test fails, looks like OnLoadingStaetChange with
# is_loading=False is being called very fast, before
# OnLoadStart and before client handler is set by calling
# browser.SetClientHandler().
# SOLUTION: allow to set OnLoadingStateChange through
# SetGlobalClientCallback similarly to _OnAfterCreated().
# self.test_case.assertFalse(self.OnLoadingStateChange_Start_True)
# self.OnLoadingStateChange_Start_True = True
pass
else:
self.test_case.assertFalse(self.OnLoadingStateChange_End_True)
self.OnLoadingStateChange_End_True = True
self.test_case.assertEqual(browser.CanGoBack(), can_go_back)
self.test_case.assertEqual(browser.CanGoForward(), can_go_forward)
class FrameSourceVisitor(object):
"""Visitor for Frame.GetSource()."""
def __init__(self, load_handler, test_case):
self.load_handler = load_handler
self.test_case = test_case
def Visit(self, value):
self.test_case.assertFalse(self.load_handler.FrameSourceVisitor_True)
self.load_handler.FrameSourceVisitor_True = True
self.test_case.assertIn("747ef3e6011b6a61e6b3c6e54bdd2dee",
value)