forked from cztomczak/cefpython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.py
More file actions
458 lines (405 loc) · 19.1 KB
/
Copy pathmain_test.py
File metadata and controls
458 lines (405 loc) · 19.1 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# Copyright (c) 2016 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython
"""General testing of CEF Python."""
import unittest
# noinspection PyUnresolvedReferences
import _test_runner
from _common import *
from cefpython3 import cefpython as cef
import glob
import os
import sys
g_datauri_data = """
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body,html {
font-family: Arial;
font-size: 11pt;
}
body {
width: 810px;
heiht: 610px;
}
</style>
<script>
function print(msg) {
console.log(msg+" [JS]");
msg = msg.replace("ok", "<b style='color:green'>ok</b>");
msg = msg.replace("error", "<b style='color:red'>error</b>");
document.getElementById("console").innerHTML += msg+"<br>";
}
function onload_helper() {
if (!window.hasOwnProperty("cefpython_version")) {
// Sometimes page could finish loading before javascript
// bindings are available. Javascript bindings are sent
// from the browser process to the renderer process via
// IPC messaging and it can take some time (5-10ms). If
// the page loads very fast window.onload could execute
// before bindings are available.
setTimeout(onload_helper, 10);
return;
}
version = cefpython_version
print("CEF Python: <b>"+version.version+"</b>");
print("Chrome: <b>"+version.chrome_version+"</b>");
print("CEF: <b>"+version.cef_version+"</b>");
// Test binding function: test_function
test_function();
print("test_function() ok");
// Test binding property: test_property1
if (test_property1 === "Test binding property to the 'window' object") {
print("test_property_1 ok");
} else {
throw new Error("test_property1 contains invalid string");
}
// Test binding property: test_property2
if (JSON.stringify(test_property2) === '{"key1":"Test binding property'+
' to the \\'window\\' object","key2":["Inside list",2147483647,"2147483648"]}') {
print("test_property2 ok");
} else {
print("test_property2 invalid value: " + JSON.stringify(test_property2));
throw new Error("test_property2 contains invalid value");
}
// Test binding function: test_property3_function
test_property3_function();
print("test_property3_function() ok");
// Test binding external object and use of javascript<>python callbacks
var start_time = new Date().getTime();
print("[TIMER] Call Python function and then js callback that was"+
" passed (Issue #277 test)");
external.test_callbacks(function(msg_from_python, py_callback){
if (msg_from_python === "String sent from Python") {
print("test_callbacks() ok");
var execution_time = new Date().getTime() - start_time;
print("[TIMER]: Elapsed = "+String(execution_time)+" ms");
} else {
throw new Error("test_callbacks(): msg_from_python contains"+
" invalid value");
}
py_callback("String sent from Javascript");
print("py_callback() ok");
});
// Test popup
window.open("about:blank");
// Done
js_code_completed();
}
window.onload = function() {
print("window.onload() ok");
onload_helper();
}
</script>
</head>
<body>
<!-- FrameSourceVisitor hash = 747ef3e6011b6a61e6b3c6e54bdd2dee -->
<h1>Main test</h1>
<div id="console"></div>
</body>
</html>
"""
g_datauri = cef.GetDataUrl(g_datauri_data)
class MainTest_IsolatedTest(unittest.TestCase):
def test_main(self):
"""Main entry point. All the code must run inside one
single test, otherwise strange things happen."""
print("")
print("CEF Python {ver}".format(ver=cef.__version__))
print("Python {ver}".format(ver=sys.version[:6]))
# Test initialization of CEF
settings = {
"debug": False,
"log_severity": cef.LOGSEVERITY_ERROR,
"log_file": "",
}
if not LINUX:
# On Linux you get a lot of "X error received" messages
# from Chromium's "x11_util.cc", so do not show them.
settings["log_severity"] = cef.LOGSEVERITY_WARNING
if "--debug" in sys.argv:
settings["debug"] = True
settings["log_severity"] = cef.LOGSEVERITY_INFO
if "--debug-warning" in sys.argv:
settings["debug"] = True
settings["log_severity"] = cef.LOGSEVERITY_WARNING
# Chrome 130+ blocks window.open() called without a user gesture.
switches = {"disable-popup-blocking": ""}
if LINUX:
# Open a GDK/X11 display connection before CEF initialises so
# that gdk_display_get_default() returns a valid display. On a
# desktop session this is required for the browser window to be
# visible; on xvfb (CI) it is a no-op.
init_gtk()
# cefpython does not ship a chrome-sandbox (setuid) binary.
# Disable SUID/namespace sandboxes; Chrome falls back to seccomp-BPF
# which keeps GlobalDescriptors key 7 registered for subprocesses.
# Do NOT pass --no-sandbox: it skips key 7 registration but encodes
# it in --pseudonymization-salt-handle, causing a CHECK-crash.
switches["disable-setuid-sandbox"] = ""
# /dev/shm is too small in CI containers.
switches["disable-dev-shm-usage"] = ""
# GPU acceleration is not available under xvfb.
switches["disable-gpu"] = ""
switches["disable-gpu-compositing"] = ""
# Run GPU process inside the browser process so it is not
# spawned during CefInitialize() where it would fail.
switches["in-process-gpu"] = ""
switches["no-zygote"] = ""
# Force X11 rendering via XWayland. On Ubuntu 24 GNOME/Wayland
# Chrome 130+ defaults to the Wayland Ozone backend when
# WAYLAND_DISPLAY is set; cefpython uses raw X11 APIs so the
# window would never appear. On CI (xvfb) this is a no-op.
switches["ozone-platform"] = "x11"
# Run the network service in-process so no utility subprocess
# needs to be spawned (reduces spawn overhead on CI).
# The feature string in Chrome 130+ is "NetworkServiceInProcess2".
switches["enable-features"] = "NetworkServiceInProcess2"
# Suppress the GNOME Keyring unlock prompt on desktop sessions.
switches["password-store"] = "basic"
if MAC:
# cefpython does not ship a chrome-sandbox binary.
switches["no-sandbox"] = ""
# No real GPU available on macOS CI runners.
switches["disable-gpu"] = ""
switches["disable-gpu-compositing"] = ""
switches["in-process-gpu"] = ""
# Prevent macOS keychain authorization prompts during init
# (matches CEF's own test infrastructure on macOS).
switches["use-mock-keychain"] = ""
# Chrome 130+ MachPortRendezvousServer registers via
# bootstrap_check_in; renderer subprocesses look up the service
# via bootstrap_look_up, which fails on unsigned CI processes
# because Chrome gives them a restricted bootstrap namespace.
# --in-process-renderer was removed from Chrome 130+.
# --single-process runs the renderer in the browser process,
# eliminating renderer subprocess bootstrap_look_up failures.
switches["single-process"] = ""
# --single-process puts the renderer's V8 in the browser process,
# which requires a large contiguous CodeRange for JIT code.
# On constrained CI runner images this reservation fails with an
# OOM error. --jitless disables all V8 JIT compilers, eliminating
# the CodeRange requirement entirely.
switches["js-flags"] = "--jitless"
# Run network service in-process to avoid Mach port rendezvous
# failures for utility subprocesses on macOS CI runners.
# The feature string in Chrome 130+ is "NetworkServiceInProcess2".
switches["enable-features"] = "NetworkServiceInProcess2"
cef.Initialize(settings, switches=switches)
subtest_message("cef.Initialize() ok")
# CRL set file
certrevoc_dir = ""
if WINDOWS:
certrevoc_dir = r"C:\localappdata\Google\Chrome\User Data" \
r"\CertificateRevocation"
elif LINUX:
certrevoc_dir = r"/home/*/.config/google-chrome" \
r"/CertificateRevocation"
elif MAC:
certrevoc_dir = r"/Users/*/Library/Application Support/Google" \
r"/Chrome/CertificateRevocation"
crlset_files = glob.iglob(os.path.join(certrevoc_dir, "*",
"crl-set"))
crlset = ""
for crlset in crlset_files:
pass
if os.path.exists(crlset):
cef.LoadCrlSetsFile(crlset)
subtest_message("cef.LoadCrlSetsFile ok")
# High DPI on Windows.
# Setting DPI awareness from Python is usually too late and should be done
# via manifest file. Alternatively change python.exe properties > Compatibility
# > High DPI scaling override > Application.
# Using cef.DpiAware.EnableHighDpiSupport is problematic, it can cause
# display glitches.
if WINDOWS:
self.assertIsInstance(cef.DpiAware.GetSystemDpi(), tuple)
window_size = cef.DpiAware.CalculateWindowSize(800, 600)
self.assertIsInstance(window_size, tuple)
self.assertGreater(window_size[0], 0)
self.assertGreater(cef.DpiAware.Scale((800, 600))[0], 0)
# Make some calls again after DPI Aware was set
self.assertIsInstance(cef.DpiAware.GetSystemDpi(), tuple)
self.assertGreater(cef.DpiAware.Scale([800, 600])[0], 0)
self.assertIsInstance(cef.DpiAware.Scale(800), int)
self.assertGreater(cef.DpiAware.Scale(800), 0)
subtest_message("cef.DpiAware ok")
# Global handler
global_handler = GlobalHandler(self)
cef.SetGlobalClientCallback("OnAfterCreated",
global_handler._OnAfterCreated)
subtest_message("cef.SetGlobalClientCallback() ok")
# Create browser
browser_settings = {
"inherit_client_handlers_for_popups": False,
}
browser = cef.CreateBrowserSync(url=g_datauri,
settings=browser_settings)
self.assertIsNotNone(browser, "Browser object")
browser.SetFocus(True)
subtest_message("cef.CreateBrowserSync() ok")
# Client handlers
display_handler2 = DisplayHandler2(self)
v8context_handler = V8ContextHandler(self)
client_handlers = [LoadHandler(self, g_datauri),
DisplayHandler(self),
display_handler2,
v8context_handler]
for handler in client_handlers:
browser.SetClientHandler(handler)
subtest_message("browser.SetClientHandler() ok")
# Javascript bindings
external = External(self)
bindings = cef.JavascriptBindings(
bindToFrames=False, bindToPopups=False)
bindings.SetFunction("js_code_completed", js_code_completed)
bindings.SetFunction("test_function", external.test_function)
bindings.SetProperty("test_property1", external.test_property1)
bindings.SetProperty("test_property2", external.test_property2)
# Property with a function value can also be bound. CEF Python
# supports passing functions as callbacks when called from
# javascript, and as a side effect any value and in this case
# a property can also be a function.
bindings.SetProperty("test_property3_function",
external.test_property3_function)
bindings.SetProperty("cefpython_version", cef.GetVersion())
bindings.SetObject("external", external)
browser.SetJavascriptBindings(bindings)
subtest_message("browser.SetJavascriptBindings() ok")
# Set auto resize. Call it after js bindings were set.
browser.SetAutoResizeEnabled(enabled=True,
min_size=[800, 600],
max_size=[1024, 768])
subtest_message("browser.SetAutoResizeEnabled() ok")
# Test Request.SetPostData(list)
# noinspection PyArgumentList
req = cef.Request.CreateRequest()
req_file = os.path.dirname(os.path.abspath(__file__))
req_file = os.path.join(req_file, "main_test.py")
if sys.version_info.major > 2:
req_file = req_file.encode("utf-8")
req_data = [b"--key=value", b"@"+req_file]
req.SetMethod("POST")
req.SetPostData(req_data)
self.assertEqual(req_data, req.GetPostData())
subtest_message("cef.Request.SetPostData(list) ok")
# Test Request.SetPostData(dict)
# noinspection PyArgumentList
req = cef.Request.CreateRequest()
req_data = {b"key": b"value"}
req.SetMethod("POST")
req.SetPostData(req_data)
self.assertEqual(req_data, req.GetPostData())
subtest_message("cef.Request.SetPostData(dict) ok")
# Cookie manager
self.assertIsInstance(cef.CookieManager.GetGlobalManager(),
cef.PyCookieManager)
subtest_message("cef.CookieManager ok")
# Window Utils
if WINDOWS:
hwnd = 1 # When using 0 getting issues with OnautoResize
self.assertFalse(cef.WindowUtils.IsWindowHandle(hwnd))
cef.WindowUtils.OnSetFocus(hwnd, 0, 0, 0)
cef.WindowUtils.OnSize(hwnd, 0, 0, 0)
cef.WindowUtils.OnEraseBackground(hwnd, 0, 0, 0)
cef.WindowUtils.GetParentHandle(hwnd)
cef.WindowUtils.SetTitle(browser, "Main test")
subtest_message("cef.WindowUtils ok")
elif LINUX:
cef.WindowUtils.InstallX11ErrorHandlers()
subtest_message("cef.WindowUtils ok")
elif MAC:
hwnd = 0
cef.WindowUtils.GetParentHandle(hwnd)
cef.WindowUtils.IsWindowHandle(hwnd)
subtest_message("cef.WindowUtils ok")
# Run message loop
run_message_loop()
# Make sure popup browser was destroyed
self.assertIsInstance(cef.GetBrowserByIdentifier(MAIN_BROWSER_ID),
cef.PyBrowser)
self.assertIsNone(cef.GetBrowserByIdentifier(POPUP_BROWSER_ID))
subtest_message("cef.GetBrowserByIdentifier() ok")
# Close browser and clean reference
browser.CloseBrowser(True)
del browser
subtest_message("browser.CloseBrowser() ok")
# Give it some time to close before checking asserts
# and calling shutdown.
do_message_loop_work(25)
# Asserts before shutdown
self.assertEqual(display_handler2.OnLoadingProgressChange_Progress,
1.0)
# noinspection PyTypeChecker
check_auto_asserts(self, [] + client_handlers
+ [global_handler,
external])
# Test shutdown of CEF
cef.Shutdown()
subtest_message("cef.Shutdown() ok")
# Display summary
show_test_summary(__file__)
sys.stdout.flush()
class DisplayHandler2(object):
def __init__(self, test_case):
self.test_case = test_case
# Asserts for True/False will be checked just before shutdown.
# Test whether asserts are working correctly.
self.test_for_True = True
# CEF 146+: SetAutoResizeEnabled no longer triggers OnAutoResize for
# windowed (non-OSR) browsers. Removed OnAutoResize_True assertion.
self.OnLoadingProgressChange_True = False
self.OnLoadingProgressChange_Progress = 0.0
def OnAutoResize(self, new_size, **_):
pass # CEF 146+: no longer fires for windowed browsers
def OnLoadingProgressChange(self, browser, progress, **_):
self.OnLoadingProgressChange_True = True
self.OnLoadingProgressChange_Progress = progress
class V8ContextHandler(object):
def __init__(self, test_case):
self.test_case = test_case
# CEF 146+: only one V8 context is created per navigation.
# The initial empty-document context that existed in older CEF
# versions (and was released immediately) is no longer created.
self.OnContextCreatedFirstCall_True = False
def OnContextCreated(self, browser, frame):
self.OnContextCreatedFirstCall_True = True
self.test_case.assertEqual(browser.GetIdentifier(), MAIN_BROWSER_ID)
self.test_case.assertTrue(frame.GetIdentifier())
def OnContextReleased(self, browser, frame):
# CEF 146+: no longer called for the initial empty-document context
# (which no longer exists). May still be called in other scenarios.
self.test_case.assertEqual(browser.GetIdentifier(), MAIN_BROWSER_ID)
self.test_case.assertTrue(frame.GetIdentifier())
class External(object):
"""Javascript 'window.external' object."""
def __init__(self, test_case):
self.test_case = test_case
# Test binding properties to the 'window' object.
# 2147483648 is out of INT_MAX limit and will be sent to JS as string value.
self.test_property1 = "Test binding property to the 'window' object"
self.test_property2 = {"key1": self.test_property1,
"key2": ["Inside list", 2147483647, 2147483648]}
# Asserts for True/False will be checked just before shutdown
self.test_for_True = True # Test whether asserts are working correctly
self.test_function_True = False
self.test_property3_function_True = False
self.test_callbacks_True = False
self.py_callback_True = False
def test_function(self):
"""Test binding function to the 'window' object."""
self.test_function_True = True
def test_property3_function(self):
"""Test binding function to the 'window' object."""
self.test_property3_function_True = True
def test_callbacks(self, js_callback):
"""Test both javascript and python callbacks."""
def py_callback(msg_from_js):
self.py_callback_True = True
self.test_case.assertEqual(msg_from_js,
"String sent from Javascript")
self.test_callbacks_True = True
js_callback.Call("String sent from Python", py_callback)
if __name__ == "__main__":
_test_runner.main(os.path.basename(__file__))