From 5eb6aa72f62f270fefc6a1f9b7613ec88394ec65 Mon Sep 17 00:00:00 2001 From: Shivanshu07 Date: Mon, 20 Apr 2026 11:21:19 +0530 Subject: [PATCH] feat: PER-7348 add waitForReady() call before serialize() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the readiness gate from percy/cli#2184. New waitForReady() helper runs PercyDOM.waitForReady via executeAsyncScript (callback signal) before the existing PercyDOM.serialize executeScript inside getSerializedDOM. Diagnostics are attached to the mutable snapshot as readiness_diagnostics. serialize is unchanged. Config precedence: options['readiness'] > cliConfig.snapshot.readiness > empty. Backward compat via in-browser typeof guard. Disabled preset short-circuits. Graceful on exception. Visibility: getSerializedDOM is now package-private so tests can call it directly; it was previously private. Tests (Mockito): diagnostics attached + readiness script contains waitForReady, disabled preset skips executeAsyncScript, readiness throw leaves serialize intact. Local: mvn test → 3 passed, 0 failed. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/main/java/io/percy/selenium/Percy.java | 58 ++++++++++++++- src/test/java/io/percy/selenium/SdkTest.java | 76 ++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/percy/selenium/Percy.java b/src/main/java/io/percy/selenium/Percy.java index 453c4bf..9489566 100644 --- a/src/main/java/io/percy/selenium/Percy.java +++ b/src/main/java/io/percy/selenium/Percy.java @@ -598,6 +598,54 @@ private String buildSnapshotJS(Map options) { return jsBuilder.toString(); } + /** + * Readiness gate (PER-7348): runs PercyDOM.waitForReady BEFORE serialize. + * + * Uses executeAsyncScript with a callback signal. The embedded JS checks + * typeof PercyDOM.waitForReady === 'function' so older CLI versions that + * lack the method are a graceful no-op. + * + * Readiness config precedence: options["readiness"] > cliConfig.snapshot.readiness + * > empty (CLI applies balanced default). "disabled" preset skips the + * executeAsyncScript call entirely. Any exception is swallowed at debug level; + * serialize still runs. + * + * @return Readiness diagnostics to attach to the domSnapshot, or null. + */ + protected Object waitForReady(JavascriptExecutor jse, Map options) { + Object perSnapshot = options != null ? options.get("readiness") : null; + JSONObject readinessConfig; + if (perSnapshot instanceof Map) { + readinessConfig = new JSONObject((Map) perSnapshot); + } else if (perSnapshot instanceof JSONObject) { + readinessConfig = (JSONObject) perSnapshot; + } else if (cliConfig != null) { + JSONObject snapshotConfig = cliConfig.optJSONObject("snapshot"); + readinessConfig = snapshotConfig == null ? new JSONObject() + : snapshotConfig.optJSONObject("readiness"); + if (readinessConfig == null) { readinessConfig = new JSONObject(); } + } else { + readinessConfig = new JSONObject(); + } + if ("disabled".equals(readinessConfig.optString("preset", null))) { + return null; + } + try { + String script = + "var cfg = " + readinessConfig.toString() + ";" + + "var done = arguments[arguments.length - 1];" + + "try {" + + " if (typeof PercyDOM !== 'undefined' && typeof PercyDOM.waitForReady === 'function') {" + + " PercyDOM.waitForReady(cfg).then(function(r){ done(r); }).catch(function(){ done(); });" + + " } else { done(); }" + + "} catch (e) { done(); }"; + return jse.executeAsyncScript(script); + } catch (Exception e) { + log("waitForReady failed, proceeding to serialize: " + e.getMessage(), "debug"); + return null; + } + } + static class FatalIframeException extends RuntimeException { FatalIframeException(String message, Throwable cause) { super(message, cause); @@ -673,10 +721,18 @@ private Map processFrame(WebElement frameElement, Map getSerializedDOM(JavascriptExecutor jse, Set cookies, Map options) { + Map getSerializedDOM(JavascriptExecutor jse, Set cookies, Map options) { + // Readiness gate before serialize (PER-7348). Graceful on old CLI. + Object readinessDiagnostics = waitForReady(jse, options); + Map domSnapshot = (Map) jse.executeScript(buildSnapshotJS(options)); Map mutableSnapshot = new HashMap<>(domSnapshot); mutableSnapshot.put("cookies", cookies); + + // Attach readiness diagnostics so the CLI can log timing and pass/fail + if (readinessDiagnostics != null) { + mutableSnapshot.put("readiness_diagnostics", readinessDiagnostics); + } try { String pageOrigin = getOrigin(driver.getCurrentUrl()); List iframes = driver.findElements(By.tagName("iframe")); diff --git a/src/test/java/io/percy/selenium/SdkTest.java b/src/test/java/io/percy/selenium/SdkTest.java index 7a92677..d891603 100644 --- a/src/test/java/io/percy/selenium/SdkTest.java +++ b/src/test/java/io/percy/selenium/SdkTest.java @@ -1109,6 +1109,82 @@ public void captureResponsiveDomRefreshesDriverForEachWidthWhenReloadFlagSet() t } } + // --- Readiness gate (PER-7348) ----------------------------------------- + + @Test + public void readinessRunsBeforeSerializeAndAttachesDiagnostics() throws Exception { + RemoteWebDriver mockedDriver = mock(RemoteWebDriver.class); + Percy mockedPercy = new Percy(mockedDriver); + setField(mockedPercy, "isPercyEnabled", true); + setField(mockedPercy, "cliConfig", new JSONObject().put("snapshot", new JSONObject())); + + Map diagnostics = new HashMap<>(); + diagnostics.put("ok", true); + diagnostics.put("timed_out", false); + // executeAsyncScript (readiness) + when(((JavascriptExecutor) mockedDriver).executeAsyncScript(any(String.class))).thenReturn(diagnostics); + // executeScript (serialize + any other sync scripts) + Map domSnap = new HashMap<>(); + domSnap.put("html", ""); + when(((JavascriptExecutor) mockedDriver).executeScript(any(String.class))).thenReturn(domSnap); + + Map result = mockedPercy.getSerializedDOM( + (JavascriptExecutor) mockedDriver, new HashSet<>(), new HashMap<>()); + + // Readiness script was sent via executeAsyncScript + ArgumentCaptor scriptCap = ArgumentCaptor.forClass(String.class); + verify((JavascriptExecutor) mockedDriver, atLeastOnce()).executeAsyncScript(scriptCap.capture()); + assertTrue(scriptCap.getValue().contains("waitForReady"), + "readiness script should mention waitForReady"); + // Diagnostics propagated to the snapshot + assertEquals(diagnostics, result.get("readiness_diagnostics")); + } + + @Test + public void readinessSkippedWhenPresetDisabled() throws Exception { + RemoteWebDriver mockedDriver = mock(RemoteWebDriver.class); + Percy mockedPercy = new Percy(mockedDriver); + setField(mockedPercy, "isPercyEnabled", true); + + Map domSnap = new HashMap<>(); + domSnap.put("html", ""); + when(((JavascriptExecutor) mockedDriver).executeScript(any(String.class))).thenReturn(domSnap); + + Map disabled = new HashMap<>(); + disabled.put("preset", "disabled"); + Map options = new HashMap<>(); + options.put("readiness", disabled); + + Map result = mockedPercy.getSerializedDOM( + (JavascriptExecutor) mockedDriver, new HashSet<>(), options); + + // executeAsyncScript must NOT have been called + verify((JavascriptExecutor) mockedDriver, never()).executeAsyncScript(any(String.class)); + // serialize still ran; no diagnostics attached + assertNull(result.get("readiness_diagnostics")); + } + + @Test + public void snapshotSurvivesReadinessThrow() throws Exception { + RemoteWebDriver mockedDriver = mock(RemoteWebDriver.class); + Percy mockedPercy = new Percy(mockedDriver); + setField(mockedPercy, "isPercyEnabled", true); + setField(mockedPercy, "cliConfig", new JSONObject().put("snapshot", new JSONObject())); + + when(((JavascriptExecutor) mockedDriver).executeAsyncScript(any(String.class))) + .thenThrow(new RuntimeException("readiness boom")); + Map domSnap = new HashMap<>(); + domSnap.put("html", ""); + when(((JavascriptExecutor) mockedDriver).executeScript(any(String.class))).thenReturn(domSnap); + + Map result = mockedPercy.getSerializedDOM( + (JavascriptExecutor) mockedDriver, new HashSet<>(), new HashMap<>()); + + // Serialize still ran; no diagnostics attached + assertNull(result.get("readiness_diagnostics")); + assertEquals("", result.get("html")); + } + private static Object invokePrivate(Object target, String methodName, Class[] paramTypes, Object... args) throws Exception { Method method = Percy.class.getDeclaredMethod(methodName, paramTypes);