diff --git a/README.md b/README.md index dbdf2a057..652f885f6 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ to heavy tools like Selenium or Puppeteer — all without relying on WebDriver. * **No external dependencies** – kdriver interacts directly with the browser using WebSockets and JSON — no need for Chromium wrappers or native libraries. * **Session and cookie management** – Start with a clean profile every time or load/save cookies between runs. +* **Remote browsers** – Attach to a browser behind a reverse proxy; CSS lookups run in the page and never transfer the + whole document (see [how lookups work](docs/home/quickstart.md#how-lookups-work)). * **Element utilities** – Coming soon: intuitive APIs to query, interact with, and wait for DOM elements. ## Motivation diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index ec98cef4c..463507635 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -19,12 +19,28 @@ import kotlin.random.Random */ open class DefaultElement( val tab: Tab, - override var node: DOM.Node, - override var tree: DOM.Node? = null, + node: DOM.Node, + tree: DOM.Node? = null, ) : Element { private val logger = KtorSimpleLogger("Element") + private val binding = ElementBinding(node, tree) + + /** + * The node of this element. For an element found in the page (no [tree]), the first read after the document was + * read, while the page has not changed since, takes the document's node of the same backend node id, with its node + * ids and parent id, as a lookup on the document gave it, when it holds the same subtree (see [ElementBinding]). + */ + override var node: DOM.Node + get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).node + set(value) = binding.replaceNode(value) + + /** The document this element was read from: for an element found in the page, filled as [node] is. */ + override var tree: DOM.Node? + get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).tree + set(value) = binding.replaceTree(value) + private var remoteObject: Runtime.RemoteObject? = null // The node the cached [remoteObject] was resolved for: [rawApply] reuses the object only while [node] is still @@ -90,6 +106,17 @@ open class DefaultElement( override val attrs: List get() = node.attributes?.chunked(2)?.map { it.first() } ?: emptyList() + /** + * Binds an element found in the page (no node id, no [tree]) to the whole document, as [update] does, without + * resolving its object again: [node] becomes the document's node of the same backend node id, with its node ids, + * and [tree] the document. Used before a lookup under this element, which queries it by node id. + */ + internal suspend fun bindToDocument() { + val doc = currentDocument() + doc.filterRecurse { it.backendNodeId == node.backendNodeId }?.let { node = it } + tree = doc + } + override suspend fun updateRemoteObject(): Runtime.RemoteObject? { val resolvedFor = backendNodeId remoteObject = tab.dom.resolveNode(backendNodeId = resolvedFor).`object` @@ -158,59 +185,7 @@ open class DefaultElement( private suspend fun getStableCoordinates(): CoordinateResult? { return try { apply( - jsFunction = """ - function() { - if (!this || !this.isConnected) return null; - - return new Promise(resolve => { - let lastTop = null; - let lastLeft = null; - let stableFrames = 0; - const maxAttempts = 10; - let attempts = 0; - - const checkStable = () => { - attempts++; - const rect = this.getBoundingClientRect(); - - if (rect.width === 0 || rect.height === 0) { - resolve(null); - return; - } - - if (lastTop !== null && - Math.abs(rect.top - lastTop) < 1 && - Math.abs(rect.left - lastLeft) < 1) { - stableFrames++; - if (stableFrames >= 2) { - resolve({ - x: rect.left + rect.width / 2, - y: rect.top + rect.height / 2 - }); - return; - } - } else { - stableFrames = 0; - } - - lastTop = rect.top; - lastLeft = rect.left; - - if (attempts < maxAttempts) { - requestAnimationFrame(checkStable); - } else { - // Timeout: use current position - resolve({ - x: rect.left + rect.width / 2, - y: rect.top + rect.height / 2 - }); - } - }; - - requestAnimationFrame(checkStable); - }); - } - """.trimIndent(), + jsFunction = STABLE_COORDINATES_JS, awaitPromise = true ) } catch (e: EvaluateException) { diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt new file mode 100644 index 000000000..401add9ef --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt @@ -0,0 +1,52 @@ +package dev.kdriver.core.dom + +import dev.kdriver.cdp.domain.DOM +import dev.kdriver.core.tab.DefaultTab + +/** + * The node and the document of a [DefaultElement], and the binding of an element found in the page to the document + * [DefaultTab] keeps from its last read, when it still matches the page, without any command: node ids, [tree] and + * parent are then those a lookup on the document gave. The document's node is taken only when it holds the same + * subtree as the one found (ids aside), so a read never changes what the element shows. Each kept document is looked + * at once; without one, the element stays as found until `update` or a lookup under it. + */ +internal class ElementBinding(node: DOM.Node, tree: DOM.Node?) { + + var node: DOM.Node = node + private set + + var tree: DOM.Node? = tree + private set + + // The epoch of the kept document the last binding attempt looked at. + private var checkedAt: Long = NOT_CHECKED + + fun replaceNode(value: DOM.Node) { + node = value + checkedAt = NOT_CHECKED + } + + fun replaceTree(value: DOM.Node?) { + tree = value + checkedAt = NOT_CHECKED + } + + /** Binds to [kept] when this element has no tree yet and [kept] was not looked at; returns this binding. */ + fun bindFrom(kept: DefaultTab.DocumentSnapshot?): ElementBinding { + if (tree == null && kept != null && kept.epoch != checkedAt) { + checkedAt = kept.epoch + val found = node + val documentNode = kept.nodeOf(found.backendNodeId) + if (documentNode != null && documentNode.withoutIds() == found.withoutIds()) { + tree = kept.root + node = documentNode + } + } + return this + } + + private companion object { + // No kept document looked at yet: epochs are never negative. + const val NOT_CHECKED = -1L + } +} diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt index 4784eb872..dde375da6 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt @@ -91,3 +91,18 @@ val Input.MouseButton.buttonsMask: Int Input.MouseButton.FORWARD -> 16 Input.MouseButton.NONE -> 0 } + +/** + * This node and its subtree without their node ids and parent ids: two reads of the same unchanged nodes, one by + * `DOM.describeNode` and one by `DOM.getDocument`, are then equal. + */ +internal fun DOM.Node.withoutIds(): DOM.Node = copy( + nodeId = 0, + parentId = null, + children = children?.map { it.withoutIds() }, + contentDocument = contentDocument?.withoutIds(), + shadowRoots = shadowRoots?.map { it.withoutIds() }, + pseudoElements = pseudoElements?.map { it.withoutIds() }, + templateContent = templateContent?.withoutIds(), + importedDocument = importedDocument?.withoutIds(), +) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt new file mode 100644 index 000000000..c5490da28 --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt @@ -0,0 +1,59 @@ +package dev.kdriver.core.dom + +/** + * The function [DefaultElement] applies to an element to read its coordinates once its position is stable across + * several frames; it resolves null when the element is detached or has no size. + */ +internal val STABLE_COORDINATES_JS = """ + function() { + if (!this || !this.isConnected) return null; + + return new Promise(resolve => { + let lastTop = null; + let lastLeft = null; + let stableFrames = 0; + const maxAttempts = 10; + let attempts = 0; + + const checkStable = () => { + attempts++; + const rect = this.getBoundingClientRect(); + + if (rect.width === 0 || rect.height === 0) { + resolve(null); + return; + } + + if (lastTop !== null && + Math.abs(rect.top - lastTop) < 1 && + Math.abs(rect.left - lastLeft) < 1) { + stableFrames++; + if (stableFrames >= 2) { + resolve({ + x: rect.left + rect.width / 2, + y: rect.top + rect.height / 2 + }); + return; + } + } else { + stableFrames = 0; + } + + lastTop = rect.top; + lastLeft = rect.left; + + if (attempts < maxAttempts) { + requestAnimationFrame(checkStable); + } else { + // Timeout: use current position + resolve({ + x: rect.left + rect.width / 2, + y: rect.top + rect.height / 2 + }); + } + }; + + requestAnimationFrame(checkStable); + }); + } +""".trimIndent() diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 3cc9ead1c..9184c7963 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -1,11 +1,13 @@ package dev.kdriver.core.tab import dev.kdriver.cdp.CDPException +import dev.kdriver.cdp.CommandMode import dev.kdriver.cdp.Serialization import dev.kdriver.cdp.domain.* import dev.kdriver.cdp.domain.Input import dev.kdriver.core.browser.Browser import dev.kdriver.core.connection.DefaultConnection +import dev.kdriver.core.connection.PendingCommand import dev.kdriver.core.dom.DefaultElement import dev.kdriver.core.dom.Element import dev.kdriver.core.dom.NodeOrElement @@ -19,19 +21,25 @@ import io.ktor.util.logging.* import io.ktor.utils.io.core.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem +import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement import kotlin.concurrent.Volatile import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.math.abs +import kotlin.random.Random import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds @@ -404,10 +412,14 @@ open class DefaultTab( while (true) { val items = mutableListOf() if (includeFrames) { - val frames = querySelectorAll("iframe") - for (fr in frames) items.addAll(fr.querySelectorAll(trimmedSelector)) + // Searching inside the frames reads the document (Element.querySelectorAll), so the whole lookup goes + // through it, as before: the frames and the page's own matches share the kept read while the page + // does not change. + for (fr in querySelectorAllInDocument("iframe")) items.addAll(fr.querySelectorAll(trimmedSelector)) + items.addAll(querySelectorAllInDocument(trimmedSelector)) + } else { + items.addAll(querySelectorAll(trimmedSelector)) } - items.addAll(querySelectorAll(trimmedSelector)) items.takeIf { it.isNotEmpty() }?.let { return it } val elapsed = Clock.System.now().toEpochMilliseconds() - startTime @@ -443,8 +455,212 @@ open class DefaultTab( selector: String, node: NodeOrElement?, ): List = - if (node == null) onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } - else querySelectorAllInternal(selector, node, retried = false, rootOf(node)) + if (node == null) querySelectorAllInPage(selector) + else bound(node).let { querySelectorAllInternal(selector, it, retried = false, rootOf(it)) } + + // querySelectorAll on the whole document read (kept while the page has not changed): the frames of + // selectAll(includeFrames = true), which need the document to be searched. + private suspend fun querySelectorAllInDocument(selector: String): List = + onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } + + /** + * `document.querySelectorAll(selector)` run by the page, each match then described with its subtree: see + * [Tab.querySelectorAll]. One round trip when nothing matches (the page answers `null`), otherwise three: the + * evaluation, the array's own properties, then every description and the release of the objects, sent together. + * + * When the matches' subtrees hold more elements than the whole document (nested matches, a selector matching most + * of the page), the page answers `"document"` instead, and the lookup reads the document, which is then the smaller + * transfer. The count stops as soon as it passes the document's, so the page never walks much more than once its + * own size. The script uses no global of the page but `document.querySelectorAll` and `getElementsByTagName`. + */ + private suspend fun querySelectorAllInPage(selector: String): List = inLookupGroup { group -> + val found = evaluateInGroup( + group, + "(() => { const all = document.querySelectorAll(${jsStringLiteral(selector)});" + + " if (!all.length) return null;" + + " const most = document.getElementsByTagName('*').length; const matches = []; let described = 0;" + + " for (let i = 0; i < all.length; i++) {" + + " described += 1 + all[i].getElementsByTagName('*').length;" + + " if (described > most) return 'document'; matches[i] = all[i]; }" + + " return matches; })()", + protocolMethod = "DOM.querySelectorAll", + ) ?: return@inLookupGroup emptyList() + val arrayId = found.objectId ?: return@inLookupGroup querySelectorAllInDocument(selector) + val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true) } + ?: return@inLookupGroup emptyList() + val matches = properties.result + .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } + .sortedBy { it.first } + .mapNotNull { (_, value) -> value?.objectId } + describeAndRelease(group, matches)?.map { DefaultElement(this, it) } ?: emptyList() + } + + /** + * `document.querySelector(selector)` run by the page, the match then described with its subtree: see + * [Tab.querySelector]. Two round trips when something matches (the evaluation, then the description and the + * release of the object, sent together), one otherwise. + */ + private suspend fun querySelectorInPage(selector: String): Element? = inLookupGroup { group -> + val match = evaluateInGroup( + group, + "document.querySelector(${jsStringLiteral(selector)})", + protocolMethod = "DOM.querySelector", + )?.objectId ?: return@inLookupGroup null + describeAndRelease(group, listOf(match))?.single()?.let { DefaultElement(this, it) } + } + + /** + * The objects an in-page lookup creates in the page (the match, or the array and its matches), all in one group + * named after the lookup, and the release of that group once it is sent. + */ + private class LookupGroup(val name: String) { + var holdsObjects = false + var release: PendingCommand? = null + } + + /** + * Runs [lookup] with a [LookupGroup] of its own, then releases the group, so that a lookup leaves no object behind + * in the page, on every path, cancellation included: an element found in the page resolves its node at its first + * call, as an element read from the document does. The release is a cleanup: it runs under NonCancellable, waits + * [LOOKUP_RELEASE_WAIT] at most, and none of its failures fails the lookup (the page drops the objects at its next + * navigation anyway). + */ + private suspend fun inLookupGroup(lookup: suspend (LookupGroup) -> T): T { + val group = LookupGroup("kdriver-lookup-${Random.nextLong().toULong().toString(LOOKUP_GROUP_RADIX)}") + try { + return lookup(group) + } finally { + if (group.holdsObjects) releaseLookupGroup(group) + } + } + + // The cleanup of [inLookupGroup], a function of its own: a cancellation of the wait goes on from here. + private suspend fun releaseLookupGroup(group: LookupGroup) { + withContext(NonCancellable) { + withTimeoutOrNull(LOOKUP_RELEASE_WAIT) { + try { + val sent = group.release + if (sent != null) sent.await() else runtime.releaseObjectGroup(group.name) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Already gone with the page, or the connection is closing: nothing left to release. + } + } + } + } + + /** + * [evaluateLookup] with the objects it creates in [group]. The group counts as holding objects from the moment the + * evaluation is sent, so that one cut while in flight (cancelled, timed out, connection lost), which the page may + * still run, is released all the same; once the page answered, only when it returned an object. + */ + private suspend fun evaluateInGroup( + group: LookupGroup, + expression: String, + protocolMethod: String, + ): Runtime.RemoteObject? { + group.holdsObjects = true + val found = try { + evaluateLookup(expression, protocolMethod, objectGroup = group.name) + } catch (e: CDPException) { + group.holdsObjects = false // answered with an error: nothing was created + throw e + } catch (e: EvaluateException) { + group.holdsObjects = false // the script threw: nothing was returned + throw e + } + group.holdsObjects = found?.objectId != null + return found + } + + /** + * Describes [objectIds] with their subtrees (`DOM.describeNode`, depth -1, piercing), then releases [group]: the + * descriptions and the release are sent one after the other, so the browser runs them in that order, in one round + * trip. Null when a match is gone before it was described (the page navigated during the lookup: no match at all, + * rather than a part of the old page's); any other error is thrown, once every reply has been read. + */ + private suspend fun describeAndRelease(group: LookupGroup, objectIds: List): List? { + val describing = objectIds.map { objectId -> + sendCommand("DOM.describeNode", describeParameter(objectId), CommandMode.DEFAULT) + } + group.release = sendCommand("Runtime.releaseObjectGroup", releaseParameter(group.name), CommandMode.DEFAULT) + val described = describing.map { pending -> awaitDescription(pending) } + described.firstNotNullOfOrNull { it.exceptionOrNull() }?.let { throw it } + val nodes = described.map { it.getOrNull() } + return if (null in nodes) null else nodes.filterNotNull() + } + + // The node of a description sent by describeAndRelease: a success holding null when the match is gone, a failure + // holding any other error, so that every reply is read before one is thrown. + private suspend fun awaitDescription(pending: PendingCommand): Result = + try { + Result.success( + unlessGone { pending.await() } + ?.let { Serialization.json.decodeFromJsonElement(it).node } + ) + } catch (e: CancellationException) { + throw e + } catch (expected: Exception) { + // Not swallowed: handed back as the failure, so that every reply is read before one is thrown. + Result.failure(expected) + } + + private fun describeParameter(objectId: String): JsonElement = + Serialization.json.encodeToJsonElement( + DOM.DescribeNodeParameter(objectId = objectId, depth = -1, pierce = true) + ) + + private fun releaseParameter(group: String): JsonElement = + Serialization.json.encodeToJsonElement(Runtime.ReleaseObjectGroupParameter(objectGroup = group)) + + /** + * Evaluates [expression] in the page and returns the object or string it yields, or null when it yields neither + * (`null`). The objects it creates go to [objectGroup] when given. + * + * An invalid selector makes the page throw a `SyntaxError`: it is thrown as the error the browser gives + * [protocolMethod] (`DOM.querySelector` or `DOM.querySelectorAll`) for that selector, a [CDPException] with code + * -32000 and the message "DOM Error while querying", after disabling the DOM agent, as a lookup on the document + * did. Any other exception of the page (a page that replaced `document.querySelector`) is thrown as an + * [EvaluateException]. + */ + private suspend fun evaluateLookup( + expression: String, + protocolMethod: String, + objectGroup: String? = null, + ): Runtime.RemoteObject? { + val evaluated = unlessGone { runtime.evaluate(expression = expression, objectGroup = objectGroup) } + ?: return null + evaluated.exceptionDetails?.let { details -> + if (details.isSyntaxError()) { + disableDomAgent() + throw CDPException(protocolMethod, INVALID_SELECTOR_CODE, INVALID_SELECTOR_MESSAGE, null) + } + throw EvaluateException(details) + } + return evaluated.result.takeIf { it.objectId != null || it.type == "string" } + } + + // The `SyntaxError` the page throws for a selector it cannot parse: a DOMException, not an error a script threw. + private fun Runtime.ExceptionDetails.isSyntaxError(): Boolean = + exception?.className == "DOMException" && exception?.description?.startsWith("SyntaxError") == true + + /** + * Runs [command] of an in-page lookup, or returns null when the browser no longer knows what it refers to: the + * object or the execution context was dropped by a navigation in between, so the lookup found nothing and `select` + * tries again. Any other protocol error is thrown. + */ + private suspend fun unlessGone(command: suspend () -> T): T? = + try { + command() + } catch (e: CDPException) { + if (GONE.any { e.originalMessage.contains(it, ignoreCase = true) }) null else throw e + } + + // A JavaScript string literal for [value]: its JSON encoding, which escapes quotes, backslashes and control + // characters, so the value can only ever be read as one string. + private fun jsStringLiteral(value: String): String = + Serialization.json.encodeToString(String.serializer(), value) // `retried` carries the "already retried once" state across the recursive call. It must be a // parameter, not a local: a local would be reset on every recursion and the guard would never @@ -487,9 +703,30 @@ open class DefaultTab( ): Element? { val trimmedSelector = selector.trim() return if (node == null) { - onDocument { doc -> querySelectorInternal(trimmedSelector, null, retried = false, doc) } + querySelectorInPage(trimmedSelector) } else { - querySelectorInternal(trimmedSelector, node, retried = false, rootOf(node)) + bound(node).let { querySelectorInternal(trimmedSelector, it, retried = false, rootOf(it)) } + } + } + + /** + * [node] ready for a lookup under it, which queries it by node id. A node found in the page has none yet (see + * [Tab.querySelector]): it is first bound to the document, an element filled from it + * ([DefaultElement.bindToDocument], [Element.update] for another implementation), a bare node replaced by the + * document's node of the same backend node id. + */ + private suspend fun bound(node: NodeOrElement): NodeOrElement { + if (node.node.nodeId != 0) return node + return when (node) { + is NodeOrElement.WrappedElement -> { + val element = node.element + if (element is DefaultElement) element.bindToDocument() else element.update() + node + } + + is NodeOrElement.WrappedNode -> currentDocument().first + .filterRecurse { it.backendNodeId == node.node.backendNodeId } + ?.let { NodeOrElement.WrappedNode(it) } ?: node } } @@ -497,23 +734,21 @@ open class DefaultTab( private fun rootOf(node: NodeOrElement): DOM.Node = if (node.node.nodeName == "IFRAME") node.node.contentDocument ?: node.node else node.node - // See querySelectorAllInternal: `retried` must be a parameter so the retry-once guard survives - // the recursive call (ISSUE-7). + // A lookup under [node] (the page runs the lookups on the whole document). See querySelectorAllInternal: + // `retried` must be a parameter so the retry-once guard survives the recursive call (ISSUE-7). private suspend fun querySelectorInternal( selector: String, - node: NodeOrElement?, + node: NodeOrElement, retried: Boolean, doc: DOM.Node, ): Element? { val nodeId = try { dom.querySelector(doc.nodeId, selector) } catch (e: Exception) { - if (node != null && e.message?.contains("could not find node", ignoreCase = true) == true) { + if (e.message?.contains("could not find node", ignoreCase = true) == true) { if (retried) return null if (node is NodeOrElement.WrappedElement) node.element.update() return querySelectorInternal(selector, node, retried = true, rootOf(node)) - } else if (e.message?.contains("could not find node", ignoreCase = true) == true) { - return null } else { disableDomAgent() throw e @@ -530,7 +765,24 @@ open class DefaultTab( * The last whole document read for a lookup (`DOM.getDocument(depth = -1, pierce = true)`), and the * [documentEpoch] it still matches the page at. */ - private class DocumentSnapshot(val root: DOM.Node, val epoch: Long) + internal class DocumentSnapshot(val root: DOM.Node, val epoch: Long) { + + private val byBackendNodeId: Map by lazy { + buildMap { + fun index(node: DOM.Node) { + for (child in node.children.orEmpty()) { + if (child.backendNodeId !in this) put(child.backendNodeId, child) + child.shadowRoots?.firstOrNull()?.let { index(it) } + index(child) + } + } + index(root) + } + } + + /** The node of [backendNodeId] in this document, as `root.filterRecurse` finds it, from an index built once. */ + fun nodeOf(backendNodeId: Int): DOM.Node? = byBackendNodeId[backendNodeId] + } @Volatile private var documentSnapshot: DocumentSnapshot? = null @@ -545,10 +797,17 @@ open class DefaultTab( * @return the root of the document, and whether it is the copy kept from an earlier read. */ internal suspend fun currentDocument(): Pair { - documentSnapshot?.takeIf { it.epoch == documentEpoch }?.let { return it.root to true } + keptDocument()?.let { return it.root to true } return readDocument() to false } + /** + * The document kept from an earlier read while it still matches the page, without reading anything: null when + * there is none. The properties of an element found in the page take their node ids and tree from it on their + * first read ([DefaultElement.node], [DefaultElement.tree]). + */ + internal fun keptDocument(): DocumentSnapshot? = documentSnapshot?.takeIf { it.epoch == documentEpoch } + private suspend fun readDocument(): DOM.Node { val before = documentEpoch val root = dom.getDocument(-1, true).root @@ -835,3 +1094,28 @@ open class DefaultTab( } } + +/** + * Error texts of the browser for an object, a node or an execution context it no longer knows (a navigation dropped + * it): "Could not find object with given id", "No node with given id found", "Cannot find context with specified id", + * "Execution context was destroyed". Not "Inspected target navigated or closed", also sent for a closed tab, which is + * an error and not a lookup to try again. + */ +private val GONE = listOf( + "could not find object", + "could not find node", + "no node with given id", + "cannot find context", + "context was destroyed", +) + +/** How long the release of the objects of an in-page lookup may hold the lookup, at most, in milliseconds. */ +private const val LOOKUP_RELEASE_WAIT = 2_000L + +// The base of the random suffix of a lookup group's name (hexadecimal). +private const val LOOKUP_GROUP_RADIX = 16 + +/** The code and message Chrome answers `DOM.querySelector(All)` with for a selector it cannot parse. */ +private const val INVALID_SELECTOR_CODE = -32000 +private const val INVALID_SELECTOR_MESSAGE = "DOM Error while querying" + diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index e8b74fd6a..ca8cd4cf1 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -294,6 +294,9 @@ interface Tab : Connection { * * This method waits for the element to appear in the DOM, retrying every 500 milliseconds until the timeout is reached. * + * The page runs the selector, and the element's node ids and tree are filled on demand: see + * [querySelector] for how lookups work. + * * @param selector The CSS selector of the element to select. * @param timeout The maximum time in milliseconds to wait for the element to appear. Defaults to 10 seconds. * @@ -329,6 +332,10 @@ interface Tab : Connection { * * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * + * The page runs the selector, and the elements' node ids and tree are filled on demand: see + * [querySelector] for how lookups work. With [includeFrames], `selectAll` reads the whole document instead + * (searching inside the frames needs it), for the page's own matches too: they then have a node id and a tree. + * * @param selector CSS selector, e\.g\., `a[href]`, `button[class*=close]`, `a > img[src]` * @param timeout Raise timeout exception when after this many milliseconds nothing is found. * @param includeFrames Whether to include results in iframes. @@ -375,6 +382,13 @@ interface Tab : Connection { * * It returns all matching [Element] objects. * + * Without [node], the page runs `document.querySelectorAll` and the matches are described together, in document + * order: one round trip when nothing matches, three otherwise (the evaluation, the list of matches, then every + * description at once, with the release of the objects the lookup created). The elements are as for + * [querySelector]. When the matches' subtrees would hold more elements than the whole + * document (nested matches, a selector matching most of the page), the document is read instead, as before, and + * the elements then have their node ids and tree. + * * @param selector CSS selector. (first time? See https://www.w3schools.com/cssref/css_selectors.php) * @param node For internal use. The node to start the search from. Defaults to the document root. * @@ -388,6 +402,41 @@ interface Tab : Connection { /** * Finds a single element based on a CSS selector string. * + * ## How lookups work + * + * Without [node] (and in [select], [selectAll] and [querySelectorAll] without it), the page runs the selector: + * `document.querySelector` is evaluated (`Runtime.evaluate`, the selector entering the script only as a JSON string + * literal), then only the match is described, with its subtree (`DOM.describeNode`, depth -1, piercing), and the + * object the page returned is released in the same round trip. The whole document is never read: two small round + * trips when something matches, one otherwise, whatever the size of the page. + * + * The element found: + * - has its node and subtree: [Element.tag], [Element.text], [Element.textAll], attributes, + * [Element.children] and [Element.backendNodeId] read as from a document; + * - keeps no object of the page: its first call (`click`, `apply`, …) resolves its node, as before; + * - gets its node ids and tree on demand: the first read of `node`, [Element.tree], [Element.parentId] or + * [Element.parent] takes them from the document kept by an earlier read ([find], [xpath], a lookup under an + * element, [Element.update]…) while the page has not changed since, with no command; a lookup under the element + * ([Element.querySelector], or a [NodeOrElement] passed back here) binds it first by itself. These are plain + * properties, so their read cannot fetch the document on its own: without such a document, `node.nodeId` and + * the node ids of its subtree may be 0, [Element.parentId] and [Element.tree] are null and [Element.parent] + * throws, until [Element.update] reads the document. The document's node is taken only when it holds the same + * subtree as the one found, so a read elsewhere never changes what the element shows. + * + * What else differs from reading the document: + * - the page's own `document.querySelector` runs: a page that replaces it changes the result; + * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends + * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner; the DOM + * agent is not enabled either, so a `DOM.disable` sent by hand then fails, as on a tab that never read it. + * + * Unchanged: shadow roots and iframes are not searched; an invalid selector throws the + * [dev.kdriver.cdp.CDPException] the browser gives `DOM.querySelector` (code -32000, "DOM Error while querying"), + * `DOM.querySelectorAll` for the other methods; a node or execution context dropped by a navigation during the + * lookup counts as no match, so [select] tries again (for [querySelectorAll], none of the old page's matches is + * returned). + * + * Lookups under a node or an element, [find], [findAll] and [xpath] read the document, as before. + * * @param selector CSS selector(s). * @param node For internal use. The node to start the search from. Defaults to the document root. * diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt index b4f5bdbf9..b2213681a 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt @@ -25,11 +25,10 @@ import kotlin.test.assertSame import kotlin.test.assertTrue /** - * A lookup on the whole document ([DefaultTab.select], [DefaultTab.selectAll], [DefaultTab.find], - * [DefaultTab.findAll], [DefaultTab.querySelector], [DefaultTab.querySelectorAll], `Element.update`) reads the document - * again only when the page may have changed since the last read: a `DOM.*` event, a command that makes the browser - * forget its node ids, or a reconnect. Otherwise a new read would return the same tree, and the round trip (the whole - * tree, often a megabyte) is saved. + * A lookup that reads the whole document ([DefaultTab.selectAll] with frames, [DefaultTab.find], [DefaultTab.findAll], + * `Element.update`, a lookup under an element found in the page) reads it again only when the page may have changed + * since the last read: a `DOM.*` event, a command that makes the browser forget its node ids, or a reconnect. + * Otherwise a new read would return the same tree, and the round trip (the whole tree, often a megabyte) is saved. */ class DocumentReuseTest { @@ -53,7 +52,9 @@ class DocumentReuseTest { "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO, latency = 10) "DOM.getDocument" -> Reply.ok(document, latency = 10) "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""", latency = 10) - "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[7,9]}""", latency = 10) + "DOM.querySelectorAll" -> + if (it.params.toString().contains("iframe")) Reply.ok("""{"nodeIds":[]}""", latency = 10) + else Reply.ok("""{"nodeIds":[7,9]}""", latency = 10) "DOM.performSearch" -> Reply.ok("""{"searchId":"s1","resultCount":1}""", latency = 10) "DOM.getSearchResults" -> Reply.ok("""{"nodeIds":[8]}""", latency = 10) "DOM.resolveNode" -> Reply.ok(objectReply("obj-${it.id}"), latency = 10) @@ -70,15 +71,18 @@ class DocumentReuseTest { private val ScriptedTransport.documentReads get() = methods.count { it == "DOM.getDocument" } + // A selector lookup that reads the document: selectAll with frames (none on this page), then the page's matches. + private suspend fun ScriptedTab.lookUp() = selectAll("#go", timeout = 1_000, includeFrames = true).first() + @Test - fun select_onAnUnchangedPage_readsTheDocumentOnce() = runTest(StandardTestDispatcher()) { + fun aLookup_onAnUnchangedPage_readsTheDocumentOnce() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - val first = tab.select("#go", timeout = 1_000) - val second = tab.select("#go", timeout = 1_000) + val first = tab.lookUp() + val second = tab.lookUp() assertEquals(1, transport.documentReads) - assertEquals(2, transport.methods.count { it == "DOM.querySelector" }) + assertEquals(4, transport.methods.count { it == "DOM.querySelectorAll" }, "frames, then the page, twice") assertEquals("Send", second.text) assertEquals(first.backendNodeId, second.backendNodeId) assertSame(first.tree, second.tree, "both elements sit in the same, unchanged tree") @@ -89,7 +93,7 @@ class DocumentReuseTest { fun selectAll_findAll_andUpdate_shareTheDocumentOfAnUnchangedPage() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - val all = tab.selectAll("button, li", timeout = 1_000) + val all = tab.selectAll("button, li", timeout = 1_000, includeFrames = true) val found = tab.findAll("Send", timeout = 1_000) all.first().update() @@ -103,10 +107,10 @@ class DocumentReuseTest { fun aDomEventBetweenLookups_makesTheNextOneReadTheDocumentAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(2, transport.documentReads) tab.close() @@ -116,10 +120,10 @@ class DocumentReuseTest { fun otherEvents_doNotMakeTheDocumentStale() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() transport.event("Network.dataReceived", """{"requestId":"r","timestamp":1,"dataLength":1}""") runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(1, transport.documentReads) tab.close() @@ -129,11 +133,11 @@ class DocumentReuseTest { fun disablingTheDomAgent_makesTheNextLookupReadTheDocumentAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.dom.disable() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.find("Send", timeout = 1_000) // disables the agent when it is done - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(3, transport.documentReads, "the find used the document kept since the second select") tab.close() @@ -143,9 +147,9 @@ class DocumentReuseTest { fun aDocumentReadByHand_makesTheNextLookupReadItAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.dom.getDocument(depth = 1) - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(3, transport.documentReads) tab.close() @@ -162,9 +166,9 @@ class DocumentReuseTest { } transport = t - assertEquals("Send", tab.select("#go", timeout = 1_000).text) - tab.select("#go", timeout = 1_000) - tab.select("#go", timeout = 1_000) + assertEquals("Send", tab.lookUp().text) + tab.lookUp() + tab.lookUp() assertEquals(2, transport.documentReads, "read again once, then kept") tab.close() @@ -175,7 +179,7 @@ class DocumentReuseTest { var queries = 0 lateinit var transport: ScriptedTransport val (tab, t) = scripted { - if (it.method == "DOM.querySelector" && ++queries == 2) { + if (it.method == "DOM.querySelectorAll" && ++queries == 3) { transport.event( "DOM.childNodeInserted", """{"parentNodeId":1,"previousNodeId":7,"node":{"nodeId":11,"backendNodeId":110,"nodeType":1,""" + @@ -185,12 +189,15 @@ class DocumentReuseTest { } transport = t - tab.select("#go", timeout = 1_000) - val again = tab.select("#go", timeout = 1_000) + tab.lookUp() + val again = tab.lookUp() assertEquals("Send", again.text) assertEquals( - listOf("DOM.getDocument", "DOM.querySelector", "DOM.querySelector", "DOM.getDocument", "DOM.querySelector"), + listOf( + "DOM.getDocument", "DOM.querySelectorAll", "DOM.querySelectorAll", + "DOM.querySelectorAll", "DOM.getDocument", "DOM.querySelectorAll", "DOM.querySelectorAll", + ), transport.methods.filter { it.startsWith("DOM.") }, ) tab.close() @@ -199,16 +206,21 @@ class DocumentReuseTest { @Test fun aChangeReportedDuringALookupOnAFreshRead_doesNotRepeatIt() = runTest(StandardTestDispatcher()) { lateinit var transport: ScriptedTransport + var queries = 0 val (tab, t) = scripted { - if (it.method == "DOM.querySelector") { + if (it.method == "DOM.querySelectorAll" && ++queries == 1) { transport.event("DOM.attributeModified", """{"nodeId":7,"name":"a","value":"b"}""") } } transport = t - tab.select("#go", timeout = 1_000) + tab.lookUp() - assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), transport.methods.filter { it.startsWith("DOM.") }) + assertEquals( + listOf("DOM.getDocument", "DOM.querySelectorAll", "DOM.getDocument", "DOM.querySelectorAll"), + transport.methods.filter { it.startsWith("DOM.") }, + "the query of the frames, on a fresh read, is not repeated; the next query reads the changed page", + ) tab.close() } @@ -226,10 +238,10 @@ class DocumentReuseTest { override fun createTransport(): WebSocketTransport = if (opened++ == 0) transports[0] else next() } - tab.select("#go", timeout = 1_000) + tab.lookUp() transports[0].close() runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(2, transports.size, "the second lookup ran on a new session") assertEquals(1, transports[1].documentReads) @@ -240,14 +252,14 @@ class DocumentReuseTest { fun anInvalidSelector_onAKeptDocument_stillThrowsTheBrowserError() = runTest(StandardTestDispatcher()) { val normal = page() val transport = ScriptedTransport(this) { - if (it.method == "DOM.querySelector" && it.params.toString().contains("li[")) { + if (it.method == "DOM.querySelectorAll" && it.params.toString().contains("li[")) { Reply.error("DOM Error while querying", latency = 10) } else normal(it) } val tab = ScriptedTab(this, transport) - tab.select("#go", timeout = 1_000) - assertFailsWith { tab.select("li[", timeout = 0) } + tab.lookUp() + assertFailsWith { tab.selectAll("li[", timeout = 0, includeFrames = true) } assertEquals(1, transport.documentReads, "the failing lookup used the kept document") assertTrue(transport.methods.contains("DOM.disable"), "and the agent is disabled on the error, as before") diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt index 02e686f82..376dd07d1 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt @@ -37,14 +37,16 @@ class LookupBehaviourTest { } @Test - fun select_returnsTheElementWithItsTextAttributesTreeAndParent() = withPage { + fun select_returnsTheElementWithItsTextAttributes_andTreeAndParentOnceUpdated() = withPage { val item = select("li[data-rank='2']", timeout = 5_000) assertEquals("li", item.tag) assertEquals("Beta", item.text) assertEquals("2", item["data-rank"]) assertEquals(listOf("class", "data-rank"), item.attrs) - assertNotNull(item.tree, "a looked-up element knows the document it is in") + assertNull(item.tree, "the page ran the lookup: no document was read") + item.update() + assertNotNull(item.tree, "an updated element knows the document it is in") assertEquals("ul", item.parent?.tag) assertEquals("list", item.parent?.get("id")) assertEquals(listOf("Alpha", "Beta", "Gamma"), item.parent!!.children.filter { it.tag == "li" }.map { it.text }) @@ -205,6 +207,7 @@ class LookupBehaviourTest { fun lookupsKeepWorking_afterTheDomAgentWasDisabledByHand() = withPage { assertEquals("Alpha", select("li[data-rank='1']", timeout = 5_000).text) + dom.enable() // a lookup run by the page does not enable the DOM agent; a document read did dom.disable() rawEvaluate("document.querySelector(\"li[data-rank='1']\").textContent = 'Omega'") @@ -219,6 +222,6 @@ class LookupBehaviourTest { val again = select("li[data-rank='1']", timeout = 5_000) assertEquals("Alpha", again.text) - assertTrue(again.tree != null) + assertTrue(again.update().tree != null) } } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt new file mode 100644 index 000000000..506c667ed --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -0,0 +1,244 @@ +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.cdp.domain.DOM +import dev.kdriver.cdp.domain.dom +import dev.kdriver.core.browser.Browser +import dev.kdriver.core.browser.createBrowser +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.sampleFile +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.runBlocking +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * On a real page, the lookups the page runs (`select`, `selectAll`, `querySelector`, `querySelectorAll` without a + * node) find what a lookup on the whole document finds (`DOM.getDocument`, then `DOM.querySelector(All)` on it, as + * these methods did before): the same elements, text, attributes, children and order, the same absence inside shadow + * roots and frames, elements that can be clicked; once updated, the same node ids, tree and parent; and for an invalid + * selector, the same exception. + */ +class LookupsInPageBehaviourTest { + + private fun onPage(block: suspend Tab.() -> Unit) = runBlocking { + val browser: Browser = createBrowser(this as CoroutineScope, headless = true, sandbox = false) + try { + browser.get(sampleFile("lookup-test.html")).apply { + // Both reads compared below must see the whole page: wait for it to be parsed and loaded first. + waitForReadyState(ReadyState.COMPLETE) + }.block() + } finally { + browser.stop() + } + } + + // A lookup on the whole document, as these methods did before: the document read, then queried by node id. + private suspend fun Tab.allOnTheDocument(selector: String): List = + querySelectorAll(selector, NodeOrElement.WrappedNode(dom.getDocument(depth = -1, pierce = true).root)) + + private suspend fun Tab.oneOnTheDocument(selector: String): Element? = + querySelector(selector, NodeOrElement.WrappedNode(dom.getDocument(depth = -1, pierce = true).root)) + + private fun Element.seen() = listOf(tag, text, textAll, attrs.joinToString(), backendNodeId.toString()) + + @Test + fun select_findsWhatTheDocumentLookupFinds() = onPage { + val before = oneOnTheDocument("li[data-rank='2']")!! + + val item = select("li[data-rank='2']", timeout = 5_000) + + assertEquals(before.seen(), item.seen()) + assertEquals(listOf("li", "Beta", "Beta", "class, data-rank"), item.seen().take(4)) + assertNull(item.objectId, "the lookup left no object in the page") + } + + @Test + fun select_findsTheSameChildren() = onPage { + val before = oneOnTheDocument("#list")!!.children.map { it.seen() } + + val children = select("#list", timeout = 5_000).children.map { it.seen() } + + assertEquals(before, children) + assertEquals(3, children.count { it.first() == "li" }) + } + + @Test + fun selectAll_findsTheSameElements_inTheSameOrder() = onPage { + val before = allOnTheDocument(".item").map { it.seen() } + + val items = selectAll(".item", timeout = 5_000).map { it.seen() } + + assertEquals(before, items) + assertEquals(listOf("Alpha", "Beta", "Gamma"), items.map { it[1] }) + } + + @Test + fun noMatch_isNoMatch() = onPage { + assertEquals(emptyList(), allOnTheDocument(".nowhere")) + assertEquals(emptyList(), querySelectorAll(".nowhere")) + assertNull(oneOnTheDocument(".nowhere")) + assertNull(querySelector(".nowhere")) + } + + @Test + fun shadowRoots_areNotPierced() = onPage { + assertEquals(emptyList(), allOnTheDocument("#shadowed")) + assertEquals(emptyList(), querySelectorAll("#shadowed")) + assertFailsWith { select("#shadowed", timeout = 0) } + } + + @Test + fun frames_areNotSearched_butSelectAllWithFramesSearchesThem() = onPage { + assertNull(oneOnTheDocument("p.inner")) + assertNull(querySelector("p.inner")) + val inFrames = selectAll("p.inner", timeout = 5_000, includeFrames = true) + assertEquals(listOf("Inside the frame"), inFrames.map { it.text }) + } + + @Test + fun aFoundElementCanBeClickedAndRead() = onPage { + rawEvaluate( + "document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'" + ) + + select("#panel", timeout = 5_000).click() + + assertEquals("open", select("#panel", timeout = 5_000)["data-state"]) + } + + @Test + fun anElementOfSelectAll_keepsNoObject_andCanBeClicked() = onPage { + rawEvaluate("document.getElementById('label').onclick = (e) => e.target.textContent = 'Hit'") + val label = selectAll("#label", timeout = 5_000).single() + + assertNull(label.objectId, "the objects of the lookup were released") + label.click() + + assertEquals("Hit", select("#label", timeout = 5_000).text) + } + + @Test + fun selectAll_readsTheDocument_whenTheMatchesOutweighIt() = onPage { + val before = allOnTheDocument("html, body").map { it.seen() } + + val outer = selectAll("html, body", timeout = 5_000) + + assertEquals(before, outer.map { it.seen() }) + assertTrue(outer.all { it.node.nodeId != 0 && it.tree != null }, "read from the document, as before") + } + + @Test + fun select_seesTheNewDocumentAfterANavigation() = onPage { + rawEvaluate("document.getElementById('title').textContent = 'Changed'") + assertEquals("Changed", select("#title", timeout = 5_000).text) + + reload() + + assertEquals("Lookup", select("#title", timeout = 5_000).text) + } + + @Test + fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = onPage { + val item = select("li[data-rank='3']", timeout = 5_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.parentId) + assertNull(item.tree) + assertFailsWith { item.parent } + + item.update() + + assertNotEquals(0, item.node.nodeId) + assertEquals("ul", item.parent?.tag) + } + + @Test + fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_onceTheDocumentWasRead() = onPage { + selectAll("p.inner", timeout = 5_000, includeFrames = true) // the frame loaded: the read below stays current + val (tree, _) = (this as DefaultTab).currentDocument() + val onTheSameRead = querySelector("li[data-rank='3']", NodeOrElement.WrappedNode(tree))!! + + val item = select("li[data-rank='3']", timeout = 5_000) + + assertEquals(onTheSameRead.node, item.node, "node, subtree and node ids of the document read") + assertEquals(tree, item.tree) + assertEquals(onTheSameRead.parentId, item.parentId) + assertEquals("ul", item.parent?.tag) + assertEquals(item.node.nodeId, dom.querySelector(tree.nodeId, "li[data-rank='3']").nodeId, "a live node id") + } + + @Test + fun update_givesTheNodeIdsTreeAndParent_theDocumentLookupGives() = onPage { + selectAll("p.inner", timeout = 5_000, includeFrames = true) // the frame loaded: both reads see the same page + // The same lookup on the whole document, read first: a later read gives every node a new id, so ids are + // compared below on the document the update read, and everything else on this earlier read. + val before = oneOnTheDocument("li[data-rank='3']")!! + val item = select("li[data-rank='3']", timeout = 5_000) + + item.update() + + val tree = assertNotNull(item.tree) + val onTheSameRead = querySelector("li[data-rank='3']", NodeOrElement.WrappedNode(tree))!! + assertEquals(onTheSameRead.node, item.node, "node, subtree and node ids of the document read") + assertEquals(onTheSameRead.parentId, item.parentId) + assertEquals(onTheSameRead.parent!!.node, item.parent!!.node) + assertEquals(item.node.nodeId, dom.querySelector(tree.nodeId, "li[data-rank='3']").nodeId, "a live node id") + assertEquals(item.node.parentId, item.parent!!.node.nodeId) + assertEquals(before.node.withoutIds(), item.node.withoutIds()) + assertEquals(before.parent!!.node.withoutIds(), item.parent!!.node.withoutIds()) + assertEquals(before.tree!!.withoutIds(), tree.withoutIds()) + } + + @Test + fun aLookupUnderAnElementFoundInThePage_bindsItFirst() = onPage { + val list = select("#list", timeout = 5_000) + + assertEquals("Gamma", list.querySelector("li[data-rank='3']")?.text) + assertEquals(listOf("Alpha", "Beta", "Gamma"), list.querySelectorAll("li").map { it.text }) + assertNotNull(list.tree) + assertEquals("body", list.parent?.tag) + } + + @Test + fun anInvalidSelector_throwsTheSameExceptionAsTheDocumentLookup() = onPage { + for (selector in listOf("li[", "", "a:unknown-pseudo")) { + val document = dom.getDocument(depth = -1, pierce = true).root + val one = assertFailsWith { dom.querySelector(document.nodeId, selector) } + val all = assertFailsWith { dom.querySelectorAll(document.nodeId, selector) } + + val ones = listOf Unit>({ select(selector, timeout = 0) }, { querySelector(selector) }) + for (lookup in ones) assertSameError(one, assertFailsWith { lookup() }) + val alls = listOf Unit>({ selectAll(selector, timeout = 0) }, { querySelectorAll(selector) }) + for (lookup in alls) assertSameError(all, assertFailsWith { lookup() }) + } + } + + private fun assertSameError(expected: CDPException, actual: CDPException) { + assertEquals(expected.method, actual.method) + assertEquals(expected.code, actual.code) + assertEquals(expected.originalMessage, actual.originalMessage) + assertEquals(expected.data, actual.data) + assertEquals(expected.message, actual.message) + } + + // The node and its subtree with every node id and parent id cleared: what two reads of the same page share. + private fun DOM.Node.withoutIds(): DOM.Node = copy( + nodeId = 0, + parentId = null, + children = children?.map { it.withoutIds() }, + contentDocument = contentDocument?.withoutIds(), + shadowRoots = shadowRoots?.map { it.withoutIds() }, + pseudoElements = pseudoElements?.map { it.withoutIds() }, + templateContent = templateContent?.withoutIds(), + importedDocument = importedDocument?.withoutIds(), + ) + +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt new file mode 100644 index 000000000..a644ec195 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt @@ -0,0 +1,338 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The elements `select`, `selectAll`, `querySelector` and `querySelectorAll` find in the page get their node ids, tree + * and parent from the document when they are updated, read after the document was read, or when a lookup runs under + * them; a frame is searched with the page from one document read. + */ +class LookupsInPageBindingTest: LookupsInPageFixtures() { + + + private val documentWithAFrame = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":2,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"P",""" + + """"localName":"p","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Outer"}]},""" + + """{"nodeId":9,"backendNodeId":90,"nodeType":1,"nodeName":"IFRAME","localName":"iframe","nodeValue":"",""" + + """"childNodeCount":0,"contentDocument":{"nodeId":10,"backendNodeId":100,"nodeType":9,""" + + """"nodeName":"#document","localName":"","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":11,"backendNodeId":110,"nodeType":1,"nodeName":"P","localName":"p","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":12,"backendNodeId":120,"nodeType":3,"nodeName":"#text",""" + + """"localName":"","nodeValue":"Inner"}]}]}}]}}""" + + @Test + fun selectAllWithAFrame_findsInsideItAndInThePage_fromOneDocumentRead() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "DOM.getDocument" -> Reply.ok(documentWithAFrame) + "DOM.querySelectorAll" -> when (it.param("nodeId")) { + "1" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") + else Reply.ok("""{"nodeIds":[7]}""") + "10" -> Reply.ok("""{"nodeIds":[11]}""") + else -> Reply.error("Could not find node with given id") + } + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"frame"}}""") + else -> Reply.ok() + } + } + + val found = tab.selectAll("p", timeout = 1_000, includeFrames = true) + + assertEquals(listOf("Inner", "Outer"), found.map { it.text }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frame and the page") + assertTrue("Runtime.evaluate" !in tab.sent) + tab.close() + } + + @Test + fun selectAllWithFrames_readsTheDocument() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelectorAll" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") + else Reply.ok("""{"nodeIds":[7]}""") + else -> Reply.ok() + } + } + + assertEquals(listOf("Send"), tab.selectAll("#go", timeout = 1_000, includeFrames = true).map { it.text }) + assertEquals( + listOf("iframe", "#go"), + tab.transport.sent.filter { it.method == "DOM.querySelectorAll" }.map { it.param("selector") } + ) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frames and the page") + assertTrue("Runtime.evaluate" !in tab.sent) + tab.close() + } + + @Test + fun aLookupUnderAnElementFoundInThePage_bindsItToTheDocumentFirst() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") + else -> Reply.ok() + } + } + val button = tab.querySelector("#go")!! + + val text = tab.querySelector("*", NodeOrElement.WrappedElement(button)) + + assertEquals(7, button.node.nodeId, "bound to the document") + assertEquals(1, button.tree?.nodeId) + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + assertEquals(8, text!!.node.nodeId) + assertNull(button.objectId, "bound without resolving its object") + tab.querySelector("*", NodeOrElement.WrappedElement(button)) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "a bound element is not bound again") + assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) + assertTrue("DOM.resolveNode" !in tab.sent) + tab.close() + } + + /** `
  • Beta
`, as the document read gives it. */ + private val list = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":5,"parentId":1,"backendNodeId":50,"nodeType":1,""" + + """"nodeName":"UL","localName":"ul","nodeValue":"","attributes":["id","list"],"childNodeCount":1,""" + + """"children":[{"nodeId":7,"parentId":5,"backendNodeId":70,"nodeType":1,"nodeName":"LI",""" + + """"localName":"li","nodeValue":"","attributes":["class","item"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"parentId":7,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Beta"}]}]}]}}""" + + /** The same `li`, as `DOM.describeNode` gives it: no node ids, no parent id. */ + private val describedItem = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"LI","localName":"li","nodeValue":"",""" + + """"attributes":["class","item"],"childNodeCount":1,"children":[{"nodeId":0,"parentId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Beta"}]}}""" + + private fun TestScope.listTab() = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(describedItem) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + // What a lookup on the whole document gave: DOM.querySelector on the document read, the match taken from it. + private suspend fun ScriptedTab.onTheDocument(selector: String): Element = + querySelector(selector, NodeOrElement.WrappedNode(currentDocument().first))!! + + @Test + fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = runTest(StandardTestDispatcher()) { + val tab = listTab() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.parentId) + assertNull(item.tree) + assertEquals( + "could not get parent since the element has no tree set", + assertFailsWith { item.parent }.message, + ) + assertEquals(listOf(0), item.children.map { it.node.nodeId }) + assertTrue("DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun update_givesTheNodeIdsTreeAndParent_aLookupOnTheDocumentGave() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.select("li.item", timeout = 1_000) + + item.update() + val before = tab.onTheDocument("li.item") + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals(before.parent!!.node, item.parent!!.node) + assertEquals("ul", item.parent!!.tag) + assertEquals(before.children.map { it.node }, item.children.map { it.node }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one document read for both") + tab.close() + } + + @Test + fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_fromAKeptDocument() = + runTest(StandardTestDispatcher()) { + val tab = listTab() + val before = tab.onTheDocument("li.item") + val item = tab.select("li.item", timeout = 1_000) + val sentBefore = tab.sent.size + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals("ul", item.parent!!.tag) + assertEquals(listOf(8), item.children.map { it.node.nodeId }) + assertEquals(sentBefore, tab.sent.size, "filled from the kept document, with no command") + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_isNotFilledFromADocumentThePageChangedSince() = runTest(StandardTestDispatcher()) { + val tab = listTab() + tab.onTheDocument("li.item") + tab.transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") + runCurrent() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.tree) + item.update() + assertEquals(7, item.node.nodeId, "update() still reads the document") + assertEquals(2, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_whoseNodeTheKeptDocumentLacks_staysAsFound() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + tab.currentDocument() + val gone = tab.select("li", timeout = 1_000) + + assertEquals(0, gone.node.nodeId) + assertNull(gone.tree) + assertEquals("Gone", gone.text) + (gone as DefaultElement).node = gone.node.copy(nodeName = "P") + assertEquals("p", gone.tag, "a node set by hand is kept") + tab.close() + } + + @Test + fun aBareNodeFoundInThePage_isReplacedByTheDocumentNode_forALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.querySelector("li.item")!! + + tab.querySelector("*", NodeOrElement.WrappedNode(item.node)) + + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + tab.close() + } + + @Test + fun aNodeFoundInThePage_butGoneFromTheDocument_isQueriedAsItIs() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.error("Could not find node with given id") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + else -> Reply.ok() + } + } + val gone = tab.querySelector("li")!! + + assertNull(tab.querySelector("*", NodeOrElement.WrappedNode(gone.node))) + assertNull(tab.querySelector("*", NodeOrElement.WrappedElement(gone))) + + assertEquals(0, gone.node.nodeId, "no node of the document to take") + assertEquals(1, gone.tree?.nodeId, "the element is bound to the document all the same, as update() does") + val queried = tab.transport.sent.filter { it.method == "DOM.querySelector" }.map { it.param("nodeId") } + assertEquals(listOf("0", "0"), queried.take(2)) + tab.close() + } + + @Test + fun anotherElementImplementation_isUpdated_beforeALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val found = tab.querySelector("li.item")!! + val wrapper: Element = object : Element by found {} + + tab.querySelector("*", NodeOrElement.WrappedElement(wrapper)) + + assertEquals(7, wrapper.node.nodeId) + assertTrue("DOM.resolveNode" in tab.sent, "Element.update resolves the object, as it always did") + tab.close() + } + + @Test + fun querySelectorAll_readsTheDocument_whenTheMatchesOutweighIt() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok("""{"result":{"type":"string","value":"document"}}""") + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[5,7]}""") + else -> Reply.ok() + } + } + + val found = tab.querySelectorAll("ul, li") + + assertEquals(listOf(5, 7), found.map { it.node.nodeId }, "read from the document, as before") + assertEquals(listOf(1, 1), found.map { it.tree?.nodeId }) + assertEquals(listOf("Runtime.evaluate", "DOM.getDocument", "DOM.querySelectorAll"), tab.sent) + tab.close() + } + + @Test + fun anElementOfQuerySelectorAll_resolvesItsNodeAtItsFirstCall() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) + else -> Reply.ok() + } + } + + tab.querySelectorAll(".item").single().click() + + assertEquals("10", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) + tab.close() + } +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt new file mode 100644 index 000000000..46547e475 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt @@ -0,0 +1,67 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The replies and helpers the tests of the lookups in the page share. */ +abstract class LookupsInPageFixtures { + + protected val button = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + + """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" + + protected fun item(backendNodeId: Int, text: String) = + """{"node":{"nodeId":0,"backendNodeId":$backendNodeId,"nodeType":1,"nodeName":"LI","localName":"li",""" + + """"nodeValue":"","childNodeCount":1,"children":[{"nodeId":0,"backendNodeId":${backendNodeId + 1},""" + + """"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"$text"}]}}""" + + // An own property of the array of `querySelectorAll`: the match at [index], as Runtime.getProperties lists it. + protected fun match(index: Int, objectId: String) = + """{"name":"$index","configurable":true,"enumerable":true,""" + + """"value":{"type":"object","subtype":"node","objectId":"$objectId"}}""" + + protected val nothing = """{"result":{"type":"object","subtype":"null","value":null}}""" + + protected fun found(objectId: String, subtype: String = "node") = + """{"result":{"type":"object","subtype":"$subtype","objectId":"$objectId"}}""" + + protected val document = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON",""" + + """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" + + protected fun TestScope.tab(answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab = + ScriptedTab(this, ScriptedTransport(this, answer)) + + protected val ScriptedTab.sent get() = transport.methods + + protected val arrayOfOne = """{"result":[""" + + """${match(0, "li-0")}""" + + """]}""" +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt new file mode 100644 index 000000000..0230562d3 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -0,0 +1,583 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * `select`, `selectAll`, `querySelector` and `querySelectorAll` without a node ask the page (`Runtime.evaluate`) and + * describe the matches (`DOM.describeNode`) instead of reading the whole document. A found element gets its node ids, + * tree and parent from the document when it is updated or a lookup runs under it, the same as a lookup on the + * document gave them; an invalid selector throws the browser's error of `DOM.querySelector(All)`. + */ +class LookupsInPageTest: LookupsInPageFixtures() { + + @Test + fun select_asksThePage_andDescribesTheMatch_withoutReadingTheDocument() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select(" #go ", timeout = 1_000) + + assertEquals("button", element.tag) + assertEquals("Send", element.text) + assertEquals("go", element["id"]) + assertEquals(0, element.node.nodeId, "no node id: no document was requested") + assertNull(element.tree) + assertEquals( + listOf("Runtime.evaluate", "DOM.describeNode", "Runtime.releaseObjectGroup"), + tab.sent.filter { it != "Target.getTargetInfo" }, + ) + val evaluate = tab.transport.sent.first { it.method == "Runtime.evaluate" } + assertEquals("document.querySelector(\"#go\")", evaluate.param("expression")) + val group = evaluate.param("objectGroup")!! + assertTrue(group.startsWith("kdriver-lookup-"), group) + val release = tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" } + assertEquals(group, release.param("objectGroup")) + assertEquals( + tab.transport.sent.single { it.method == "DOM.describeNode" }.atMillis, + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.atMillis, + "the release goes with the description, after it", + ) + val describe = tab.transport.sent.first { it.method == "DOM.describeNode" } + assertEquals("obj-1", describe.param("objectId")) + assertEquals("-1", describe.param("depth")) + assertEquals("true", describe.param("pierce")) + tab.close() + } + + @Test + fun select_leavesNoObject_andTheFirstCallResolvesTheNode_asBefore() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","objectId":"obj-2"}}""") + "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select("#go", timeout = 1_000) + assertNull(element.objectId) + element.click() + + assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) + assertEquals("70", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + tab.close() + } + + @Test + fun theReleaseOfTheObjects_holdsTheLookupTwoSecondsAtMost() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "Runtime.releaseObjectGroup" -> Reply.ok(latency = 60_000) + else -> Reply.ok() + } + } + + assertEquals("button", tab.querySelector("#go")?.tag) + + assertEquals(2_000, testScheduler.currentTime) + tab.close() + } + + @Test + fun select_triesAgain_whileThePageHasNoMatch_thenTimesOut() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(nothing) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + assertFailsWith { tab.select("#missing", timeout = 1_200) } + + assertTrue(tab.sent.count { it == "Runtime.evaluate" } >= 3, "polled every 500 ms") + assertTrue("DOM.describeNode" !in tab.sent && "DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun select_triesAgain_whenTheMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + var describes = 0 + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-${describes + 1}")) + "DOM.describeNode" -> + if (describes++ == 0) Reply.error("Could not find object with given id") else Reply.ok(button) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select("#go", timeout = 5_000) + + assertEquals("button", element.tag) + assertEquals(2, tab.sent.count { it == "Runtime.evaluate" }) + tab.close() + } + + private fun syntaxError(selector: String, method: String) = + """{"result":{"type":"object","subtype":"error","className":"DOMException","objectId":"err"},""" + + """"exceptionDetails":{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","className":"DOMException","description":"SyntaxError: Failed to """ + + """execute '$method' on 'Document': '$selector' is not a valid selector.\\n at :1:10"}}}""" + + @Test + fun anInvalidSelector_throwsTheErrorOfDomQuerySelector_andDisablesDom() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelector")) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val error = assertFailsWith { tab.select("li[", timeout = 0) } + + assertEquals("DOM.querySelector", error.method) + assertEquals(-32000, error.code) + assertEquals("DOM Error while querying", error.originalMessage) + assertNull(error.data) + assertEquals( + "Error while calling command DOM.querySelector: DOM Error while querying (code: -32000)", + error.message, + ) + assertTrue("DOM.disable" in tab.sent, "the DOM agent is disabled on the error, as before") + tab.close() + } + + @Test + fun anInvalidSelector_throwsTheErrorOfDomQuerySelectorAll_forTheListMethods() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelectorAll")) + else -> Reply.ok() + } + } + + val lookups = listOf Unit>({ tab.querySelectorAll("li[") }, { tab.selectAll("li[", timeout = 0) }) + for (lookup in lookups) { + val error = assertFailsWith { lookup() } + assertEquals("DOM.querySelectorAll", error.method) + assertEquals(-32000, error.code) + assertEquals("DOM Error while querying", error.originalMessage) + } + tab.close() + } + + @Test + fun anotherExceptionOfThePage_isThrownAsAnEvaluateException() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok( + """{"result":{"type":"object","subtype":"error","objectId":"err"},"exceptionDetails":""" + + """{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","description":"TypeError: replaced by the page"}}}""" + ) + else -> Reply.ok() + } + } + + val error = assertFailsWith { tab.querySelector("#go") } + + assertTrue(error.jsError.startsWith("TypeError"), error.jsError) + assertTrue("DOM.disable" !in tab.sent) + tab.close() + } + + @Test + fun querySelector_passesTheSelectorAsOneJsonStringLiteral() = runTest(StandardTestDispatcher()) { + val tab = tab { Reply.ok(nothing) } + val selector = "a[title=\"x\\\") + alert(1) + (\"\n\u2028\"]" + + assertNull(tab.querySelector(selector)) + + val expression = tab.transport.sent.single().param("expression")!! + assertEquals( + "document.querySelector(\"a[title=\\\"x\\\\\\\") + alert(1) + (\\\"\\n\u2028\\\"]\")", + expression, + ) + tab.close() + } + + @Test + fun querySelectorAll_withNoMatch_costsOneRoundTrip() = runTest(StandardTestDispatcher()) { + val tab = tab { Reply.ok(nothing) } + + assertEquals(emptyList(), tab.querySelectorAll(".item")) + + assertEquals(listOf("Runtime.evaluate"), tab.sent) + assertEquals( + "(() => { const all = document.querySelectorAll(\".item\");" + + " if (!all.length) return null;" + + " const most = document.getElementsByTagName('*').length; const matches = []; let described = 0;" + + " for (let i = 0; i < all.length; i++) {" + + " described += 1 + all[i].getElementsByTagName('*').length;" + + " if (described > most) return 'document'; matches[i] = all[i]; }" + + " return matches; })()", + tab.transport.sent.single().param("expression"), + ) + tab.close() + } + + @Test + fun querySelectorAll_describesEveryMatch_inDocumentOrder() = runTest(StandardTestDispatcher()) { + val items = mapOf("li-0" to item(10, "Alpha"), "li-1" to item(20, "Beta"), "li-2" to item(30, "Gamma")) + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """${match(2, "li-2")},""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")},""" + + """{"name":"3","configurable":true,"enumerable":true,""" + + """"get":{"type":"function","objectId":"getter"}},""" + + """{"name":"4","configurable":true,"enumerable":true,"value":{"type":"number","value":4}},""" + + """{"name":"length","configurable":false,"enumerable":false,""" + + """"value":{"type":"number","value":3}},""" + + """{"name":"__proto__","configurable":true,"enumerable":false,""" + + """"value":{"type":"object","objectId":"proto"}}""" + + """]}""" + ) + "DOM.describeNode" -> Reply.ok(items.getValue(it.param("objectId")!!), latency = 100) + else -> Reply.ok() + } + } + + val found = tab.querySelectorAll(".item") + + assertEquals(listOf("Alpha", "Beta", "Gamma"), found.map { it.text }) + assertEquals(listOf(10, 20, 30), found.map { it.backendNodeId }) + assertEquals("array", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("objectId")) + assertEquals("true", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("ownProperties")) + assertEquals(100, testScheduler.currentTime, "the descriptions are sent together, one round trip for all") + val group = tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup")!! + assertTrue(group.startsWith("kdriver-lookup-"), group) + assertEquals( + listOf("DOM.describeNode", "DOM.describeNode", "DOM.describeNode", "Runtime.releaseObjectGroup"), + tab.sent.dropWhile { it != "DOM.describeNode" }, + "the objects of the lookup are released in the same round trip, after the descriptions", + ) + val released = tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" } + assertEquals(group, released.param("objectGroup")) + assertEquals(listOf(null, null, null), found.map { it.objectId }, "no object of the page is kept") + assertTrue("DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun querySelectorAll_findsNothing_whenAMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")}""" + + """]}""" + ) + "DOM.describeNode" -> + if (it.param("objectId") == "li-0") Reply.error("Could not find object with given id") + else Reply.ok(item(20, "Beta")) + "Runtime.releaseObjectGroup" -> Reply.error("Could not find object with given id") + else -> Reply.ok() + } + } + + assertEquals(emptyList(), tab.querySelectorAll(".item"), "the page navigated: none of its old matches") + assertTrue("Runtime.releaseObjectGroup" in tab.sent) + tab.close() + } + + @Test + fun selectAll_asksThePage_andTimesOutWhenNothingMatches() = runTest(StandardTestDispatcher()) { + val tab = tab { Reply.ok(nothing) } + + assertFailsWith { tab.selectAll(".item", timeout = 1_200) } + + assertTrue(tab.sent.isNotEmpty() && tab.sent.all { it == "Runtime.evaluate" }, tab.sent.toString()) + tab.close() + } + + @Test + fun underANode_lookupsReadTheDocument_asBefore() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") + else -> Reply.ok() + } + } + val parent = dev.kdriver.core.scriptedNode(7, name = "DIV", children = listOf(dev.kdriver.core.scriptedNode(8))) + + val child = tab.querySelector("input", NodeOrElement.WrappedNode(parent)) + + assertEquals(8, child!!.node.nodeId) + assertEquals(listOf("DOM.querySelector"), tab.sent) + tab.close() + } + + @Test + fun querySelectorAll_findsNothing_whenTheArrayIsGoneBeforeItIsRead() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.error("Could not find object with given id") + else -> Reply.ok() + } + } + + assertEquals(emptyList(), tab.querySelectorAll(".item")) + assertEquals(listOf("Runtime.evaluate", "Runtime.getProperties", "Runtime.releaseObjectGroup"), tab.sent) + tab.close() + } + + @Test + fun querySelector_findsNothing_whenTheContextIsGone() = runTest(StandardTestDispatcher()) { + for (error in listOf( + "Cannot find context with specified id", + "Execution context was destroyed.", + )) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.error(error) + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go"), error) + assertEquals(listOf("Runtime.evaluate"), tab.sent) + tab.close() + } + } + + @Test + fun querySelector_findsNothing_whenTheNodeIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.error("No node with given id found") + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go")) + tab.close() + } + + @Test + fun aClosedTarget_isAnError_notANoMatch() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.error("Inspected target navigated or closed") + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelector("#go") } + tab.close() + } + + @Test + fun aDescriptionThatFails_isThrown_onceEveryReplyIsRead() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")}""" + + """]}""" + ) + "DOM.describeNode" -> + if (it.param("objectId") == "li-0") Reply.error("Message is too large", latency = 10) + else Reply.ok(item(20, "Beta"), latency = 1_000) + "Runtime.releaseObjectGroup" -> Reply.ok(latency = 50) + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelectorAll(".item") } + assertTrue("Runtime.releaseObjectGroup" in tab.sent) + assertEquals(1_000, testScheduler.currentTime, "every reply was read before the error was thrown") + tab.close() + } + + @Test + fun aLookupCancelledWhileTheArrayIsRead_stillReleasesItsObjects() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne, latency = 1_000) + else -> Reply.ok() + } + } + + val lookup = launch { tab.querySelectorAll(".item") } + advanceTimeBy(100) + lookup.cancel() + advanceUntilIdle() + + assertTrue(lookup.isCancelled) + assertEquals( + tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup"), + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.param("objectGroup"), + ) + tab.close() + } + + @Test + fun aLookupCancelledWhileThePageEvaluates_stillReleasesItsObjects() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1"), latency = 1_000) + else -> Reply.ok() + } + } + + val lookup = launch { tab.querySelector("#go") } + advanceTimeBy(100) + lookup.cancel() + advanceUntilIdle() + + assertTrue(lookup.isCancelled) + assertEquals( + tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup"), + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.param("objectGroup"), + "the page may still run an evaluation cut in flight", + ) + tab.close() + } + + @Test + fun aLookupThatFindsNothing_sendsNoRelease() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(nothing) + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go")) + assertEquals(emptyList(), tab.querySelectorAll("#go")) + + assertTrue("Runtime.releaseObjectGroup" !in tab.sent) + tab.close() + } + + @Test + fun anyOtherProtocolError_isThrown() = runTest(StandardTestDispatcher()) { + val describing = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.error("Message is too large") + else -> Reply.ok() + } + } + assertEquals( + "Message is too large", + assertFailsWith { describing.querySelector("#go") }.originalMessage + ) + describing.close() + + val listing = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.error("Message is too large") + else -> Reply.ok() + } + } + assertEquals( + "Message is too large", + assertFailsWith { listing.querySelectorAll(".item") }.originalMessage + ) + assertTrue("Runtime.releaseObjectGroup" in listing.sent, "the objects are released before the error is thrown") + listing.close() + + val evaluating = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.error("Session closed") + else -> Reply.ok() + } + } + assertFailsWith { evaluating.querySelectorAll(".item") } + evaluating.close() + } + + @Test + fun querySelectorAll_keepsItsMatches_whenTheReleaseOfTheArrayFails() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "Runtime.releaseObjectGroup" -> Reply.error("Session closed") + else -> Reply.ok() + } + } + + assertEquals(listOf("Alpha"), tab.querySelectorAll(".item").map { it.text }) + tab.close() + } + @Test + fun aSyntaxErrorThrownByAScriptOfThePage_isAnEvaluateException() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok( + """{"result":{"type":"object","subtype":"error","objectId":"err"},"exceptionDetails":""" + + """{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","className":"SyntaxError",""" + + """"description":"SyntaxError: thrown by the page"}}}""" + ) + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelector("#go") } + tab.close() + } + + @Test + fun aStringAnsweredForQuerySelector_isNoMatch() = runTest(StandardTestDispatcher()) { + val tab = tab { Reply.ok("""{"result":{"type":"string","value":"document"}}""") } + + assertNull(tab.querySelector("#go")) + assertEquals(listOf("Runtime.evaluate"), tab.sent) + tab.close() + } +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt index d98bc3d2c..ab3e61e2b 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt @@ -28,6 +28,11 @@ class SettledLookupTest { """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" + private val button = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + + """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" + /** A page with one ``; [found] false makes every lookup come back empty. */ private fun browser(found: Boolean = true, targetError: String? = null): (ScriptedTransport.Sent) -> Reply = { when (it.method) { @@ -35,6 +40,10 @@ class SettledLookupTest { if (targetError != null) Reply.error(targetError, latency = 100) else Reply.ok(ScriptedTab.TARGET_INFO, latency = 100) "DOM.getDocument" -> Reply.ok(document, latency = 100) + "Runtime.evaluate" -> + if (found) Reply.ok("""{"result":{"type":"object","objectId":"obj-1"}}""", latency = 100) + else Reply.ok("""{"result":{"type":"object","subtype":"null","value":null}}""", latency = 100) + "DOM.describeNode" -> Reply.ok(button, latency = 100) "DOM.querySelector" -> Reply.ok(if (found) """{"nodeId":7}""" else """{"nodeId":0}""", latency = 100) "DOM.performSearch" -> Reply.ok("""{"searchId":"s1","resultCount":${if (found) 1 else 0}}""", latency = 100) "DOM.getSearchResults" -> Reply.ok("""{"nodeIds":[7]}""", latency = 100) @@ -53,9 +62,12 @@ class SettledLookupTest { assertEquals("Send", button.text) assertEquals("https://example.test/", tab.targetInfo!!.url, "the target info is still refreshed") val sentAtStart = transport.methodsSentAt(0) - assertEquals(setOf("DOM.getDocument", "Target.getTargetInfo"), sentAtStart) - assertEquals(listOf("DOM.querySelector"), transport.sent.filter { it.atMillis > 0 }.map { it.method }) - assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ document, then query), not three") + assertEquals(setOf("Runtime.evaluate", "Target.getTargetInfo"), sentAtStart) + assertEquals( + listOf("DOM.describeNode", "Runtime.releaseObjectGroup"), + transport.sent.filter { it.atMillis > 0 }.map { it.method }, + ) + assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ evaluation, then describe), not three") tab.close() } @@ -67,7 +79,7 @@ class SettledLookupTest { val error = assertFailsWith { tab.select("#missing", timeout = 50) } assertTrue(error.message!!.contains("#missing")) - val attempts = transport.methods.count { it == "DOM.querySelector" } + val attempts = transport.methods.count { it == "Runtime.evaluate" } assertTrue(attempts >= 1, "polled ($attempts)") assertEquals(attempts, transport.methods.count { it == "Target.getTargetInfo" }, "one refresh per attempt") tab.close() diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index d0c0e8de9..ed97ea058 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -188,3 +188,50 @@ fun main() = runBlocking { The browser advertises its own, internal, address in `webSocketDebuggerUrl`; when `browserUrl` is set, kdriver keeps only the path of that URL and connects to it on `browserUrl`. Without `browserUrl`, `host` and `port` keep working as before. + +## How lookups work + +`select`, `selectAll`, `querySelector` and `querySelectorAll` (without a node) let the page run the +selector: kdriver evaluates `document.querySelector(…)` / `document.querySelectorAll(…)` in the page, +then asks the browser to describe only the matching elements, each with its subtree. The whole +document is never transferred, which matters most when the browser is far away (`browserUrl`) and +the page is large or keeps changing. + +| What | How | +| --- | --- | +| Commands for `select` / `querySelector` | `Runtime.evaluate`, then `DOM.describeNode` of the match with the release of the object the lookup created (one round trip when nothing matches) | +| Commands for `selectAll` / `querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then every `DOM.describeNode` sent together, with the release of the objects the lookup created | +| Data received | the matches and their subtrees; when they would hold more elements than the whole document (nested matches, a selector matching most of the page), the document is read instead, as before | +| First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`), as before: a lookup leaves no object behind in the page | +| Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | +| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | filled on their first read from the document kept by an earlier read (`find`, `xpath`, a lookup under an element, `update`…) while the page has not changed since; otherwise `nodeId` may be 0, `parentId` and `tree` are `null` and `parent` throws, until `element.update()` reads the document; a lookup under the element binds it by itself | +| Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | +| Waiting | `select` / `selectAll` retry every 500 ms until the timeout, as before | +| A navigation during the lookup | an object or context dropped by the navigation counts as no match: `select` tries again | +| Invalid selector | the same `CDPException` as before (`DOM.querySelector` or `DOM.querySelectorAll`, code -32000, "DOM Error while querying") | + +```kotlin +val item = tab.select("li.item") +item.text // read from the match +item.click() // resolves the element, then clicks it +item.tree // null: no document was read yet +item.update() // reads the document (one DOM.getDocument) +item.parent?.tag // "ul" + +val other = tab.select("li.other") +other.parent?.tag // "ul": the document read above still matches the page, no command sent +``` + +What still differs from reading the whole document: + +- the page's own `document.querySelector` runs, so a page that replaces it changes the result; +- until something reads the document (`find`, `update`, a lookup under an element…), the browser + sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner, and the DOM + agent is not enabled: a `tab.dom.disable()` sent by hand then fails, as on a tab that never read it; +- `element.node.nodeId`, `element.parentId`, `element.tree` and `element.parent` are plain + properties, not suspend functions: their first read fills them from a document kept by an earlier + read, but cannot fetch one by itself. When no document was read since the page last changed, code + that reads them calls `element.update()` first. + +Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` +and `xpath` read the document, as before.