<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kritagya on Medium]]></title>
        <description><![CDATA[Stories by Kritagya on Medium]]></description>
        <link>https://medium.com/@kritagya2022?source=rss-11465733f7e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Kritagya on Medium</title>
            <link>https://medium.com/@kritagya2022?source=rss-11465733f7e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:16:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kritagya2022/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Triage Layer]]></title>
            <link>https://medium.com/@kritagya2022/the-triage-layer-af26f61240dd?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/af26f61240dd</guid>
            <category><![CDATA[restassuared]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[playwrights]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 17:51:01 GMT</pubDate>
            <atom:updated>2026-08-15T17:51:01.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>“37 tests failed” is not information. It’s the start of a scavenger hunt. Here’s how to skip it.</h3><p>Picture the Monday-morning ritual most QA teams know too well: the overnight regression suite finished, 37 tests are red, and someone — usually the least senior person in the room — spends the next ninety minutes opening each failure one at a time, reading a stack trace, and mentally sorting it into a bucket: <em>real bug</em>, <em>flaky test</em>, <em>environment was down again</em>, <em>someone changed a locator and didn’t tell anyone</em>.</p><p>That sorting is real engineering work. It’s also completely mechanical, it happens every single day, and — this is the part that should bother you — the answer is usually sitting right there in the exception message. A StaleElementReferenceException doesn&#39;t need a human to recognize it. Neither does Connection refused. The information needed to triage most failures already exists in the failure itself. Nobody&#39;s reading it programmatically; they&#39;re reading it with their eyes, one Jenkins tab at a time.</p><p>That’s the entire premise of a failure classifier: stop making a human do pattern matching that a switch statement can do in microseconds.</p><h3>Why this isn’t a machine-learning problem</h3><p>The instinct, when you first think about “automatically categorizing failures,” is to reach for something smart — an LLM call, a trained classifier, sentiment-analysis-for-stack-traces. Resist it. Test failures aren’t an open-ended NLP problem; they come from a closed, bounded universe. There are only so many ways a test can fail:</p><ul><li>An element wasn’t where you expected it (ELEMENT_NOT_FOUND, STALE_ELEMENT)</li><li>Something took too long (WAIT_TIMEOUT, PAGE_LOAD_TIMEOUT)</li><li>An assertion genuinely didn’t hold (ASSERTION_FAILURE)</li><li>The environment wasn’t there (CONNECTION_REFUSED, SERVICE_UNAVAILABLE)</li><li>Auth expired mid-run (AUTH_TOKEN_EXPIRED)</li><li>The machine running the test ran out of something (OUT_OF_MEMORY, DISK_FULL)</li></ul><p>That’s maybe fifteen to twenty categories for most suites, ever. A hand-written, ordered pattern table beats a model here on every axis that matters for this job: it’s deterministic (same input, same output, forever), it’s free, it’s debuggable by anyone on the team in thirty seconds, and — critically — you can explain exactly why it made the call it made, which matters a lot when someone disputes the classification.</p><pre>public enum FailureCategory {<br>    ELEMENT_NOT_FOUND, STALE_ELEMENT_REFERENCE, ELEMENT_NOT_INTERACTABLE,<br>    WAIT_TIMEOUT, PAGE_LOAD_TIMEOUT,<br>    ASSERTION_FAILURE,<br>    CONNECTION_REFUSED, NETWORK_ISSUE, SERVICE_UNAVAILABLE,<br>    AUTH_TOKEN_EXPIRED, PERMISSION_ISSUE,<br>    BROWSER_CRASH, SESSION_NOT_CREATED,<br>    OUT_OF_MEMORY, RESOURCE_NOT_FOUND,<br>    TEST_DATA_ISSUE,<br>    UNKNOWN<br>}</pre><p>That last one — UNKNOWN — is not a rounding error. It&#39;s load-bearing. More on that shortly.</p><h3>The design that actually works: order is the whole algorithm</h3><p>A failure classifier is, at its core, an ordered list of “if this looks like X, call it X” checks that stops at the first match. The entire design skill is in getting the order right and the patterns tight, because two failure signatures can look almost identical and mean completely different things depending on which check runs first.</p><pre>public class FailureClassifier {</pre><pre>    public static FailureCategory classify(Throwable t) {<br>        if (t == null) return UNKNOWN;</pre><pre>        // 1. Exception TYPE checks first — the strongest signal, zero ambiguity<br>        if (t instanceof StaleElementReferenceException)      return STALE_ELEMENT_REFERENCE;<br>        if (t instanceof NoSuchElementException)                return ELEMENT_NOT_FOUND;<br>        if (t instanceof ElementNotInteractableException)      return ELEMENT_NOT_INTERACTABLE;<br>        if (t instanceof TimeoutException)                      return WAIT_TIMEOUT;<br>        if (t instanceof AssertionError)                         return ASSERTION_FAILURE;</pre><pre>        // 2. Message pattern checks second — weaker signal, needs specific-to-general order<br>        String msg = safeMessage(t);<br>        if (containsAny(msg, &quot;Connection refused&quot;, &quot;ECONNREFUSED&quot;))  return CONNECTION_REFUSED;<br>        if (containsAny(msg, &quot;401&quot;, &quot;token expired&quot;, &quot;Unauthorized&quot;)) return AUTH_TOKEN_EXPIRED;<br>        if (containsAny(msg, &quot;session not created&quot;))                  return SESSION_NOT_CREATED;<br>        if (containsAny(msg, &quot;out of memory&quot;, &quot;OutOfMemoryError&quot;))    return OUT_OF_MEMORY;</pre><pre>        // 3. Cause chain — sometimes the real signal is one level down<br>        if (t.getCause() != null &amp;&amp; t.getCause() != t) {<br>            return classify(t.getCause());<br>        }</pre><pre>        // 4. Give up honestly, rather than guess<br>        return UNKNOWN;<br>    }<br>}</pre><p>Three rules make this design hold up instead of quietly rotting:</p><p>Type checks before message checks, always. An exception’s Java type is a guarantee; a substring match on its message is a bet. Spend the guarantee first. If you check message patterns before type checks, a generic RuntimeException wrapping a StaleElementReferenceException with an unhelpful message can slip past a category it should obviously hit.</p><p>Specific before general, deliberately, not accidentally. &quot;401&quot; and &quot;Unauthorized&quot; should be checked before any broad &quot;error&quot; catch-all — because a broad catch-all placed earlier in the list will happily swallow every category that comes after it in the table, and nobody notices until someone audits the actual distribution six months later and finds one category eating 80% of failures it doesn&#39;t belong to.</p><p>Walk the cause chain. Frameworks love to wrap exceptions — a WebDriverException wrapping an IOException wrapping the thing you actually care about. Classify recursively on getCause() with a self-reference guard, or you&#39;ll misclassify a large fraction of real failures as whatever generic wrapper type happens to sit on top.</p><h3>The rule that keeps it honest: fail safe to UNKNOWN</h3><p>Here’s the mistake that will quietly poison this system if you don’t guard against it on day one: the temptation to make UNKNOWN disappear.</p><p>It’s tempting to write one broad, greedy pattern near the end — msg.contains(&quot;error&quot;) — that mops up everything unclassified into whatever category feels most common, just so the pie chart looks tidy. Don&#39;t. That single decision is how a classifier goes from useful to actively misleading, because now a chunk of <em>real, novel failures</em> are silently wearing the label of whatever bucket you dumped them into, and nobody goes looking for them again.</p><p>UNKNOWN should be allowed to exist, and — this is the part people miss — it should be tracked as its own metric, not treated as a defect in the classifier. A rising UNKNOWN rate is a genuinely useful signal: it means your suite just started failing in a new way you haven&#39;t taught the table to recognize yet. That&#39;s exactly the moment you want a human to look, not the moment to paper over with a fake match. Treat every UNKNOWN classification during triage as a two-minute task: read the real message, and if it&#39;s a pattern you&#39;ll see again, add one line to the table. The classifier gets more accurate the same way a spam filter does — one corrected miss at a time, in production, forever. It&#39;s never &quot;finished,&quot; and that&#39;s fine.</p><h3>Where this actually pays off: analytics, not the pie chart</h3><p>A single pretty pie chart of failure categories for one run is a nice demo and a weak product. The real value shows up the moment you do what the <a href="https://claude.ai/code/artifact/3205e65b-9e4e-4eeb-8672-3de9c5f682da">observability layer</a> does with any other metric: look at the category distribution across runs, not within one.</p><p>Trend the categories, not just the counts. A steady 5% STALE_ELEMENT_REFERENCE rate is background noise every UI suite has. A STALE_ELEMENT_REFERENCE rate that&#39;s climbed from 5% to 30% over three weeks is a very different story — it usually means a recent frontend change introduced re-rendering the suite hasn&#39;t adapted its waits to yet, and it&#39;s visible in the data a full sprint before someone notices &quot;the suite feels flakier lately.&quot;</p><p>Route by category, not by test. The categories map cleanly onto <em>who should look at this</em>, which is the actual point of triage:</p><p>Category clusterWho owns itWhat it usually meansSTALE_ELEMENT, ELEMENT_NOT_FOUND, WAIT_TIMEOUTQA/automation teamThe test needs a better wait or locator, or the UI genuinely changedCONNECTION_REFUSED, SERVICE_UNAVAILABLE, SESSION_NOT_CREATEDInfra / DevOpsThe environment was down, not the productASSERTION_FAILUREProduct engineeringThis might be a real regression — escalate, don&#39;t dismissAUTH_TOKEN_EXPIRED, PERMISSION_ISSUEWhoever owns the auth serviceToken lifecycle or a permissions change broke somethingTEST_DATA_ISSUEAutomation teamThe fixture, not the product, is stale</p><p>Once failures are pre-sorted into these clusters, a failed overnight run stops being “37 red tests, go read them all” and starts being “6 are a real regression in checkout — escalate now; 24 are the staging environment being flaky again — infra already knows; 7 are UNKNOWN — somebody take a look.&quot; That&#39;s a five-minute Slack message instead of a ninety-minute investigation, and it&#39;s the same underlying failures — just pre-sorted by a table lookup instead of a human&#39;s eyes.</p><p>Feed flaky-test detection. A test that fails with a <em>transient</em> category (STALE_ELEMENT, WAIT_TIMEOUT, NETWORK_ISSUE) on one run and passes clean on the next, repeatedly, is a flaky-test candidate — quarantine it, don&#39;t keep re-triaging it by hand. A test that fails with ASSERTION_FAILURE consistently, run after run, is not flaky — it&#39;s telling you the truth, and it should never get auto-quarantined by a &quot;flaky&quot; heuristic that doesn&#39;t distinguish the two. This distinction — <em>transient category vs. deterministic category</em> — is the single most useful thing the classifier buys a flaky-detection system, and it&#39;s a one-line lookup once the categories exist.</p><h3>The mistake that costs you trust, not just accuracy</h3><p>I want to flag a specific failure mode of this pattern, because it’s subtle and it’s the kind of thing that erodes an otherwise-good system slowly enough that nobody notices until it’s a running joke on the team.</p><p>Imagine a pattern early in the table: msg.contains(&quot;timed out&quot;) → WAIT_TIMEOUT. Reasonable-looking. Except a slow backend endpoint that genuinely regressed — a real, product-facing performance bug — <em>also</em> produces a message containing &quot;timed out,&quot; because the HTTP client&#39;s own exception text uses that phrase for a connection-level timeout too. Every occurrence of that real regression now gets silently sorted into the same bucket as &quot;the UI took an extra 200ms to render a dropdown,&quot; and because the team has learned to treat WAIT_TIMEOUT as background noise, the real bug gets ignored by the same system built to surface it.</p><p>The pattern wasn’t wrong, exactly — it just wasn’t specific enough, and it was sitting in a spot where two genuinely different failure classes collided on a shared vocabulary word. The fix is always the same shape: split the overly broad pattern into narrower ones the moment you notice two different root causes hiding behind it (UI_WAIT_TIMEOUT vs. HTTP_REQUEST_TIMEOUT, distinguished by which layer threw it), and audit your UNKNOWN bucket and your largest bucket on a regular cadence — the largest category in any classifier is exactly where a silent catch-all is most likely to be hiding.</p><p>The general lesson generalizes past this one example: a pattern-based classifier is only as trustworthy as its most generic rule. Every classifier accumulates a few of these over time as the suite grows. Treat “audit the biggest bucket” as a five-minute monthly habit, not a one-time build step.</p><h3>Build the smallest version this week</h3><ol><li>Write the enum first, short. Ten categories, based on the failures you <em>actually see</em> in your last month of CI history — not a hypothetical exhaustive list. You’ll extend it; you don’t need to predict it.</li><li>Order type checks before message checks, and walk the cause chain. This alone fixes most of the misclassification you’d otherwise spend weeks debugging.</li><li>Wire classify() into whatever already runs on test failure — your existing listener, no new infrastructure needed.</li><li>Chart the category distribution across your last N runs, not just the run that just finished. This is where the actual insight lives.</li><li>Treat UNKNOWN as a to-do list, not a bug. Every time you see one during triage, decide in two minutes whether it deserves a new pattern.</li></ol><p>None of this requires a platform, a vendor, or a model. It requires an enum, an ordered if chain, and the discipline to keep the table honest instead of tidy. That trade — a slightly messier-looking chart in exchange for one you can actually trust — is the whole game.</p><p><em>The patterns above are generalized from a production test-automation framework — specific implementation details have been abstracted to focus on the design principles rather than any particular codebase.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af26f61240dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Observability, For Free]]></title>
            <link>https://medium.com/@kritagya2022/test-observability-for-free-32d33e26f58b?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/32d33e26f58b</guid>
            <category><![CDATA[restassured]]></category>
            <category><![CDATA[reporting]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[playwrights]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 19:45:54 GMT</pubDate>
            <atom:updated>2026-08-14T19:45:54.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>You already generate the data a $20k/year tool would sell you back. Here’s how to stop throwing it away.</h3><p>Every test automation team hits the same wall eventually.</p><p>You’ve got a solid Selenium/TestNG (or Playwright, or Cypress) suite. It runs in CI. It produces a report. And the report is <em>useless</em> the moment you close the tab, because it only ever answers one question: how did this one run go?</p><p>The questions that actually matter live one level up:</p><ul><li>Is module X getting flakier over the last two weeks, or was that just a bad Tuesday?</li><li>Which failure category is eating the most engineering time — real bugs, or infrastructure noise?</li><li>Are our slowest 10 tests the same 10 tests they were last sprint?</li><li>Did the API layer get slower this release, or does it just feel that way?</li></ul><p>None of that lives in a single HTML report. It lives <em>across</em> runs. And the moment a team notices this gap, the reflex is to reach for a vendor: ReportPortal, Allure TestOps, a hosted analytics SaaS. Which is a fine choice — but it’s worth knowing what you’re actually buying, because most of it is a rollup of data your framework is already producing and discarding after every run.</p><p>I found this out by building the free version first.</p><h3>The reframe</h3><p>The insight that unlocks this isn’t clever architecture. It’s a one-sentence reframe:</p><blockquote><em>A test report is a snapshot. Test observability is what you get when you stop deleting the snapshots.</em></blockquote><p>That’s it. If every run already writes a structured result somewhere, and you keep those files instead of overwriting them, you have a time series. A time series of pass/fail data is a dashboard away from being a trend chart, a flaky-test detector, and a failure-pattern analyzer — all without a database, a backend service, or a monthly invoice.</p><p>The rest of this is just plumbing that respects that idea.</p><h3>The four layers</h3><p>Strip away the Selenium-specific plumbing and any test framework’s reporting pipeline decomposes into four layers that barely know about each other:</p><pre>COLLECTION        →  something taps into the test lifecycle and records events<br>AGGREGATION       →  events get folded into one in-memory model, per run<br>PERSISTENCE       →  the model gets written to disk as a durable snapshot<br>PRESENTATION      →  a dashboard reads every snapshot on disk, not just today&#39;s</pre><p>The trick that turns “reporting” into “observability” happens entirely in the last layer, and it’s almost embarrassingly simple: the dashboard-builder doesn’t read one file. It globs the whole snapshot directory.</p><p>Everything before that is just making sure the snapshot is trustworthy. Let’s go layer by layer.</p><h3>1. Collection — tap the lifecycle you already have</h3><p>Every test framework worth using exposes lifecycle hooks: onTestStart, onTestSuccess, onTestFailure, beforeEach, afterEach. You don&#39;t need custom instrumentation — you need one listener that&#39;s a good citizen of the events already firing.</p><pre>public class ObservabilityListener implements ITestListener, ISuiteListener {</pre><pre>    @Override<br>    public void onTestStart(ITestResult result) {<br>        TestRunModel model = TestRunModel.from(result);   // module, tags, id, etc.<br>        ThreadLocalTestContext.init(model);                // one model per thread<br>    }</pre><pre>    @Override<br>    public void onTestSuccess(ITestResult result) {<br>        ThreadLocalTestContext.get().markStatus(PASSED);<br>        RunAggregator.getInstance().register(ThreadLocalTestContext.get());<br>        ThreadLocalTestContext.clear();<br>    }</pre><pre>    @Override<br>    public void onTestFailure(ITestResult result) {<br>        var ctx = ThreadLocalTestContext.get();<br>        ctx.markStatus(FAILED);<br>        ctx.setFailureCategory(FailureClassifier.classify(result.getThrowable()));<br>        RunAggregator.getInstance().register(ctx);<br>        ThreadLocalTestContext.clear();<br>    }<br>}</pre><p>Two design choices here matter more than they look:</p><p>Thread-local, not shared state. If your suite runs in parallel — and it should — a shared mutable “current test” object is a race condition waiting for a Tuesday demo to fail. One model per thread, cleared at the end of every test, is non-negotiable.</p><p>Status is never assumed. Notice there’s no default. If a listener callback never fires for some reason, the test’s status should render as UNKNOWN, not silently inherit PASSED. A reporting pipeline that fails safe into a false positive is worse than no reporting at all — it&#39;s actively lying to you with a green checkmark. Make the failure mode loud.</p><h3>2. Aggregation — one model, recomputed, not incremented</h3><p>Every test that finishes needs to land somewhere shared. The naive version is a counter you increment: passedCount++. Don&#39;t do this. In a parallel suite, incrementing counters from multiple threads is a subtle bug generator, and worse, it drifts silently — a miscount doesn&#39;t crash, it just quietly under-reports.</p><p>The sturdier pattern: keep the individual test results in a ConcurrentHashMap, and compute the summary fresh, every time it&#39;s requested, by iterating the map.</p><pre>public class RunAggregator {<br>    private static final RunAggregator INSTANCE = new RunAggregator();<br>    private final Map&lt;String, TestRunModel&gt; tests = new ConcurrentHashMap&lt;&gt;();</pre><pre>    public void register(TestRunModel test) {<br>        tests.put(test.getId(), test);<br>    }</pre><pre>    public RunSummary summary() {<br>        // recomputed from the live map on every call — never trusted from a counter<br>        long passed = tests.values().stream().filter(TestRunModel::isPassed).count();<br>        long failed = tests.values().stream().filter(TestRunModel::isFailed).count();<br>        long skipped = tests.values().stream().filter(TestRunModel::isSkipped).count();<br>        return new RunSummary(tests.size(), passed, failed, skipped);<br>    }<br>}</pre><p>It’s a little more CPU per call. It’s completely immune to a whole category of concurrency bugs. That trade is almost always worth it at test-suite scale (hundreds to low thousands of tests) — re-evaluate only if you’re aggregating tens of thousands of results per run.</p><h3>3. Persistence — snapshot atomically, or don’t bother</h3><p>This is the layer people skip, and it’s the one that actually earns you the word “observability.” Two rules:</p><p>Write atomically. Never write directly to the file a reader might be looking at. Write to a temp file, then rename. A rename is atomic on every OS that matters; a partial write is a corrupted JSON file that breaks your dashboard the one time you need it most — usually right after a CI box got killed.</p><pre>public void writeSnapshot(RunModel run) {<br>    Path tmp = snapshotDir.resolve(run.getRunId() + &quot;.json.tmp&quot;);<br>    Path finalPath = snapshotDir.resolve(run.getRunId() + &quot;.json&quot;);</pre><pre>    objectMapper.writeValue(tmp.toFile(), run);<br>    Files.move(tmp, finalPath, StandardCopyOption.ATOMIC_MOVE,<br>                                StandardCopyOption.REPLACE_EXISTING);<br>}</pre><p>Snapshot on a timer <em>and</em> on every event, not just at the end. A run that finishes cleanly should have near-real-time JSON on disk the whole way through — flush after every test result, not only at suite completion. Then add a periodic flush (every 10 seconds is a reasonable default) as a safety net, and a JVM shutdown hook that forces one last write. The combination means a process that gets killed mid-suite — OOM, a CI timeout, someone closing their laptop — still leaves you the last-known-good state instead of nothing.</p><pre>Runtime.getRuntime().addShutdownHook(new Thread(() -&gt; {<br>    aggregator.summary().markHalted();     // be honest: this run did NOT finish<br>    writer.writeSnapshot(aggregator.getRunModel());<br>}));</pre><p>That markHalted() line matters as much as the atomic write. A snapshot should tell you when it&#39;s incomplete. A dashboard that can&#39;t distinguish &quot;this run finished and everything passed&quot; from &quot;this run got killed before most tests even started&quot; will eventually cost someone a very confusing debugging session.</p><h3>4. Presentation — the one line that makes it observability</h3><p>Here’s the actual unlock, and it’s almost anticlimactic:</p><pre>public class InsightsGenerator {</pre><pre>    public void generateDashboard(Path snapshotDir, Path outputHtml) {<br>        List&lt;RunModel&gt; allRuns = Files.list(snapshotDir)<br>            .filter(p -&gt; p.toString().endsWith(&quot;.json&quot;))<br>            .map(this::parseSnapshot)          // &lt;-- reads EVERY run on disk<br>            .collect(Collectors.toList());</pre><pre>        renderDashboard(allRuns, outputHtml);<br>    }<br>}</pre><p>That’s the whole trick. Not “read the JSON file this run just wrote.” Read every JSON file that’s ever been written, and aggregate across all of them. One extra line of code is the entire difference between a single-run report and a multi-run observability dashboard. Everything downstream — trend lines, flaky-test detection, failure-pattern frequency — is just different views over that same list of historical runs.</p><p>From there, a genuinely useful dashboard needs a handful of views, and they’re all cheap once you have the historical list:</p><ul><li>Stat tiles + a pass/fail/skip donut for the latest run — the “is anything on fire right now” glance.</li><li>A duration trend line across runs — this is the one people underrate. A test that silently goes from 4s to 40s over three weeks is a leading indicator of a flaky test or a real performance regression, and nobody notices until it’s a timeout. A line chart over historical durations catches it for free.</li><li>Breakdowns by module / severity / category — stacked bars, one per dimension, built off whatever metadata tag your team already puts on tests (you’re already tagging tests as smoke/regression/critical for CI filtering — reuse the same tags here instead of inventing new ones).</li><li>Failure root-cause distribution — a pie chart over failure <em>categories</em>, not raw stack traces. This only works if collection classified the failure at capture time (see below).</li><li>A halted-run banner — if any scanned snapshot has status: HALTED, say so loudly at the top. Silence here is how a team stops trusting the dashboard.</li></ul><h3>The failure classifier: cheap, and worth it</h3><p>One layer that punches well above its size: a pattern table that turns a raw exception into a category.</p><pre>public enum FailureCategory {<br>    ELEMENT_NOT_FOUND, STALE_ELEMENT, WAIT_TIMEOUT,<br>    ASSERTION_FAILURE, NETWORK_ISSUE, CONNECTION_REFUSED,<br>    AUTH_EXPIRED, INFRASTRUCTURE_FAILURE, UNKNOWN<br>}</pre><pre>public class FailureClassifier {<br>    public static FailureCategory classify(Throwable t) {<br>        String msg = t == null ? &quot;&quot; : String.valueOf(t.getMessage());<br>        if (t instanceof StaleElementReferenceException) return STALE_ELEMENT;<br>        if (msg.contains(&quot;Connection refused&quot;))          return CONNECTION_REFUSED;<br>        if (msg.contains(&quot;Timed out waiting&quot;))            return WAIT_TIMEOUT;<br>        if (t instanceof AssertionError)                   return ASSERTION_FAILURE;<br>        // ...a dozen more patterns, tuned to what actually shows up in YOUR suite<br>        return UNKNOWN;<br>    }<br>}</pre><p>This is the difference between a dashboard that says “37 tests failed” and one that says “37 tests failed: 22 were a shared staging outage, 9 were a real regression in checkout, 6 are flaky waits.” The first number is noise. The second is a Monday-morning triage list. And it costs about an hour to write a pattern table tuned to your own suite’s actual exception shapes — this is not a machine-learning problem, it’s a switch statement that gets more accurate every time you add a new pattern you recognize.</p><h3>The bug I’d tell you to avoid before you write it</h3><p>I want to be honest about a mistake in an earlier version of this design, because it’s the kind of thing that looks completely reasonable until you measure it.</p><p>The original model tried to correlate captured network calls to individual test <em>steps</em> — “which API calls happened during step 3.” The implementation took a shortcut: instead of real timestamp-windowing, it attached the test’s <em>entire</em> list of API calls to <em>every single step</em>.</p><p>It worked, in the sense that the data was technically present everywhere someone might look for it. It was also a silent multiplier: for a test with 9 steps and 6 API calls, that’s 54 stored objects instead of 6. Scaled across a few hundred tests, that’s the difference between a report file measured in megabytes and one measured in hundreds of megabytes — and nobody notices until the dashboard starts taking twenty seconds to load and someone finally opens the JSON to see why.</p><p>The fix wasn’t clever — it was store the list once, at the level it actually belongs to (the test, not the step), and derive any step-level view at render time instead of persisting the duplication. Rule of thumb that generalizes past this specific bug: if you’re about to attach the same collection to N different parents “for convenience,” you’re not correlating data, you’re multiplying it. Either do the real correlation (timestamps, windows) or store it once and join at read time.</p><h3>What this buys you, and what it doesn’t</h3><p>To be fair to the vendors: this pattern gets you 80% of what a paid test-observability tool sells, for the cost of a few hundred lines of code you already half-have in your reporting listener. It does not get you:</p><ul><li>Team-wide auth, RBAC, and shareable hosted links out of the box</li><li>Native CI-system integrations beyond “read a folder of JSON”</li><li>A support contract when something breaks at 2am</li><li>Long-term storage/retention policies, backups, and query performance once you’re past thousands of runs</li></ul><p>If any of those are the actual bottleneck for your team, buy the tool — that’s a legitimate trade of engineering time for a solved problem. But if what’s stopping you from having <em>any</em> trend visibility is “we don’t have budget approved yet,” you don’t need to wait. You need four files: a listener, an aggregator, an atomic writer, and an HTML generator that globs a directory instead of reading one file.</p><h3>Try it this weekend</h3><p>If you want the smallest possible version of this to exist in your suite by Monday:</p><ol><li>Find your existing report listener. You have one — Extent, a custom TestNG listener, a Playwright reporter. It already knows when a test starts, passes, and fails.</li><li>Add one write: serialize a minimal {testId, status, durationMs, module, failureCategory} per test to a JSON file per run, named by timestamp, in a folder you don&#39;t .gitignore.</li><li>Don’t delete old ones. That’s the whole “strategy” — retention is the feature.</li><li>Write forty lines of HTML + Chart.js that globs the folder and plots pass rate and duration over the last N runs.</li></ol><p>You’ll have something worse than ReportPortal and better than nothing by the end of a Saturday. Keep iterating on it only as fast as it actually pays for itself — that’s the same discipline you’d apply to any other piece of internal tooling, and test reporting has no business being exempt from it.</p><p><em>The patterns above are generalized from a production Selenium/TestNG framework — details have been abstracted to focus on the architecture rather than any specific implementation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32d33e26f58b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Test Data Management System: DB-First Architecture with JSON Fallback]]></title>
            <link>https://medium.com/@kritagya2022/building-a-production-grade-test-data-management-system-db-first-architecture-with-json-fallback-2e696c412fc4?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e696c412fc4</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[test-data-management]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 21:21:14 GMT</pubDate>
            <atom:updated>2026-04-10T21:21:14.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aReyq25AXGxp8R7qxw9xXw.png" /><figcaption>Test Data Management Layer High Level Architecture Design</figcaption></figure><h3>Introduction</h3><p>Test automation at scale is not limited by test coverage or tooling — it is limited by <strong>how test data is managed</strong>.</p><p>In large systems with:</p><ul><li>Hundreds of E2E flows</li><li>Multiple services and platforms</li><li>Frequent schema and business logic changes</li></ul><p>static approaches like JSON files and .properties quickly become unmaintainable.</p><p>This article presents a <strong>DB-first Test Data Management (TDM) architecture with a JSON fallback mechanism</strong>, designed to:</p><ul><li>Centralize test data</li><li>Enable cross-test state sharing</li><li>Support safe migration without breaking existing tests</li></ul><p>The focus here is not just on <em>what</em> was built, but <em>how to implement it in a real system</em>.</p><h3>Core Design Principles</h3><p>The system is built around five key principles:</p><ol><li><strong>Database as the primary source of truth</strong><br>Test data is no longer file-based — it is stored, queried, and versioned in a database.</li><li><strong>Separation of concerns via dual flags<br></strong>app.db.enabled → application validation <br>test.data.db.enabled → test data sourcin</li><li><strong>Runtime state sharing across tests</strong><br>Using JSONB columns to persist dynamic values.</li><li><strong>Resilient fallback mechanism</strong><br>DB → JSON → Hardcoded ensures no runtime failures.</li><li><strong>Externalized SQL management</strong><br>Queries are stored in files and dynamically loaded with parameter binding.</li></ol><h3>Problem: Why File-Based Test Data Fails at Scale</h3><p>In a system with:</p><ul><li>40+ modules</li><li>200+ E2E tests</li><li>7 platforms × 4 environments</li></ul><p>test data becomes a distributed problem.</p><h3>Key issues:</h3><ul><li><strong>Duplication:</strong> Same data replicated across multiple environment files</li><li><strong>Drift:</strong> JSON and property files fall out of sync</li><li><strong>No shared state:</strong> Tests cannot reuse runtime-generated data</li><li><strong>Parallel conflicts:</strong> Collisions during concurrent execution</li><li><strong>High maintenance cost:</strong> Small changes require multiple file updates</li></ul><p>At this scale, test data management becomes a <strong>bottleneck for development velocity</strong>.</p><h3>Architecture Overview</h3><p>The solution is based on a <strong>dual-database architecture</strong>, separating application validation from test data management.</p><h3>Dual-Flag Configuration</h3><pre>app.db.enabled        → Connects to application DB (for assertions)<br>test.data.db.enabled  → Connects to TDM DB (for test data)</pre><p>This ensures:</p><ul><li>Clean separation of responsibilities</li><li>No coupling between validation logic and test data sourcing</li></ul><h3>Data Flow and Execution Model</h3><p>All test data access is routed through a central orchestration layer.</p><h3>Execution Flow</h3><ol><li>Test requests data via TestDataManager</li><li>Check ThreadLocal cache</li><li>If enabled → fetch from TDM DB</li><li>If not found → fallback to JSON</li><li>If still not found → fallback to hardcoded defaults</li></ol><p>This creates a <strong>fault-tolerant system with deterministic behavior</strong>.</p><h3>Core Components</h3><h3>1. TestDataManager (Orchestration Layer)</h3><p>This is the entry point for all test data interactions.</p><p>Responsibilities:</p><ul><li>Fetch test data</li><li>Manage shared runtime state</li><li>Implement fallback chain</li><li>Handle caching</li></ul><h3>Example:</h3><pre>SalesOrderTestData testData = SalesOrderTestData.forCase(&quot;accepted&quot;);</pre><p>This abstraction ensures that test code remains clean and independent of data source complexity.</p><h3>2. DAO Layer (Database Access)</h3><p>Database interactions are handled via a DAO (BaseTestDataDAO) backed by connection pooling.</p><p>Responsibilities:</p><ul><li>Execute queries</li><li>Map results to domain objects</li><li>Handle connection lifecycle</li></ul><h3>3. SQL Loader (Query Abstraction)</h3><p>Instead of embedding SQL in code, queries are externalized.</p><pre>SqlLoader sql = SqlLoader.load(&quot;queries/testdata/fetch_test_data.sql&quot;)<br>    .bind(&quot;scriptId&quot;, &quot;101&quot;)<br>    .bind(&quot;environment&quot;, &quot;UAT&quot;);</pre><p>Benefits:</p><ul><li>Prevents SQL injection</li><li>Improves readability</li><li>Enables version control of queries</li></ul><h3>4. ThreadLocal Caching</h3><p>To reduce database round trips, a ThreadLocal cache is introduced.</p><ul><li>Each test thread maintains its own cache</li><li>Frequently accessed data is reused</li><li>Improves performance in parallel execution</li></ul><h3>Cross-Test Data Sharing</h3><p>One of the most critical capabilities is <strong>sharing runtime-generated data across tests</strong>.</p><h3>Implementation</h3><pre>TestDataManager.putSharedData(&quot;so_number&quot;, soNumber);<br>String sharedSO = TestDataManager.getSharedValue(&quot;so_number&quot;);</pre><h3>How it works:</h3><ul><li>Data is persisted in sharable_data (JSONB column)</li><li>Scoped to execution run</li><li>Accessible across different test cases and modules</li></ul><h3>Use cases:</h3><ul><li>Order created in Service A → validated in Service B</li><li>Token generated in login flow → reused across APIs</li><li>IDs generated in upstream tests → consumed downstream</li></ul><p>This enables <strong>true end-to-end testing across distributed systems</strong>.</p><h3>Database Design</h3><p>The system uses PostgreSQL with JSONB for flexibility.</p><h3>test_script_runs</h3><p>Tracks execution metadata:</p><pre>CREATE TABLE test_script_runs (<br>    run_id SERIAL PRIMARY KEY,<br>    script_id BIGINT NOT NULL,<br>    environment VARCHAR(50),<br>    triggered_by VARCHAR(50)<br>);</pre><h3>test_script_results</h3><p>Stores detailed execution results:</p><pre>CREATE TABLE test_script_results (<br>    result_id SERIAL PRIMARY KEY,<br>    run_id BIGINT REFERENCES test_script_runs(run_id),<br>    status VARCHAR(20),<br>    logs JSONB,<br>    sharable_data JSONB,<br>    duration_ms BIGINT<br>);</pre><h3>Design decisions:</h3><ul><li>JSONB for flexible payload storage</li><li>Run-level scoping for traceability</li><li>Separation of runs and results for normalization</li></ul><h3>Fallback Chain: Ensuring Reliability</h3><p>A critical requirement was <strong>zero disruption during migration</strong>.</p><h3>Fallback Strategy</h3><pre>Database → JSON → Hardcoded</pre><h3>Behavior:</h3><ul><li>If DB is available → use it</li><li>If DB mapping missing → fallback to JSON</li><li>If JSON missing → fallback to defaults</li></ul><p>This ensures:</p><ul><li>No test failures due to missing data</li><li>Backward compatibility</li><li>Safe incremental adoption</li></ul><h3>Migration Strategy</h3><p>Instead of a big-bang migration, the system supports <strong>phased rollout</strong>.</p><h3>Approach:</h3><ol><li>Start with existing JSON-based tests</li><li>Gradually onboard test cases to DB</li><li>Use fallback chain to ensure continuity</li><li>Validate stability before full migration</li></ol><h3>Outcome:</h3><ul><li>No CI/CD disruption</li><li>No false negatives</li><li>Smooth transition across teams</li></ul><h3>Results and Impact</h3><p>After implementing this architecture:</p><h3>Measurable Improvements</h3><ul><li><strong>~60% reduction in test data maintenance</strong></li><li>Elimination of duplicated configuration files</li><li>Stable parallel execution</li><li>Reduced flakiness due to controlled data</li><li>Faster onboarding for new test scenarios</li></ul><h3>Engineering Impact</h3><ul><li>Test logic is fully decoupled from test data</li><li>Test execution becomes <strong>data-driven</strong></li><li>Cross-system validation becomes practical</li><li>Automation framework evolves into a <strong>scalable platform</strong></li></ul><h3>Conclusion</h3><p>A DB-first Test Data Management system is not just an optimization — it is a <strong>necessary architectural evolution</strong> for large-scale automation.</p><p><strong>By introducing:</strong></p><ul><li>Centralized data storage</li><li>Runtime state sharing</li><li>Resilient fallback mechanisms</li><li>Clean abstraction layers</li></ul><p>you move from fragile, file-based testing to a <strong>robust, production-grade system</strong>.</p><p><strong>The key takeaway:</strong></p><blockquote><em>Treat test data as a system design problem — not a configuration detail.</em></blockquote><p>Once that layer is solved, test automation becomes predictable, scalable, and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e696c412fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relative XPath in Automation: A Practical Guide to Every XPath Pattern You’ll Actually Use]]></title>
            <link>https://medium.com/@kritagya2022/relative-xpath-in-automation-a-practical-guide-to-every-xpath-pattern-youll-actually-use-b920a023f2ad?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b920a023f2ad</guid>
            <category><![CDATA[relative-xpath]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[xpath]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 12:32:24 GMT</pubDate>
            <atom:updated>2025-12-30T12:32:24.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgNujq1d63Sfs-ma02RPiQ.png" /><figcaption>Types of Relative XPaths</figcaption></figure><p>Most XPath articles stop at syntax. They show <em>what</em> to write, but rarely explain <em>why one XPath survives production while another quietly turns flaky</em>.</p><p>This article focuses <strong>entirely on Relative XPath</strong>, because that’s what real automation frameworks rely on. Absolute XPath has its place during learning and debugging, but scalable automation lives and dies by how well relative paths are designed.</p><p>Each XPath type below is explained with <strong>practical intent</strong>, <strong>real usage scenarios</strong>, and <strong>clear drawbacks</strong> — so you know not just how to write an XPath, but when to trust it.</p><h3>How Relative XPath Sees the DOM</h3><p>Relative XPath views the DOM as a tree of relationships rather than a fixed path.</p><p>Instead of asking <em>“Where exactly is this element?”</em>, Relative XPath asks:</p><ul><li>What uniquely identifies it?</li><li>How is it related to nearby elements?</li><li>What part of the DOM is stable?</li></ul><p>Once you start thinking in terms of <strong>relationships and constraints</strong>, XPath becomes predictable, readable, and maintainable.</p><h3>Absolute vs Relative XPath (Quick Context)</h3><h3>Absolute XPath</h3><p><strong>Syntax</strong></p><pre>/html/body/div/button</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Helps in debugging locator issues quickly</li><li>Useful while learning and understanding the DOM structure</li><li>Can be used in quick experiments or one-off scripts</li></ol><p><strong>Pitfalls</strong></p><ol><li>Extremely brittle in nature</li><li>Breaks with even minor DOM changes and requires fixes</li><li>Not suitable for long-term automation</li><li>Should never be part of a scalable framework</li></ol><h3>Relative XPath (Primary Focus)</h3><p><strong>Syntax</strong></p><pre>//button[@id=&#39;submit&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Ideal for dynamic and frequently changing applications</li><li>Preferred for maintainable and scalable automation frameworks</li><li>Works well with component-based UI architectures</li><li>Easier to refactor and reason about</li></ol><p><strong>Pitfalls</strong></p><ol><li>Overusing // can reduce readability</li><li>Poor scoping can lead to multiple matches</li><li>Requires discipline to keep expressions clean</li></ol><h3>/ vs // — A Small Choice with Big Impact</h3><ul><li>/ selects <strong>direct children only</strong></li><li>// searches <strong>anywhere within the subtree</strong></li></ul><pre>/div/p     → direct child only  <br>//div//p   → any depth under div</pre><p><strong>Rule of thumb:</strong><br>Use // for flexibility, but <strong>scope early</strong> to avoid ambiguity and performance overhead.</p><h3>Performance Reality (Short and Honest)</h3><ul><li>CSS selectors are faster for simple cases like IDs and classes</li><li>XPath is superior when <strong>relationships or text matter</strong></li></ul><p><strong>Prefer CSS when:</strong></p><ol><li>ID or class is stable</li><li>No relationship traversal is required</li></ol><p><strong>Prefer XPath when:</strong></p><ol><li>Navigating parents, siblings, or tables</li><li>Identifying elements by text</li><li>Working with dynamic or generated DOM structures</li></ol><p>Modern browsers handle XPath well, but sloppy expressions still hurt test reliability.</p><h3>Core Relative XPath Patterns</h3><h3>Parent–Child XPath</h3><p><strong>Syntax</strong></p><pre>//div/child::button</pre><p><strong>Best use-case scenarios</strong></p><ol><li>DOM hierarchy is stable and predictable</li><li>Forms, cards, and structured layouts</li></ol><p><strong>Pitfalls</strong></p><ol><li>Breaks when nesting levels change</li><li>Deep chaining increases fragility</li></ol><h3>Sibling XPath</h3><p><strong>Syntax</strong></p><pre>//h2/following-sibling::p<br>//h2/preceding-sibling::p</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Label–value or title–content relationships</li><li>Flat, predictable layouts</li></ol><p><strong>Pitfalls</strong></p><ol><li>Sensitive to layout reordering</li><li>Breaks if sibling structure changes</li></ol><h3>Attribute-based XPath</h3><p><strong>Syntax</strong></p><pre>//input[@name=&#39;username&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Stable attributes (data-test, aria-*)</li><li>Clean and readable locators</li></ol><p><strong>Pitfalls</strong></p><ol><li>Dynamic attributes cause instability</li><li>Requires frontend testability discipline</li></ol><h3>Text-based XPath</h3><p><strong>Syntax</strong></p><pre>//a[text()=&#39;Submit&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Static buttons and labels</li><li>Clear, human-readable intent</li></ol><p><strong>Pitfalls</strong></p><ol><li>Breaks with localization</li><li>Whitespace inconsistencies cause failures</li></ol><h3>contains()</h3><p><strong>Syntax</strong></p><pre>//input[contains(@name,&#39;user&#39;)]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Dynamic or partially predictable attributes</li><li>Framework-generated IDs</li></ol><p><strong>Pitfalls</strong></p><ol><li>Can match unintended elements</li><li>Needs strong scoping</li></ol><h3>starts-with()</h3><p><strong>Syntax</strong></p><pre>//input[starts-with(@id,&#39;user&#39;)]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Consistent naming conventions</li><li>Component-driven DOMs</li></ol><p><strong>Pitfalls</strong></p><ol><li>Breaks if prefix changes</li><li>Less flexible than contains()</li></ol><h3>Logical Operators</h3><p><strong>Syntax</strong></p><pre>//button[@type=&#39;submit&#39; and @id=&#39;login&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Disambiguating similar elements</li><li>Improving locator precision</li></ol><p><strong>Pitfalls</strong></p><ol><li>Reduces readability when overused</li><li>Harder to maintain at scale</li></ol><h3>Index-based XPath</h3><p><strong>Syntax</strong></p><pre>(//div[@class=&#39;item&#39;])[2]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Temporary workarounds</li><li>Exploratory automation</li></ol><p><strong>Pitfalls</strong></p><ol><li>Extremely fragile</li><li>Breaks on any order change</li><li>Should not exist in long-term tests</li></ol><h3>Wildcard XPath</h3><p><strong>Syntax</strong></p><pre>//div/*</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Debugging and DOM exploration</li><li>Understanding unknown layouts</li></ol><p><strong>Pitfalls</strong></p><ol><li>Very low specificity</li><li>Not suitable for automation</li></ol><h3>Parent Axis</h3><p><strong>Syntax</strong></p><pre>//span[text()=&#39;Hello&#39;]/parent::div</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Starting from a known child</li><li>Navigating to containers</li></ol><p><strong>Pitfalls</strong></p><ol><li>Highly DOM-dependent</li><li>Breaks with structural changes</li></ol><h3>Ancestor Axis</h3><p><strong>Syntax</strong></p><pre>//span[text()=&#39;Hello&#39;]/ancestor::div</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Deeply nested components</li><li>Cards, modals, and sections</li></ol><p><strong>Pitfalls</strong></p><ol><li>Can match unintended ancestors</li><li>Requires strict scoping</li></ol><h3>Descendant Axis</h3><p><strong>Syntax</strong></p><pre>//div//p</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Unknown nesting depth</li><li>Content scanning</li></ol><p><strong>Pitfalls</strong></p><ol><li>Performance impact if overused</li><li>Can return excessive matches</li></ol><h3>not()</h3><p><strong>Syntax</strong></p><pre>//button[not(contains(@class,&#39;disabled&#39;))]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Filtering inactive UI states</li><li>Handling dynamic class toggles</li></ol><p><strong>Pitfalls</strong></p><ol><li>Can hide real UI issues</li><li>Must be validated with UI state checks</li></ol><h3>normalize-space()</h3><p><strong>Syntax</strong></p><pre>//span[normalize-space()=&#39;Login&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Inconsistent whitespace</li><li>Framework-rendered text</li></ol><p><strong>Pitfalls</strong></p><ol><li>Minor performance cost</li><li>Use only when necessary</li></ol><h3>position()</h3><p><strong>Syntax</strong></p><pre>//ul/li[position()&gt;1]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Skipping headers or placeholders</li><li>Ordered lists</li></ol><p><strong>Pitfalls</strong></p><ol><li>Order-dependent</li><li>Breaks when structure changes</li></ol><h3>last()</h3><p><strong>Syntax</strong></p><pre>(//tr)[last()]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Latest entries in tables</li><li>Append-only data</li></ol><p><strong>Pitfalls</strong></p><ol><li>Assumes correct ordering</li><li>Breaks if sorting logic changes</li></ol><h3>Union Operator (|)</h3><p><strong>Syntax</strong></p><pre>//button[text()=&#39;Save&#39;] | //button[text()=&#39;Submit&#39;]</pre><p><strong>Best use-case scenarios</strong></p><ol><li>Handling UI variations across releases</li><li>Backward compatibility</li></ol><p><strong>Pitfalls</strong></p><ol><li>Can mask UI inconsistency</li><li>Should not replace proper standardization</li></ol><h3>Final Thoughts: Relative XPath Is a Design Skill</h3><p>Relative XPath is not about clever syntax.<br>It’s about <strong>intent, stability, and restraint</strong>.</p><p>Strong XPath expressions are:</p><ul><li>Scoped</li><li>Readable</li><li>Purpose-driven</li></ul><p>Weak ones introduce flakiness long before they fail visibly.</p><p>Treat XPath as a design decision, not a shortcut — and your automation will scale with far less pain.</p><p>If you want, next we can:</p><ul><li>Convert this into <strong>cheat-sheet graphics</strong></li><li>Add <strong>Selenium / Playwright examples</strong></li><li>Or optimize it specifically for <strong>Medium SEO + reach</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b920a023f2ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XPath Demystified: From Basic Selectors to Real-World Automation]]></title>
            <link>https://medium.com/@kritagya2022/xpath-demystified-from-basic-selectors-to-real-world-automation-9f82d8fb33b9?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f82d8fb33b9</guid>
            <category><![CDATA[xpath]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 10:05:17 GMT</pubDate>
            <atom:updated>2025-12-29T10:05:17.150Z</atom:updated>
            <content:encoded><![CDATA[<p>XPath, or <strong>XML Path Language</strong>, is a powerful tool for navigating and querying XML and HTML documents. For developers, data analysts, and automation engineers, XPath is more than just syntax — it’s a <strong>problem-solving tool for complex document structures</strong>.</p><p>As modern web applications become increasingly dynamic and data-driven, understanding XPath can dramatically improve how you <strong>extract data, build stable automation, and handle brittle DOMs</strong>. This article takes you from XPath fundamentals to <strong>real-world automation use cases</strong>, with practical code examples along the way.</p><p>Whether you’re a beginner learning XPath for the first time or an experienced engineer looking to sharpen your locator strategy, this guide will help you use XPath <strong>intentionally and effectively</strong>.</p><h3>Understanding XPath: The Basics of XML Path Language</h3><h3>What is XPath?</h3><p>XPath is a <strong>query language used to navigate structured documents</strong> like XML and HTML. It allows you to locate elements based on their:</p><ul><li>hierarchy</li><li>attributes</li><li>text</li><li>relationships to other elements</li></ul><p>Think of XPath as a <strong>navigation system for the DOM tree</strong>. Instead of manually traversing nodes, XPath lets you declare <em>what</em> you want and <em>where</em> it exists.</p><p>Example XML:</p><pre>&lt;users&gt;<br>  &lt;user id=&quot;101&quot;&gt;<br>    &lt;name&gt;Kritagya&lt;/name&gt;<br>    &lt;role&gt;SDET&lt;/role&gt;<br>  &lt;/user&gt;<br>&lt;/users&gt;</pre><p>XPath query:</p><pre>//user[@id=&#39;101&#39;]/name</pre><p>Result:</p><pre>Kritagya</pre><h3>History and Evolution of XPath</h3><p>XPath emerged in the late 1990s alongside XML and XSLT. It was designed to solve a simple but critical problem: <strong>how do you reliably query structured documents?</strong></p><p>Over time, XPath became foundational to:</p><ul><li>XSLT transformations</li><li>XQuery</li><li>Web automation tools like Selenium</li><li>XML parsers across languages</li></ul><p>Despite newer technologies, XPath remains relevant because <strong>document trees still exist everywhere</strong> — HTML, XML, SVG, and even API responses.</p><h3>XPath Syntax and Structure: Key Components</h3><h3>Nodes and Axes in XPath</h3><p>XPath treats documents as a <strong>tree of nodes</strong>:</p><ul><li>element nodes</li><li>attribute nodes</li><li>text nodes</li></ul><p>Axes define <strong>directional relationships</strong> between nodes.</p><p>Common axes:</p><ul><li>child</li><li>parent</li><li>ancestor</li><li>descendant</li><li>following-sibling</li><li>preceding-sibling</li></ul><p>Example:</p><pre>//label[text()=&#39;Email&#39;]/following-sibling::input</pre><p>This reads logically:</p><blockquote><em>Find the input that follows the “Email” label.</em></blockquote><p>This <strong>context-aware selection</strong> is where XPath truly shines.</p><h3>Expressions and Predicates</h3><p>Predicates ([...]) filter results.</p><pre>//user[role=&#39;SDET&#39;]</pre><p>You can also filter by position:</p><pre>//user[1]</pre><p>Or combine conditions:</p><pre>//user[@id=&#39;101&#39; and role=&#39;SDET&#39;]</pre><p>Predicates allow XPath to act like <strong>logic</strong>, not just a selector.</p><h3>Common XPath Selectors: Navigating Documents</h3><h3>Basic Selectors (Element Names)</h3><pre>//button</pre><p>Selects all button elements.</p><pre>//form//input</pre><p>Selects all inputs inside a form.</p><p>These are simple but powerful when combined correctly.</p><h3>Attribute Selectors</h3><pre>//input[@name=&#39;email&#39;]</pre><p>This should always be your <strong>first choice</strong> when attributes are stable.</p><p>Partial matches:</p><pre>//button[contains(@class,&#39;submit&#39;)]</pre><p>Dynamic DOMs demand <strong>flexible selectors</strong>, not brittle ones.</p><h3>Text and Position Functions</h3><p>Text-based selection:</p><pre>//button[text()=&#39;Login&#39;]</pre><p>Partial text:</p><pre>//a[contains(text(),&#39;Forgot&#39;)]</pre><p>Position-based:</p><pre>(//input[@type=&#39;text&#39;])[2]</pre><p>Use position only when <strong>no better semantic anchor exists</strong>.</p><h3>Advanced XPath Techniques: Functions and Operators</h3><h3>Built-in Functions</h3><p>String functions:</p><pre>//input[starts-with(@id,&#39;user_&#39;)]</pre><p>Boolean logic:</p><pre>//button[@enabled=&#39;true&#39; or @aria-disabled=&#39;false&#39;]</pre><p>Numeric functions:</p><pre>//product[price &gt; 1000]</pre><p>XPath functions allow <strong>expressive, data-aware queries</strong>.</p><h3>Combining Queries (Union)</h3><pre>//input[@type=&#39;email&#39;] | //input[@type=&#39;password&#39;]</pre><p>Union (|) merges results from multiple paths—useful in flexible test logic.</p><h3>Real-World Applications: Automating Data Extraction</h3><h3>Case Study: Web Scraping with XPath (Python)</h3><p>HTML snippet:</p><pre>&lt;div class=&quot;product&quot;&gt;<br>  &lt;span class=&quot;price&quot;&gt;₹999&lt;/span&gt;<br>&lt;/div&gt;</pre><p>Python with lxml:</p><pre>from lxml import html</pre><pre>tree = html.fromstring(page_content)<br>price = tree.xpath(&quot;//span[@class=&#39;price&#39;]/text()&quot;)<br>print(price)</pre><p>XPath lets you <strong>extract exactly what you need</strong>, without parsing everything.</p><h3>Using XPath in API Responses</h3><p>API XML response:</p><pre>&lt;user&gt;<br>  &lt;name&gt;Kritagya&lt;/name&gt;<br>  &lt;email&gt;test@example.com&lt;/email&gt;<br>&lt;/user&gt;</pre><p>XPath:</p><pre>//user/email/text()</pre><p>This is cleaner than manually traversing response objects.</p><h3>XPath in Automation Tools</h3><h3>XPath in Selenium (Java)</h3><pre>driver.findElement(By.xpath(&quot;//button[text()=&#39;Buy Now&#39;]&quot;)).click();</pre><p>Context-based selection:</p><pre>driver.findElement(<br>  By.xpath(&quot;//label[text()=&#39;Password&#39;]/following::input[1]&quot;)<br>).sendKeys(&quot;secret&quot;);</pre><p>XPath helps <strong>avoid index-based locators</strong>, a major source of flaky tests.</p><h3>XPath with XML Parsing Libraries</h3><p>Python:</p><pre>tree.xpath(&quot;//config/property[@enabled=&#39;true&#39;]&quot;)</pre><p>Java:</p><pre>XPathExpression expr = xpath.compile(&quot;//user/name&quot;);</pre><p>XPath is <strong>language-agnostic</strong>, which makes it extremely versatile.</p><h3>Best Practices for Writing Efficient XPath</h3><h3>Optimize for Stability, Not Cleverness</h3><p>Bad:</p><pre>//div/div/div[2]/span</pre><p>Good:</p><pre>//span[@data-test=&#39;price&#39;]</pre><p>Push for <strong>test-friendly attributes</strong> — this is an SDET responsibility.</p><h3>Keep XPath Readable</h3><p>Write XPath that reads like intent:</p><pre>//order[.//status=&#39;Completed&#39;]//button[text()=&#39;View&#39;]</pre><p>If another engineer can’t understand it, refactor it.</p><h3>Troubleshooting XPath</h3><h3>Debugging XPath</h3><p>Use browser DevTools:</p><pre>$x(&quot;//button[text()=&#39;Login&#39;]&quot;)</pre><p>If it doesn’t return results there, it won’t work in automation.</p><h3>Handling Namespaces</h3><p>Namespace-aware XPath:</p><pre>//ns:user/ns:name</pre><p>Always bind namespaces explicitly in XML-heavy systems.</p><h3>Conclusion</h3><p>Mastering XPath unlocks a powerful ability: <strong>navigating complex document structures with confidence</strong>. When used correctly, XPath enables stable automation, precise data extraction, and resilient test frameworks.</p><p>XPath isn’t outdated.<br>XPath isn’t slow.<br><strong>XPath is misunderstood.</strong></p><p>Treat it as code. Review it. Design it. And it will scale with your automation.</p><h3>FAQ</h3><p><strong>XPath vs XQuery?</strong><br>XPath selects nodes. XQuery queries and transforms XML.</p><p><strong>Can XPath be used with HTML?</strong><br>Yes — HTML is a tree structure, making XPath fully applicable.</p><p><strong>Is XPath case-sensitive?</strong><br>Yes. Element and attribute names must match exactly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f82d8fb33b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flaky Tests in Selenium Automation: Causes, Consequences, and a Framework for Elimination]]></title>
            <link>https://medium.com/@kritagya2022/flaky-tests-in-selenium-automation-causes-consequences-and-a-framework-for-elimination-3a4d84c1ebef?source=rss-11465733f7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a4d84c1ebef</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[qa-automation]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[flaky-tests]]></category>
            <dc:creator><![CDATA[Kritagya]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 17:45:32 GMT</pubDate>
            <atom:updated>2025-12-05T17:45:32.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6y8_l6oO_dN3ZvRlgribtQ.png" /><figcaption>The Signal vs. The Noise</figcaption></figure><p>Automation promises speed, confidence, and repeatability. Flaky Selenium tests deliver the opposite — uncertainty, noise, and erosion of trust.</p><p>Every mature automation team eventually faces flaky tests. The real difference between a fragile Selenium framework and a resilient one is not whether flaky tests appear, but <strong>how systematically they are designed out of the system</strong>.</p><p>This article breaks flakiness down not as a scripting issue, but as a <strong>test architecture, environment control, and CI discipline problem</strong> — and presents a <strong>framework-driven approach to eliminating flaky Selenium tests at scale</strong>.</p><h3>What Are Flaky Tests — Really?</h3><p>Flaky tests are Selenium automated tests that pass and fail inconsistently <strong>without any changes in application code, test code, or test data</strong>.</p><p>The definition is simple. The damage is not.</p><blockquote>A flaky Selenium test:</blockquote><ul><li>Weakens CI/CD signal quality</li><li>Trains engineers to ignore failures</li><li>Normalizes pipeline retries</li><li>Slows down release cycles</li><li>And silently kills automation credibility</li></ul><p>A deterministic failure is debuggable. A random failure is organizational debt.</p><h3>The Engineering Root Causes of Flaky Selenium Tests</h3><p>Flakiness rarely comes from one source. It emerges from <strong>uncontrolled complexity across concurrency, environment, time, UI rendering, and data</strong>.</p><p>These are the six dominant root causes in real-world Selenium frameworks:</p><h4>1. Concurrency Issues (Parallel Selenium Execution)</h4><p>Modern pipelines run Selenium tests in parallel using TestNG, JUnit, Grid, or cloud providers. When multiple tests share:</p><ul><li>Users</li><li>Databases</li><li>Test data</li><li>Sessions</li><li>Files</li></ul><p>…race conditions are inevitable.</p><p><strong>Symptoms:</strong></p><ul><li>One test deletes data required by another.</li><li>Login sessions override each other.</li><li>State-dependent UI elements behave unpredictably.</li></ul><p>This is not a Selenium problem. This is a <strong>shared-state architecture failure</strong>.</p><h4>2. External Dependencies (APIs, Network, Third Parties)</h4><p>If your Selenium test depends on:</p><ul><li>Live APIs</li><li>Payment gateways</li><li>OTP services</li><li>Feature flag services</li><li>Network stability</li></ul><p>…it inherits their reliability profile.</p><p>A UI test waiting for a slow API is already flaky — even if your locators are perfect.</p><h4>3. Non-Deterministic Behavior (Time, Randomness, Dynamic DOM)</h4><p>Selenium tests often fail due to:</p><ul><li>Date/time-dependent UI logic</li><li>Random test data</li><li>Dynamically generated IDs</li><li>Auto-refreshing components</li></ul><p>If identical tests do not produce identical UI states, <strong>your automation is probabilistic — not deterministic</strong>. That is incompatible with CI.</p><h4>4. Unstable or Shared Test Environments</h4><p>Flaky Selenium tests thrive in environments that are:</p><ul><li>Reused across pipelines</li><li>Modified mid-execution</li><li>Poorly reset</li><li>Running inconsistent builds</li></ul><p>One pipeline’s cleanup is another pipeline’s corruption.</p><p>When the environment is unstable, <strong>no amount of WebDriver waits can save you</strong>.</p><h4>5. Weak Assertions (The Silent Flakiness)</h4><p>These tests don’t fail immediately — they fail later and randomly.</p><p>Examples:</p><ul><li>Asserting only page load, not business state</li><li>Checking element presence but not visibility or content</li><li>Ignoring backend side effects</li><li>Skipping validation after form submission</li></ul><p>These introduce <strong>false positives</strong>, which later collapse into flaky failures downstream.</p><h4>6. Flawed Selenium Test Logic</h4><p>This is the most common — and the most preventable — cause:</p><ul><li>Thread.sleep() instead of proper waits</li><li>Overly complex XPath</li><li>Stale element references</li><li>Implicit and explicit wait misuse</li><li>Poor page object design</li></ul><p>Bad Selenium code amplifies every other instability in the system.</p><h3>Why Most Teams Fail at Fixing Flaky Selenium Tests</h3><p>The most common industry responses:</p><ul><li>Add Thread.sleep(5000).</li><li>Increase explicit wait timeout</li><li>Retry failed tests in CI</li><li>Quarantine and forget</li></ul><p>These actions do not eliminate flakiness. They <strong>compress instability into future pipelines</strong>.</p><p>Every sleep added to “stabilize” Selenium is simply <strong>technical debt with a delayed blast radius</strong>.</p><p>Flakiness is a <strong>signal problem</strong>, not a patience problem.</p><h3>A Framework-Driven Approach to Eliminating Flaky Selenium Tests</h3><p>Flaky Selenium tests require <strong>systemic correction</strong>, not reactive patching.</p><h4>1. Test Isolation as a First-Class Citizen</h4><p>Every Selenium test must be:</p><ul><li>Independent</li><li>Idempotent</li><li>Stateless across executions</li></ul><blockquote><strong>Hard Requirements:</strong></blockquote><ul><li>Dedicated users per test</li><li>Unique test data per run</li><li>API-driven data seeding</li><li>Database cleanup hooks</li><li>Zero dependency on execution order</li></ul><p>If two Selenium tests can influence each other, flakiness is guaranteed.</p><h4>2. Eliminate All Randomness from Selenium Tests</h4><p>Any source of randomness must be explicitly controlled.</p><p><strong>Controls:</strong></p><ul><li>Freeze application time using test configs</li><li>Replace random values with seeded generators</li><li>Stub UUID generation via APIs</li><li>Lock deterministic test datasets</li></ul><p>Your Selenium test should behave the same:</p><ul><li>On <a href="http://localhost/">localhost</a></li><li>On CI</li><li>At 2 AM</li><li>Under parallel execution</li></ul><p>If not — it’s already flaky.</p><h4>3. Replace Blind Waits with Logical Synchronization</h4><p>This is where most Selenium frameworks collapse.</p><p>This is not synchronization:</p><pre>Thread.sleep(5000);</pre><p>This is synchronization:</p><pre>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));<br>wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(&quot;dashboard&quot;)));</pre><p>But even explicit waits are not enough.</p><p>True stability comes from:</p><ul><li>Waiting on API completion</li><li>Waiting for DOM state transitions</li><li>Waiting for network idle</li><li>Waiting for backend-driven UI changes</li></ul><p>Assertions must validate:</p><ul><li>Correct UI state</li><li>Correct data persistence</li><li>Correct side effects</li></ul><p>Not just element visibility.</p><h4>4. Simplify and Harden Selenium Test Logic</h4><p>Selenium test code is <strong>production software</strong>, not a side script.</p><blockquote><strong>Engineering Discipline Rules:</strong></blockquote><ul><li>One business flow per test</li><li>Strict Page Object separation</li><li>Zero locator duplication</li><li>Deterministic assertions</li><li>Predictable control flow</li><li>High-signal logging</li></ul><p>Over-engineered tests become flakiness factories.</p><h3>Flaky Selenium Tests Are an Observability Failure</h3><p>When a Selenium test fails, the core question is not:</p><blockquote>“Did the test fail?”</blockquote><p>It is:</p><blockquote>“Can we explain exactly why it failed without re-running it?”</blockquote><p>A mature Selenium framework must surface:</p><ul><li>Browser console logs</li><li>Network traffic (HAR)</li><li>API request/response</li><li>DOM snapshots</li><li>Screenshots</li><li>Video recordings</li><li>Precise timestamps</li></ul><p>Without this, every failure becomes speculation — and flakiness thrives in speculation.</p><h3>The Flaky Test Operational Playbook (CI-Grade Discipline)</h3><p>Stable Selenium teams <strong>operationalize flakiness</strong> instead of emotionally reacting to it.</p><p>A proven playbook:</p><ul><li>Immediate flaky-test tagging</li><li>Tracking flakiness percentage over time</li><li>Auto-quarantining unstable tests</li><li>Enforcing test ownership</li><li>Fixing infra before fixing scripts</li><li>Strict retry limits (never infinite retries)</li></ul><p>Retries should <strong>expose instability</strong>, not normalize it.</p><h3>When Flaky Selenium Tests Become a Business Risk</h3><p>Flaky Selenium automation directly impacts:</p><ul><li>Release velocity</li><li>Regression confidence</li><li>Incident frequency</li><li>Team credibility</li><li>Management trust in automation</li></ul><p>At scale, flakiness becomes <strong>organizational entropy</strong> — risk quietly increasing while metrics look green.</p><h3>Closing Perspective</h3><p>Every Selenium team encounters flaky tests. That is reality. What defines engineering maturity is the <strong>refusal to normalize non-determinism in systems built for determinism</strong>.</p><blockquote>Selenium stability is not achieved with:</blockquote><ul><li>Retries</li><li>Sleeps</li><li>Or “it passed locally” explanations</li></ul><blockquote>It is achieved through:</blockquote><ul><li>Deterministic test design</li><li>Controlled environments</li><li>Strong isolation</li><li>Precise synchronization</li><li>Ruthless observability</li></ul><p>A Selenium test that passes randomly is already failing — it just hasn’t failed loudly enough yet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a4d84c1ebef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>