<?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[TestCraft - Medium]]></title>
        <description><![CDATA[No theory — just practice. This space is for QA professionals who share real-world test automation stories, code snippets, and lessons learned from daily work. - Medium]]></description>
        <link>https://medium.com/quality-is-everything?source=rss----d09c502483ba---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TestCraft - Medium</title>
            <link>https://medium.com/quality-is-everything?source=rss----d09c502483ba---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:30:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/quality-is-everything" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Visual Regression Testing with Playwright and Storybook]]></title>
            <link>https://medium.com/quality-is-everything/automated-visual-regression-testing-with-playwright-and-storybook-eab8f8cd6be1?source=rss----d09c502483ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/eab8f8cd6be1</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[visual-regression-testing]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Nikolai Boiko]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 05:10:41 GMT</pubDate>
            <atom:updated>2025-12-23T05:10:42.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8uz0yOUwdIL1fsd3P76kvA.png" /></figure><h2>Storybook Integration with Playwright</h2><p>In my recent project, I implemented a comprehensive Storybook testing solution using Playwright that automatically discovers and tests all components in our design system. This integration has proven invaluable for maintaining visual consistency across our large React application with hundreds of components.</p><p><strong>Why this matters</strong>: Traditional testing approaches miss visual regressions — those subtle changes in spacing, colors, or layout that can break user experience. By combining Storybook’s component isolation with Playwright’s powerful testing capabilities, we now catch these issues automatically before they reach production.</p><p>The solution I built provides:</p><ul><li><strong>Automatic story discovery</strong> — No manual maintenance of test lists</li><li><strong>Visual regression protection</strong> — Screenshots catch any visual changes</li><li><strong>Batch error reporting</strong> — All failures reported together for efficient debugging</li><li><strong>Seamless integration</strong> — Works with existing CI/CD pipelines</li></ul><h2>Why Playwright + Storybook is the Perfect Combination</h2><p>This integration gives you everything in one place: component development, visual regression testing, E2E testing, and API testing — all in a single framework.</p><p><strong>Key advantages over paid services:</strong></p><ul><li><strong>No per-screenshot fees</strong> — Take unlimited screenshots without hitting usage caps</li><li><strong>No vendor lock-in</strong> — Your tests run locally and in your own CI/CD</li><li><strong>Familiar tooling</strong> — If you’re already using Playwright, no additional tools to learn</li><li><strong>Self-hosted</strong> — Complete control over your testing infrastructure</li></ul><p>Let me show you exactly how to implement this in your own projects.</p><h2>The Problem: Component Drift in Large Applications</h2><p>In modern React applications, especially those with large component libraries, maintaining visual consistency becomes increasingly challenging. As your team grows and components evolve, subtle visual changes can slip through code reviews and break the user experience. Traditional unit tests catch logic errors, but they don’t protect against visual regressions — those subtle changes in spacing, colors, or layout that can make your app look broken.</p><p>This is where <strong>Storybook testing</strong> becomes invaluable. By combining Storybook’s component isolation with Playwright’s powerful testing capabilities, you can catch visual regressions before they reach production.</p><h2>Why Storybook Testing Matters</h2><figure><img alt="Why storybook testing matters" src="https://cdn-images-1.medium.com/max/1024/0*cxI4_JoPIO6g0vCj" /></figure><h3>1. Component Isolation</h3><p>Storybook allows you to test components in complete isolation, free from the context of your main application. This means you can verify that a button component works correctly across all its variants without needing to navigate through complex user flows.</p><h3>2. Visual Regression Detection</h3><p>Automated screenshot testing catches visual changes that human eyes might miss during code reviews. A 2px margin change might seem trivial, but it can break your entire layout.</p><h3>3. Design System Validation</h3><p>For teams maintaining design systems, Storybook testing ensures that component updates don’t break existing implementations across different contexts.</p><h3>4. Documentation as Tests</h3><p>Your Storybook stories serve dual purposes: they document component usage <strong>and</strong> provide test cases. This creates a single source of truth for how components should look and behave.</p><h2>Implementation: Automated Storybook Testing with Playwright</h2><p>Let me walk you through a production-ready implementation that automatically discovers and tests all your Storybook stories.</p><h3>Step 1: Storybook Configuration</h3><p>First, ensure your Storybook is properly configured with essential addons:</p><pre>// .storybook/main.ts<br>import type { StorybookConfig } from &#39;@storybook/react-vite&#39;;<br><br>const config: StorybookConfig = {<br>  stories: [&#39;../src/**/*.stories.@(ts|tsx)&#39;],<br>  addons: [<br>    &#39;@storybook/addon-links&#39;,<br>    {<br>      name: &#39;@storybook/addon-essentials&#39;,<br>      options: {<br>        backgrounds: false,<br>      },<br>    },<br>    &#39;@storybook/addon-interactions&#39;,<br>    &#39;@storybook/addon-a11y&#39;,<br>  ],<br>  framework: &#39;@storybook/react-vite&#39;,<br>  typescript: {<br>    reactDocgen: &#39;react-docgen-typescript&#39;,<br>  },<br>};<br>export default config;</pre><h3>Step 2: Dedicated Playwright Configuration</h3><p>Create a separate Playwright configuration specifically for Storybook testing:</p><pre>// storybook.config.ts<br>import { PlaywrightTestConfig } from &#39;@playwright/test&#39;;<br><br>const config: PlaywrightTestConfig = {<br>  timeout: 900000, // 15 minutes for comprehensive testing<br>  retries: 0,<br>  testDir: &#39;playwright/tests/storybook&#39;,<br>  reporter: [<br>    [&#39;html&#39;, { outputFolder: &#39;playwright/reports/test-storybook-reports&#39; }], <br>  ],<br>  outputDir: &#39;playwright/reports/test-storybook-results&#39;,<br>  use: {<br>    trace: &#39;on-first-retry&#39;,<br>    baseURL: &#39;http://localhost:6006/&#39;,<br>  },<br>  projects: [<br>    {<br>      name: &#39;chromium&#39;, <br>      use: { browserName: &#39;chromium&#39; },<br>    }<br>  ],<br>};<br><br>export default config;</pre><h3>Step 3: Intelligent Story Discovery and Testing</h3><p>The magic happens in the test implementation. Instead of manually maintaining a list of stories to test, we automatically discover them:</p><pre>// playwright/tests/storybook/story.spec.ts<br>import test, { expect } from &quot;@playwright/test&quot;;<br><br>test(&quot;Verify storybooks&quot;, async ({ page }) =&gt; {<br>  // Fetch the Storybook index to discover all available stories<br>  const response = await page.request.get(`index.json`);<br>  const storybookJson = await response.json();<br><br>  // Filter for actual stories and take the first 10 for testing<br>  const stories = Object.values(storybookJson.entries)<br>    .filter((entry) =&gt; (entry as { type: string }).type === &#39;story&#39;)<br>    .slice(0, 10)<br>    .map((entry) =&gt; (entry as { id: string }).id);<br><br>   const errors = [];<br><br>  // Test each story individually<br>  for (const storyId of stories) {<br>    const url = `iframe.html?id=${storyId}&amp;viewMode=story`;<br>    try {<br>      await page.goto(url);<br>      <br>      // Wait for the story to load completely<br>      await expect(page.locator(&quot;#storybook-root&quot;)).toBeVisible();<br>      await expect(page.locator(&quot;.sb-preparing-story .sb-loader&quot;)).toBeHidden();<br>      <br>      // Take a full-page screenshot for visual regression testing<br>      await expect(page).toHaveScreenshot(`${storyId}.png`, { <br>        fullPage: true,<br>        timeout: 10000 <br>      });<br>    } catch (error) {<br>      errors.push(`Story ${storyId} failed: ${error.message}`);<br>    }<br>  }<br><br>  // Report all failures together for better debugging<br>  if (errors.length) {<br>    throw new Error(`Visual regression failures:\n${errors.join(&#39;\n&#39;)}`);<br>  }<br>});</pre><h3>Step 4: NPM Scripts for Easy Testing</h3><p>Add convenient scripts to your package.json:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;test-storybook&quot;: &quot;playwright test --config=storybook.config.ts&quot;,<br>    &quot;test-storybook-update&quot;: &quot;playwright test --config=storybook.config.ts --update-snapshots&quot;,<br>    &quot;storybook&quot;: &quot;storybook dev -p 6006&quot;,<br>    &quot;build-storybook&quot;: &quot;storybook build&quot;<br>  }<br>}</pre><h2>Understanding Your NPM Scripts</h2><p>Each script serves a specific purpose in your Storybook testing workflow:</p><pre>yarn storybook</pre><blockquote><strong>What it does</strong>: Starts the Storybook development server on port 6006</blockquote><ul><li><strong>When to use</strong>: When you want to manually browse and develop your stories</li><li><strong>Command</strong>: storybook dev -p 6006</li><li><strong>Output</strong>: Interactive Storybook interface at <a href="http://localhost:6006/">http://localhost:6006</a></li></ul><pre>yarn test-storybook</pre><blockquote><strong>What it does</strong>: Runs all your Storybook visual regression tests</blockquote><ul><li><strong>When to use</strong>: Before committing changes to ensure no visual regressions</li><li><strong>Command</strong>: playwright test --config=storybook.config.ts</li><li><strong>Output</strong>: Test results and screenshots in playwright/reports/test-storybook-reports</li></ul><p>If the test fails in report you can see all the failed tests with screenshoots you can switch between actual and expected tabs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPMWAhtALzzYgc_al6PMsw.png" /></figure><pre>yarn test-storybook-update</pre><blockquote><strong>What it does</strong>: Updates all visual regression snapshots with current component states</blockquote><ul><li><strong>When to use</strong>: When you’ve intentionally made visual changes and want to update the baseline</li><li><strong>Command</strong>: playwright test --config=storybook.config.ts --update-snapshots</li><li><strong>⚠️ Use carefully</strong>: This overwrites existing screenshots, so only run when you’re sure the changes are intentional</li></ul><pre>yarn build-storybook</pre><blockquote><strong>What it does</strong>: Creates a static build of your Storybook for deployment</blockquote><ul><li><strong>When to use</strong>: When you want to deploy Storybook to a static hosting service</li><li><strong>Command</strong>: storybook build</li><li><strong>Output</strong>: Static files in storybook-static/ directory</li></ul><h2>Typical Workflow</h2><p>Here’s how these scripts fit into your daily development workflow:</p><pre># 1. Start developing components<br>yarn storybook<br><br># 2. Make changes to your components<br># ... edit your code ...<br><br># 3. Run tests to check for regressions<br>yarn test-storybook<br><br># 4. If tests fail due to intentional changes, update snapshots<br>yarn test-storybook-update<br><br># 5. Deploy your Storybook (optional)<br>yarn build-storybook</pre><h2>Viewing Failed Tests and Screenshots</h2><p>One of the best parts of this setup is the <strong>visual feedback</strong> you get when a test fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4fjANtAyofrbQCjy9635g.png" /><figcaption>Actual result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjjmz-yJD-FAZXXMAxq52w.png" /><figcaption>Expected result</figcaption></figure><p>In the Playwright HTML report:</p><ul><li>You can see <strong>all failed tests</strong> listed in a single view.</li><li>For each failed story, Playwright provides <strong>screenshots</strong> of the component.</li><li>You can switch between <strong>Actual</strong> and <strong>Expected</strong> tabs to quickly identify visual differences.</li><li>This makes debugging <strong>fast and intuitive</strong>, letting you pinpoint exactly what changed</li></ul><h2>Key Benefits of This Implementation</h2><h3>1. Automatic Discovery</h3><p>No need to manually maintain lists of stories to test. The system automatically finds and tests all available stories.</p><h3>2. Batch Error Reporting</h3><p>Instead of failing on the first error, the test collects all failures and reports them together, making debugging more efficient.</p><h3>3. Proper Loading States</h3><p>The test waits for Storybook’s loading indicators to disappear, ensuring screenshots capture the final rendered state.</p><h3>4. Isolated Testing</h3><p>Each story is tested in its own iframe context, preventing cross-contamination between tests.</p><h3>5. Visual Regression Protection</h3><p>Full-page screenshots catch any visual changes, from major layout shifts to subtle color adjustments.</p><h2>Best Practices for Storybook Testing</h2><h3>1. Start Small</h3><p>Begin by testing a subset of your stories (like the first 10) to avoid overwhelming your CI/CD pipeline.</p><h3>2. Regular Updates</h3><p>Run visual regression tests on every PR to catch issues early.</p><h3>3. Meaningful Story Names</h3><p>Use descriptive story IDs that make it easy to identify which component failed in test reports.</p><h3>4. Consistent Environments</h3><p>Run tests in the same browser and viewport size to ensure consistent results.</p><h3>5. Review Screenshots</h3><p>Don’t just rely on automated comparisons — periodically review the generated screenshots to ensure they capture the intended state.</p><h2>Running Your Local Development Server</h2><p>For the tests to work properly, you need to ensure Storybook is running before executing the tests. You can configure Playwright to automatically start the Storybook dev server:</p><pre>// playwright.config.ts<br>export default defineConfig({<br>  // ... other configuration<br>  webServer: {<br>    command: &#39;yarn storybook&#39;,<br>    url: &#39;http://localhost:6006&#39;,<br>    reuseExistingServer: !process.env.CI<br>  },<br>});</pre><p>This configuration tells Playwright to:</p><ul><li>Start the Storybook server using yarn storybook</li><li>Wait for it to be available at <a href="http://localhost:6006/">http://localhost:6006</a></li><li>Reuse an existing server if one is already running (useful for local development)</li><li>Wait up to 2 minutes for the server to start</li></ul><p>Alternatively, you can manually start Storybook in a separate terminal:</p><pre># Terminal 1: Start Storybook<br>yarn storybook<br><br># Terminal 2: Run tests<br>npm run test-storybook</pre><h2>The Bottom Line</h2><p>Storybook testing isn’t just about catching bugs — it’s about building confidence in your component library. When you know that every visual change is automatically validated, you can refactor and improve components without fear of breaking existing implementations.</p><p>The implementation I’ve shown provides a solid foundation that scales with your application. As your component library grows, your test coverage grows automatically. This creates a safety net that allows your team to move fast without breaking things.</p><p>Start with this foundation, and you’ll find that visual regression testing becomes an integral part of your development workflow — one that saves hours of manual testing and prevents embarrassing production issues.</p><p><em>👍 If you found this guide helpful, please give it a like and share your experiences with Storybook testing in the comments below!</em></p><p><em>🚀 In Part 2, I’ll show you how to integrate this setup into your CI/CD pipeline and run it in Docker for production-ready visual regression testing.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab8f8cd6be1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quality-is-everything/automated-visual-regression-testing-with-playwright-and-storybook-eab8f8cd6be1">Visual Regression Testing with Playwright and Storybook</a> was originally published in <a href="https://medium.com/quality-is-everything">TestCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Data Parsing for Your AI Models — and Why Shift-Left Testing Might Save Your Project]]></title>
            <link>https://medium.com/quality-is-everything/how-to-test-data-parsing-for-your-ai-models-and-why-shift-left-testing-might-save-your-project-25cc631dfbf0?source=rss----d09c502483ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/25cc631dfbf0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[shiftleft]]></category>
            <dc:creator><![CDATA[Nikolai Boiko]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 04:44:30 GMT</pubDate>
            <atom:updated>2025-12-24T07:43:28.723Z</atom:updated>
            <content:encoded><![CDATA[<h2>How to Test Data Parsing for Your AI Models — and Why Shift-Left Testing Might Save Your Project</h2><p>Modern AI systems live or die by the quality of their data. It doesn’t matter how advanced your model is — if the underlying dataset is parsed incorrectly, missing fields, or mapped to the wrong schema, everything built on top of it becomes unreliable.</p><p>This problem is especially visible in data-heavy industries such as healthcare and pharmaceuticals. Teams often aggregate data from dozens of external providers: clinical trials, patents, scientific publications, chemical structures, pricing data, disease taxonomies, treatment outcomes, real-world evidence, and more. Each provider delivers this information in a different format, with different field names, different nesting, and different update schedules.</p><p>Before machine learning engineers can train a single model, all of this fragmented data must be parsed, normalized, validated, and stored in a structured dataset.</p><p>This is the stage where the majority of critical bugs occur.</p><p>And this is exactly where a shift-left testing approach becomes a game-changer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRcaF28Hk2cKfo1zbnN5Iw.png" /></figure><h2>Why Data Parsing Fails in AI Projects</h2><h3>1. Schemas are complex and evolving</h3><p>AI-first companies create rich schemas to unify data from many sources — sometimes hundreds of fields wide:</p><pre>Drug:<br>  id: string<br>  name: string<br>  molecule_type: string<br>  side_effects: array<br>  clinical_trials:<br>    - id: string<br>      phase: int<br>      status: string<br>  ...</pre><p>But external sources rarely match these clean definitions. One provider may call the field “moleculeType”, another “mol_type”, another “type”. The parsing logic that maps these must be maintained constantly — and this is where breakage is most common.</p><h3>2. Parsing logic grows quickly and unpredictably</h3><p>For each datasource you may have:</p><ul><li>different pagination strategies</li><li>different JSON structures</li><li>different rate limits</li><li>different data quality issues</li><li>different update timestamps</li></ul><p>This creates large, multi-branch parsing scripts that often break silently.</p><h3>3. Bugs in parsing propagate downstream</h3><p>A small parsing mistake becomes a massive problem:</p><ul><li>Features become wrong → Models become wrong</li><li>Data scientists lose trust in the dataset</li><li>Business KPIs degrade without understanding why</li></ul><p>Most AI failures originate not in the modeling stage, but in the data ingestion layer.</p><h2>The Shift-Left Solution: Test Parsers Early, Test Schemas Early, Test Everything Early</h2><p>Traditionally, QA validates outputs after the entire parsing pipeline is implemented. But by then:</p><ul><li>developers already moved on</li><li>bugs are deeply embedded</li><li>manual testers struggle to pinpoint root causes</li><li>fixes often introduce new bugs by breaking existing functionality</li><li>team morale starts to decline</li></ul><p>Shift-left testing solves this by validating data parsing during development, directly inside CI/CD.</p><p><strong>How shift-left applies to data parsing:</strong></p><ul><li><strong>Developers provide early script segments</strong> — Instead of waiting for a complete parser, they share smaller functional parts (e.g., the mapper logic for a single endpoint).</li><li><strong>Test Automation Engineers create parser-level tests</strong> — These tests verify:</li><li>JSON fields are mapped to schema correctly</li><li>CSV outputs contain equal headers</li><li>Count of records from API = count of records in stored files</li><li>Data types match the schema</li><li>Mandatory fields are not empty</li><li>Foreign keys match primary keys</li><li><strong>Manual testers create prime datasets</strong> — A small but realistic sample dataset is used as a source of truth for tests.</li><li><strong>CI/CD runs these validation tests on each commit</strong> — No new parsing logic is allowed to break the existing data layer.</li></ul><h2>Real-World Test Patterns: What We Actually Test</h2><p>Based on a production data ingestion pipeline handling pharmaceutical data from multiple providers (Infor, Tellis, R2K), here are the actual test patterns that catch parsing errors before they reach models:</p><h3>Test Pattern 1: Schema-to-CSV Header Validation</h3><p><strong>The Problem:</strong> CSV headers must exactly match the Physical Data Model (PDM) schema. A single renamed column breaks downstream joins.</p><p>Architectural Diagram:</p><pre>Physical Data Model (PDM)<br>                    │<br>                    │  schema contract<br>                    ▼<br>        ┌──────────────────────────┐<br>        │  Header Validation Test  │   ← runs in CI<br>        └──────────────────────────┘<br>                    │<br>         ┌──────────┴──────────┐<br>         │                     │<br>         ▼                     ▼<br>     CSV Files           Config / Metadata<br>   (real incoming)        (sources, layers)<br>         │<br>         ▼<br>   ❌ Pipeline blocked if mismatch</pre><p><strong>The Test:</strong> Compare PDM column definitions with actual CSV headers.</p><pre>from pdmreader.parser import PDMParser<br>from pathlib import Path<br>from csv import reader<br>from yaml import safe_load<br>import logging<br>from typing import Dict, List, Tuple<br><br>logger = logging.getLogger(__name__)<br><br># -----------------------------<br># Named datasources<br># -----------------------------<br>DATASOURCES: Dict[str, Path] = {<br>    &quot;ingest_root&quot;: Path(&quot;ingest/root&quot;),<br>    &quot;config&quot;: Path(&quot;../../config/ingenerator/config.yaml&quot;),<br>    &quot;docs_root&quot;: Path(&quot;../docs_root&quot;),<br>}<br><br>def check_headers_dm_csv() -&gt; None:<br>    &quot;&quot;&quot;<br>    Validate CSV headers match Physical Data Model schema definitions.<br><br>    Raises:<br>        AssertionError: If headers don&#39;t match schema<br>        FileNotFoundError: If config or CSV files are missing<br>    &quot;&quot;&quot;<br>    try:<br>        input_conf = safe_load(DATASOURCES[&quot;config&quot;].read_text())[&quot;input&quot;]<br>    except FileNotFoundError:<br>        logger.error(<br>            f&quot;Config file not found: {DATASOURCES[&#39;config&#39;].absolute()}&quot;<br>        )<br>        raise<br><br>    mismatches: List[Tuple[str, List[str], List[str]]] = []<br><br>    for source in input_conf[&quot;source&quot;]:<br>        for endpoint in input_conf[&quot;source&quot;][source]:<br>            try:<br>                # -----------------------------<br>                # PDM datasource<br>                # -----------------------------<br>                pdm_path = (<br>                    DATASOURCES[&quot;ingest_root&quot;]<br>                    / source<br>                    / input_conf[&quot;layer&quot;][0]<br>                    / input_conf[&quot;type&quot;][&quot;pdm&quot;][&quot;dir&quot;]<br>                    / f&quot;{source}_{endpoint}_stage.pdm&quot;<br>                )<br><br>                parsed_pdm = PDMParser(str(pdm_path)).parse_tables()<br><br>                for table in parsed_pdm:<br>                    # Schema columns<br>                    columns_list = [column.code for column in table.columns]<br><br>                    # -----------------------------<br>                    # CSV datasource<br>                    # -----------------------------<br>                    csv_path = (<br>                        DATASOURCES[&quot;docs_root&quot;]<br>                        / &quot;csv&quot;<br>                        / source.lower()<br>                        / endpoint.lower()<br>                        / table.code<br>                        / f&quot;{table.code}.csv&quot;<br>                    )<br><br>                    if not csv_path.exists():<br>                        logger.warning(f&quot;CSV file not found: {csv_path}&quot;)<br>                        continue<br><br>                    csv_headers = list(reader(csv_path.open()))[0]<br>                    csv_headers_lower = [h.lower() for h in csv_headers]<br><br>                    # Compare headers<br>                    if columns_list != csv_headers_lower:<br>                        mismatches.append(<br>                            (table.code, columns_list, csv_headers)<br>                        )<br>                        logger.error(<br>                            f&quot;Schema mismatch for {table.code}:\n&quot;<br>                            f&quot;PDM: {columns_list}\n&quot;<br>                            f&quot;CSV: {csv_headers}&quot;<br>                        )<br><br>            except Exception as e:<br>                logger.error(f&quot;Error processing {source}/{endpoint}: {e}&quot;)<br>                raise<br><br>    if mismatches:<br>        error_msg = &quot;Headers in CSV and PDM do not match:\n&quot;<br>        for table, schema, csv in mismatches:<br>            error_msg += (<br>                f&quot;\n{table}:\n&quot;<br>                f&quot;  PDM: {schema}\n&quot;<br>                f&quot;  CSV: {csv}\n&quot;<br>            )<br>        raise AssertionError(error_msg)</pre><p><strong>What This Catches:</strong></p><ul><li>Missing schema fields</li><li>Extra fields added without schema updates</li><li>Renamed fields (e.g., drug_id → drugid)</li><li>Case sensitivity mismatches</li><li>Silent breakage in mapper scripts</li></ul><p><strong>Real Example Failure:</strong></p><pre>AssertionError: Headers in CSV and PDM is not equal.<br>PDM: [&#39;drug_id&#39;, &#39;name&#39;, &#39;status&#39;, &#39;updated_at&#39;]<br>CSV: [&#39;drug_id&#39;, &#39;drugname&#39;, &#39;status&#39;, &#39;updated&#39;]</pre><p>Instead of discovering this weeks later during model training.</p><h3>Test Pattern 2: API-to-JSON Field Validation</h3><p><strong>The Problem:</strong> Individual fields from API responses must match parsed JSON exactly. A single field mapping error can corrupt thousands of records.</p><p><strong>The Test:</strong> Extract specific fields from API responses and compare with parsed JSON files.</p><pre>import json<br>import os<br>import requests<br>from requests.auth import HTTPDigestAuth<br>from requests.exceptions import RequestException, Timeout<br>import s3fs<br>import logging<br>from typing import Optional<br>from utils import get_token  # Centralized auth utility<br><br>logger = logging.getLogger(__name__)<br><br># -----------------------------<br># Named datasources<br># -----------------------------<br>DATASOURCES = {<br>    &quot;apis&quot;: {<br>        &quot;infor&quot;: &quot;https://api.infor.com/v1/feed&quot;,<br>        &quot;tellis&quot;: &quot;https://api.tellis.com/api-ws/ws/rs/drugs-v2&quot;,<br>    },<br>    &quot;s3&quot;: {<br>        &quot;json_root_env&quot;: &quot;API2JSON_JSON_DIR&quot;,<br>        &quot;date_env&quot;: &quot;DATE&quot;,<br>    },<br>}<br><br># S3 filesystem datasource<br>fs = s3fs.S3FileSystem(key=&quot;&quot;, token=&quot;&quot;, secret=&quot;&quot;)<br><br>def assert_api_json(<br>    data_source: str,<br>    data_set: str,<br>    first_arg: str,<br>    sec_arg: str<br>) -&gt; None:<br>    &quot;&quot;&quot;<br>    Compare a specific field from API response with parsed JSON.<br>    &quot;&quot;&quot;<br>    try:<br>        api_param = get_param_from_api(<br>            data_source, data_set, first_arg, sec_arg<br>        )<br>        json_param = get_param_from_json(<br>            data_source, data_set, first_arg, sec_arg<br>        )<br><br>        if api_param != json_param:<br>            error_msg = (<br>                f&quot;Field mismatch for {data_source}/{data_set}:\n&quot;<br>                f&quot;  API value: {api_param}\n&quot;<br>                f&quot;  JSON value: {json_param}\n&quot;<br>                f&quot;  Field path: {first_arg}[0].{sec_arg}&quot;<br>            )<br>            logger.error(error_msg)<br>            raise AssertionError(error_msg)<br><br>        logger.debug(f&quot;Field validation passed: {sec_arg} = {api_param}&quot;)<br><br>    except RequestException as e:<br>        logger.error(f&quot;API request failed for {data_source}/{data_set}: {e}&quot;)<br>        raise ConnectionError(f&quot;Failed to fetch from API: {e}&quot;) from e<br><br><br>def get_param_from_api(<br>    data_source: str,<br>    data_set: str,<br>    first_arg: str,<br>    sec_arg: str<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    Extract field from live API response.<br>    &quot;&quot;&quot;<br>    try:<br>        if data_source == &quot;infor&quot;:<br>            url = f&quot;{DATASOURCES[&#39;apis&#39;][&#39;infor&#39;]}/{data_set}&quot;<br>            headers = {<br>                &quot;Authorization&quot;: f&quot;Bearer {get_token(data_source)}&quot;<br>            }<br><br>            response = requests.get(<br>                url=url,<br>                headers=headers,<br>                timeout=30,<br>            )<br>            response.raise_for_status()<br><br>            json_response = response.json()<br>            return str(json_response[first_arg][0][sec_arg])<br><br>        elif data_source == &quot;tellis&quot;:<br>            url = (<br>                f&quot;{DATASOURCES[&#39;apis&#39;][&#39;tellis&#39;]}/&quot;<br>                f&quot;{data_set}/search?query=*&amp;fmt=json&quot;<br>            )<br><br>            response = requests.get(<br>                url,<br>                auth=HTTPDigestAuth(<br>                    aws_api_user(data_set),<br>                    aws_api_pass(data_set),<br>                ),<br>                timeout=30,<br>            )<br>            response.raise_for_status()<br><br>            return response.json()[<br>                &quot;drugResultsOutput&quot;<br>            ][&quot;SearchResults&quot;][&quot;Drug&quot;][0][&quot;@id&quot;]<br><br>        # other data sources here<br><br>    except Timeout:<br>        logger.error(f&quot;API timeout for {data_source}/{data_set}&quot;)<br>        raise<br><br>    except KeyError as e:<br>        logger.error(f&quot;Missing field in API response: {e}&quot;)<br>        raise ValueError(<br>            f&quot;Field not found in API response: {e}&quot;<br>        ) from e<br><br><br>def get_param_from_json(<br>    data_source: str,<br>    data_set: str,<br>    first_arg: str,<br>    sec_arg: str<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    Extract same field from parsed JSON file stored in S3.<br>    &quot;&quot;&quot;<br><br>    json_root = os.environ.get(<br>        DATASOURCES[&quot;s3&quot;][&quot;json_root_env&quot;]<br>    )<br>    date = os.environ.get(<br>        DATASOURCES[&quot;s3&quot;][&quot;date_env&quot;]<br>    )<br><br>    if not json_root or not date:<br>        raise ValueError(<br>            &quot;Required environment variables not set: &quot;<br>            f&quot;{DATASOURCES[&#39;s3&#39;][&#39;json_root_env&#39;]}, &quot;<br>            f&quot;{DATASOURCES[&#39;s3&#39;][&#39;date_env&#39;]}&quot;<br>        )<br><br>    # -----------------------------<br>    # JSON datasource paths<br>    # -----------------------------<br>    if data_set.endswith(&quot;increment&quot;):<br>        path = (<br>            f&quot;{json_root}/{data_source}/{data_set}/{date}/&quot;<br>            f&quot;{data_set[:-9]}/{data_set[:-9]}-0.json&quot;<br>        )<br>    else:<br>        path = (<br>            f&quot;{json_root}/{data_source}/{data_set}/{date}/&quot;<br>            f&quot;{data_set}/{data_set}-0.json&quot;<br>        )<br><br>    try:<br>        with fs.open(path, &quot;r&quot;) as file:<br>            file_json = json.load(file)<br><br>        # Data-source–specific structures<br>        if data_source == &quot;infor&quot; and data_set.endswith(&quot;increment&quot;):<br>            return file_json[0][&quot;data&quot;][sec_arg]<br><br>        elif data_source == &quot;infor&quot;:<br>            return file_json[0][sec_arg]<br><br>        elif data_source == &quot;tellis&quot;:<br>            return file_json[&quot;drugRecordsOutput&quot;][&quot;Drug&quot;][30][&quot;@id&quot;]<br><br>        else:<br>            return str(file_json[first_arg][0][sec_arg])<br><br>    except FileNotFoundError:<br>        logger.error(f&quot;JSON file not found: {path}&quot;)<br>        raise<br><br>    except KeyError as e:<br>        logger.error(f&quot;Field not found in JSON: {e}&quot;)<br>        raise ValueError(<br>            f&quot;Field not found in JSON file: {e}&quot;<br>        ) from e</pre><p><strong>What This Catches:</strong></p><ul><li>Field mapping errors (e.g., type mapped to molecule_type instead of drug_type)</li><li>Data transformation bugs (e.g., string truncation, date format changes)</li><li>Missing field handling</li><li>Nested object parsing errors</li></ul><p><strong>Test Coverage:</strong> This pattern is applied across multiple data sources:</p><ul><li>Infor: Drug, Trial, Event, Catalyst (and their increment versions)</li><li>R2K: Institution, Submission, Reference data (Countries, Regions, InstitutionTypes)</li><li>Tellis: Drug records</li></ul><h3>Test Pattern 3: Record Count Validation (API → JSON → CSV)</h3><p><strong>The Problem:</strong> Record counts must match at every stage. If an API returns 12,453 records but only 12,102 are stored, downstream models train on incomplete data.</p><p><strong>The Test:</strong> Compare total record counts across the pipeline.</p><pre>import os<br>import json<br>import requests<br>from requests.auth import HTTPDigestAuth<br>from requests.exceptions import RequestException<br>import s3fs<br>import logging<br>from typing import Dict<br>from utils import get_token, aws_api_user, aws_api_pass<br><br>logger = logging.getLogger(__name__)<br><br># -----------------------------<br># Named datasources<br># -----------------------------<br>DATASOURCES: Dict[str, Dict[str, str]] = {<br>    &quot;apis&quot;: {<br>        &quot;infor&quot;: &quot;https://api.infor.com/v1/feed&quot;,<br>        &quot;tellis&quot;: &quot;https://api.tellis.com/api-ws/ws/rs/drugs-v2&quot;,<br>    },<br>    &quot;env&quot;: {<br>        &quot;date&quot;: &quot;DATE&quot;,<br>        &quot;json_root&quot;: &quot;JSON2CSV_JSON_DIR&quot;,<br>    },<br>    &quot;dataset_aliases&quot;: {<br>        &quot;drugevent&quot;: &quot;event&quot;,<br>    },<br>}<br><br># S3 datasource<br>fs = s3fs.S3FileSystem(key=&quot;&quot;, token=&quot;&quot;, secret=&quot;&quot;)<br><br>def compare_count_api_json(<br>    data_source: str,<br>    data_set: str,<br>    tolerance: int = 0<br>) -&gt; None:<br>    &quot;&quot;&quot;<br>    Compare total record count from API with JSON files.<br>    &quot;&quot;&quot;<br>    api_count = get_total_count_from_api(data_source, data_set)<br>    json_count = get_total_count_json(data_source, data_set)<br><br>    difference = abs(api_count - json_count)<br><br>    logger.info(<br>        f&quot;Count comparison for {data_source}/{data_set}: &quot;<br>        f&quot;API={api_count}, JSON={json_count}, diff={difference}&quot;<br>    )<br><br>    if difference &gt; tolerance:<br>        error_msg = (<br>            f&quot;Record count mismatch for {data_source}/{data_set}:\n&quot;<br>            f&quot;  API count: {api_count}\n&quot;<br>            f&quot;  JSON count: {json_count}\n&quot;<br>            f&quot;  Difference: {difference} (tolerance: {tolerance})&quot;<br>        )<br>        logger.error(error_msg)<br>        raise AssertionError(error_msg)<br><br><br>def get_total_count_from_api(<br>    data_source: str,<br>    data_set: str<br>) -&gt; int:<br>    &quot;&quot;&quot;<br>    Get total record count from API endpoint.<br>    &quot;&quot;&quot;<br>    try:<br>        if data_source == &quot;infor&quot;:<br>            date = os.environ.get(<br>                DATASOURCES[&quot;env&quot;][&quot;date&quot;],<br>                &quot;2025-11-01&quot;,<br>            )<br><br>            if data_set.endswith(&quot;increment&quot;):<br>                url = (<br>                    f&quot;{DATASOURCES[&#39;apis&#39;][&#39;infor&#39;]}/&quot;<br>                    f&quot;{data_set}/changes/count?since={date}&quot;<br>                )<br>            else:<br>                url = (<br>                    f&quot;{DATASOURCES[&#39;apis&#39;][&#39;infor&#39;]}/&quot;<br>                    f&quot;{data_set}/count&quot;<br>                )<br><br>            headers = {<br>                &quot;Authorization&quot;: f&quot;Bearer {get_token(data_source)}&quot;<br>            }<br><br>            response = requests.get(<br>                url=url,<br>                headers=headers,<br>                timeout=60,<br>            )<br>            response.raise_for_status()<br><br>            return response.json()[&quot;data&quot;][&quot;count&quot;]<br><br>        elif data_source == &quot;tellis&quot;:<br>            url = (<br>                f&quot;{DATASOURCES[&#39;apis&#39;][&#39;tellis&#39;]}/&quot;<br>                f&quot;{data_set}/search?&quot;<br>                f&quot;query=*&amp;returnFilterCount=1000&amp;fmt=json&quot;<br>            )<br><br>            response = requests.get(<br>                url,<br>                auth=HTTPDigestAuth(<br>                    aws_api_user(data_set),<br>                    aws_api_pass(data_set),<br>                ),<br>                timeout=60,<br>            )<br>            response.raise_for_status()<br><br>            return int(<br>                response.json()[&quot;drugResultsOutput&quot;][&quot;@totalResults&quot;]<br>            )<br><br>        else:<br>            raise ValueError(f&quot;Unsupported data source: {data_source}&quot;)<br><br>    except RequestException as e:<br>        logger.error(f&quot;API request failed: {e}&quot;)<br>        raise ConnectionError(<br>            f&quot;Failed to get count from API: {e}&quot;<br>        ) from e<br><br><br>def get_total_count_json(<br>    data_source: str,<br>    data_set: str<br>) -&gt; int:<br>    &quot;&quot;&quot;<br>    Count records across all JSON files in S3.<br>    &quot;&quot;&quot;<br>    json_root = os.environ.get(<br>        DATASOURCES[&quot;env&quot;][&quot;json_root&quot;]<br>    )<br>    date = os.environ.get(<br>        DATASOURCES[&quot;env&quot;][&quot;date&quot;]<br>    )<br><br>    if not json_root or not date:<br>        raise ValueError(<br>            &quot;Required environment variables not set&quot;<br>        )</pre><p><strong>What This Catches:</strong></p><ul><li>Pagination errors (missing pages)</li><li>Filtering bugs (records incorrectly excluded)</li><li>Duplicate detection failures</li><li>File writing errors (partial writes)</li></ul><p><strong>Real Example:</strong> This test runs for full loads across:</p><ul><li>Tellis Drug (full dataset)</li><li>Infor: Drug, Trial, Event, Catalyst (full and increment loads)</li><li>R2L: Institution, Submission (full and increment loads)</li></ul><h3>Test Pattern 4: JSON-to-CSV Data Integrity</h3><p><strong>The Problem:</strong> Data must be correctly transformed from JSON structure to flat CSV format. Nested objects, arrays, and relationships must be preserved.</p><p><strong>The Test:</strong> Match individual records from JSON files with corresponding CSV rows.</p><pre>def matching_data_json_to_csv(project_type, data_type):<br>    &quot;&quot;&quot;<br>    Route to appropriate comparison function based on data source<br>    &quot;&quot;&quot;<br>    if project_type == &#39;infor&#39; and data_type == &#39;drug&#39;:<br>        compare_infor_drug_files()<br>    elif project_type == &#39;infor&#39; and data_type == &#39;trial&#39;:<br>        compare_infor_trial_files()<br><br>    # ... handles multiple data sources and types<br>def compare_infor_drug_files():<br>    &quot;&quot;&quot;<br>    Compare JSON records with CSV rows for Infor Drug data<br>    &quot;&quot;&quot;<br><br>    # Load JSON files<br>    json_data = upload_json()  # Loads from S3<br><br>    # Load corresponding CSV files<br>    csv_data = bmtdrug_csv()  # Loads from S3<br><br>    # Compare field-by-field<br>    for json_record, csv_row in zip(json_data, csv_data):<br>        assert json_record[&#39;id&#39;] == csv_row[0]<br>        assert json_record[&#39;name&#39;] == csv_row[1]<br><br>        # ... validate all fields</pre><p><strong>What This Catches:</strong></p><ul><li>Data transformation errors (e.g., nested objects not flattened correctly)</li><li>Array handling bugs (e.g., multiple values not split into separate rows)</li><li>Data type conversion errors (e.g., dates, numbers)</li><li>Character encoding issues</li><li>Null/missing value handling</li></ul><h3>Test Pattern 5: CSV Structure Consistency</h3><p><strong>The Problem:</strong> Every CSV row must have the same number of columns as the header. Missing columns indicate parsing errors.</p><p><strong>The Test:</strong> Verify row-column consistency across all CSV files.</p><pre>import os<br>import csv<br>import logging<br>import s3fs<br><br>logger = logging.getLogger(__name__)<br><br># -----------------------------<br># Named datasources<br># -----------------------------<br>DATASOURCES = {<br>    &quot;env&quot;: {<br>        &quot;csv_root&quot;: &quot;JSON2CSV_CSV_DIR&quot;,<br>        &quot;date&quot;: &quot;DATE&quot;,<br>    }<br>}<br><br>fs = s3fs.S3FileSystem(key=&quot;&quot;, token=&quot;&quot;, secret=&quot;&quot;)<br><br>def check_rows_columns(project_type: str, data_type: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Verify that all CSV rows contain the same number of columns as the header.<br><br>    Raises:<br>        AssertionError: if any row has missing or extra columns<br>        ValueError: if required environment variables are missing<br>    &quot;&quot;&quot;<br>    csv_root = os.environ.get(DATASOURCES[&quot;env&quot;][&quot;csv_root&quot;])<br>    date = os.environ.get(DATASOURCES[&quot;env&quot;][&quot;date&quot;])<br><br>    if not csv_root or not date:<br>        raise ValueError(<br>            &quot;Required environment variables not set: &quot;<br>            f&quot;{DATASOURCES[&#39;env&#39;][&#39;csv_root&#39;]}, &quot;<br>            f&quot;{DATASOURCES[&#39;env&#39;][&#39;date&#39;]}&quot;<br>        )<br><br>    base_path = f&quot;{csv_root}/{project_type}/{data_type}/{date}&quot;<br><br>    for directory in fs.listdir(base_path):<br>        directory_key = directory[&quot;Key&quot;]<br><br>        for csv_file in fs.listdir(f&quot;s3://{directory_key}&quot;):<br>            file_key = csv_file[&quot;Key&quot;]<br><br>            logger.debug(f&quot;Validating CSV file: {file_key}&quot;)<br><br>            with fs.open(f&quot;s3://{file_key}&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>                reader = csv.reader(file)<br>                headers = next(reader)<br>                expected_columns = len(headers)<br><br>                for row_number, row in enumerate(reader, start=2):<br>                    if len(row) != expected_columns:<br>                        error_msg = (<br>                            f&quot;Column count mismatch in file: {file_key}\n&quot;<br>                            f&quot;Expected columns: {expected_columns}, &quot;<br>                            f&quot;Found: {len(row)}, &quot;<br>                            f&quot;Line: {row_number}&quot;<br>                        )<br>                        logger.error(error_msg)<br>                        raise AssertionError(error_msg)</pre><p><strong>What This Catches:</strong></p><ul><li>Missing field values (causing column count mismatches)</li><li>Incorrect CSV escaping (breaking column boundaries)</li><li>Truncated records</li><li>Encoding issues causing parsing errors</li></ul><h3>Test Pattern 6: Foreign Key Integrity</h3><p><strong>The Problem:</strong> Foreign keys in related tables must reference valid primary keys. Broken relationships break joins and corrupt analysis.</p><p><strong>The Test:</strong> Verify all foreign keys exist as primary keys in referenced tables.</p><pre>import os<br>import csv<br>import logging<br>import s3fs<br><br>logger = logging.getLogger(__name__)<br><br># -----------------------------<br># Named datasources<br># -----------------------------<br>DATASOURCES = {<br>    &quot;env&quot;: {<br>        &quot;csv_root&quot;: &quot;JSON2CSV_CSV_DIR&quot;,<br>        &quot;date&quot;: &quot;DATE&quot;,<br>    }<br>}<br><br>fs = s3fs.S3FileSystem(key=&quot;&quot;, token=&quot;&quot;, secret=&quot;&quot;)<br><br>def match_fk_with_pk(data_source: str, data_set: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Verify that all foreign keys exist in the set of primary keys.<br><br>    Raises:<br>        AssertionError: if any foreign key does not match a primary key<br>        ValueError: if required environment variables are missing<br>    &quot;&quot;&quot;<br>    csv_root = os.environ.get(DATASOURCES[&quot;env&quot;][&quot;csv_root&quot;])<br>    date = os.environ.get(DATASOURCES[&quot;env&quot;][&quot;date&quot;])<br><br>    if not csv_root or not date:<br>        raise ValueError(<br>            &quot;Required environment variables not set: &quot;<br>            f&quot;{DATASOURCES[&#39;env&#39;][&#39;csv_root&#39;]}, {DATASOURCES[&#39;env&#39;][&#39;date&#39;]}&quot;<br>        )<br><br>    base_path = f&quot;{csv_root}/{data_source}/{data_set}/{date}&quot;<br><br>    pk_set = set()<br>    fk_set = set()<br><br>    for directory in fs.listdir(base_path):<br>        directory_key = directory[&quot;Key&quot;]<br><br>        for csv_file in fs.listdir(f&quot;s3://{directory_key}&quot;):<br>            file_key = csv_file[&quot;Key&quot;]<br>            logger.debug(f&quot;Processing CSV file: {file_key}&quot;)<br><br>            with fs.open(f&quot;s3://{file_key}&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>                reader = csv.reader(file)<br>                headers = next(reader)  # Skip header<br><br>                for row_number, row in enumerate(reader, start=2):<br>                    if len(row) &lt; 2:<br>                        logger.warning(<br>                            f&quot;Skipping malformed row {row_number} in {file_key}&quot;<br>                        )<br>                        continue<br>                    fk_value = row[0].strip(&#39;&quot;&#39;)<br>                    pk_value = row[1].strip(&#39;&quot;&#39;)<br>                    fk_set.add(fk_value)<br>                    pk_set.add(pk_value)<br><br>    orphan_fks = fk_set - pk_set<br>    if orphan_fks and orphan_fks != {&#39;&#39;}:<br>        error_msg = (<br>            f&quot;The following foreign keys do not match any primary keys:\n&quot;<br>            f&quot;{orphan_fks}&quot;<br>        )<br>        logger.error(error_msg)<br>        raise AssertionError(error_msg)</pre><p><strong>What This Catches:</strong></p><ul><li>Orphaned records (foreign keys pointing to non-existent records)</li><li>Referential integrity violations</li><li>Join failures waiting to happen</li><li>Data relationship corruption</li></ul><p><strong>Test Coverage:</strong> Applied to:</p><ul><li>Tellis Drug relationships</li><li>Infor: Drug, Trial, Event, Catalyst relationships</li><li>R2L: Institution, Submission, Reference data relationships</li></ul><h3>Test Pattern 7: Header Name Validation</h3><p><strong>The Problem:</strong> CSV headers must match expected names exactly. Typos or naming inconsistencies break downstream processing.</p><p><strong>The Test:</strong> Validate header names against expected lists.</p><pre>def check_headers(project_type, data_type):<br>    &quot;&quot;&quot;<br>    Route to data-source-specific header validation<br>    &quot;&quot;&quot;<br>    if project_type == &#39;infor&#39; and data_type == &#39;drug&#39;:<br>        check_headers_name_infor_drug()<br>    elif project_type == &#39;infor&#39; and data_type == &#39;trial&#39;:<br>        check_headers_name_infor_trial()<br>    <br>    # ... handles all data sources<br><br>def check_headers_name_infor_drug():<br>    &quot;&quot;&quot;<br>    Validate Infor Drug CSV headers<br>    &quot;&quot;&quot;<br>    expected_headers = {<br>        &#39;bmtdrug&#39;: [&#39;id&#39;, &#39;drug_id&#39;, &#39;name&#39;, ...],<br>        &#39;casnumber&#39;: [&#39;id&#39;, &#39;drug_id&#39;, &#39;cas_number&#39;, ...],<br>        <br>    # ... all expected tables<br>    }<br>    <br>    # Load actual headers from CSV files<br>    # Compare with expected headers<br>    # Raise AssertionError on mismatch</pre><p><strong>What This Catches:</strong></p><ul><li>Header name typos</li><li>Naming convention violations</li><li>Missing required headers</li><li>Unexpected headers added</li></ul><h3>Test Pattern 8: Pipeline Stage Validation (Orchestrator Tests)</h3><p><strong>The Problem:</strong> Files must exist and be properly sized at each pipeline stage. Missing or empty files indicate pipeline failures.</p><p><strong>The Test:</strong> Verify file availability and size at different pipeline stages.</p><pre>def check_csv_file_availability(data_source, data_set):<br>    &quot;&quot;&quot;<br>    Verify CSV files exist and have content at specific pipeline stage<br>    &quot;&quot;&quot;<br>    # Check files at JSON_TO_CSV stage<br>    # Check files at RAW stage<br>    # Check files at TRIGGER stage<br>    # Check files at ARCHIVE stage</pre><p><strong>What This Catches:</strong></p><ul><li>Pipeline stage failures</li><li>File transfer errors</li><li>Empty output files</li><li>Missing files in expected locations</li></ul><h2>Test Architecture: Building Maintainable Test Frameworks</h2><h3>Design Principles</h3><p>To architect scalable test frameworks, here are the key principles applied in this pipeline:</p><p><strong>1. Separation of Concerns</strong></p><ul><li><strong>Python Libraries</strong>: Core validation logic (reusable across projects)</li><li><strong>Robot Keywords</strong>: Test orchestration and reporting</li><li><strong>Configuration</strong>: Environment variables and secrets management</li><li><strong>Test Data</strong>: Prime datasets stored separately from test code</li></ul><p><strong>2. Centralized Authentication</strong></p><pre>def get_token(data_source: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Centralized token management via AWS Secrets Manager<br>    &quot;&quot;&quot;<br>    secrets_client = boto3.client(&quot;secretsmanager&quot;)<br>    secret_id = os.environ[f&quot;{data_source.upper()}_SECRET_ID&quot;]<br>    secret = json.loads(secrets_client.get_secret_value(SecretId=secret_id)[&quot;SecretString&quot;])<br>    # ... token generation logic</pre><p><strong>3. Logging Strategy</strong></p><pre>def logging_level():<br>    &quot;&quot;&quot;Suppress noisy third-party logs, keep test logs visible&quot;&quot;&quot;<br>    noisy_loggers = [&#39;fsspec&#39;, &#39;urllib3&#39;, &#39;botocore&#39;, &#39;boto3&#39;, &#39;s3fs&#39;]<br>    for name in logging.Logger.manager.loggerDict.keys():<br>        if name in noisy_loggers:<br>            logging.getLogger(name).setLevel(logging.ERROR)</pre><p>Informative error messages and structured logging clearly show what failed, where it failed, and the expected outcome.</p><pre>logger.info(f&quot;Comparing counts: API={api_count}, JSON={json_count}&quot;)<br>if api_count != json_count:<br>    error_msg = (<br>        f&quot;Record count mismatch for {data_source}/{data_set}:\n&quot;<br>        f&quot;  API count: {api_count}\n&quot;<br>        f&quot;  JSON count: {json_count}\n&quot;<br>        f&quot;  Difference: {abs(api_count - json_count)}&quot;<br>    )<br>    logger.error(error_msg)<br>    raise AssertionError(error_msg)</pre><p><strong>4. Error Handling Patterns</strong></p><ul><li><strong>Fail Fast</strong>: Tests fail immediately on critical errors</li><li><strong>Informative Messages</strong>: Error messages include context (file paths, field names, expected vs actual)</li><li><strong>Graceful Degradation</strong>: Non-critical validations continue even if one fails</li></ul><p><strong>5. Test Data Management</strong></p><ul><li><strong>Environment Variables</strong>: Paths and dates configured via env vars (not hardcoded)</li><li><strong>S3 Integration</strong>: Test data stored in S3 for scalability</li><li><strong>Prime Datasets</strong>: Small, representative datasets for fast smoke tests</li><li><strong>Full Datasets</strong>: Complete datasets for regression testing</li></ul><h2>Test Automation Framework: Robot Framework</h2><p>Robot Framework is chosen to make test scenarios easily readable for data analysts. At this stage, the Test Automation Engineer closely collaborates with data analysts, which helps in designing and expanding additional test scenarios.</p><p>The tests are implemented using <strong>Robot Framework</strong>, a keyword-driven test automation framework that enables:</p><ul><li><strong>Reusable test keywords</strong> — Common validation logic is abstracted into keywords</li><li><strong>Data-driven testing</strong> — Same test logic applied across multiple data sources</li><li><strong>Parallel execution</strong> — Tests run in parallel using Pabot for faster feedback</li><li><strong>Clear reporting</strong> — Detailed test reports showing exactly what failed and why</li><li><strong>Tag-based execution</strong> — Selective test runs (smoke, regression, data-source-specific)</li></ul><p><strong>Example Test Structure:</strong></p><pre>*** Test Cases ***<br>Match Infor Drug Json To CSV<br>    [Documentation]    Verifies CSV files existence and matches data<br>    ...                from CSV files with data from Json file.<br>    [Tags]    json_to_csv    smoke    regression<br>    Match Json To CSV    ${INFOR}    ${DRUG}</pre><pre>Compare Full Load Infor Drug API Json Count<br>    [Documentation]    Compares the total amount of items from API<br>    ...                with items from JSON.<br>    [Tags]    drug_full_data<br>    Full Load Compare API Json    ${INFOR}    ${DRUG}</pre><p><strong>Test Execution:</strong></p><ul><li><strong>Smoke tests:</strong> robot -i smoke Tests — Quick validation of critical paths</li><li><strong>Regression tests:</strong> robot -i regression Tests — Full test suite</li><li><strong>Parallel execution:</strong> pabot --processes 4 -i smoke Tests — Faster feedback</li></ul><h2>Why Shift-Left Works for AI Data Projects</h2><p><strong>Speed:</strong> Bugs are caught during development, not weeks later<br><strong>Reliability:</strong> Data scientists get trustworthy, stable datasets<br><strong>Transparency:</strong> Logging and assertions show exactly where parsing failed<br><strong>Collaboration:</strong> Developers and QA work together from day one<br><strong>Automation:</strong> CI/CD prevents regressions on every commit<br><strong>Multi-Source Validation:</strong> Tests handle multiple data providers<br><strong>Incremental Testing:</strong> Both full loads and incremental updates are validated<br><strong>Relationship Integrity:</strong> Foreign key validation prevents join failures</p><p>Data parsing becomes predictable instead of chaotic.</p><h2>Conclusion</h2><p>AI systems fail not because the models are weak — but because the data feeding them is broken, misaligned, or incomplete.</p><p>Shift-left testing is one of the most effective ways to guarantee that your data parsing layer stays consistent, correct, and predictable.</p><p>By testing schemas early (PDM vs CSV headers), validating API-to-JSON field mapping, verifying record counts across pipeline stages, checking JSON-to-CSV data integrity, ensuring CSV structure consistency, validating foreign key relationships, and automating everything inside CI/CD, teams prevent catastrophic downstream failures and dramatically speed up the entire AI development lifecycle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25cc631dfbf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quality-is-everything/how-to-test-data-parsing-for-your-ai-models-and-why-shift-left-testing-might-save-your-project-25cc631dfbf0">How to Test Data Parsing for Your AI Models — and Why Shift-Left Testing Might Save Your Project</a> was originally published in <a href="https://medium.com/quality-is-everything">TestCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best testing framework guidelines 2020.]]></title>
            <link>https://medium.com/quality-is-everything/best-testing-framework-guidelines-2020-34b25ed52b8b?source=rss----d09c502483ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/34b25ed52b8b</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Nikolai Boiko]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 12:03:07 GMT</pubDate>
            <atom:updated>2025-11-08T12:03:02.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing framework guidelines 2020</h3><p>Having an extensive experience as a Team Lead working for different projects with test automation engineers of different levels, I found out that QA teams can avoid a number of drawbacks, if they follow certain rules in automation testing. The below guideline describes the most cost-effective and productive approach to build framework, test architecture and run tests.</p><p>Before we start talking about the guidelines, it’s important to understand what test automation framework actually is. Testing framework is a set of guidelines or rules used for creating and designing test cases. It comprises a combination of practices and tools designed to help QA automation engineers to carry out tests in a more efficient way.</p><h3>1. Take some time to understand the project first.</h3><p>When you start working on a new project as a QA Automation engineer, you have to get an insight of the project first. Don’t start automation before you familiarize yourself with the documentation and all the requirements. Try to figure out how many parts are in the project and how they relate to each other. It might be API sources, microservices, database and so on. Discuss it with manual testers, developers, delivery or project managers. Try to elicit as many questions as possible that will help you to understand the project better. For example, the number of API sources, types of db, and services to be in use, etc.</p><p>As soon as you have clear understanding of the project, reflect it in a draft schema with explanation of each block. It can be done even manually on the paper.</p><p>Example of the draft schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3QdtobesiVLdQcaJ-WxfQ.jpeg" /></figure><p>Choose a block from this schema that you are planning to automate first. For example, as you can see from the draft you have to be able to send API requests to three API sources to verify, if data is retrieved.</p><p>Another example, to verify python parser you have to create a set of integration tests. At this step you should talk to the system architect and devops about the catalogue naming and its structure where are you planning to store your sample data. It will help you to avoid test refactoring further and pass CI/CD process smooth.</p><h3>2. Choose the framework.</h3><p>When you are done with the requirements and the draft schema, choose the framework that meets your needs.</p><p>Raise a query about the test framework requirements, if there is any. If there are no requirements, take the next step — choose the language.</p><p>If you need to create only API and UI tests choose any language you are confident with. If you decide to add some Integration tests, I would suggest to use the language used in the project, in case any assistance is required you can seek for assistance from developers.</p><p>As soon as you decide on the language it’s time to choose the framework. I would suggest to use only one framework for all types of testing because it is more efficient to support. Make sure the framework you are planning to work with meets your requirements, such as the number of browsers supported by the framework, the ability to parallelize the tests further if the number of tests is exceeding certain amount, etc.</p><p>For example, you have requirements to support multiple browsers and planning to parallelize the tests, you may choose to work with Cypress as the easiest to work with, it has good documentation and support. But if it turns out that Cypress supports only Chrome or Chromium browser and parallelization is not free, it may change your plans and you may go with standard tools like TestNG, Protractor, Robot, etc.</p><h3>3. Page Object and Page Factory Patterns</h3><p>Having chosen the right framework, the next step is test design. I would suggest to consider Page Object Model (POM) as an approach that will help you to have well structured tests and improve code maintainability.</p><p>Page Object Pattern is a design pattern widely used in automation. The main idea of this pattern is to describe a page or another UI entity — dialog, panel, container as an object.</p><p>Page Factory is used to initialize the elements of the Page Object or instantiate the Page Object itself. If any object changes in UI, then the tester just need to update locator in one centralized location thus minimizing the code maintenance effort.</p><p>Page Object contains a few layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*t7h7fEnUF8fVOKErkkxiLw.jpeg" /></figure><p><strong>Page Layer</strong></p><p>Page Object model divides the app into blocks with separate classes for each page. For example: if we work with Login page and Registration page, we should create Login class and registration class accordingly. The number of classes is equal to the number of pages. As soon as the separate classes are created for each page, you have to define Object Repository and Actions.</p><p>Object Repository is a collection of web objects and web elements as username, password, login button, submit button and other web elements on the page. All these elements are called Login Page elements.</p><p>Actions are methods that reflect some actions on the page like login(), signIn(), register(), etc.</p><pre>public class LoginPage extends TestBase {</pre><pre>@FindBy(id=”username”)<br>WebElement username;</pre><pre>@FindBy(id=”password”)<br>WebElement pass;</pre><pre>@FindBy(id=”loginBtn”)<br>WebElement loginBtn;</pre><pre>@FindBy(id=”title”)<br>WebElement title;</pre><pre>// Initializing all elements with driver<br>public loginPage(){<br>    PageFactory.initElements(driver, this)<br>}</pre><pre>public String titleLoginPage(){<br>    return driver.getTitle();<br>}</pre><pre>public void login(String uname, String pwd){<br>    username.sendKeys(uname);<br>    pass.sendKeys(pwd);<br>    loginBtn.click();<br>}<br>}</pre><p><strong>Test Layer</strong></p><p>Tests should be written in a separate class called LoginPageTest.java as in the below example. At this layer test methods are defined with the help of TestNG annotation.</p><pre>public class LoginPageTest extends TestBase {</pre><pre>LoginPage loginPage;</pre><pre>@BeforeMethod<br>public void setUp(){<br>   initialize();<br>   loginPage = new LoginPage();<br>}</pre><pre>@Test<br>public void verifyLogin(){<br>   String title = loginPage.titleLoginPage();<br>   Assert.assertEquals(title, “This is Login Page”);<br>   loginPage.login(“username”, “pass”);<br>   Assert.assertEquals(title, “Welcome!”);<br>}</pre><pre>@AfterMethod<br>public void tearDown(){<br>   driver.quit();<br>}<br>}</pre><p><strong>Test Base class</strong></p><p>Test Base is a Parent class, and all other classes from Page and Test layers are Test Base child classes. Webdriver and other properties like page load timeout, maximize window, implicit wait, delete cookies etc, should be initialized here.</p><pre>public class TestBase {</pre><pre>public static WebDriver driver;<br>public static Properties properties;</pre><pre>public static void initialize() {<br>   String browser = properties.getProperty(“browser”);<br>if (browser.equals(“chrome”)) {<br>   System.setProperty(“chromedriver”, “the/way/to/chromedriver”);<br>   driver = new ChromeDriver();<br>} else if (browser.equals(“FF”)) {<br>   System.setProperty(“geckodriver”, “the/way/to/geckodriver”);<br>   driver = new FirefoxDriver();<br>}</pre><pre>driver.manage().window().maximize();<br>driver.manage().deleteAllCookies();<br>driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);<br>driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);<br>driver.get(properties.getProperty(“www.testurl.com”))<br>}<br>}</pre><p><em>For better code maintainability all elements, parameters and variables should be stored in one or more centralized locations rather than letting them be scattered all over the test scripts.</em></p><p><strong>Configuration</strong></p><p>Url, timeouts and other configuration parameters can be stored in configuration file. Also I would highly recommend to store all sensitive data like password and username in global environment variables to avoid direct access to them.</p><p><strong>Data Storage</strong></p><p>All global variables should be set in data storage. For such purposes, to store all the variables in one place Csv, xml, db or just separate file can be used.</p><p><strong>Common Utilities</strong></p><p>Common utilities are reusable methods for other test cases. For example, custom drag and drop or input functionality can be stored in utilities catalogue. For better organization of common utilities separate catalogue is recommended. The same catalog is used as a storage for methods in other languages. For example, if Java or Python is used as a primary language and it requires to create automated tests for draft.js form, scripts in JS can be stored in utilities too.</p><p><strong>Reporter</strong></p><p>The importance of reports should not be underestimated especially if CI is used. All the team members should clearly understand the causes of test failure from the report. If TestNG or Robot is used on the project then standard reporter in HTML or XML format can be used.</p><p>As described above, test automation infrastructure is a set of test tools, test scripts, procedures, and human resources to carry out test automation efficiently and effectively. Consider these tips on your project to achieve the utmost result. Good Luck!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*a_GR3xy3ch_7PJDxwK_GIw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b25ed52b8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quality-is-everything/best-testing-framework-guidelines-2020-34b25ed52b8b">Best testing framework guidelines 2020.</a> was originally published in <a href="https://medium.com/quality-is-everything">TestCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperledger Blockchain & Smart Contract Testing: Unit Testing and BDD with Cucumber and Gherkin]]></title>
            <link>https://medium.com/quality-is-everything/how-to-test-hyperledger-blockchain-business-model-unit-testing-and-bdd-cucumber-and-gherkin-5a7e16b561d?source=rss----d09c502483ba---4</link>
            <guid isPermaLink="false">https://medium.com/p/5a7e16b561d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[hyperledger]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[cucumber]]></category>
            <dc:creator><![CDATA[Nikolai Boiko]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 10:56:49 GMT</pubDate>
            <atom:updated>2026-05-01T08:04:20.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOUFVYVMjd8HCFAD55098A.png" /></figure><h3><strong>What is Blockchain?</strong></h3><p>Blockchain is an enabling technology with big potential. You can think of blockchain as a shared ledger for recording transactions in a secure, and verifiable way.</p><p>In the case of cryptocurrency, this becomes a means of transferring value authentically without involving third party intermediaries, such as credit card agencies, or banks. Or introducing the risk of falsification and tampering along the way.</p><p>Blockchain has <strong>two unique characteristics</strong> that differentiate it from Excel spreadsheet or relational database:</p><p>The first is that <strong>the ledger is distributed</strong>, or shared between multiple parties. Each party has an identical copy or version of the ledger.<br>Whenever a new transaction is committed, each participant on the network nodes is notified.</p><p>The second characteristic is that the ledger is cryptographically immutable. If I want to enter a transaction to the ledger, the network participants must agree that the transaction is true or authentic.</p><p>This is done using a consensus mechanism that the participants agree to use and verify the authenticity and the validity of the transaction. Once the transaction is committed to the ledger, it’s signed and hashed, and cannot be changed later.</p><p>Blockchain ledger concept can be applied to any multi-party process, or an asset by moving across organizational boundaries. It has a big potential for more mainstream uses.</p><p>Think of a supply chain, maybe even an application for a loan. These are the cases where you need some system of accountability.</p><p>In the early days blockchain technology was used to facilitates the immediate transfer of value without intermediaries. It turned out appealing to many businesses.Since then business units have started stipulating terms and conditions of the transferred value using a smart contract mechanism. It serves as sort of a digital representation of a real world contract, with a set of conditions and terms that govern the changes made in the ledger.</p><p>Let’s walk through a real world example of what smart contracts might look like within the blockchain world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE4fDC9EKUHV4oVFErub3w.png" /><figcaption>Ice cream business model</figcaption></figure><h3><strong>Example of an Ice Cream business model?</strong></h3><p>The thing about ice cream is that it’s gotta be milked, it’s gotta be manufactured, and shipped before it’s sold.</p><p>So there are at least three parties involved in the process before the ice cream reaches the customer. <strong>The dairy farmer</strong>, <strong>the ice cream manufacturer</strong>, and <strong>the shipper</strong>.</p><p>As an ice cream retailer, I have terms with each of these parties. I may want contractually require that the dairy farmer produces only organic milk. I want my manufacturer to make the ice cream according to my quality specifications. And I certainly expect the shipper to keep the ice cream cold, as they move it across the country. Because if it melts, and later refreezes before I sell it, people can get sick.</p><p>In each case all the parties that are involved here have a vested interest to make sure that the ice cream is arriving safely, stored safely, and everyone’s using an SLA. And I have contracts already in place with these parties.</p><p>What we can do with the blockchain is codify those contracts, and track the ice cream as it moves across parties in the chain, validating that the contractual terms have been met in real time, and entering the results to the ledger.</p><p>Using the blockchain as a <strong>single source of truth</strong>, it enables you to track the process and have an insight any time. For example, I could authorize a contract use<strong> IoT sensors</strong> on the refrigerated truck to record the temperature, and notify the network if a reading falls outside the pre-agreed range. This reading can trigger remediated action downstream and could stop the store from having the delivery of a contaminated ice cream truck.</p><h3><strong>Run the business model.</strong></h3><p>Our business model includes: a Manufacturer who is producing ice cream, a Shipper who is delivering it, and a Retailer who is selling it. The agreement among the various participants in this network is modeled using the CTO modeling language, and enforced by the chaincode (smart contract) written in JavaScript.</p><p>Business model has a function that simulates IoT GPS sensor we need it to check the location of the truck, if it reached its destination.</p><p>The first thing you see here are Mocha tests, indicating the tests were successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*xMMqSSdpNnpCTBBV6ql-_Q.jpeg" /></figure><h3>Why BDD?</h3><p>It helps people involved in the project like developers, testers and product owners collaborate with each other. By using Gherkin and Cucumber, business people who don’t know JavaScript but know business logic and business cases get an ability to write unit tests that have more human-readable syntax.</p><p>Cucumber test scenarios in a language called Gherkin have fairly simple syntax and consist of Scenarios that look like this:</p><blockquote><em>Feature :</em> The application feature I want to test</blockquote><blockquote><em>Background:</em> Given some pre-condition that applies to each test</blockquote><blockquote><em>Scenario:</em> The test I want to run</blockquote><blockquote><strong><em>Given</em></strong> some initial context (the givens),</blockquote><blockquote><strong><em>When</em></strong> an event occurs,</blockquote><blockquote><strong><em>Then</em></strong> ensure some outcomes.</blockquote><p>For example let’s take a look closely to one of our scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FII11LBBk-5oNgdLDMzbyg.jpeg" /><figcaption>In this Scenario, the min temperature drops to -31 degrees Celsius and then maximum temperature rises to -16, and the Manufacturer is penalized for each degree Celsius below the threshold.</figcaption></figure><p>There are three keywords:</p><blockquote><strong><em>Given</em></strong><em> I submit the following transaction of type</em> org.acme.shipping.perishable.TemperatureReading</blockquote><blockquote><strong><em>When</em></strong><em> I submit the following transaction of type</em> org.acme.shipping.perishable.ShipmentReceived</blockquote><blockquote><strong>Then</strong> <em>I should have the following participants</em></blockquote><p>Cucumber makes no distinction between the three keywords (they are just steps), but the patterns following the keywords must match one (and only one) step.</p><p>Otherwise, the test will not run, because there is no code to run it.</p><p>In the first instance, Cucumber looks for a pattern (that is, a regular expression) that matches “I submit the following transaction of type<em> org.acme.shipping.perishable.TemperatureReading</em>”. The JavaScript function that runs when this step executes calls <strong><em>step definition</em></strong>. It is a small piece of code that links a pattern in the Gherkin plain language text to actual code and looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*sme8_ou6ojAntxrEtLsceQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*YkSI4LK-_aJhiyKI2OJw8Q.jpeg" /><figcaption>Step Defenitions</figcaption></figure><p>Take into account, Cucumber doesn’t distinguish between any of the step keywords (Given, When, And, and so forth). It only matches the pattern.</p><p>The pattern to match is the <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> between the / characters in parentheses, including the capture groups (([.\w]+)\.(\w+)), which are used to parse the arguments that are passed to the function that gets invoked: <em>namespace</em>(org.acme.shipping.perishable), <em>name</em> (TemperatureReading), and <em>table.</em></p><p><strong>Objects in Gherkin</strong></p><p>There are two ways to represent objects from the Perishable Goods network model in the Gherkin examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*RVp9_oYgPpFTfXxRXZkKJg.jpeg" /><figcaption>Data table</figcaption></figure><p>The first type of object representation is called a <em>data table. </em>The first line contains the property names, followed by one or more lines that contain the property values. The <em>data table</em> does not support nested objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*5AAW0tVA1LiEklD0KAS2XA.jpeg" /><figcaption>DocString</figcaption></figure><p>The second type uses type a <em>docstring</em>, which is a JSON representation of the object, and supports nested objects (for example, notice the nested Address object).</p><p>Following this example you can create your own business model and test it.<br><a href="https://github.com/postoronnii/icecream-perishable-network"><strong>Github Source code</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7e16b561d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quality-is-everything/how-to-test-hyperledger-blockchain-business-model-unit-testing-and-bdd-cucumber-and-gherkin-5a7e16b561d">Hyperledger Blockchain &amp; Smart Contract Testing: Unit Testing and BDD with Cucumber and Gherkin</a> was originally published in <a href="https://medium.com/quality-is-everything">TestCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>