diff --git a/src/client_handler/cookie_visitor.h b/src/client_handler/cookie_visitor.h index 0b990bac..e7d2c9c8 100644 --- a/src/client_handler/cookie_visitor.h +++ b/src/client_handler/cookie_visitor.h @@ -13,9 +13,9 @@ class CookieVisitor : public CefCookieVisitor { public: - int cookieVisitorId_; + int64_t cookieVisitorId_; public: - CookieVisitor(int cookieVisitorId) + CookieVisitor(int64_t cookieVisitorId) : cookieVisitorId_(cookieVisitorId) { } diff --git a/src/client_handler/resource_handler.h b/src/client_handler/resource_handler.h index fc81264a..6ae63c91 100644 --- a/src/client_handler/resource_handler.h +++ b/src/client_handler/resource_handler.h @@ -13,9 +13,9 @@ class ResourceHandler : public CefResourceHandler { public: - int resourceHandlerId_; + int64_t resourceHandlerId_; public: - ResourceHandler(int resourceHandlerId) + ResourceHandler(int64_t resourceHandlerId) : resourceHandlerId_(resourceHandlerId) { } diff --git a/src/client_handler/string_visitor.h b/src/client_handler/string_visitor.h index c36cf40f..633b82bc 100644 --- a/src/client_handler/string_visitor.h +++ b/src/client_handler/string_visitor.h @@ -13,9 +13,9 @@ class StringVisitor : public CefStringVisitor { public: - int stringVisitorId_; + int64_t stringVisitorId_; public: - StringVisitor(int stringVisitorId) + StringVisitor(int64_t stringVisitorId) : stringVisitorId_(stringVisitorId) { } diff --git a/src/client_handler/task.cpp b/src/client_handler/task.cpp index 62a9fcbf..6eecf536 100644 --- a/src/client_handler/task.cpp +++ b/src/client_handler/task.cpp @@ -7,7 +7,7 @@ #include "include/base/cef_bind.h" #include "include/base/cef_callback.h" -void PostTaskWrapper(int threadId, int taskId) { +void PostTaskWrapper(int threadId, int64_t taskId) { CefPostTask( static_cast(threadId), CefCreateClosureTask(base::BindOnce( @@ -17,7 +17,7 @@ void PostTaskWrapper(int threadId, int taskId) { ); } -void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int taskId) { +void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int64_t taskId) { CefPostDelayedTask( static_cast(threadId), CefCreateClosureTask(base::BindOnce( diff --git a/src/client_handler/task.h b/src/client_handler/task.h index a7d8c5b3..3a038f3b 100644 --- a/src/client_handler/task.h +++ b/src/client_handler/task.h @@ -8,8 +8,8 @@ #include "include/cef_cookie.h" #include "include/cef_task.h" -void PostTaskWrapper(int threadId, int taskId); -void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int taskId); +void PostTaskWrapper(int threadId, int64_t taskId); +void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int64_t taskId); CefRefPtr CreateTask_SetCookie( CefCookieManager* obj, diff --git a/src/client_handler/web_request_client.h b/src/client_handler/web_request_client.h index 8f5bce96..65e264d7 100644 --- a/src/client_handler/web_request_client.h +++ b/src/client_handler/web_request_client.h @@ -13,9 +13,9 @@ class WebRequestClient : public CefURLRequestClient { public: - int webRequestId_; + int64_t webRequestId_; public: - WebRequestClient(int webRequestId) : + WebRequestClient(int64_t webRequestId) : webRequestId_(webRequestId) { } virtual ~WebRequestClient(){} diff --git a/src/cookie.pyx b/src/cookie.pyx index 52c66e7f..8377c6a4 100644 --- a/src/cookie.pyx +++ b/src/cookie.pyx @@ -3,6 +3,7 @@ # Project website: https://github.com/cztomczak/cefpython include "cefpython.pyx" +from libc.stdint cimport int64_t from task cimport * @@ -28,7 +29,7 @@ cdef PyCookieManager g_globalCookieManager = None # See StoreUserCookieVisitor(). import weakref cdef object g_userCookieVisitors = weakref.WeakValueDictionary() -cdef int g_userCookieVisitorMaxId = 0 +cdef int64_t g_userCookieVisitorMaxId = 0 # ------------------------------------------------------------------------------ # Cookie @@ -232,7 +233,7 @@ cdef class PyCookieManager: cpdef py_bool VisitAllCookies(self, object userCookieVisitor): self.ValidateUserCookieVisitor(userCookieVisitor) - cdef int cookieVisitorId = StoreUserCookieVisitor(userCookieVisitor) + cdef int64_t cookieVisitorId = StoreUserCookieVisitor(userCookieVisitor) cdef CefRefPtr[CefCookieVisitor] cefCookieVisitor = ( new CookieVisitor( cookieVisitorId)) @@ -242,7 +243,7 @@ cdef class PyCookieManager: cpdef py_bool VisitUrlCookies(self, py_string url, py_bool includeHttpOnly, object userCookieVisitor): self.ValidateUserCookieVisitor(userCookieVisitor) - cdef int cookieVisitorId = StoreUserCookieVisitor(userCookieVisitor) + cdef int64_t cookieVisitorId = StoreUserCookieVisitor(userCookieVisitor) cdef CefRefPtr[CefCookieVisitor] cefCookieVisitor = ( new CookieVisitor( cookieVisitorId)) @@ -272,14 +273,14 @@ cdef class PyCookieManager: # PyCookieVisitor # ------------------------------------------------------------------------------ -cdef int StoreUserCookieVisitor(object userCookieVisitor) except *: +cdef int64_t StoreUserCookieVisitor(object userCookieVisitor) except *: global g_userCookieVisitorMaxId global g_userCookieVisitors g_userCookieVisitorMaxId += 1 g_userCookieVisitors[g_userCookieVisitorMaxId] = userCookieVisitor return g_userCookieVisitorMaxId -cdef PyCookieVisitor GetPyCookieVisitor(int cookieVisitorId): +cdef PyCookieVisitor GetPyCookieVisitor(int64_t cookieVisitorId): global g_userCookieVisitors cdef object userCookieVisitor cdef PyCookieVisitor pyCookieVisitor @@ -305,7 +306,7 @@ cdef class PyCookieVisitor: # ------------------------------------------------------------------------------ cdef public cpp_bool CookieVisitor_Visit( - int cookieVisitorId, + int64_t cookieVisitorId, const CefCookie& cookie, int count, int total, diff --git a/src/extern/cookie_visitor.pxd b/src/extern/cookie_visitor.pxd index e5ce8be4..3749a4b7 100644 --- a/src/extern/cookie_visitor.pxd +++ b/src/extern/cookie_visitor.pxd @@ -2,7 +2,9 @@ # All rights reserved. Licensed under BSD 3-clause license. # Project website: https://github.com/cztomczak/cefpython +from libc.stdint cimport int64_t + cdef extern from "client_handler/cookie_visitor.h": cdef cppclass CookieVisitor: - CookieVisitor(int cookieVisitorId) + CookieVisitor(int64_t cookieVisitorId) diff --git a/src/extern/resource_handler.pxd b/src/extern/resource_handler.pxd index 3467157a..6eab7189 100644 --- a/src/extern/resource_handler.pxd +++ b/src/extern/resource_handler.pxd @@ -2,7 +2,9 @@ # All rights reserved. Licensed under BSD 3-clause license. # Project website: https://github.com/cztomczak/cefpython +from libc.stdint cimport int64_t + cdef extern from "client_handler/resource_handler.h": cdef cppclass ResourceHandler: - ResourceHandler(int resourceHandlerId) + ResourceHandler(int64_t resourceHandlerId) diff --git a/src/extern/string_visitor.pxd b/src/extern/string_visitor.pxd index ec9e83de..501bfae2 100644 --- a/src/extern/string_visitor.pxd +++ b/src/extern/string_visitor.pxd @@ -2,7 +2,9 @@ # All rights reserved. Licensed under BSD 3-clause license. # Project website: https://github.com/cztomczak/cefpython +from libc.stdint cimport int64_t + cdef extern from "client_handler/string_visitor.h": cdef cppclass StringVisitor: - StringVisitor(int stringVisitorId) + StringVisitor(int64_t stringVisitorId) diff --git a/src/extern/task.pxd b/src/extern/task.pxd index 3c883ad9..17257d63 100644 --- a/src/extern/task.pxd +++ b/src/extern/task.pxd @@ -16,8 +16,8 @@ from libc.stdint cimport int64_t cdef extern from "client_handler/task.h": - void PostTaskWrapper(int threadId, int taskId) nogil - void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int taskId) nogil + void PostTaskWrapper(int threadId, int64_t taskId) nogil + void PostDelayedTaskWrapper(int threadId, int64_t delay_ms, int64_t taskId) nogil cdef CefRefPtr[CefTask] CreateTask_SetCookie( CefCookieManager* obj, diff --git a/src/extern/web_request_client.pxd b/src/extern/web_request_client.pxd index 0aaa124c..88b1772f 100644 --- a/src/extern/web_request_client.pxd +++ b/src/extern/web_request_client.pxd @@ -2,7 +2,9 @@ # All rights reserved. Licensed under BSD 3-clause license. # Project website: https://github.com/cztomczak/cefpython +from libc.stdint cimport int64_t + cdef extern from "client_handler/web_request_client.h": cdef cppclass WebRequestClient: - WebRequestClient(int webRequestId) + WebRequestClient(int64_t webRequestId) diff --git a/src/handlers/resource_handler.pyx b/src/handlers/resource_handler.pyx index ad559161..a7f62cfb 100644 --- a/src/handlers/resource_handler.pyx +++ b/src/handlers/resource_handler.pyx @@ -12,7 +12,7 @@ import weakref # See StoreUserCookieVisitor(). cdef object g_userResourceHandler = weakref.WeakValueDictionary() -cdef int g_userResourceHandlerMaxId = 0 +cdef int64_t g_userResourceHandlerMaxId = 0 # ----------------------------------------------------------------------------- @@ -34,20 +34,20 @@ cdef py_void ValidateUserResourceHandler(object userResourceHandler): cdef CefRefPtr[CefResourceHandler] CreateResourceHandler( object userResourceHandler) except *: ValidateUserResourceHandler(userResourceHandler) - cdef int resourceHandlerId = StoreUserResourceHandler(userResourceHandler) + cdef int64_t resourceHandlerId = StoreUserResourceHandler(userResourceHandler) cdef CefRefPtr[CefResourceHandler] resourceHandler =\ new ResourceHandler( resourceHandlerId) return resourceHandler -cdef int StoreUserResourceHandler(object userResourceHandler) except *: +cdef int64_t StoreUserResourceHandler(object userResourceHandler) except *: global g_userResourceHandlerMaxId global g_userResourceHandler g_userResourceHandlerMaxId += 1 g_userResourceHandler[g_userResourceHandlerMaxId] = userResourceHandler return g_userResourceHandlerMaxId -cdef PyResourceHandler GetPyResourceHandler(int resourceHandlerId): +cdef PyResourceHandler GetPyResourceHandler(int64_t resourceHandlerId): global g_userResourceHandler cdef object userResourceHandler cdef PyResourceHandler pyResourceHandler @@ -73,7 +73,7 @@ cdef class PyResourceHandler: # ------------------------------------------------------------------------------ cdef public cpp_bool ResourceHandler_ProcessRequest( - int resourceHandlerId, + int64_t resourceHandlerId, CefRefPtr[CefRequest] cefRequest, CefRefPtr[CefCallback] cefCallback ) noexcept with gil: @@ -100,7 +100,7 @@ cdef public cpp_bool ResourceHandler_ProcessRequest( sys.excepthook(exc_type, exc_value, exc_trace) cdef public void ResourceHandler_GetResponseHeaders( - int resourceHandlerId, + int64_t resourceHandlerId, CefRefPtr[CefResponse] cefResponse, int64_t& cefResponseLength, CefString& cefRedirectUrl @@ -132,7 +132,7 @@ cdef public void ResourceHandler_GetResponseHeaders( sys.excepthook(exc_type, exc_value, exc_trace) cdef public cpp_bool ResourceHandler_ReadResponse( - int resourceHandlerId, + int64_t resourceHandlerId, void* cefDataOut, int bytesToRead, int& cefBytesRead, @@ -183,7 +183,7 @@ cdef public cpp_bool ResourceHandler_ReadResponse( sys.excepthook(exc_type, exc_value, exc_trace) cdef public void ResourceHandler_Cancel( - int resourceHandlerId + int64_t resourceHandlerId ) noexcept with gil: cdef PyResourceHandler pyResourceHandler cdef object userCallback diff --git a/src/string_visitor.pyx b/src/string_visitor.pyx index ccf14819..c3da145e 100644 --- a/src/string_visitor.pyx +++ b/src/string_visitor.pyx @@ -3,6 +3,7 @@ # Project website: https://github.com/cztomczak/cefpython include "cefpython.pyx" +from libc.stdint cimport int64_t import weakref @@ -11,16 +12,16 @@ import weakref # ----------------------------------------------------------------------------- cdef object g_userStringVisitors = weakref.WeakValueDictionary() -cdef int g_userStringVisitorMaxId = 0 +cdef int64_t g_userStringVisitorMaxId = 0 -cdef int StoreUserStringVisitor(object userStringVisitor) except *: +cdef int64_t StoreUserStringVisitor(object userStringVisitor) except *: global g_userStringVisitorMaxId global g_userStringVisitors g_userStringVisitorMaxId += 1 g_userStringVisitors[g_userStringVisitorMaxId] = userStringVisitor return g_userStringVisitorMaxId -cdef PyStringVisitor GetUserStringVisitor(int stringVisitorId): +cdef PyStringVisitor GetUserStringVisitor(int64_t stringVisitorId): global g_userStringVisitors cdef object userStringVisitor cdef PyStringVisitor pyStringVisitor @@ -51,13 +52,13 @@ cdef CefRefPtr[CefStringVisitor] CreateStringVisitor( raise Exception("userStringVisitor object missing") if not hasattr(userStringVisitor, "Visit"): raise Exception("userStringVisitor object is missing Visit() method") - cdef int stringVisitorId = StoreUserStringVisitor(userStringVisitor) + cdef int64_t stringVisitorId = StoreUserStringVisitor(userStringVisitor) cdef CefRefPtr[CefStringVisitor] cefStringVisitor = ( new StringVisitor(stringVisitorId)) return cefStringVisitor cdef public void StringVisitor_Visit( - int stringVisitorId, + int64_t stringVisitorId, const CefString& string ) noexcept with gil: cdef str pyString diff --git a/src/task.pyx b/src/task.pyx index 72eefbad..786572b2 100644 --- a/src/task.pyx +++ b/src/task.pyx @@ -3,6 +3,7 @@ # Project website: https://github.com/cztomczak/cefpython include "cefpython.pyx" +from libc.stdint cimport int64_t g_taskMaxId = 0 g_tasks = {} @@ -29,7 +30,7 @@ def PostTask(int thread, object func, *args): } # Call C++ wrapper. - cdef int cTaskId = int(g_taskMaxId) + cdef int64_t cTaskId = int(g_taskMaxId) with nogil: PostTaskWrapper(thread, cTaskId) @@ -56,12 +57,12 @@ def PostDelayedTask(int thread, int delay_ms, object func, *args): } # Call C++ wrapper. - cdef int cTaskId = int(g_taskMaxId) + cdef int64_t cTaskId = int(g_taskMaxId) with nogil: PostDelayedTaskWrapper(thread, delay_ms, cTaskId) -cdef public void PyTaskRunnable(int taskId) noexcept with gil: +cdef public void PyTaskRunnable(int64_t taskId) noexcept with gil: cdef object func cdef list params cdef object task diff --git a/src/web_request.pyx b/src/web_request.pyx index acb9d56a..28290dfe 100644 --- a/src/web_request.pyx +++ b/src/web_request.pyx @@ -7,7 +7,7 @@ from libc.stdint cimport int64_t import weakref cdef object g_pyWebRequests = weakref.WeakValueDictionary() -cdef int g_webRequestMaxId = 0 +cdef int64_t g_webRequestMaxId = 0 # ----------------------------------------------------------------------------- # WebRequest @@ -61,7 +61,7 @@ cdef PyWebRequest CreatePyWebRequest(PyRequest request, g_pyWebRequests[webRequest.webRequestId] = webRequest return webRequest -cdef PyWebRequest GetPyWebRequest(int webRequestId): +cdef PyWebRequest GetPyWebRequest(int64_t webRequestId): global g_pyWebRequests if webRequestId in g_pyWebRequests: return g_pyWebRequests[webRequestId] @@ -69,7 +69,7 @@ cdef PyWebRequest GetPyWebRequest(int webRequestId): cdef class PyWebRequest: cdef object __weakref__ # see g_pyWebRequests - cdef int webRequestId + cdef int64_t webRequestId cdef CefRefPtr[CefURLRequest] cefWebRequest cdef object pyWebRequestClient @@ -121,7 +121,7 @@ cdef class PyWebRequest: # ----------------------------------------------------------------------------- cdef public void WebRequestClient_OnUploadProgress( - int webRequestId, + int64_t webRequestId, CefRefPtr[CefURLRequest] cefWebRequest, int64_t current, int64_t total @@ -142,7 +142,7 @@ cdef public void WebRequestClient_OnUploadProgress( sys.excepthook(exc_type, exc_value, exc_trace) cdef public void WebRequestClient_OnDownloadProgress( - int webRequestId, + int64_t webRequestId, CefRefPtr[CefURLRequest] cefWebRequest, int64_t current, int64_t total @@ -163,7 +163,7 @@ cdef public void WebRequestClient_OnDownloadProgress( sys.excepthook(exc_type, exc_value, exc_trace) cdef public void WebRequestClient_OnDownloadData( - int webRequestId, + int64_t webRequestId, CefRefPtr[CefURLRequest] cefWebRequest, const void* data, size_t dataLength @@ -183,7 +183,7 @@ cdef public void WebRequestClient_OnDownloadData( sys.excepthook(exc_type, exc_value, exc_trace) cdef public void WebRequestClient_OnRequestComplete( - int webRequestId, + int64_t webRequestId, CefRefPtr[CefURLRequest] cefWebRequest ) noexcept with gil: cdef PyWebRequest webRequest diff --git a/unittests/issue765.py b/unittests/issue765.py new file mode 100644 index 00000000..3f6bfc1e --- /dev/null +++ b/unittests/issue765.py @@ -0,0 +1,475 @@ +# Copyright (c) 2026 CEF Python, see the Authors file. +# All rights reserved. Licensed under BSD 3-clause license. +# Project website: https://github.com/cztomczak/cefpython + +""" +Automated regression test script for Issue #765 and PR #768. + +Validates 8 checks across the 7 subsystems where 32-bit ID counters are used: + 1a. PostTask (TID_UI) + 1b. PostDelayedTask (TID_UI) + 2. JavaScript callback (JS passing function to Python, Python executing it) + 3. Python callback (Python passing function to JS, JS executing it) + 4. ResourceHandler (custom URL intercept with payload verification) + 5. WebRequest (cef.WebRequest.Create to local server with status and payload verification) + 6. StringVisitor (frame.GetSource) + 7. CookieVisitor (specific cookie name/value verification via VisitAllCookies) + +Runs automatically on startup. Returns exit code 0 on success, exit code 1 on failure. +""" + +import http.server +import socketserver +import sys +import threading +import time +from cefpython3 import cefpython as cef + +# ----------------------------------------------------------------------------- +# Test Status Tracking +# ----------------------------------------------------------------------------- + +TEST_CHECKLIST = { + "1a_post_task": { + "title": "1a. PostTask", + "passed": False, + "detail": "" + }, + "1b_post_delayed_task": { + "title": "1b. PostDelayedTask", + "passed": False, + "detail": "" + }, + "2_js_callback": { + "title": "2. JavaScript callback (JS -> Python -> JS)", + "passed": False, + "detail": "" + }, + "3_py_callback": { + "title": "3. Python callback (Python -> JS -> Python)", + "passed": False, + "detail": "" + }, + "4_resource_handler": { + "title": "4. ResourceHandler (ProcessRequest & ReadResponse verified)", + "passed": False, + "detail": "" + }, + "5_web_request": { + "title": "5. WebRequest (status=Success & payload verified)", + "passed": False, + "detail": "" + }, + "6_string_visitor": { + "title": "6. StringVisitor (frame.GetSource)", + "passed": False, + "detail": "" + }, + "7_cookie_visitor": { + "title": "7. CookieVisitor ('test_issue765' cookie verified)", + "passed": False, + "detail": "" + }, +} + +g_browser = None +g_done = False +g_all_tests_passed = False +g_http_server = None +g_http_port = 0 + +# Strong references for CEF WeakValueDictionary registries +g_references = { + "handlers": [], + "web_requests": [], + "string_visitor": None, + "cookie_visitor": None, +} + + +def mark_test_passed(test_key, detail=""): + def _inner(): + if test_key in TEST_CHECKLIST and not TEST_CHECKLIST[test_key]["passed"]: + TEST_CHECKLIST[test_key]["passed"] = True + TEST_CHECKLIST[test_key]["detail"] = detail + print("[CHECKLIST PASS] %s %s" % ( + TEST_CHECKLIST[test_key]["title"], + ("(%s)" % detail) if detail else "" + )) + check_all_completed() + cef.PostTask(cef.TID_UI, _inner) + + +def print_final_report(): + print("\n" + "=" * 70) + print("CEF Python - Issue #765 / PR #768 Regression Test Report") + print("=" * 70) + all_ok = True + for key in sorted(TEST_CHECKLIST.keys()): + item = TEST_CHECKLIST[key] + status = "[PASS]" if item["passed"] else "[FAIL / TIMEOUT]" + if not item["passed"]: + all_ok = False + print(" %-16s %-48s %s" % (status, item["title"], item["detail"])) + print("=" * 70) + if all_ok: + print("SUCCESS: All 8 checks across 7 subsystems verified successfully!") + else: + print("FAILURE: Some tests did not complete or failed verification.") + print("=" * 70 + "\n") + return all_ok + + +def finish_testing(all_passed=True): + global g_done, g_browser, g_all_tests_passed + if g_done: + return + g_done = True + g_all_tests_passed = print_final_report() + if g_http_server: + threading.Thread(target=g_http_server.shutdown).start() + if g_browser: + g_browser.CloseBrowser(True) + cef.QuitMessageLoop() + + +def check_all_completed(): + if all(item["passed"] for item in TEST_CHECKLIST.values()): + cef.PostTask(cef.TID_UI, finish_testing, True) + + +def on_timeout(): + if not g_done: + print("[WARNING] Test suite timeout (10s) reached.") + finish_testing(False) + + +# ----------------------------------------------------------------------------- +# Local HTTP Server (For genuine CefURLRequest / WebRequest verification) +# ----------------------------------------------------------------------------- + +WEBREQUEST_PAYLOAD = b"WebRequest Verified Payload for Issue #765" + + +class LocalHttpHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/webrequest.txt": + self.send_response(200) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", str(len(WEBREQUEST_PAYLOAD))) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(WEBREQUEST_PAYLOAD) + else: + self.send_response(404) + self.end_headers() + + def log_message(self, format, *args): + pass # Suppress HTTP server logging + + +def start_local_http_server(): + global g_http_server, g_http_port + g_http_server = socketserver.TCPServer(("127.0.0.1", 0), LocalHttpHandler) + g_http_port = g_http_server.server_address[1] + t = threading.Thread(target=g_http_server.serve_forever) + t.daemon = True + t.start() + + +# ----------------------------------------------------------------------------- +# 1a. PostTask & 1b. PostDelayedTask +# ----------------------------------------------------------------------------- + +def task_callback(msg): + mark_test_passed("1a_post_task", "executed on TID_UI: %s" % msg) + + +def delayed_task_callback(msg): + mark_test_passed("1b_post_delayed_task", "executed with 50ms delay: %s" % msg) + + +# ----------------------------------------------------------------------------- +# 2. JavaScript Callback & 3. Python Callback +# ----------------------------------------------------------------------------- + +def my_python_callback(response_from_js): + """ + Executed when JavaScript invokes the Python callback function passed to it. + Tests 3: Python callback executed (PutPythonCallback / ExecutePythonCallback). + """ + if response_from_js == "Response sent from V8 JavaScript engine": + mark_test_passed("3_py_callback", "V8 called Python callback with valid payload") + else: + print("[FAIL] Python callback received unexpected: %s" % response_from_js) + + +def py_setup_callbacks(js_callback): + """ + Called from JavaScript. Receives js_callback (cef.JavascriptCallback). + Tests 2: JS callback received (PutJavascriptCallback). + Calls js_callback passing my_python_callback as argument, which tests + passing Python callbacks to JavaScript via IPC. + """ + mark_test_passed("2_js_callback", "Python received and calling js_callback") + js_callback.Call(my_python_callback) + + +# ----------------------------------------------------------------------------- +# 4. ResourceHandler +# ----------------------------------------------------------------------------- + +HTML_PAGE_CONTENT = b""" + +Test Issue #765 + +

Test Runner: Issue #765 ID Check

+
Running tests...
+ + + + +""" + +MESSAGE_CONTENT = b"Custom ResourceHandler Content for Issue #765" + + +class CustomResourceHandler(object): + def __init__(self, data, mime_type="text/plain"): + self.offset = 0 + self.data = data + self.mime_type = mime_type + + def ProcessRequest(self, request, callback): + callback.Continue() + return True + + def GetResponseHeaders(self, response, response_length_out, redirect_url_out): + response.SetStatus(200) + response.SetMimeType(self.mime_type) + response_length_out[0] = len(self.data) + + def ReadResponse(self, data_out, bytes_to_read, bytes_read_out, callback): + if self.offset < len(self.data): + chunk = self.data[self.offset:self.offset + bytes_to_read] + self.offset += len(chunk) + data_out[0] = chunk + bytes_read_out[0] = len(chunk) + return True + else: + bytes_read_out[0] = 0 + return False + + def Cancel(self): + pass + + +def py_notify_resource_handler_content(content): + if content.encode("utf-8") == MESSAGE_CONTENT: + mark_test_passed("4_resource_handler", "Content verified end-to-end (%d bytes)" % len(content)) + else: + print("[FAIL] ResourceHandler content mismatch: %r" % content) + + +class RequestHandler(object): + def GetResourceHandler(self, browser, frame, request): + url = request.GetUrl() + handler = None + if "test-resource-handler.local/index.html" in url: + handler = CustomResourceHandler(HTML_PAGE_CONTENT, "text/html") + elif "test-resource-handler.local/message.txt" in url: + handler = CustomResourceHandler(MESSAGE_CONTENT, "text/plain") + if handler: + g_references["handlers"].append(handler) + return handler + + +# ----------------------------------------------------------------------------- +# 5. WebRequest +# ----------------------------------------------------------------------------- + +class CustomWebRequestClient(object): + def __init__(self): + self.received_data = b"" + + def OnUploadProgress(self, web_request, current, total): + pass + + def OnDownloadProgress(self, web_request, current, total): + pass + + def OnDownloadData(self, web_request, data): + if data: + self.received_data += data + + def OnRequestComplete(self, web_request): + status = web_request.GetRequestStatus() + success_status = cef.WebRequest.Status["Success"] + if status == success_status and self.received_data == WEBREQUEST_PAYLOAD: + mark_test_passed("5_web_request", "status=Success, payload verified (%d bytes)" % len(self.received_data)) + else: + print("[FAIL] WebRequest failed: status=%s (expected %s), data=%r" % ( + status, success_status, self.received_data + )) + + +def run_web_request_test(): + request = cef.Request.CreateRequest() + request.SetUrl("http://127.0.0.1:%d/webrequest.txt" % g_http_port) + client = CustomWebRequestClient() + web_request = cef.WebRequest.Create(request, client) + g_references["web_requests"].append((web_request, client)) + + +# ----------------------------------------------------------------------------- +# 6. StringVisitor (GetSource) +# ----------------------------------------------------------------------------- + +class CustomStringVisitor(object): + def Visit(self, value): + if "Test Issue #765" in value: + mark_test_passed("6_string_visitor", "Visited & validated HTML source (%d chars)" % len(value)) + else: + print("[FAIL] StringVisitor received unexpected HTML source") + + +# ----------------------------------------------------------------------------- +# 7. CookieVisitor (VisitAllCookies) +# ----------------------------------------------------------------------------- + +class CustomCookieVisitor(object): + def __init__(self): + self.found = False + + def Visit(self, cookie, count, total, delete_cookie_out): + if cookie.GetName() == "test_issue765" and cookie.GetValue() == "int64_val": + self.found = True + mark_test_passed("7_cookie_visitor", "Verified cookie 'test_issue765'='int64_val'") + return False # Target cookie found, stop iteration + return True + + +def run_cookie_test(): + manager = cef.CookieManager.GetGlobalManager() + cookie = cef.Cookie() + cookie.Set({ + "name": "test_issue765", + "value": "int64_val", + "domain": "test-resource-handler.local", + "path": "/", + "secure": False, + "httpOnly": False, + "hasExpires": False + }) + manager.SetCookie("http://test-resource-handler.local/", cookie) + + def do_visit(): + g_references["cookie_visitor"] = CustomCookieVisitor() + manager.VisitAllCookies(g_references["cookie_visitor"]) + + cef.PostDelayedTask(cef.TID_UI, 250, do_visit) + + +# ----------------------------------------------------------------------------- +# CEF Client Handlers +# ----------------------------------------------------------------------------- + +class LoadHandler(object): + def __init__(self): + self.tests_started = False + + def OnLoadingStateChange(self, browser, is_loading, **_): + if not is_loading and not self.tests_started: + self.tests_started = True + frame = browser.GetMainFrame() + + # 6. StringVisitor: request HTML source + g_references["string_visitor"] = CustomStringVisitor() + frame.GetSource(g_references["string_visitor"]) + + # Trigger JS-side tests (initiates py_setup_callbacks and fetch) + frame.ExecuteJavascript("start_js_tests();") + + # 5. WebRequest: initiate web request + cef.PostDelayedTask(cef.TID_UI, 150, run_web_request_test) + + +# ----------------------------------------------------------------------------- +# Main Execution +# ----------------------------------------------------------------------------- + +def main(): + global g_browser + + print("=" * 70) + print("Starting automated tests for Issue #765 / PR #768...") + print("=" * 70) + + start_local_http_server() + + sys.excepthook = cef.ExceptHook + settings = {} + cef.Initialize(settings) + + # Setup JS Bindings + bindings = cef.JavascriptBindings(bindToFrames=True, bindToPopups=True) + bindings.SetFunction("py_setup_callbacks", py_setup_callbacks) + bindings.SetFunction("py_notify_resource_handler_content", py_notify_resource_handler_content) + + # Create Browser loading our intercepted local domain + g_browser = cef.CreateBrowserSync( + url="http://test-resource-handler.local/index.html", + window_title="Test Issue #765 IDs" + ) + g_browser.SetJavascriptBindings(bindings) + g_browser.SetClientHandler(LoadHandler()) + g_browser.SetClientHandler(RequestHandler()) + + # 1a. PostTask test + cef.PostTask(cef.TID_UI, task_callback, "Immediate Task") + + # 1b. PostDelayedTask test + cef.PostDelayedTask(cef.TID_UI, 50, delayed_task_callback, "Delayed Task") + + # 7. CookieVisitor test + cef.PostDelayedTask(cef.TID_UI, 100, run_cookie_test) + + # 10s safety timeout to avoid hanging + cef.PostDelayedTask(cef.TID_UI, 10000, on_timeout) + + cef.MessageLoop() + cef.Shutdown() + + if not g_all_tests_passed: + sys.exit(1) + else: + sys.exit(0) + + +if __name__ == "__main__": + main()