Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions percy/screenshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,42 @@ def process_frame(page, frame, options, percy_dom_script):
return None


def _wait_for_ready(page, kwargs):
"""Run readiness checks before serialize. PER-7348.

Uses page.evaluate (sync Playwright auto-awaits Promises). The embedded
JS checks typeof PercyDOM.waitForReady === 'function' so old CLI versions
without the method are a graceful no-op.

Returns readiness diagnostics dict or None, to be attached to the
domSnapshot.

Readiness config precedence: kwargs['readiness'] > cached
percy.config.snapshot.readiness > {} (CLI applies balanced default).
"""
readiness_config = kwargs.get('readiness')
if readiness_config is None:
data = _is_percy_enabled()
if isinstance(data, dict):
readiness_config = (data.get('config') or {}).get('snapshot', {}).get('readiness', {}) or {}
else:
readiness_config = {}
if isinstance(readiness_config, dict) and readiness_config.get('preset') == 'disabled':
return None
try:
return page.evaluate(
"(cfg) => {"
" if (typeof PercyDOM !== 'undefined' && typeof PercyDOM.waitForReady === 'function') {"
" return PercyDOM.waitForReady(cfg);"
" }"
"}",
readiness_config,
)
except Exception as e:
log(f'waitForReady failed, proceeding to serialize: {e}', 'debug')
return None


def get_serialized_dom(page, cookies, percy_dom_script=None, **kwargs):
"""
Serializes the DOM and captures cross-origin iframes.
Expand All @@ -166,7 +202,12 @@ def get_serialized_dom(page, cookies, percy_dom_script=None, **kwargs):
Returns:
Dictionary containing the DOM snapshot with cross-origin iframe data
"""
# Readiness gate before serialize (PER-7348). Graceful on old CLI.
readiness_diagnostics = _wait_for_ready(page, kwargs)
dom_snapshot = page.evaluate(f"PercyDOM.serialize({json.dumps(kwargs)})")
# Attach readiness diagnostics so the CLI can log timing and pass/fail
if readiness_diagnostics and isinstance(dom_snapshot, dict):
dom_snapshot['readiness_diagnostics'] = readiness_diagnostics

# Process CORS IFrames
# Note: Blob URL handling (data-src images, blob background images) is now handled
Expand Down
63 changes: 63 additions & 0 deletions tests/test_screenshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,69 @@ def test_raise_error_poa_token_with_snapshot(self):
str(context.exception),
)

# --- Readiness gate (PER-7348) ---------------------------------------

def test_readiness_runs_before_serialize_by_default(self):
mock_healthcheck()
mock_snapshot()

with patch.object(self.page, 'evaluate', wraps=self.page.evaluate) as spy:
percy_snapshot(self.page, 'readiness-happy-path')

scripts = [c.args[0] for c in spy.call_args_list if c.args and isinstance(c.args[0], str)]
# Readiness evaluate fires first (contains waitForReady)
self.assertTrue(any('waitForReady' in s for s in scripts),
f'expected readiness script, got: {scripts}')
self.assertTrue(any('PercyDOM.serialize' in s for s in scripts),
f'expected serialize script, got: {scripts}')
readiness_idx = next(i for i, s in enumerate(scripts) if 'waitForReady' in s)
serialize_idx = next(i for i, s in enumerate(scripts) if 'PercyDOM.serialize' in s)
self.assertLess(readiness_idx, serialize_idx)

def test_readiness_uses_per_snapshot_config(self):
mock_healthcheck()
mock_snapshot()
readiness = {'preset': 'strict', 'stabilityWindowMs': 500}

with patch.object(self.page, 'evaluate', wraps=self.page.evaluate) as spy:
percy_snapshot(self.page, 'readiness-config', readiness=readiness)

# Find the readiness evaluate call and assert the config arg
for call in spy.call_args_list:
if call.args and isinstance(call.args[0], str) and 'waitForReady' in call.args[0]:
self.assertEqual(call.args[1], readiness)
return
self.fail('readiness evaluate call not found')

def test_readiness_skipped_when_preset_disabled(self):
mock_healthcheck()
mock_snapshot()

with patch.object(self.page, 'evaluate', wraps=self.page.evaluate) as spy:
percy_snapshot(self.page, 'readiness-disabled',
readiness={'preset': 'disabled'})

scripts = [c.args[0] for c in spy.call_args_list if c.args and isinstance(c.args[0], str)]
self.assertFalse(any('waitForReady' in s for s in scripts))
self.assertTrue(any('PercyDOM.serialize' in s for s in scripts))

def test_snapshot_still_posts_when_readiness_raises(self):
mock_healthcheck()
mock_snapshot()

orig_evaluate = self.page.evaluate

def side_effect(script, *args, **kwargs):
if isinstance(script, str) and 'waitForReady' in script:
raise RuntimeError('readiness boom')
return orig_evaluate(script, *args, **kwargs)

with patch.object(self.page, 'evaluate', side_effect=side_effect):
percy_snapshot(self.page, 'readiness-boom')

paths = [req.path for req in httpretty.latest_requests()]
self.assertIn('/percy/snapshot', paths)


class TestPercyFunctions(unittest.TestCase):
@patch("requests.get")
Expand Down
Loading