<?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 krishna chetan on Medium]]></title>
        <description><![CDATA[Stories by krishna chetan on Medium]]></description>
        <link>https://medium.com/@krishnachetan?source=rss-2ecf1b8a928f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gcGpOoR0sDvg3PL1otk89w.jpeg</url>
            <title>Stories by krishna chetan on Medium</title>
            <link>https://medium.com/@krishnachetan?source=rss-2ecf1b8a928f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:28:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishnachetan/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[Build a Playwright Framework with Isolated Browser State]]></title>
            <link>https://krishnachetan.medium.com/build-a-playwright-framework-with-isolated-browser-state-913c206d2938?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/913c206d2938</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 08:25:16 GMT</pubDate>
            <atom:updated>2026-10-28T08:25:16.042Z</atom:updated>
            <content:encoded><![CDATA[<p>A browser test can leave a convincing screenshot path that points to nothing. This exercise keeps a real assertion failure visible, removes the temporary screenshot folder, and then reads the surviving screenshot and trace. The same framework runs two behavior tests in both declared orders with fresh cookie and local-storage state.</p><figure><img alt="PLAYWRIGHT — ISOLATE BROWSER STATE; conceptual browser illustration." src="https://cdn-images-1.medium.com/max/1024/1*SvdBiT3BkBE_Sp9Si6zAeg.png" /></figure><p>The application is an original, loopback-only task board with three fake tasks. No account, external service, model task or user browser is involved. BoardPage handles the page boundary; TaskCard scopes edits to a task ID. The tests express rename and fresh-state behavior. Fixtures own the server, browser context and evidence lifetime.</p><h2>Reproduce the exercise</h2><p>You can reconstruct this exercise without downloading a ZIP. Create a fresh owned folder and save every file shown below at its stated relative path, including subdirectories. Run from that reconstructed folder. Any extraction instructions below describe the optional archive route; the reconstructed folder supplies the same required inputs.</p><p>Extract exercise.zip. Its root is playwright-lab. The recorded host used macOS arm64, Node 26.3.0, npm 11.16.0 and Python 3.13.14. The lock pins Playwright 1.63.0; the actual browser reported Chromium 153.0.8010.12, revision 1243. This package uses the verified playwright/test export included in that pinned package.</p><p>With Node and Python available, run these commands from the extracted root. Dependency setup requires a working registry/download path or a verified local cache. Keep the browser directory owned by this exercise.</p><pre>cd demo<br>npm ci --ignore-scripts --no-audit --no-fund<br>PLAYWRIGHT_BROWSERS_PATH=&quot;../browsers&quot; node node_modules/playwright/cli.js install chromium --only-shell<br>cd ..<br>python3 -B run_exercise.py --output results --browsers browsers<br>python3 -B demo/check_artifacts.py --results results<br>cd demo<br>BROWSER_RESULTS=&quot;../results&quot; python3 -B -m unittest discover -v</pre><p>Use a new results directory each time. The runner refuses an existing directory. It records the original three child exit codes: forward 0, reverse 0, seeded failure 1. The outer runner returns zero only when those outcomes match the declared experiment; it never changes the failed browser test into a passing test.</p><p>On the recorded host, npm metadata and the Node browser downloader timed out. Those original errors remain in the evidence. Verified local tarballs supplied Playwright and its matching core through offline npm ci. A normal-TLS Python download from the same official browser URL supplied the matching browser; its ZIP and executable hashes were recorded. The later browser version readback, tests and artifact reads establish what actually ran. A successful online install or universal offline setup is not claimed.</p><h2>Predict the lifetime before reading the result</h2><p>The fixture first writes temporary-evidence-.../screen.png, then copies it to the persistent test output directory. Which path will still work after the temporary folder is removed? Inspect the order around await use(), the copy, attachment and removal before answering.</p><p>The surviving file is the copied screen.png in the test output directory. trace: &#39;retain-on-failure&#39; also retains the seeded failed run&#39;s trace ZIP. The original temporary path is deliberately passed to the checker after cleanup: it is rejected with exit two. A path string in a log is not proof that bytes survived.</p><h2>Follow ownership and actual outcomes</h2><p>The built-in page belongs to a fresh test context. A worker shares the browser process and the owned static server. The rename test stores an edited title and a harmless training cookie. The fresh-state test sees the seed title, no cookie and no stored task array. Both declared orders pass. This is evidence for these two cases and orders, not proof against every possible interaction.</p><p>The separate negative test expects 999 tasks when the visible page contains 3 tasks. It genuinely fails with a 600-millisecond assertion deadline and exit one. Its screenshot shows the actual three-task page. The trace ZIP retains structured trace events, including the failed expectation. The original error is preserved rather than caught and replaced by a pass.</p><p>The canonical run records four outer commands, three Playwright child commands, three browser processes, three owned server processes and five test contexts. There are four passing browser executions across two distinct normal tests and one separate failed browser test. Eight Python methods inspect the actual result artifacts; they are not eight additional browser tests. All five screenshots and the one retained trace are readable after fixture cleanup. Browser exit logs and server receipts record normal closure. Platform-specific display warnings remain in stderr. Exact browser API call count was not measured.</p><h2>Deliberately reject the stale path</h2><p>Read results/seeded/tests/.../fixture.json, copy its ephemeral value, and pass that exact path to python3 demo/check_artifacts.py --file. It must return REJECTED and exit two because the file is gone. Repeat with the retained path: the checker reports a SHA-256, byte count and image dimensions. The check establishes header readability and retained bytes; the author also decodes and visually inspects the PNG separately. The trace check verifies ZIP CRCs and parses trace events, without claiming that every Trace Viewer feature was manually exercised.</p><h2>Complete source</h2><p>The following files are the exact authored files in the archive. Dependencies, downloaded browsers and result folders are intentionally outside the source archive; the lockfile retains dependency identity.</p><h3>demo/.node-version</h3><pre>26.3.0</pre><h3>demo/AGENTS.md</h3><pre># Owned browser framework<br>Read PROJECT_MEMORY.md. Work only in this training project and explicitly selected fresh results folders. Use the pinned local toolchain and an owned browser profile. No real accounts, user-browser attachment, external services or shared settings changes. Preserve seeded failures and their evidence.</pre><h3>demo/PROJECT_MEMORY.md</h3><pre># Browser isolation exercise<br>The task board contains authored fake tasks. Browser state belongs to a test context; failure traces and screenshots belong to a persistent results folder. Two test orders are observed separately, not claimed as all possible orders. A deleted temporary path is not preserved evidence. Model and learner execution are not claimed.</pre><h3>demo/board.spec.js</h3><pre>&#39;use strict&#39;;<br>const { test, expect } = require(&#39;./fixtures&#39;);<br><br>const cases = [<br>  [&#39;rename and mark only this context&#39;, async ({ board, context }) =&gt; {<br>    await expect(board.task(&#39;task-01&#39;).title).toHaveValue(&#39;Read the guide&#39;);<br>    await expect(context.cookies()).resolves.toEqual([]);<br>    await board.task(&#39;task-01&#39;).rename(&#39;Review fixture ownership&#39;);<br>    await context.addCookies([{ name: &#39;case_marker&#39;, value: &#39;training-only&#39;, url: board.page.url() }]);<br>    const saved = await board.storedTasks();<br>    expect(saved[0].title).toBe(&#39;Review fixture ownership&#39;);<br>    expect(saved[1].title).toBe(&#39;Check keyboard focus&#39;);<br>  }],<br>  [&#39;fresh context starts from the seed&#39;, async ({ board, context }) =&gt; {<br>    await expect(board.task(&#39;task-01&#39;).title).toHaveValue(&#39;Read the guide&#39;);<br>    await expect(context.cookies()).resolves.toEqual([]);<br>    expect(await board.storedTasks()).toBeNull();<br>  }]<br>];<br>if (process.env.TEST_ORDER === &#39;reverse&#39;) cases.reverse();<br>if (process.env.SEED_FAILURE === &#39;1&#39;) {<br>  test(&#39;seeded count failure retains the actual page&#39;, async ({ board }) =&gt; {<br>    await expect(board.page.getByRole(&#39;status&#39;, { name: &#39;Task count&#39;, exact: true })).toHaveText(&#39;999 tasks&#39;, { timeout: 600 });<br>  });<br>} else {<br>  for (const [name, body] of cases) test(name, body);<br>}</pre><h3>demo/board_page.js</h3><pre>&#39;use strict&#39;;<br>const { expect } = require(&#39;playwright/test&#39;);<br><br>class TaskCard {<br>  constructor(page, id) {<br>    this.root = page.getByTestId(id);<br>    this.title = this.root.getByRole(&#39;textbox&#39;, { name: &#39;Title&#39;, exact: true });<br>    this.save = this.root.getByRole(&#39;button&#39;, { name: &#39;Save&#39;, exact: true });<br>  }<br>  async rename(title) {<br>    await this.title.fill(title);<br>    await this.save.click();<br>    await expect(this.root.getByRole(&#39;status&#39;)).toContainText(&#39;Saved&#39;);<br>  }<br>}<br><br>class BoardPage {<br>  constructor(page) { this.page = page; }<br>  task(id) { return new TaskCard(this.page, id); }<br>  async open(url) {<br>    await this.page.goto(url);<br>    await expect(this.page.getByRole(&#39;heading&#39;, { name: &#39;Local task board&#39;, exact: true })).toBeVisible();<br>  }<br>  async storedTasks() {<br>    return this.page.evaluate(() =&gt; JSON.parse(localStorage.getItem(&#39;training-task-board&#39;)));<br>  }<br>}<br>module.exports = { BoardPage };</pre><h3>demo/check_artifacts.py</h3><pre>&quot;&quot;&quot;Read surviving browser results; a printed temporary path is not evidence.&quot;&quot;&quot;<br>import argparse<br>import hashlib<br>import json<br>from pathlib import Path<br>import re<br>import struct<br>import zipfile<br><br><br>def read_json(path):<br>    return json.loads(Path(path).read_text())<br><br><br>def sha(path):<br>    return hashlib.sha256(Path(path).read_bytes()).hexdigest()<br><br><br>def inspect_file(path):<br>    path = Path(path)<br>    data = path.read_bytes()<br>    if path.suffix == &#39;.png&#39;:<br>        if data[:8] != b&#39;\x89PNG\r\n\x1a\n&#39; or data[12:16] != b&#39;IHDR&#39;:<br>            raise ValueError(&#39;not a PNG image&#39;)<br>        width, height = struct.unpack(&#39;&gt;II&#39;, data[16:24])<br>        if width &lt;= 0 or height &lt;= 0:<br>            raise ValueError(&#39;empty image dimensions&#39;)<br>        details = {&#39;width&#39;: width, &#39;height&#39;: height}<br>    elif path.suffix == &#39;.zip&#39;:<br>        with zipfile.ZipFile(path) as archive:<br>            if archive.testzip() is not None:<br>                raise ValueError(&#39;trace ZIP CRC failure&#39;)<br>            traces = [n for n in archive.namelist() if n.endswith(&#39;.trace&#39;)]<br>            events = [json.loads(line) for n in traces for line in archive.read(n).splitlines()]<br>            if not traces or not any(e.get(&#39;type&#39;) == &#39;before&#39; for e in events):<br>                raise ValueError(&#39;no trace events&#39;)<br>            details = {&#39;members&#39;: len(archive.namelist()), &#39;trace_events&#39;: len(events)}<br>    else:<br>        raise ValueError(&#39;expected a PNG screenshot or ZIP trace&#39;)<br>    return {&#39;path&#39;: str(path.resolve()), &#39;sha256&#39;: sha(path), &#39;bytes&#39;: len(data), **details}<br><br><br>def specs(report):<br>    def walk(suite):<br>        yield from suite.get(&#39;specs&#39;, [])<br>        for child in suite.get(&#39;suites&#39;, []):<br>            yield from walk(child)<br>    return [s for suite in report[&#39;suites&#39;] for s in walk(suite)]<br><br><br>def inspect_results(root):<br>    root = Path(root).resolve()<br>    execution = read_json(root / &#39;execution.json&#39;)<br>    if execution[&#39;status&#39;] != &#39;RECORDED_OUTCOMES_REQUIRE_ARTIFACT_REVIEW&#39;:<br>        raise ValueError(&#39;the browser commands did not finish as declared&#39;)<br>    checks = {}<br>    runs = {}<br>    pictures = []<br>    for command in execution[&#39;commands&#39;]:<br>        name = command[&#39;name&#39;]<br>        folder = root / name<br>        report = read_json(folder / &#39;report.json&#39;)<br>        runtime = read_json(folder / &#39;runtime.json&#39;)<br>        fixtures = [read_json(p) for p in sorted((folder / &#39;tests&#39;).rglob(&#39;fixture.json&#39;))]<br>        rows = specs(report)<br>        results = [r for s in rows for t in s[&#39;tests&#39;] for r in t[&#39;results&#39;]]<br>        stderr = (root / command[&#39;stderr&#39;][&#39;path&#39;]).read_text()<br>        browser_pids = re.findall(r&#39;&lt;launched&gt; pid=(\d+)&#39;, stderr)<br>        server = read_json(folder / &#39;server-process.json&#39;)<br>        server_receipt = read_json(folder / &#39;server.json&#39;)<br>        for fixture in fixtures:<br>            retained = Path(fixture[&#39;retained&#39;])<br>            if not retained.is_relative_to(folder / &#39;tests&#39;):<br>                raise ValueError(&#39;screenshot is outside the owned results folder&#39;)<br>            pictures.append(inspect_file(retained))<br>        runs[name] = dict(report_sha256=sha(folder / &#39;report.json&#39;), runtime=runtime,<br>                          order=[s[&#39;title&#39;] for s in rows], outcomes=[r[&#39;status&#39;] for r in results],<br>                          fixtures=fixtures, browser_pids=[int(p) for p in browser_pids],<br>                          browser_exit_observed=len(browser_pids) == 1 and all(<br>                              f&#39;[pid={p}] &lt;process did exit: exitCode=0, signal=null&gt;&#39; in stderr for p in browser_pids),<br>                          server=server, server_closed=server_receipt[&#39;server_closed&#39;],<br>                          assertion_errors=[r.get(&#39;error&#39;, {}).get(&#39;message&#39;, &#39;&#39;) for r in results])<br>    checks[&#39;command_streams_and_exits&#39;] = (list(runs) == [&#39;forward&#39;, &#39;reverse&#39;, &#39;seeded&#39;] and<br>        [c[&#39;exit_code&#39;] for c in execution[&#39;commands&#39;]] == [0, 0, 1] and all(<br>            sha(root / c[s][&#39;path&#39;]) == c[s][&#39;sha256&#39;] for c in execution[&#39;commands&#39;] for s in (&#39;stdout&#39;, &#39;stderr&#39;)))<br>    checks[&#39;two_declared_orders_pass&#39;] = (runs[&#39;forward&#39;][&#39;order&#39;] == list(reversed(runs[&#39;reverse&#39;][&#39;order&#39;])) and<br>        len(set(runs[&#39;forward&#39;][&#39;order&#39;])) == 2 and all(runs[n][&#39;outcomes&#39;] == [&#39;passed&#39;, &#39;passed&#39;] for n in (&#39;forward&#39;, &#39;reverse&#39;)))<br>    checks[&#39;context_state_isolated&#39;] = all(<br>        len(runs[n][&#39;fixtures&#39;]) == 2 and all(<br>            (f[&#39;cookies&#39;] == [] and f[&#39;savedTasks&#39;] is None) if f[&#39;title&#39;].startswith(&#39;fresh context&#39;) else<br>            (f[&#39;cookies&#39;] == [{&#39;name&#39;: &#39;case_marker&#39;, &#39;value&#39;: &#39;training-only&#39;}] and<br>             json.loads(f[&#39;savedTasks&#39;])[0][&#39;title&#39;] == &#39;Review fixture ownership&#39;) for f in runs[n][&#39;fixtures&#39;])<br>        for n in (&#39;forward&#39;, &#39;reverse&#39;))<br>    error = &#39;\n&#39;.join(runs[&#39;seeded&#39;][&#39;assertion_errors&#39;])<br>    checks[&#39;original_seeded_failure_retained&#39;] = (runs[&#39;seeded&#39;][&#39;outcomes&#39;] == [&#39;failed&#39;] and &#39;999&#39; in error and<br>                                                &#39;3&#39; in error and &#39;Task count&#39; in error)<br>    checks[&#39;temporary_evidence_removed&#39;] = all(f[&#39;temporaryRemoved&#39;] and not Path(f[&#39;scratch&#39;]).exists() and<br>        not Path(f[&#39;ephemeral&#39;]).exists() for r in runs.values() for f in r[&#39;fixtures&#39;])<br>    traces = list((root / &#39;seeded/tests&#39;).rglob(&#39;trace.zip&#39;))<br>    trace = inspect_file(traces[0]) if len(traces) == 1 else None<br>    checks[&#39;persistent_images_and_trace_readable&#39;] = len(pictures) == 5 and trace is not None<br>    checks[&#39;owned_processes_closed&#39;] = all(r[&#39;browser_exit_observed&#39;] and r[&#39;server_closed&#39;] and<br>        r[&#39;server&#39;][&#39;code&#39;] == 0 and r[&#39;server&#39;][&#39;signal&#39;] is None for r in runs.values())<br>    checks[&#39;exact_recorded_runtime&#39;] = all((r[&#39;runtime&#39;][&#39;node&#39;], r[&#39;runtime&#39;][&#39;playwright&#39;], r[&#39;runtime&#39;][&#39;browser&#39;]) ==<br>        (&#39;26.3.0&#39;, &#39;1.63.0&#39;, &#39;153.0.8010.12&#39;) for r in runs.values())<br>    if not all(checks.values()):<br>        raise ValueError(&#39;failed artifact checks: &#39; + &#39;, &#39;.join(k for k, v in checks.items() if not v))<br>    return {&#39;status&#39;: &#39;PASS&#39;, &#39;checks&#39;: checks, &#39;runs&#39;: runs, &#39;screenshots&#39;: pictures, &#39;trace&#39;: trace,<br>            &#39;browser_test_executions&#39;: 5, &#39;normal_unique_tests&#39;: 2, &#39;seeded_failed_tests&#39;: 1,<br>            &#39;model_requests&#39;: 0, &#39;learner_outcomes&#39;: &#39;NOT_RUN&#39;}<br><br><br>def main():<br>    parser = argparse.ArgumentParser()<br>    group = parser.add_mutually_exclusive_group(required=True)<br>    group.add_argument(&#39;--results&#39;, type=Path)<br>    group.add_argument(&#39;--file&#39;, type=Path)<br>    args = parser.parse_args()<br>    try:<br>        result = inspect_results(args.results) if args.results else inspect_file(args.file)<br>    except (OSError, ValueError, KeyError, zipfile.BadZipFile) as exc:<br>        print(json.dumps({&#39;status&#39;: &#39;REJECTED&#39;, &#39;reason&#39;: str(exc)}))<br>        return 2<br>    print(json.dumps(result, indent=2))<br>    return 0<br><br><br>if __name__ == &#39;__main__&#39;:<br>    raise SystemExit(main())</pre><h3>demo/fixtures.js</h3><pre>&#39;use strict&#39;;<br>const { test: base, expect } = require(&#39;playwright/test&#39;);<br>const { spawn } = require(&#39;node:child_process&#39;);<br>const fs = require(&#39;node:fs/promises&#39;);<br>const path = require(&#39;node:path&#39;);<br>const readline = require(&#39;node:readline&#39;);<br>const { BoardPage } = require(&#39;./board_page&#39;);<br><br>const test = base.extend({<br>  runtime: [async ({ browser }, use) =&gt; {<br>    const output = path.resolve(process.env.RESULTS_DIR);<br>    await fs.mkdir(output, { recursive: true });<br>    await fs.writeFile(path.join(output, &#39;runtime.json&#39;), JSON.stringify({<br>      node: process.versions.node, playwright: require(&#39;playwright/package.json&#39;).version,<br>      browser: browser.version(), workerPid: process.pid,<br>      browsersPath: process.env.PLAYWRIGHT_BROWSERS_PATH<br>    }, null, 2) + &#39;\n&#39;);<br>    await use();<br>  }, { scope: &#39;worker&#39;, auto: true }],<br>  boardURL: [async ({}, use) =&gt; {<br>    const output = path.resolve(process.env.RESULTS_DIR);<br>    await fs.mkdir(output, { recursive: true });<br>    const child = spawn(process.env.PROJECT_PYTHON || &#39;python3&#39;,<br>      [&#39;-B&#39;, &#39;serve_board.py&#39;, &#39;--receipt&#39;, path.join(output, &#39;server.json&#39;)],<br>      { cwd: __dirname, stdio: [&#39;pipe&#39;, &#39;pipe&#39;, &#39;pipe&#39;] });<br>    let stderr = &#39;&#39;;<br>    child.stderr.on(&#39;data&#39;, data =&gt; { stderr += data.toString(); });<br>    const exited = new Promise(resolve =&gt; child.once(&#39;exit&#39;, (code, signal) =&gt; resolve({ code, signal })));<br>    let ready;<br>    try {<br>      ready = await new Promise((resolve, reject) =&gt; {<br>        const lines = readline.createInterface({ input: child.stdout });<br>        const timer = setTimeout(() =&gt; reject(new Error(&#39;Owned server readiness deadline exceeded&#39;)), 5000);<br>        lines.once(&#39;line&#39;, line =&gt; { clearTimeout(timer); resolve(JSON.parse(line)); });<br>        child.once(&#39;error&#39;, error =&gt; { clearTimeout(timer); reject(error); });<br>      });<br>      await use(ready.url);<br>    } finally {<br>      child.stdin.end();<br>      const timer = setTimeout(() =&gt; child.kill(&#39;SIGTERM&#39;), 5000);<br>      const result = await exited;<br>      clearTimeout(timer);<br>      await fs.writeFile(path.join(output, &#39;server-process.json&#39;), JSON.stringify({<br>        pid: child.pid, ready, ...result, stderr<br>      }, null, 2) + &#39;\n&#39;);<br>      if (result.code !== 0) throw new Error(`Owned server cleanup failed: ${JSON.stringify(result)}`);<br>    }<br>  }, { scope: &#39;worker&#39; }],<br>  board: async ({ page, boardURL }, use) =&gt; {<br>    const board = new BoardPage(page);<br>    await board.open(boardURL);<br>    await use(board);<br>  },<br>  retainedEvidence: [async ({ page }, use, testInfo) =&gt; {<br>    const scratch = await fs.mkdtemp(testInfo.outputPath(&#39;temporary-evidence-&#39;));<br>    const ephemeral = path.join(scratch, &#39;screen.png&#39;);<br>    const retained = testInfo.outputPath(&#39;screen.png&#39;);<br>    const record = { title: testInfo.title, startedAt: new Date().toISOString(), scratch, ephemeral, retained };<br>    try {<br>      await use();<br>    } finally {<br>      record.status = testInfo.status;<br>      record.expectedStatus = testInfo.expectedStatus;<br>      record.cookies = (await page.context().cookies()).map(cookie =&gt; ({ name: cookie.name, value: cookie.value }));<br>      record.savedTasks = await page.evaluate(() =&gt; localStorage.getItem(&#39;training-task-board&#39;));<br>      await page.screenshot({ path: ephemeral, fullPage: true });<br>      await fs.copyFile(ephemeral, retained);<br>      await testInfo.attach(&#39;owned-board-screen&#39;, { path: retained, contentType: &#39;image/png&#39; });<br>      await fs.rm(scratch, { recursive: true });<br>      record.temporaryRemoved = true;<br>      record.finishedAt = new Date().toISOString();<br>      await fs.writeFile(testInfo.outputPath(&#39;fixture.json&#39;), JSON.stringify(record, null, 2) + &#39;\n&#39;);<br>    }<br>  }, { auto: true }]<br>});<br>module.exports = { test, expect };</pre><h3>demo/package-lock.json</h3><pre>{<br>  &quot;name&quot;: &quot;task-board-isolation-lab&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;lockfileVersion&quot;: 3,<br>  &quot;requires&quot;: true,<br>  &quot;packages&quot;: {<br>    &quot;&quot;: {<br>      &quot;name&quot;: &quot;task-board-isolation-lab&quot;,<br>      &quot;version&quot;: &quot;1.0.0&quot;,<br>      &quot;devDependencies&quot;: {<br>        &quot;playwright&quot;: &quot;1.63.0&quot;<br>      },<br>      &quot;engines&quot;: {<br>        &quot;node&quot;: &quot;26.3.0&quot;<br>      }<br>    },<br>    &quot;node_modules/playwright-core&quot;: {<br>      &quot;version&quot;: &quot;1.63.0&quot;,<br>      &quot;resolved&quot;: &quot;https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz&quot;,<br>      &quot;integrity&quot;: &quot;sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==&quot;,<br>      &quot;dev&quot;: true,<br>      &quot;license&quot;: &quot;Apache-2.0&quot;,<br>      &quot;bin&quot;: {<br>        &quot;playwright-core&quot;: &quot;cli.js&quot;<br>      },<br>      &quot;engines&quot;: {<br>        &quot;node&quot;: &quot;&gt;=20&quot;<br>      }<br>    },<br>    &quot;node_modules/playwright&quot;: {<br>      &quot;version&quot;: &quot;1.63.0&quot;,<br>      &quot;resolved&quot;: &quot;https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz&quot;,<br>      &quot;integrity&quot;: &quot;sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==&quot;,<br>      &quot;dev&quot;: true,<br>      &quot;license&quot;: &quot;Apache-2.0&quot;,<br>      &quot;bin&quot;: {<br>        &quot;playwright&quot;: &quot;cli.js&quot;<br>      },<br>      &quot;engines&quot;: {<br>        &quot;node&quot;: &quot;&gt;=20&quot;<br>      },<br>      &quot;dependencies&quot;: {<br>        &quot;playwright-core&quot;: &quot;1.63.0&quot;<br>      }<br>    }<br>  }<br>}</pre><h3>demo/package.json</h3><pre>{<br>  &quot;name&quot;: &quot;task-board-isolation-lab&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;playwright test&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;playwright&quot;: &quot;1.63.0&quot;<br>  },<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;26.3.0&quot;<br>  }<br>}</pre><h3>demo/playwright.config.js</h3><pre>&#39;use strict&#39;;<br>const { defineConfig } = require(&#39;playwright/test&#39;);<br>const path = require(&#39;node:path&#39;);<br>if (!process.env.RESULTS_DIR) throw new Error(&#39;RESULTS_DIR must name an owned persistent results directory&#39;);<br>const output = path.resolve(process.env.RESULTS_DIR);<br>module.exports = defineConfig({<br>  testDir: __dirname,<br>  testMatch: &#39;board.spec.js&#39;,<br>  fullyParallel: false,<br>  workers: 1,<br>  retries: 0,<br>  timeout: 15000,<br>  outputDir: path.join(output, &#39;tests&#39;),<br>  reporter: [[&#39;list&#39;], [&#39;json&#39;, { outputFile: path.join(output, &#39;report.json&#39;) }]],<br>  use: { browserName: &#39;chromium&#39;, headless: true, viewport: { width: 1280, height: 900 },<br>    trace: &#39;retain-on-failure&#39;, screenshot: &#39;off&#39; }<br>});</pre><h3>demo/portal_server.py</h3><pre>&quot;&quot;&quot;Serve only files in a completed owned build on an ephemeral loopback port.&quot;&quot;&quot;<br>from contextlib import contextmanager<br>from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer<br>from pathlib import Path<br>from urllib.parse import urlsplit, unquote<br>import threading<br><br><br>@contextmanager<br>def serve(directory):<br>    root = Path(directory).resolve()<br>    requests = []<br>    class Handler(BaseHTTPRequestHandler):<br>        def log_message(self, *args):<br>            pass<br>        def do_GET(self):<br>            route = unquote(urlsplit(self.path).path)<br>            path = (root / (route.lstrip(&#39;/&#39;) or &#39;index.html&#39;)).resolve()<br>            valid = path.is_relative_to(root) and path.is_file() and path.suffix in {&#39;.html&#39;, &#39;.json&#39;, &#39;.js&#39;}<br>            code, body = (200, path.read_bytes()) if valid else (404, b&#39;Not found&#39;)<br>            kind = {&#39;.html&#39;: &#39;text/html; charset=utf-8&#39;, &#39;.json&#39;: &#39;application/json&#39;, &#39;.js&#39;: &#39;text/javascript&#39;}.get(path.suffix, &#39;text/plain&#39;)<br>            requests.append(dict(method=&#39;GET&#39;, path=route, status=code))<br>            self.send_response(code); self.send_header(&#39;Content-Type&#39;, kind); self.send_header(&#39;Content-Length&#39;, str(len(body))); self.end_headers(); self.wfile.write(body)<br>    server = ThreadingHTTPServer((&#39;127.0.0.1&#39;, 0), Handler)<br>    thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()<br>    try:<br>        yield &#39;http://127.0.0.1:&#39; + str(server.server_port), requests<br>    finally:<br>        server.shutdown(); server.server_close(); thread.join(timeout=3)<br>        if thread.is_alive(): raise RuntimeError(&#39;Owned server did not stop&#39;)</pre><h3>demo/serve_board.py</h3><pre>&quot;&quot;&quot;Run the reused owned file server until its owning fixture closes stdin.&quot;&quot;&quot;<br>from pathlib import Path<br>from datetime import datetime, timezone<br>import argparse<br>import json<br>import os<br>import sys<br>from portal_server import serve<br><br>parser = argparse.ArgumentParser()<br>parser.add_argument(&#39;--receipt&#39;, type=Path, required=True)<br>args = parser.parse_args()<br>record = {&#39;pid&#39;: os.getpid(), &#39;started_at&#39;: datetime.now(timezone.utc).isoformat()}<br>with serve(Path(__file__).parent / &#39;web&#39;) as (url, requests):<br>    record[&#39;url&#39;] = url<br>    print(json.dumps({&#39;url&#39;: url, &#39;pid&#39;: os.getpid()}), flush=True)<br>    sys.stdin.read()<br>record.update(finished_at=datetime.now(timezone.utc).isoformat(), server_closed=True, requests=requests)<br>args.receipt.write_text(json.dumps(record, indent=2) + &#39;\n&#39;)</pre><h3>demo/test_artifacts.py</h3><pre>&quot;&quot;&quot;Eight acceptance checks over actual browser output, not simulated browser runs.&quot;&quot;&quot;<br>import os<br>from pathlib import Path<br>import unittest<br>from check_artifacts import inspect_file, inspect_results<br><br><br>class ArtifactChecks(unittest.TestCase):<br>    @classmethod<br>    def setUpClass(cls):<br>        cls.result = inspect_results(Path(os.environ[&#39;BROWSER_RESULTS&#39;]))<br><br>    def test_command_streams_and_expected_exits(self):<br>        self.assertTrue(self.result[&#39;checks&#39;][&#39;command_streams_and_exits&#39;])<br><br>    def test_both_declared_orders_pass(self):<br>        self.assertTrue(self.result[&#39;checks&#39;][&#39;two_declared_orders_pass&#39;])<br><br>    def test_cookie_and_storage_state_are_isolated(self):<br>        self.assertTrue(self.result[&#39;checks&#39;][&#39;context_state_isolated&#39;])<br><br>    def test_seeded_failure_is_not_converted_to_success(self):<br>        self.assertEqual(self.result[&#39;runs&#39;][&#39;seeded&#39;][&#39;outcomes&#39;], [&#39;failed&#39;])<br><br>    def test_deleted_temporary_path_is_rejected(self):<br>        for run in self.result[&#39;runs&#39;].values():<br>            for fixture in run[&#39;fixtures&#39;]:<br>                with self.assertRaises(FileNotFoundError):<br>                    inspect_file(fixture[&#39;ephemeral&#39;])<br><br>    def test_persistent_trace_and_screenshots_remain_readable(self):<br>        self.assertEqual(len(self.result[&#39;screenshots&#39;]), 5)<br>        self.assertGreater(self.result[&#39;trace&#39;][&#39;trace_events&#39;], 0)<br><br>    def test_owned_browser_and_server_processes_closed(self):<br>        self.assertTrue(self.result[&#39;checks&#39;][&#39;owned_processes_closed&#39;])<br><br>    def test_actual_runtime_matches_the_pin(self):<br>        self.assertTrue(self.result[&#39;checks&#39;][&#39;exact_recorded_runtime&#39;])<br><br><br>if __name__ == &#39;__main__&#39;:<br>    unittest.main(verbosity=2)</pre><h3>demo/web/app.js</h3><pre>&#39;use strict&#39;;<br>const seed = [<br>  { id: &#39;task-01&#39;, title: &#39;Read the guide&#39;, status: &#39;active&#39; },<br>  { id: &#39;task-02&#39;, title: &#39;Check keyboard focus&#39;, status: &#39;active&#39; },<br>  { id: &#39;task-03&#39;, title: &#39;Save a baseline&#39;, status: &#39;completed&#39; }<br>];<br>const storageKey = &#39;training-task-board&#39;;<br>let tasks = JSON.parse(localStorage.getItem(storageKey) || JSON.stringify(seed));<br>document.querySelector(&#39;#count&#39;).textContent = `${tasks.length} tasks`;<br>for (const task of tasks) {<br>  const card = document.createElement(&#39;article&#39;);<br>  card.dataset.testid = task.id;<br>  card.setAttribute(&#39;aria-label&#39;, task.id);<br>  const heading = document.createElement(&#39;h2&#39;);<br>  heading.textContent = task.id;<br>  const state = document.createElement(&#39;span&#39;);<br>  state.className = &#39;state&#39;;<br>  state.textContent = task.status;<br>  const label = document.createElement(&#39;label&#39;);<br>  label.htmlFor = `${task.id}-title`;<br>  label.textContent = &#39;Title&#39;;<br>  const input = document.createElement(&#39;input&#39;);<br>  input.id = label.htmlFor;<br>  input.value = task.title;<br>  const save = document.createElement(&#39;button&#39;);<br>  save.textContent = &#39;Save&#39;;<br>  const result = document.createElement(&#39;output&#39;);<br>  result.setAttribute(&#39;aria-label&#39;, &#39;Save result&#39;);<br>  save.addEventListener(&#39;click&#39;, () =&gt; {<br>    task.title = input.value;<br>    localStorage.setItem(storageKey, JSON.stringify(tasks));<br>    result.textContent = `Saved ${task.id}`;<br>  });<br>  card.append(heading, state, label, input, save, result);<br>  document.querySelector(&#39;#tasks&#39;).append(card);<br>}</pre><h3>demo/web/index.html</h3><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>&lt;title&gt;Local task board&lt;/title&gt;<br>&lt;style&gt;<br>body { font:18px system-ui; background:#071523; color:#eaf3fc; padding:30px; }<br>main { max-width:880px; margin:auto; } .note { color:#a5c3d9; }<br>article { background:#102c40; border:1px solid #325970; border-radius:12px; padding:20px; margin:16px 0; }<br>label { display:block; margin:12px 0 5px; } input { font:inherit; width:65%; padding:10px; }<br>button { font:inherit; padding:11px 24px; background:#40d4e8; border:0; border-radius:6px; margin-left:12px; }<br>.state { color:#70e3b0; } output { display:block; min-height:26px; color:#f8d581; }<br>&lt;/style&gt;<br>&lt;main&gt;<br>&lt;p class=&quot;note&quot;&gt;OWNED TRAINING TASKS · NO REAL ACCOUNT&lt;/p&gt;<br>&lt;h1&gt;Local task board&lt;/h1&gt;<br>&lt;p role=&quot;status&quot; aria-label=&quot;Task count&quot; id=&quot;count&quot;&gt;&lt;/p&gt;<br>&lt;section id=&quot;tasks&quot; aria-label=&quot;Tasks&quot;&gt;&lt;/section&gt;<br>&lt;/main&gt;<br>&lt;script src=&quot;/app.js&quot;&gt;&lt;/script&gt;<br>&lt;/html&gt;</pre><h3>run_exercise.py</h3><pre>&quot;&quot;&quot;Record two declared test orders and a separate expected failing browser run.&quot;&quot;&quot;<br>from datetime import datetime, timezone<br>from pathlib import Path<br>import argparse<br>import hashlib<br>import json<br>import os<br>import subprocess<br>import sys<br><br>ROOT = Path(__file__).resolve().parent<br>parser = argparse.ArgumentParser()<br>parser.add_argument(&#39;--output&#39;, type=Path, required=True)<br>parser.add_argument(&#39;--browsers&#39;, type=Path, default=ROOT / &#39;toolchain/browsers&#39;)<br>args = parser.parse_args()<br>out = args.output.resolve()<br>out.mkdir(parents=True, exist_ok=False)<br>sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()<br>now = lambda: datetime.now(timezone.utc).isoformat()<br>source = {str(p.relative_to(ROOT / &#39;demo&#39;)): sha(p) for p in (ROOT / &#39;demo&#39;).rglob(&#39;*&#39;)<br>          if p.is_file() and &#39;node_modules&#39; not in p.parts and &#39;__pycache__&#39; not in p.parts}<br>proof = {&#39;status&#39;: &#39;RUNNING&#39;, &#39;controller_pid&#39;: os.getpid(), &#39;started_at&#39;: now(),<br>         &#39;source_hashes&#39;: source, &#39;commands&#39;: [], &#39;model_requests&#39;: 0, &#39;learner_outcomes&#39;: &#39;NOT_RUN&#39;}<br>def save():<br>    (out / &#39;execution.json&#39;).write_text(json.dumps(proof, indent=2) + &#39;\n&#39;)<br>save()<br>for name, order, failure, expected in [(&#39;forward&#39;, &#39;forward&#39;, &#39;0&#39;, 0), (&#39;reverse&#39;, &#39;reverse&#39;, &#39;0&#39;, 0), (&#39;seeded&#39;, &#39;forward&#39;, &#39;1&#39;, 1)]:<br>    result_dir = out / name<br>    result_dir.mkdir()<br>    temporary = result_dir / &#39;process-tmp&#39;<br>    temporary.mkdir()<br>    selected = {&#39;RESULTS_DIR&#39;: str(result_dir), &#39;TEST_ORDER&#39;: order, &#39;SEED_FAILURE&#39;: failure,<br>                &#39;PROJECT_PYTHON&#39;: sys.executable, &#39;PLAYWRIGHT_BROWSERS_PATH&#39;: str(args.browsers.resolve()),<br>                &#39;TMPDIR&#39;: str(temporary), &#39;DEBUG&#39;: &#39;pw:browser&#39;}<br>    argv = [&#39;node&#39;, &#39;node_modules/playwright/cli.js&#39;, &#39;test&#39;]<br>    row = {&#39;name&#39;: name, &#39;argv&#39;: argv, &#39;cwd&#39;: str(ROOT / &#39;demo&#39;), &#39;started_at&#39;: now(),<br>           &#39;environment_overrides&#39;: selected, &#39;expected_exit_code&#39;: expected}<br>    proof[&#39;commands&#39;].append(row)<br>    with (out / (name + &#39;.stdout.txt&#39;)).open(&#39;wb&#39;) as stdout, (out / (name + &#39;.stderr.txt&#39;)).open(&#39;wb&#39;) as stderr:<br>        child = subprocess.Popen(argv, cwd=ROOT / &#39;demo&#39;, env={**os.environ, **selected}, stdout=stdout, stderr=stderr)<br>        row[&#39;pid&#39;] = child.pid<br>        save()<br>        row[&#39;exit_code&#39;] = child.wait(timeout=180)<br>    row[&#39;finished_at&#39;] = now()<br>    for stream in [&#39;stdout&#39;, &#39;stderr&#39;]:<br>        path = out / (name + &#39;.&#39; + stream + &#39;.txt&#39;)<br>        row[stream] = {&#39;path&#39;: path.name, &#39;sha256&#39;: sha(path)}<br>    save()<br>    print(name, row[&#39;exit_code&#39;], flush=True)<br>    if row[&#39;exit_code&#39;] != expected:<br>        proof.update(status=&#39;UNEXPECTED_OUTCOME_REQUIRES_REVIEW&#39;, finished_at=now())<br>        save()<br>        raise SystemExit(1)<br>assert all(sha(ROOT / &#39;demo&#39; / name) == value for name, value in source.items())<br>proof.update(status=&#39;RECORDED_OUTCOMES_REQUIRE_ARTIFACT_REVIEW&#39;, sources_unchanged=True, finished_at=now())<br>save()</pre><h2>Practice and next step</h2><p>Recall which title and cookie the fresh-state test observed when it ran second. We already saw both declared orders pass; verify that result in its fixture receipt, then read the retained failed screenshot. Keep the seeded failure red; improving the framework means preserving its explanation, not changing its expected value.</p><p>Next, lesson 112, <strong>Build a Selenium Framework with Owned Driver Lifecycles</strong>. Reuse this task board to give session creation, explicit waits, first failure evidence and driver shutdown clear owners. The next question is whether cleanup preserves the first useful exception when an interaction fails.</p><h2>Sources</h2><p>The current official <a href="https://playwright.dev/docs/test-fixtures">fixture documentation</a> describes test-scoped page/context fixtures and worker browser sharing. The <a href="https://playwright.dev/docs/test-use-options#recording-options">recording options</a> describe trace retention; the <a href="https://playwright.dev/docs/test-reporters#json-reporter">reporter documentation</a> describes JSON output. The actual installed package and browser identities come from local runtime evidence, not an assumption that the documentation version equals the installed version.</p><p>This local macOS exercise did not run on Windows or Linux, did not use real authentication, and did not measure model behavior, learner outcomes or audience retention. Public article and video URLs remain unset until verified publication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=913c206d2938" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab CI Rules — Run the Right Tests]]></title>
            <link>https://krishnachetan.medium.com/gitlab-ci-rules-run-the-right-tests-130f2ba1551f?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/130f2ba1551f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 22:07:34 GMT</pubDate>
            <atom:updated>2026-10-26T22:07:34.279Z</atom:updated>
            <content:encoded><![CDATA[<p>A bad rule can create two pipelines, skip a required test, or run expensive work for a tiny document change. We will design the event table first, then check the rules with code.</p><figure><img alt="GITLAB CI RULES — RUN THE RIGHT TESTS; conceptual pipeline illustration." src="https://cdn-images-1.medium.com/max/1024/1*lnYlCOob0Ogx2hv7s_NSag.png" /></figure><p><a href="https://www.youtube.com/watch?v=H9KeLsnZ2KA">Watch the matching lesson: GitLab CI Rules — Run the Right Tests</a></p><h3>A fast pipeline is useful only when it starts for the right event and runs the right tests</h3><p>Keep these decisions separate. First accept or reject the event. Then choose unit, integration, UI, mobile, or hardware work from risk and cost.</p><p>List merge request, default branch push, schedule, manual run, changed files, expected pipeline, and expected jobs. This makes missing and duplicate paths easy to see.</p><h3>The pipeline source tells you why GitLab is evaluating the configuration</h3><p>A push, merge request, schedule, web run, trigger, and parent pipeline are different events. Do not treat every event as the same branch build.</p><p>Put narrow important cases first. End workflow rules with an explicit never fallback so an unknown event does not quietly create a pipeline.</p><p>The example accepts the merge-request event but rejects a normal feature-branch push. The checked event pair creates exactly one feature pipeline.</p><h3>A push to the default branch should still receive the required verification</h3><p>The workflow accepts the default branch. Unit and integration jobs enter the pipeline, and each job keeps its own report after pass or fail.</p><p>The example accepts a schedule and runs both lanes. A real plan can add browser matrices, security checks, long simulations, or hardware jobs when their resources and cleanup are controlled.</p><p>Unit tests are cheap and run on every accepted event. Integration tests run on the default branch, on a schedule, or on a relevant merge-request change.</p><h3>Changed-file rules can save time, but they need a safe fallback</h3><p>The lesson watches source and integration-test paths. A documentation-only merge request skips integration, but still runs unit tests. Full default-branch and scheduled runs protect against a weak change map.</p><p>The checked model proves that result. This is a deliberate policy, not a guess. If documentation can change generated code or deployment behavior, the policy must be wider.</p><p>The path match makes the expensive boundary check visible. The event table expects both jobs, and the code fails if selection becomes smaller or larger by accident.</p><h3>An event that is not approved should create nothing</h3><p>The manual web run on a feature branch is rejected in this small policy. If manual runs are needed, add one clear rule and test its branch, permissions, variables, and job set.</p><p>The static check refuses only and except in this lesson. Keep one reviewed style, and test the complete event matrix when the configuration changes.</p><p>The example rejects allowed failure and commands that force success. Rules choose when work appears. The pytest exit code still decides whether that work passed.</p><h3>Every selected test job should publish useful evidence after failure</h3><p>The unit and integration examples create separate JUnit paths and upload them always. Separate names prevent one lane from replacing another lane’s report.</p><p>Every event has an exact expected job list. A changed rule must update a visible expectation instead of changing production behavior silently.</p><p>Use CI lint and a private pipeline before trusting production YAML. Read back the pipeline source, variables, jobs, test selection, reports, and final status.</p><h3>Review rules by asking what can run, what can disappear, and what can run twice</h3><p>Check every source, protected branch, tag, schedule, child pipeline, file path, fallback, and manual action that matters. Missing evidence means the policy is not yet proven.</p><p>Run the model and change the docs path to a source path.</p><h3>Define pipeline creation separately from job inclusion</h3><p>The outer workflow:rules decides whether a pipeline exists. Each job&#39;s rules then select its work. This lesson permits merge-request events, the default branch, and schedules. The example blocks a manual web run on a feature branch; a manual run on the default branch still matches the branch rule. Read the conditions, not only the event name.</p><p>This is the lesson’s rules fragment for .gitlab-ci.yml. Supply the intended Python environment, dependencies, and real tests/unit and tests/integration directories before using it in a project. The <a href="https://docs.gitlab.com/ci/jobs/job_rules/">GitLab rules reference</a> describes the provider&#39;s actual evaluation behavior.</p><pre>workflow:<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH&#39;<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;schedule&quot;&#39;<br>    - when: never<br><br>stages:<br>  - test<br><br>unit_tests:<br>  stage: test<br>  script:<br>    - python -m pytest tests/unit --junitxml=reports/unit.xml<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH&#39;<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;schedule&quot;&#39;<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: reports/unit.xml<br><br>integration_tests:<br>  stage: test<br>  script:<br>    - python -m pytest tests/integration --junitxml=reports/integration.xml<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;schedule&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH&#39;<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>      changes:<br>        - src/**/*<br>        - tests/integration/**/*<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: reports/integration.xml</pre><h2>Check the event matrix before changing a live pipeline</h2><p>Save the self-contained teaching model as cicd-332-example.py and run python cicd-332-example.py with Python 3.10 or later. It was checked locally with Python 3.13.14. The special path matching below implements only the small patterns in this lesson; it is not a replacement for GitLab&#39;s parser.</p><pre>from dataclasses import dataclass<br><br>from fnmatch import fnmatch<br><br>import hashlib<br><br>import json<br><br>@dataclass(frozen=True)<br>class Event:<br>    name: str<br>    source: str<br>    branch: str<br>    default_branch: str = &quot;main&quot;<br>    changed_files: tuple = ()<br><br>def workflow_allows(event):<br>    return (<br>        event.source == &quot;merge_request_event&quot;<br>        or event.branch == event.default_branch<br>        or event.source == &quot;schedule&quot;<br>    )<br><br>def path_matches(path, pattern):<br>    if pattern == &quot;src/**/*&quot;:<br>        return path.startswith(&quot;src/&quot;)<br>    if pattern == &quot;tests/integration/**/*&quot;:<br>        return path.startswith(&quot;tests/integration/&quot;)<br>    return fnmatch(path, pattern)<br><br>def changed(event, patterns):<br>    return any(path_matches(path, pattern) for path in event.changed_files for pattern in patterns)<br><br>def selected_jobs(event):<br>    if not workflow_allows(event):<br>        return ()<br>    jobs = [&quot;unit_tests&quot;]<br>    integration = (<br>        event.source == &quot;schedule&quot;<br>        or event.branch == event.default_branch<br>        or (<br>            event.source == &quot;merge_request_event&quot;<br>            and changed(event, (&quot;src/**/*&quot;, &quot;tests/integration/**/*&quot;))<br>        )<br>    )<br>    if integration:<br>        jobs.append(&quot;integration_tests&quot;)<br>    return tuple(jobs)<br><br>events = (Event(&#39;feature_push&#39;, &#39;push&#39;, &#39;feature/login&#39;, changed_files=(&#39;src/login.py&#39;,)), Event(&#39;code_merge_request&#39;, &#39;merge_request_event&#39;, &#39;feature/login&#39;, changed_files=(&#39;src/login.py&#39;,)), Event(&#39;docs_merge_request&#39;, &#39;merge_request_event&#39;, &#39;docs/readme&#39;, changed_files=(&#39;README.md&#39;,)), Event(&#39;default_branch_push&#39;, &#39;push&#39;, &#39;main&#39;, changed_files=(&#39;src/login.py&#39;,)), Event(&#39;nightly_schedule&#39;, &#39;schedule&#39;, &#39;main&#39;), Event(&#39;manual_web_run&#39;, &#39;web&#39;, &#39;feature/login&#39;))<br><br>actual = {event.name: list(selected_jobs(event)) for event in events}<br><br>expected = {&#39;feature_push&#39;: [], &#39;code_merge_request&#39;: [&#39;unit_tests&#39;, &#39;integration_tests&#39;], &#39;docs_merge_request&#39;: [&#39;unit_tests&#39;], &#39;default_branch_push&#39;: [&#39;unit_tests&#39;, &#39;integration_tests&#39;], &#39;nightly_schedule&#39;: [&#39;unit_tests&#39;, &#39;integration_tests&#39;], &#39;manual_web_run&#39;: []}<br><br>assert actual == expected<br><br>assert len([name for name in (&#39;feature_push&#39;, &#39;code_merge_request&#39;) if actual[name]]) == 1<br>print(json.dumps(actual, indent=2))</pre><p>The feature push selects no jobs, the code merge request selects both jobs, the documentation merge request selects unit tests, and default-branch and scheduled changes select both. For the paired feature-push and merge-request examples, only one pipeline is allowed. Those are six modeled events, not six submitted pipelines.</p><h2>Common problems and fixes</h2><p>If the same change creates both branch and merge-request pipelines, inspect workflow:rules first. If integration unexpectedly disappears, check the changed paths and the comparison base used for that event. If a manual run is blocked, decide which branch and source should be allowed and add a specific rule; a catch-all final success rule can reintroduce duplicates.</p><p>The local model and static checks passed. GitLab CI Lint, merged configuration, actual event variables, and saved job reports still need verification in the target project. Scheduled and new-branch change detection can differ from a merge request, which is why this example handles schedule and default-branch cases explicitly.</p><h3>Continue learning</h3><p><a href="https://www.youtube.com/watch?v=M1pEiDluamI">CI vs Continuous Delivery vs Continuous Deployment</a> builds on this lesson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130f2ba1551f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Serial Communication — No Hanging Reads]]></title>
            <link>https://krishnachetan.medium.com/python-serial-communication-no-hanging-reads-95205590330e?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/95205590330e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 22:06:12 GMT</pubDate>
            <atom:updated>2026-10-26T22:06:12.840Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Watch the matching lesson: </em><a href="https://www.youtube.com/watch?v=79_fmnD7Hv8"><em>Python Serial Communication — No Hanging Reads</em></a><em>.</em></blockquote><p>The device stays silent, readline waits forever, and cleanup never starts. Serial automation needs exact settings, a frame rule, read and write limits, useful evidence, and clear ownership.</p><figure><img alt="SERIAL READS — WITHOUT HANGS; conceptual bus illustration." src="https://cdn-images-1.medium.com/max/1024/1*e753pcDEBUzJO10d4anrXA.png" /></figure><h3>A serial read without a limit can hold the whole run</h3><p>Python opens a named port, writes bytes, and reads bytes. The test must know the speed, data bits, parity, stop bits, flow control, timeout, and message framing.</p><p>UART describes signal timing and frame bits. A serial adapter and driver expose a computer port. This lesson checks software framing with loopback; real boards need separate wiring and signal checks.</p><h3>Both ends must agree before text can make sense</h3><p>The example uses one hundred fifteen thousand two hundred baud, eight data bits, no parity, one stop bit, and no flow control. Real settings must come from the interface contract.</p><p>Windows may show COM names. Mac and Ubuntu use device paths. Match a known adapter identity when possible, record the selected port, and fail when the choice is unclear.</p><p>PySerial loop URL lets this lesson test open, write, flush, read, framing, and close without a physical device. It does not prove board wiring or firmware behavior.</p><h3>Encode before writing and decode only after a full frame</h3><p>The command STATUS question mark becomes UTF-8 bytes plus newline. PySerial writes bytes, not a Python text string. The response stays raw until framing is checked.</p><p>Read until newline or the maximum frame size. A different device may use carriage return, fixed length, a length field, or a binary marker. Write the actual protocol rule.</p><p>Compare written bytes with payload length, then flush to wait until outgoing data is sent. A partial write is a failure with expected and actual byte counts.</p><h3>A timeout turns silence into a bounded result</h3><p>The example gives reads a time limit. An empty loopback read returns after about five hundredths of a second instead of waiting forever. The code checks that bounded behavior.</p><p>Read until can return partial data when its time limit ends. The decoder refuses a frame without newline and reports byte count and safe hexadecimal evidence.</p><p>The example caps a frame at one hundred twenty-eight bytes. It refuses an outgoing command that is already too large and stops reading when the limit is reached.</p><h3>Invalid text bytes need a clear error, not silent replacement</h3><p>After a complete frame arrives, decode it with the documented encoding. If bytes are invalid, report safe hexadecimal data and the decode error. Binary protocols should stay bytes.</p><p>The demo records sent and received byte counts and hex. Real evidence must remove passwords, tokens, personal data, and other private payloads before it is saved or shared.</p><p>Before this isolated loopback exchange, the example clears input and output buffers. On real hardware, clear only when the protocol and ownership rules say old data is not meaningful.</p><h3>Two readers on one port can split one message</h3><p>Give one connection to one owner. Put command and response work behind that owner, then let tests use its methods. Do not let parallel tests read the same port directly.</p><p>Catch a serial error only where you can add the operation, port identity, settings, and safe state. Keep the original error as the cause and always release the connection.</p><p>The with block owns the loopback connection. When work leaves the block, the port closes. Real cleanup may also restore device mode or release a power controller.</p><h3>Prove one full frame, one bounded empty read, and one refused partial frame</h3><p>Open the included Python file. It echoes STATUS question mark, checks byte counts and hex, measures the empty-read timeout, rejects a partial frame, and closes every connection.</p><p>Next, send SCPI commands, read identified responses, validate numeric units and ranges, manage errors, save evidence, and leave the instrument in a known state.</p><h2>Prove exact bytes through a serial loopback</h2><p>The loop:// endpoint echoes bytes without needing a physical serial device. The demo sends STATUS? followed by a newline, checks the write count, reads up to a delimiter and maximum frame length, then decodes only a complete frame. Two negative paths matter as much as the echo: an empty read must time out, and a partial frame without its newline must be refused.</p><h3>Prepare the loopback example</h3><p>Use an isolated Python environment with pySerial installed, and save the complete block below as serial_loopback_demo.py. The package is named pyserial; the import is serial. The local check used Python 3.13.14 and pyserial 3.5. In your selected environment, python -m pip install pyserial==3.5 installs that recorded dependency; then run python serial_loopback_demo.py. Package installation was not repeated for the check reported here.</p><p>The <a href="https://pyserial.readthedocs.io/en/latest/pyserial.html#installation">pySerial installation guide</a> explains the package/import names. The <a href="https://pyserial.readthedocs.io/en/latest/url_handlers.html#loop">loop URL documentation</a> describes a simulated connection. Keep loop:// for this exercise: no USB adapter or board is needed.</p><p>The following example is included in the lesson package.</p><pre>&quot;&quot;&quot;Check serial framing and timeout handling with pySerial loopback.&quot;&quot;&quot;<br><br>import json<br>from dataclasses import dataclass<br>from time import monotonic<br><br>import serial<br><br><br>@dataclass(frozen=True)<br>class SerialConfig:<br>    port_url: str = &quot;loop://&quot;<br>    baudrate: int = 115200<br>    read_timeout_seconds: float = 0.2<br>    write_timeout_seconds: float = 0.2<br>    maximum_frame_bytes: int = 128<br><br>    def __post_init__(self):<br>        if self.baudrate &lt;= 0:<br>            raise ValueError(&quot;baudrate must be greater than zero&quot;)<br>        if self.read_timeout_seconds &lt;= 0 or self.write_timeout_seconds &lt;= 0:<br>            raise ValueError(&quot;read and write timeouts must be greater than zero&quot;)<br>        if self.maximum_frame_bytes &lt; 2:<br>            raise ValueError(&quot;maximum frame size must allow data and a newline&quot;)<br><br><br>def decode_line(raw_frame):<br>    if not raw_frame.endswith(b&quot;\n&quot;):<br>        raise TimeoutError(<br>            f&quot;complete newline frame not received; bytes={len(raw_frame)}; &quot;<br>            f&quot;hex={raw_frame.hex()}&quot;<br>        )<br>    try:<br>        return raw_frame[:-1].decode(&quot;utf-8&quot;)<br>    except UnicodeDecodeError as error:<br>        raise ValueError(f&quot;frame is not valid UTF-8; hex={raw_frame.hex()}&quot;) from error<br><br><br>def exchange_line(config, command):<br>    if not isinstance(command, str) or not command:<br>        raise ValueError(&quot;command must be non-empty text&quot;)<br>    if &quot;\r&quot; in command or &quot;\n&quot; in command:<br>        raise ValueError(&quot;command must not contain a line ending&quot;)<br><br>    payload = command.encode(&quot;utf-8&quot;) + b&quot;\n&quot;<br>    if len(payload) &gt; config.maximum_frame_bytes:<br>        raise ValueError(&quot;encoded command is larger than the frame limit&quot;)<br><br>    with serial.serial_for_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20config.port_url,%3Cbr%3E%20%20%20%20%20%20%20%20baudrate=config.baudrate,%3Cbr%3E%20%20%20%20%20%20%20%20bytesize=serial.EIGHTBITS,%3Cbr%3E%20%20%20%20%20%20%20%20parity=serial.PARITY_NONE,%3Cbr%3E%20%20%20%20%20%20%20%20stopbits=serial.STOPBITS_ONE,%3Cbr%3E%20%20%20%20%20%20%20%20timeout=config.read_timeout_seconds,%3Cbr%3E%20%20%20%20%20%20%20%20write_timeout=config.write_timeout_seconds,%3Cbr%3E%20%20%20%20%20%20%20%20xonxoff=False,%3Cbr%3E%20%20%20%20%20%20%20%20rtscts=False,%3Cbr%3E%20%20%20%20%20%20%20%20dsrdtr=False,%3Cbr%3E) as connection:<br>        connection.reset_input_buffer()<br>        connection.reset_output_buffer()<br>        written = connection.write(payload)<br>        connection.flush()<br>        raw_response = connection.read_until(<br>            expected=b&quot;\n&quot;,<br>            size=config.maximum_frame_bytes,<br>        )<br><br>    if written != len(payload):<br>        raise IOError(f&quot;partial write: expected {len(payload)} bytes, wrote {written}&quot;)<br><br>    return {<br>        &quot;port&quot;: config.port_url,<br>        &quot;baudrate&quot;: config.baudrate,<br>        &quot;sent_bytes&quot;: written,<br>        &quot;received_bytes&quot;: len(raw_response),<br>        &quot;sent_hex&quot;: payload.hex(),<br>        &quot;received_hex&quot;: raw_response.hex(),<br>        &quot;received_text&quot;: decode_line(raw_response),<br>    }<br><br><br>def prove_empty_read_times_out(config):<br>    with serial.serial_for_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20config.port_url,%3Cbr%3E%20%20%20%20%20%20%20%20baudrate=config.baudrate,%3Cbr%3E%20%20%20%20%20%20%20%20timeout=0.05,%3Cbr%3E%20%20%20%20%20%20%20%20write_timeout=config.write_timeout_seconds,%3Cbr%3E) as connection:<br>        started = monotonic()<br>        raw_response = connection.read_until(b&quot;\n&quot;, size=config.maximum_frame_bytes)<br>        elapsed = monotonic() - started<br><br>    assert raw_response == b&quot;&quot;<br>    assert 0.04 &lt;= elapsed &lt; 0.5<br>    return round(elapsed, 3)<br><br><br>def main():<br>    config = SerialConfig()<br>    result = exchange_line(config, &quot;STATUS?&quot;)<br>    empty_read_seconds = prove_empty_read_times_out(config)<br><br>    assert result[&quot;received_text&quot;] == &quot;STATUS?&quot;<br>    assert result[&quot;sent_bytes&quot;] == result[&quot;received_bytes&quot;]<br>    assert result[&quot;sent_hex&quot;] == result[&quot;received_hex&quot;]<br><br>    try:<br>        decode_line(b&quot;PARTIAL&quot;)<br>    except TimeoutError as error:<br>        assert &quot;complete newline frame not received&quot; in str(error)<br>    else:<br>        raise AssertionError(&quot;a partial frame should be refused&quot;)<br><br>    print(json.dumps({&quot;exchange&quot;: result, &quot;empty_read_seconds&quot;: empty_read_seconds}, indent=2))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>The sent and received byte counts and hex strings should match, and received_text should be STATUS?. The empty read returns no bytes near its configured 0.05-second wait; the demo uses a tolerance rather than exact timing. The partial frame check raises a clear timeout instead of treating incomplete text as a valid reply.</p><p>Lesson check: the existing demonstration passed locally on Python 3.13.14 with pyserial 3.5. Save the complete block as serial_loopback_demo.py and run python serial_loopback_demo.py in an environment with those dependencies.</p><h3>Prove that malformed input is rejected before opening a port</h3><p>The echo, empty-read and partial-frame checks above cover framing and timeout handling. Add three different checks: a complete frame with invalid UTF-8, a command longer than the byte limit, and a command containing its own newline. The byte ff is invalid UTF-8; its final 0a is a valid newline. That distinction makes this an encoding failure rather than an incomplete frame.</p><p>Save this as additional_checks.py beside serial_loopback_demo.py, then run python additional_checks.py. It imports the existing functions rather than copying them. patch.object temporarily replaces the connection factory; the final assertion proves these checks never opened it.</p><pre>from unittest.mock import patch<br>import serial_loopback_demo as demo<br>cases = [<br>    (&quot;invalid UTF-8&quot;, lambda: demo.decode_line(b&quot;\xff\n&quot;),<br>     ValueError, &quot;frame is not valid UTF-8; hex=ff0a&quot;),<br>    (&quot;oversized command&quot;, lambda: demo.exchange_line(<br>        demo.SerialConfig(maximum_frame_bytes=4), &quot;STATUS?&quot;),<br>     ValueError, &quot;encoded command is larger than the frame limit&quot;),<br>    (&quot;embedded newline&quot;, lambda: demo.exchange_line(<br>        demo.SerialConfig(), &quot;STATUS?\n&quot;),<br>     ValueError, &quot;command must not contain a line ending&quot;),<br>]<br>with patch.object(demo.serial, &quot;serial_for_url&quot;) as open_port:<br>    for name, call, error_type, expected in cases:<br>        try:<br>            call()<br>        except error_type as error:<br>            assert str(error) == expected, str(error)<br>            print(f&quot;{name}: {type(error).__name__}: {error}&quot;)<br>        else:<br>            raise AssertionError(f&quot;{name} should have been rejected&quot;)<br>    open_port.assert_not_called()<br>print(&quot;No serial connection was opened by these three checks.&quot;)</pre><p>The actual local output was:</p><pre>invalid UTF-8: ValueError: frame is not valid UTF-8; hex=ff0a<br>oversized command: ValueError: encoded command is larger than the frame limit<br>embedded newline: ValueError: command must not contain a line ending<br>No serial connection was opened by these three checks.</pre><p>The unchanged main demo also passed locally: the echo’s text, byte count and hex matched, the empty read returned no bytes, and the partial frame was refused. Its measured empty-read wait is a host observation, not a real-time guarantee. The 0.5 upper bound is this demo&#39;s tolerance; if a heavily scheduled host exceeds it, retain the timing result and investigate scheduling instead of declaring a hardware failure. These checks establish software validation only, not wiring or firmware behavior.</p><p><a href="https://docs.python.org/3/library/unittest.mock.html#patch">Python’s patch documentation</a> explains the temporary replacement. <a href="https://pyserial.readthedocs.io/en/latest/shortintro.html#readline">pySerial’s timeout guidance</a> explains why a missing line ending needs an explicit timeout and interpretation.</p><h2>Common problems and fixes</h2><p><strong>Symptom:</strong> The program receives only part of a message</p><p><strong>What to check or change:</strong> Define framing and maximum length; do not assume a single read returns a whole application message.</p><p><strong>Symptom:</strong> Text looks correct but bytes differ</p><p><strong>What to check or change:</strong> Inspect encoding, line endings, byte counts, and hexadecimal evidence.</p><p><strong>Symptom:</strong> A port remains busy after failure</p><p><strong>What to check or change:</strong> Own the connection in a context manager and verify cleanup on exception paths.</p><h3>Try the next check</h3><p>Pass a command containing a newline and verify it is rejected before opening the connection. Then reduce the frame limit below the encoded command length and inspect that error separately.</p><h3>Scope and limits</h3><p>Loopback verifies the Python framing path, not wiring, voltage levels, parity compatibility, hardware buffering, or a device protocol. The read timeout does not guarantee a successful response; partial and empty results still need explicit interpretation.</p><h3>Continue learning</h3><p>Next: <a href="https://www.youtube.com/watch?v=3iOooUJd8mI">Automate Lab Instruments with Python and SCPI</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95205590330e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Pipelines Tutorial — Run Tests and Publish Results]]></title>
            <link>https://krishnachetan.medium.com/azure-pipelines-tutorial-run-tests-and-publish-results-5c9d68959e11?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9d68959e11</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 22:05:27 GMT</pubDate>
            <atom:updated>2026-10-26T22:05:27.842Z</atom:updated>
            <content:encoded><![CDATA[<p>We will use one Ubuntu job, select Python, build one identified artifact, verify it, run pytest honestly, publish every test result, and keep the evidence after failure.</p><figure><img alt="AZURE PIPELINES — RUN TESTS, KEEP RESULTS; conceptual pipeline illustration." src="https://cdn-images-1.medium.com/max/1024/1*GS-kWItobQcfwnwl2kG6Mw.png" /></figure><p><a href="https://www.youtube.com/watch?v=lw4FErghUgo">Watch the matching lesson: Azure Pipelines Tutorial — Run Tests and Publish Results</a></p><h3>Build and test Python in Azure Pipelines without losing the result</h3><p>The pipeline starts from a chosen event. A job is the scheduled unit of work. The job gets an agent and workspace. Its steps run in order and return results and files.</p><p>Find the build output. Run the exact test command. Read the exit code and XML report. Automation should repeat this known path instead of hiding an unknown process.</p><h3>Keep azure-pipelines.yml beside the project code</h3><p>A versioned YAML file makes the pipeline path reviewable. This lesson uses YAML, not the older visual editor. Keep the first pipeline small enough to explain every line.</p><p>The trigger section covers main branch changes. The P R section covers proposed changes. Start with clear events, then add schedules or manual paths only when their job set is understood.</p><p>The job uses the current hosted Ubuntu image label and a fifteen-minute limit. Mac and Windows need separate setup and behavior lessons, so we do not mix their commands into this first example.</p><h3>Get a clean, shallow copy of the source for this run</h3><p>The checkout step gets the project. Clean removes leftover workspace changes. A shallow copy is enough for this small test path. Some version or release tasks need deeper history, so change that deliberately.</p><p>The current Python selection task adds the requested version to the path. The following steps call python from that selected environment. Hosted and self-hosted agents have different tool-cache rules.</p><p>Run python -m pip with the dependency file. Keep versions controlled. A missing package or unsafe credential problem must fail clearly. Never print a private token into the job log.</p><h3>Create one artifact and a manifest that names its revision and digest</h3><p>The build script writes the app file under evidence and records its path, source revision, and SHA-256 digest. The next step checks that identity before testing.</p><p>The verification script hashes the file and compares it with the saved digest. A mismatch fails before pytest. Testing a changed or wrong artifact would give a result for the wrong thing.</p><p>Strict markers catch selection errors. Exit zero means pass. Exit one means a test failed. Exit five means nothing was collected. Do not use a setting that turns these results into false success.</p><h3>Run the result task even after the pytest step fails</h3><p>The always condition lets the publisher read the XML after pass, fail, or empty selection. It rejects missing files, publishing errors, and failed test cases instead of showing a misleading healthy task.</p><p>The artifact task also uses always. It publishes the manifest, built file, and reports under one clear name. This task is for the hosted service example; server editions may need a different artifact path.</p><p>Pass creates two cases and exit zero. Controlled failure keeps its reason and exits one. Empty selection exits five. A changed artifact fails its digest check before the test can mislead us.</p><h3>Task names include a major version, so record what was checked</h3><p>This lesson records the current major task versions and its check date. Recheck task inputs, hosted image changes, service limits, and breaking updates before reusing an old YAML file.</p><p>The local script checks required YAML fragments and runs the Python behavior. The real service must still validate the YAML, select the agent, run tasks, publish results, and provide downloadable evidence.</p><p>Confirm the project, event, revision, hosted image, Python version, build digest, selected tests, exit code, published cases, artifact contents, task versions, and final job status.</p><h3>Add Windows, Mac, stages, templates, and service connections in separate lessons</h3><p>Each addition changes setup, permissions, or failure behavior. Keep the working Ubuntu path as a known base. Add one new need, validate it, and save new evidence.</p><p>Run the local demo, then validate this YAML in your own private project after configuring the intended test environment.</p><h3>Make missing reports fail explicitly</h3><p>The example declares PublishTestResults@2 with missing-file, publication-error, and failed-test checks enabled. PublishPipelineArtifact@1 retains the evidence directory. Both publication tasks use always() after the test attempt.</p><p>Save this configuration as azure-pipelines.yml. It is the lesson&#39;s integration example, reviewed against the <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/publish-pipeline-artifact-v1?view=azure-pipelines">official configuration reference</a>. The local checks below do not submit it to the provider.</p><pre>trigger:<br>  branches:<br>    include:<br>      - main<br><br>pr:<br>  branches:<br>    include:<br>      - main<br><br>variables:<br>  pythonVersion: &#39;3.14&#39;<br><br>jobs:<br>  - job: test<br>    displayName: Build and test<br>    timeoutInMinutes: 15<br>    pool:<br>      vmImage: ubuntu-latest<br>    steps:<br>      - checkout: self<br>        clean: true<br>        fetchDepth: 1<br>      - task: UsePythonVersion@0<br>        inputs:<br>          versionSpec: &#39;$(pythonVersion)&#39;<br>          architecture: x64<br>      - script: python -m pip install -r requirements.txt<br>        displayName: Install test dependencies<br>      - script: python build_demo.py<br>        displayName: Build one artifact<br>      - script: python verify_artifact.py evidence/manifest.json<br>        displayName: Verify artifact identity<br>      - script: python -m pytest tests --strict-markers --junitxml=evidence/reports/pytest.xml<br>        displayName: Run pytest<br>      - task: PublishTestResults@2<br>        displayName: Publish test results<br>        condition: always()<br>        inputs:<br>          testResultsFormat: JUnit<br>          testResultsFiles: evidence/reports/pytest.xml<br>          failTaskOnFailedTests: true<br>          failTaskOnFailureToPublishResults: true<br>          failTaskOnMissingResultsFile: true<br>          testRunTitle: Python tests<br>      - task: PublishPipelineArtifact@1<br>        displayName: Publish test evidence<br>        condition: always()<br>        inputs:<br>          targetPath: &#39;$(Build.SourcesDirectory)/evidence&#39;<br>          artifact: test-evidence<br>          publishLocation: pipeline</pre><h2>Build the small local project</h2><p>Use an empty practice directory with Python 3.10 or later. The fresh local checks used Python 3.13.14 and pytest 9.1.1; provider examples request their own explicitly shown runtimes. Create the following files. The artifact helpers retain the lesson’s exact build and verification functions, with small command-line entry points added here.</p><p>tests/test_artifact.py:</p><pre>import json<br>import os<br>from pathlib import Path<br><br><br>def test_built_artifact_is_ready():<br>    data = json.loads(Path(&quot;evidence/app.json&quot;).read_text(encoding=&quot;utf-8&quot;))<br>    assert data[&quot;ready&quot;] is True<br><br><br>def test_controlled_failure():<br>    observed = os.getenv(&quot;DEMO_FAIL&quot;, &quot;0&quot;)<br>    assert observed == &quot;0&quot;, f&quot;DEMO_FAIL was {observed}&quot;</pre><p>requirements.txt:</p><pre>pytest==9.1.1</pre><p>build_demo.py:</p><pre>from pathlib import Path<br>import hashlib<br>import json<br><br>def canonical_bytes(value):<br>    return json.dumps(value, sort_keys=True, separators=(&quot;,&quot;, &quot;:&quot;)).encode()<br><br>def build_artifact(project):<br>    evidence = project / &quot;evidence&quot;<br>    evidence.mkdir()<br>    artifact = {&quot;name&quot;: &quot;azure-demo&quot;, &quot;revision&quot;: &quot;local-demo-001&quot;, &quot;ready&quot;: True}<br>    artifact_path = evidence / &quot;app.json&quot;<br>    artifact_path.write_bytes(canonical_bytes(artifact))<br>    manifest = {<br>        &quot;artifact&quot;: &quot;evidence/app.json&quot;,<br>        &quot;revision&quot;: artifact[&quot;revision&quot;],<br>        &quot;sha256&quot;: hashlib.sha256(artifact_path.read_bytes()).hexdigest(),<br>    }<br>    manifest_path = evidence / &quot;manifest.json&quot;<br>    manifest_path.write_text(json.dumps(manifest, indent=2) + &quot;\n&quot;, encoding=&quot;utf-8&quot;)<br>    return manifest_path<br><br>if __name__ == &#39;__main__&#39;:<br>    print(build_artifact(Path.cwd()))</pre><p>verify_artifact.py:</p><pre>from pathlib import Path<br>import hashlib<br>import json<br>import sys<br><br>def verify_artifact(project, manifest_path):<br>    manifest = json.loads(manifest_path.read_text(encoding=&quot;utf-8&quot;))<br>    artifact_path = project / manifest[&quot;artifact&quot;]<br>    actual = hashlib.sha256(artifact_path.read_bytes()).hexdigest()<br>    if actual != manifest[&quot;sha256&quot;]:<br>        raise ValueError(f&quot;artifact digest mismatch: expected {manifest[&#39;sha256&#39;]}, got {actual}&quot;)<br>    return {&quot;verified&quot;: True, &quot;revision&quot;: manifest[&quot;revision&quot;], &quot;sha256&quot;: actual}<br><br>if __name__ == &#39;__main__&#39;:<br>    print(verify_artifact(Path.cwd(), Path(sys.argv[1])))</pre><p>Create a virtual environment and install requirements.txt there. For a POSIX shell, use python3 -m venv .venv, activate it with . .venv/bin/activate, and run python -m pip install -r requirements.txt. This installation is a reader setup step; the validation used the existing local environment.</p><p>From the practice project root, run the build once and verify the resulting manifest. The source helper creates a fresh output directory, so use a new empty practice directory for another full build.</p><pre>python build_demo.py<br>python verify_artifact.py evidence/manifest.json</pre><p>Run these commands separately in a POSIX shell so you can inspect each exit code and report. The last two are deliberate negative cases. In PowerShell, set $env:DEMO_FAIL=&#39;1&#39; for the failing run and remove it afterward.</p><pre>python -m pytest tests --strict-markers --junitxml=reports/passing.xml<br>DEMO_FAIL=1 python -m pytest tests --strict-markers --junitxml=reports/failing.xml<br>python -m pytest tests -k no_test_has_this_name --strict-markers --junitxml=reports/empty.xml</pre><p>The recorded demonstration produced these results:</p><p><strong>Selection:</strong> Normal inputs</p><p><strong>Exit code:</strong> 0</p><p><strong>Tests:</strong> 2</p><p><strong>Failures:</strong> 0</p><p><strong>Selection:</strong> DEMO_FAIL=1</p><p><strong>Exit code:</strong> 1</p><p><strong>Tests:</strong> 2</p><p><strong>Failures:</strong> 1</p><p><strong>Selection:</strong> Empty selection</p><p><strong>Exit code:</strong> 5</p><p><strong>Tests:</strong> 0</p><p><strong>Failures:</strong> 0</p><p>The nonzero results are expected evidence that failures and empty selections remain visible. Do not convert them to zero to make the tutorial green.</p><h3>Common problems and fixes</h3><p>PublishPipelineArtifact@1 targets Azure DevOps Services; an on-premises Azure DevOps Server requires the supported build-artifact task instead. Also check the repository integration: YAML pr triggers are not how Azure Repos Git branch validation is configured; use the appropriate branch policy there.</p><h3>Validation boundary</h3><p>The Python behavior and reports were checked in disposable local directories. The provider configuration was inspected as text. No remote pipeline, runner, service account, cloud resource, or deployment was created. A private end-to-end trial must still confirm the exact revision, runtime, report download, permissions, and failed-job behavior. The pr integration distinction is documented in the <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/pr?view=azure-pipelines">Azure Pipelines PR schema</a>.</p><h3>Continue learning</h3><p><a href="https://www.youtube.com/watch?v=5Tiv4rDMAKU">GitHub Actions vs GitLab CI vs CircleCI vs Azure Pipelines</a> builds on this lesson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9d68959e11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions Tutorial — Test and Save Reports]]></title>
            <link>https://krishnachetan.medium.com/github-actions-tutorial-test-and-save-reports-2443b034d92d?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2443b034d92d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 22:05:01 GMT</pubDate>
            <atom:updated>2026-10-26T22:05:01.472Z</atom:updated>
            <content:encoded><![CDATA[<p>The test result stays honest. A failure makes the job red, while a later always step still uploads the JUnit report. We will also prove pass, fail, and empty paths locally.</p><figure><img alt="GITHUB ACTIONS — TEST AND SAVE REPORTS; conceptual pipeline illustration." src="https://cdn-images-1.medium.com/max/1024/1*TYJwYOzvtTKzDZPjnMbUFA.png" /></figure><p><a href="https://www.youtube.com/watch?v=z1O1xGR4dIU">Watch the matching lesson: GitHub Actions Tutorial — Test and Save Reports</a></p><h3>Build one GitHub Actions workflow that runs pytest and keeps failure evidence</h3><p>It reads the source, prepares one Python version, installs dependencies, runs pytest with a JUnit path, and uploads that report after both pass and fail.</p><p>Use a clear file name such as tests.yaml. The repository can hold several workflows, so the file and displayed workflow names should explain their purpose.</p><h3>Start with pull requests and pushes to the default branch</h3><p>Pull requests give feedback before merge. The default branch confirms the integrated result. Add schedules, manual runs, or release events only when they have a clear job set.</p><p>This test job uses contents read. Do not give broad write access to a job that only checks code. Add any extra permission one at a time with a clear reason.</p><p>The example uses the current major action version checked for this lesson. For stronger supply-chain control, a production workflow can pin a reviewed full commit identity and update it deliberately.</p><h3>Choose the Python version instead of trusting the runner default</h3><p>The workflow requests Python 3.14. A declared version makes the environment easier to repeat and review when hosted runner images change.</p><p>The Python setup step can cache pip downloads using the requirements file. A cache makes setup faster, but the normal install command still defines what the job needs.</p><p>Use python -m pip install with the dependency file. Keep versions controlled. Do not print private package credentials or hide an installation failure.</p><h3>Call pytest through Python and write one JUnit report to a known path</h3><p>Strict markers catch selection mistakes. The JUnit path in the command must match the later artifact path. Pytest’s exit code remains the job result.</p><p>Exit zero means passed. Exit one means tests failed. Exit five means no tests were collected. The workflow rejects forced success and continue-on-error for this required job.</p><p>Normal later steps may be skipped after a failure. Always tells this evidence step to run even when pytest is red. It does not change the pytest result.</p><h3>Give the report artifact a clear name and exact path</h3><p>The example uses the current major upload action, a pytest report name, the XML file path, and a fourteen-day retention. Missing report files make the upload step fail.</p><p>The job has a fifteen-minute limit. Choose a value from expected runtime and safe cleanup. Split genuinely longer work into a clear lane instead of using an unlimited wait.</p><p>The validator parses the XML instead of trusting terminal color. It confirms two tests, zero failures, a real report file, and a successful process status.</p><h3>The checked local failure stays red and keeps its failure text</h3><p>One controlled environment flag makes one test fail. Pytest returns one, the XML contains two cases and one failure, and the reason remains readable.</p><p>The empty path still writes a report and returns exit five. A required workflow should fail so the missing selection is repaired instead of published as green.</p><p>The local validator records the major versions and verification date. Recheck official action releases, runner requirements, permissions, and breaking changes before copying an old workflow.</p><h3>Run a new workflow on a small private test change and read back every result</h3><p>Check the event, revision, runner, Python version, dependency install, selected tests, exit status, artifact name, file content, retention, and permissions before making it required.</p><p>Run the demo and inspect all three reports.</p><h3>Upload evidence even after the test command fails</h3><p>The upload step uses always() so the failed test still leaves a report. if-no-files-found: error makes a missing report visible. The job requests read access to contents; this example does not need a write token or a deployment secret.</p><p>Save this configuration as .github/workflows/tests.yml. It is the lesson&#39;s integration example, reviewed against the <a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions">official configuration reference</a>. The local checks below do not submit it to the provider.</p><pre>name: tests<br><br>on:<br>  pull_request:<br>  push:<br>    branches:<br>      - main<br><br>permissions:<br>  contents: read<br><br>jobs:<br>  pytest:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 15<br>    steps:<br>      - name: Check out source<br>        uses: actions/checkout@v7<br>      - name: Set up Python<br>        uses: actions/setup-python@v7<br>        with:<br>          python-version: &#39;3.14&#39;<br>          cache: pip<br>          cache-dependency-path: requirements.txt<br>      - name: Install dependencies<br>        run: python -m pip install -r requirements.txt<br>      - name: Run tests<br>        run: python -m pytest tests --strict-markers --junitxml=reports/pytest.xml<br>      - name: Keep test report<br>        if: ${{ always() }}<br>        uses: actions/upload-artifact@v7<br>        with:<br>          name: pytest-report<br>          path: reports/pytest.xml<br>          if-no-files-found: error<br>          retention-days: 14</pre><h2>Build the small local project</h2><p>Use an empty practice directory with Python 3.10 or later. The fresh local checks used Python 3.13.14 and pytest 9.1.1; provider examples request their own explicitly shown runtimes. Create the following files. The artifact helpers retain the lesson’s exact build and verification functions, with small command-line entry points added here.</p><p>tests/test_demo.py:</p><pre>import os<br><br><br>def test_total():<br>    assert 2 + 3 == 5<br><br><br>def test_optional_failure():<br>    observed = os.getenv(&quot;DEMO_FAIL&quot;, &quot;0&quot;)<br>    assert observed == &quot;0&quot;, f&quot;DEMO_FAIL was {observed}&quot;</pre><p>requirements.txt:</p><pre>pytest==9.1.1</pre><p>Create a virtual environment and install requirements.txt there. For a POSIX shell, use python3 -m venv .venv, activate it with . .venv/bin/activate, and run python -m pip install -r requirements.txt. This installation is a reader setup step; the validation used the existing local environment.</p><p>Run these commands separately in a POSIX shell so you can inspect each exit code and report. The last two are deliberate negative cases. In PowerShell, set $env:DEMO_FAIL=&#39;1&#39; for the failing run and remove it afterward.</p><pre>python -m pytest tests --strict-markers --junitxml=reports/passing.xml<br>DEMO_FAIL=1 python -m pytest tests --strict-markers --junitxml=reports/failing.xml<br>python -m pytest tests -k no_test_has_this_name --strict-markers --junitxml=reports/empty.xml</pre><p>The recorded demonstration produced these results:</p><p><strong>Selection:</strong> Normal inputs</p><p><strong>Exit code:</strong> 0</p><p><strong>Tests:</strong> 2</p><p><strong>Failures:</strong> 0</p><p><strong>Selection:</strong> DEMO_FAIL=1</p><p><strong>Exit code:</strong> 1</p><p><strong>Tests:</strong> 2</p><p><strong>Failures:</strong> 1</p><p><strong>Selection:</strong> Empty selection</p><p><strong>Exit code:</strong> 5</p><p><strong>Tests:</strong> 0</p><p><strong>Failures:</strong> 0</p><p>The nonzero results are expected evidence that failures and empty selections remain visible. Do not convert them to zero to make the tutorial green.</p><h3>Common problems and fixes</h3><p>If the workflow stays queued, inspect runner availability and event filters. If caching fails before tests start, verify that requirements.txt exists at the declared path. Keep the failure visible while fixing the report upload path; adding continue-on-error to pytest changes the gate&#39;s meaning.</p><h3>Validation boundary</h3><p>The Python behavior and reports were checked in disposable local directories. The provider configuration was inspected as text. No remote pipeline, runner, service account, cloud resource, or deployment was created. A private end-to-end trial must still confirm the exact revision, runtime, report download, permissions, and failed-job behavior. The v7 action major versions were rechecked against the official <a href="https://github.com/actions/checkout/releases/tag/v7.0.1">checkout</a>, <a href="https://github.com/actions/setup-python/releases/tag/v7.0.0">setup-python</a>, and <a href="https://github.com/actions/upload-artifact/releases/tag/v7.0.1">upload-artifact</a> releases. A major tag is movable; use reviewed full commit pins where the repository requires immutable dependencies.</p><h3>Continue learning</h3><p><a href="https://www.youtube.com/watch?v=HjWnGX-CLW8">GitLab CI Tutorial — Build, Test, and Keep Evidence</a> builds on this lesson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2443b034d92d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Secrets — Store, Use, and Rotate Them Safely]]></title>
            <link>https://krishnachetan.medium.com/ci-cd-secrets-store-use-and-rotate-them-safely-acd0ce11fefb?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd0ce11fefb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 22:04:19 GMT</pubDate>
            <atom:updated>2026-10-26T22:04:19.094Z</atom:updated>
            <content:encoded><![CDATA[<p>We will follow one CI secret from creation to safe use, log checks, rotation, and leak response. The example uses only a fake teaching value. No real key, token, password, or account is touched.</p><figure><img alt="CI/CD SECRETS — STORE, USE, ROTATE; conceptual lock illustration." src="https://cdn-images-1.medium.com/max/1024/1*CLlZs-wBapOpdHdw1XfEdQ.png" /></figure><p><a href="https://www.youtube.com/watch?v=pv_QX3lTO7k">Watch the matching lesson: CI/CD Secrets — Store, Use, and Rotate Them Safely</a></p><h3>One leaked key can turn a green job into a serious failure</h3><p>A password, API key, signing key, device token, or short-lived credential can be a secret. A normal setting such as a timeout is not a secret. Labeling every value secret makes real risks harder to see.</p><p>Write what the job must read or change, which system it may reach, and how long access is needed. If the job only reads device status, do not give it release, delete, or admin access.</p><h3>Avoid a key that stays valid for months when the job needs ten minutes</h3><p>OpenID Connect can exchange the workflow identity for a short-lived credential when the target system supports it. This removes one stored long-lived key, but the identity rules still need narrow limits.</p><p>A short lifetime is not enough. Restrict who may ask for the token, where it can be used, what it can do, and which branch or protected environment may receive it. Start with no access and add one need.</p><p>When a stored secret is still needed, add it through the protected settings page or approved secret service. Never commit it, paste it into workflow YAML, keep it in a sample file, or place it in a container image.</p><h3>Large JSON or YAML secrets are harder to hide safely</h3><p>Keep important values separate. Exact redaction can fail after formatting, splitting, or changing a structured value. A small named secret is easier to limit, rotate, audit, and remove.</p><p>Use a protected environment when the action is important. Limit who can change the workflow and who can start that job. Do not give secrets to untrusted forks or changes that run unknown code.</p><p>Set the smallest token permissions for the job. Raise one permission only for the step that needs it. A test job usually does not need to write source, create releases, or change settings.</p><h3>Process arguments may be visible to other work on the runner</h3><p>Do not write tool --token followed by the secret. Prefer a protected environment variable, standard input, or a tool-specific credential file with small file access. Never print environment values during debugging.</p><p>Turn off command tracing around private steps. Do not echo the value, request body, full header, or complete environment. Log the secret name, access purpose, result, and safe reference instead.</p><p>If a step creates a session token, signed value, encoded value, or other private output, mark that new value secret before another command can print it. Automatic redaction is not guaranteed for every transformation.</p><h3>A tool may print private input only when it fails</h3><p>Run both valid and invalid cases in a safe test. Inspect standard output, standard error, debug logs, reports, and retry messages. The included model catches a fake token in an error and saves only redacted text.</p><p>Review the action, give it small permissions, and pin it to an approved full commit ID when strong immutability is needed. A convenient tag can move. Remove actions that do not need secret access.</p><p>Search the work folder before upload. Check logs, JUnit, screenshots, traces, archives, build metadata, container layers, and cache paths. Block publishing when a known private value or form of it appears.</p><h3>A persistent runner may keep files and processes after the job</h3><p>Use trusted private work, clean folders, small network access, short-lived credentials, and separate runner groups. Remember that masking does not stop a malicious process from reading a value already present on the machine.</p><p>Record who owns it, where it is used, when it was created, and how to replace it without a long outage. Remove unused secrets. Test rotation before the old value becomes an emergency.</p><p>Stop the affected job, revoke or rotate the credential, remove public access to the log or artifact, preserve safe evidence, find the source, fix the path, and check for unexpected use. Hiding the text alone does not cancel access.</p><h3>Prove the controls with fake values before trusting real access</h3><p>Try a secret in source, process arguments, plain and encoded logs, a failed tool message, an artifact, a cache, an untrusted change, an expired credential, and rotation. Each case needs a clear blocked result.</p><p>It uses no real secret and makes no network call. Use its rules as a small review contract for each pipeline.</p><h3>Check a fake credential without creating a real exposure</h3><p>The guard registers a made-up value and its Base64 and URL-encoded forms. It redacts a simulated error and rejects placing the fake value in process arguments. The plan separately records credential source, scope, lifetime, trust, storage, and revocation.</p><p>The following self-contained extract uses the lesson’s data structures and decision functions. Save it as cicd-210-example.py and run python cicd-210-example.py with Python 3.10 or later.</p><pre>from __future__ import annotations<br><br>import base64<br><br>import json<br><br>import urllib.parse<br><br>from dataclasses import dataclass<br><br>@dataclass(frozen=True)<br>class SecretPlan:<br>    source: str<br>    permission: str<br>    lifetime_minutes: int<br>    protected_environment: bool<br>    untrusted_change: bool<br>    placed_in_command_line: bool<br>    stored_in_cache: bool<br>    stored_in_artifact: bool<br>    log_audit_enabled: bool<br>    rotation_and_revocation_ready: bool<br><br>SAFE_PLAN = SecretPlan(<br>    source=&quot;short-lived-identity&quot;,<br>    permission=&quot;device-status:read&quot;,<br>    lifetime_minutes=10,<br>    protected_environment=True,<br>    untrusted_change=False,<br>    placed_in_command_line=False,<br>    stored_in_cache=False,<br>    stored_in_artifact=False,<br>    log_audit_enabled=True,<br>    rotation_and_revocation_ready=True,<br>)<br><br>def validate_plan(plan: SecretPlan) -&gt; list[str]:<br>    errors = []<br>    if plan.source not in {&quot;short-lived-identity&quot;, &quot;protected-secret-store&quot;}:<br>        errors.append(&quot;use a protected source or short-lived identity&quot;)<br>    if plan.permission == &quot;*&quot;:<br>        errors.append(&quot;secret access is too broad&quot;)<br>    if plan.lifetime_minutes &gt; 60:<br>        errors.append(&quot;credential lives too long&quot;)<br>    if not plan.protected_environment:<br>        errors.append(&quot;sensitive job needs a protected environment&quot;)<br>    if plan.untrusted_change:<br>        errors.append(&quot;untrusted change must not receive the secret&quot;)<br>    if plan.placed_in_command_line:<br>        errors.append(&quot;do not place a secret in process arguments&quot;)<br>    if plan.stored_in_cache or plan.stored_in_artifact:<br>        errors.append(&quot;do not save a secret in caches or artifacts&quot;)<br>    if not plan.log_audit_enabled:<br>        errors.append(&quot;valid and invalid runs both need a log audit&quot;)<br>    if not plan.rotation_and_revocation_ready:<br>        errors.append(&quot;prepare rotation and revocation before use&quot;)<br>    return errors<br><br>class SecretGuard:<br>    def __init__(self) -&gt; None:<br>        self._registered: set[str] = set()<br><br>    def register(self, value: str) -&gt; None:<br>        if len(value) &lt; 8:<br>            raise ValueError(&quot;teaching value is too short for a useful check&quot;)<br>        variants = {<br>            value,<br>            base64.b64encode(value.encode()).decode(),<br>            urllib.parse.quote(value, safe=&quot;&quot;),<br>        }<br>        self._registered.update(variants)<br><br>    def exposed_variants(self, text: str) -&gt; list[str]:<br>        return sorted(value for value in self._registered if value in text)<br><br>    def safe_text(self, text: str) -&gt; str:<br>        cleaned = text<br>        for value in sorted(self._registered, key=len, reverse=True):<br>            cleaned = cleaned.replace(value, &quot;[REDACTED]&quot;)<br>        return cleaned<br><br>    def check_process(self, arguments: list[str], environment: dict[str, str]) -&gt; dict:<br>        joined_arguments = &quot; &quot;.join(arguments)<br>        argument_leaks = self.exposed_variants(joined_arguments)<br>        if argument_leaks:<br>            raise ValueError(&quot;secret found in process arguments&quot;)<br>        return {<br>            &quot;arguments&quot;: arguments,<br>            &quot;environment_names&quot;: sorted(environment),<br>            &quot;environment_values_printed&quot;: False,<br>        }<br><br>assert validate_plan(SAFE_PLAN) == []<br><br>unsafe_plan = SecretPlan(**{**SAFE_PLAN.__dict__, &#39;permission&#39;: &#39;*&#39;, &#39;untrusted_change&#39;: True, &#39;placed_in_command_line&#39;: True})<br><br>unsafe_errors = validate_plan(unsafe_plan)<br><br>assert len(unsafe_errors) == 3<br><br>guard = SecretGuard()<br>fake = &#39;example-only-token-210&#39;<br>guard.register(fake)<br>print(guard.safe_text(&#39;request failed with token=&#39; + fake))<br>try:<br>    guard.check_process([&#39;tool&#39;, &#39;--token&#39;, fake], {})<br>except ValueError as error:<br>    print(type(error).__name__, str(error))</pre><h2>Common problems and fixes</h2><p>If a secret was exposed, remove access and rotate it through the owning system; deleting one log is not revocation. If masking misses a transformed value, fix the logging path first. This demo intentionally uses a recognizable fake value throughout.</p><h2>What the check proves</h2><p>The recorded lesson demonstration passed all its assertions. The 60-minute lifetime threshold is this example’s policy, not a universal provider limit. This is an exact-match teaching guard. It cannot detect every transform, split string, file leak, inherited environment exposure, or downstream tool behavior. Environment injection is not a complete secret-management policy.</p><h2>Continue learning</h2><p><a href="https://www.youtube.com/watch?v=IDvI3pqqYeo">Save Test Reports and Failure Evidence in CI</a> builds on this lesson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd0ce11fefb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automotive Firmware Interviews: Wire Formats, Deadlocks and Recovery]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://krishnachetan.medium.com/automotive-firmware-interviews-wire-formats-deadlocks-and-recovery-0df626f4c483?source=rss-2ecf1b8a928f------2"><img src="https://cdn-images-1.medium.com/max/1600/1*UcnB1WHs-lxKONjRbES56Q.jpeg" width="1600"></a></p><p class="medium-feed-snippet">Embedded Systems Interview Series &#x2014; Part 18 of 18</p><p class="medium-feed-link"><a href="https://krishnachetan.medium.com/automotive-firmware-interviews-wire-formats-deadlocks-and-recovery-0df626f4c483?source=rss-2ecf1b8a928f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://krishnachetan.medium.com/automotive-firmware-interviews-wire-formats-deadlocks-and-recovery-0df626f4c483?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0df626f4c483</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 13:04:16 GMT</pubDate>
            <atom:updated>2026-10-23T13:04:16.818Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Firmware Interviews: C++ Ownership, Toolchains and Multiuser Protocols]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://krishnachetan.medium.com/firmware-interviews-c-ownership-toolchains-and-multiuser-protocols-613add38c431?source=rss-2ecf1b8a928f------2"><img src="https://cdn-images-1.medium.com/max/1600/1*UcnB1WHs-lxKONjRbES56Q.jpeg" width="1600"></a></p><p class="medium-feed-snippet">Embedded Systems Interview Series &#x2014; Part 17 of 18</p><p class="medium-feed-link"><a href="https://krishnachetan.medium.com/firmware-interviews-c-ownership-toolchains-and-multiuser-protocols-613add38c431?source=rss-2ecf1b8a928f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://krishnachetan.medium.com/firmware-interviews-c-ownership-toolchains-and-multiuser-protocols-613add38c431?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/613add38c431</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 13:03:51 GMT</pubDate>
            <atom:updated>2026-10-23T13:03:51.410Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[When GitHub Actions Fails: An AI-Assisted Investigation]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">How testers can use AI to inspect workflows, compare attempts, and explain a failure.</p><p class="medium-feed-link"><a href="https://krishnachetan.medium.com/when-github-actions-fails-an-ai-assisted-investigation-d8d00ac9db56?source=rss-2ecf1b8a928f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://krishnachetan.medium.com/when-github-actions-fails-an-ai-assisted-investigation-d8d00ac9db56?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d00ac9db56</guid>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 06:23:09 GMT</pubDate>
            <atom:updated>2026-10-22T06:23:09.172Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Use AI to Turn a Jira Queue into a Test Plan]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">A step-by-step approach to sorting work, finding missing requirements, and tracking test evidence.</p><p class="medium-feed-link"><a href="https://krishnachetan.medium.com/use-ai-to-turn-a-jira-queue-into-a-test-plan-b707b34e001c?source=rss-2ecf1b8a928f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://krishnachetan.medium.com/use-ai-to-turn-a-jira-queue-into-a-test-plan-b707b34e001c?source=rss-2ecf1b8a928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b707b34e001c</guid>
            <dc:creator><![CDATA[krishna chetan]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 06:22:53 GMT</pubDate>
            <atom:updated>2026-10-22T06:22:53.739Z</atom:updated>
        </item>
    </channel>
</rss>