FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cefpython/unittests/main_test.py at refs/heads/cefpython147 · linesight/cefpython · GitHub
linesight
/
cefpython
Public
forked from
cztomczak/cefpython
Notifications
You must be signed in to change notification settings
Fork
2
Star
11
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cefpython
/
unittests
/
main_test.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
443 lines (385 loc) · 17.6 KB
Breadcrumbs
cefpython
/
unittests
/
main_test.py
Copy path
File metadata and controls
443 lines (385 loc) · 17.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# 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
)
def
main_test_async_completed
(
global_handler
,
objects
,
loading_progress
):
"""Return whether all asynchronous main-test work has finished."""
main_browser
=
cef
.
GetBrowserByIdentifier
(
MAIN_BROWSER_ID
)
if
(
not
is_js_code_completed
()
or
not
global_handler
.
HasDevTools_True
or
main_browser
is
None
or
main_browser
.
HasDevTools
()
or
cef
.
GetBrowserByIdentifier
(
POPUP_BROWSER_ID
)
is
not
None
or
loading_progress
!=
1.0
):
return
False
return
all
(
value
for
obj
in
objects
for
key
,
value
in
obj
.
__dict__
.
items
()
if
"_True"
in
key
)
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
# The popup sub-test opens a window via window.open() during page
# load, i.e. without a user gesture, which Chrome blocks by default.
# This is a functional requirement of the test itself (not a CI
# workaround), so it applies on every platform.
switches
=
{
"disable-popup-blocking"
:
""
}
cef
.
Initialize
(
settings
,
switches
=
switches
)
# Ensure assertion and timeout failures still release CEF and its child
# processes. The explicit shutdown near the end uses this same helper,
# making the unittest cleanup a no-op on the success path.
cef_active
=
True
def
shutdown_cef
():
nonlocal
cef_active
if
cef_active
:
cef_active
=
False
cef
.
Shutdown
()
self
.
addCleanup
(
shutdown_cef
)
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"
)
# Exercise the external-loop MessageLoopWork() API until the complete
# asynchronous flow finishes: JavaScript opens a popup, the popup is
# destroyed, and its follow-up DevTools test succeeds. Browser and
# renderer startup duration varies between systems, so completion must
# not depend on a fixed number of message-loop iterations.
async_objects
=
client_handlers
+
[
global_handler
,
external
]
async_completed
=
run_message_loop_until
(
lambda
:
main_test_async_completed
(
global_handler
,
async_objects
,
display_handler2
.
OnLoadingProgressChange_Progress
))
self
.
assertTrue
(
async_completed
,
"Timed out waiting for load/JavaScript callbacks, popup "
"destruction and DevTools closure"
)
subtest_message
(
"cef.MessageLoopWork() ok"
)
# 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"
)
# CloseBrowser() is asynchronous. Process pending close work before
# checking callbacks and shutting CEF down. For synchronously created
# macOS browsers, OnBeforeClose may be deferred until Shutdown()
# (CEF issues #3469 and #3810).
do_message_loop_work
(
25
)
# Asserts before shutdown
self
.
assertEqual
(
display_handler2
.
OnLoadingProgressChange_Progress
,
1.0
)
# noinspection PyTypeChecker
check_auto_asserts
(
self
,
async_objects
)
# Test shutdown of CEF
shutdown_cef
()
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__
))
Back
|
FazBrowse Home
|
New Git URL