<?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 Dhrumil Soni on Medium]]></title>
        <description><![CDATA[Stories by Dhrumil Soni on Medium]]></description>
        <link>https://medium.com/@dksoni0812?source=rss-7726a9e5db4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ENFKPdMEucDjJ52ugxoUdg.jpeg</url>
            <title>Stories by Dhrumil Soni on Medium</title>
            <link>https://medium.com/@dksoni0812?source=rss-7726a9e5db4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:18:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dksoni0812/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[BOLA vs. BFLA: Understanding API Security Vulnerabilities Through Real-World Examples]]></title>
            <link>https://medium.com/@dksoni0812/bola-vs-bfla-understanding-api-security-vulnerabilities-through-real-world-examples-65f916b0f334?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f916b0f334</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[owasp]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 11:49:48 GMT</pubDate>
            <atom:updated>2026-10-29T11:49:48.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQ63OV3hHm0tbI0RKVtiTQ.png" /><figcaption>BOLA vs BFLA</figcaption></figure><p><em>Change one ID in a URL and see someone else’s data. Here’s how to tell these two API authorization bugs apart, and how to test for both.</em></p><p>You fetch your bank details:</p><pre>GET /api/v1/users/101/financials</pre><p>You change 101 to 202. The API returns someone else&#39;s balance.</p><p>No stolen password. No forged token. Just one changed number.</p><p>Now you, a regular user, try an admin endpoint:</p><pre>DELETE /api/v1/admin/users/202</pre><p>The account gets deleted.</p><p><strong>Same bug?</strong> No. The first is <strong>BOLA</strong>. The second is <strong>BFLA</strong>. Both are on the OWASP API Security Top 10, and both hide in the gap between <em>who you are</em> and <em>what you’re allowed to do</em>.</p><blockquote><em>Authentication proves who you are (fails with 401). Authorization decides what you may do (fails with 403). A valid token only covers the first.</em></blockquote><h3>BOLA: can you touch this object?</h3><p><strong>Broken Object Level Authorization</strong> (OWASP API1:2023) means the API checks that you’re logged in, but not that the record is yours.</p><p>Alice uses her own token to request Bob’s data:</p><pre>GET /api/v1/users/202/financials<br>Authorization: Bearer &lt;alice_token&gt;</pre><p>A secure API returns 403 (or 404 to hide the record). A vulnerable one returns 200 with Bob&#39;s balance.</p><p><em>Change one ID in a URL and see someone else’s data. Here’s how to tell these two API authorization bugs apart, and how to test for both.</em></p><p><strong>“We use UUIDs, so we’re safe.”</strong> No. Random IDs are harder to guess, but they leak through logs, links and other responses. Knowing an ID is not permission.</p><h3>BFLA: can you run this function?</h3><p><strong>Broken Function Level Authorization</strong> (OWASP API5:2023) means the API never checks whether your role may perform the action at all.</p><pre>DELETE /api/v1/admin/users/202<br>Authorization: Bearer &lt;customer_token&gt;</pre><p>Expected: 403. Vulnerable: 204, and the account is gone.</p><p><strong>“The admin button is hidden.”</strong> Irrelevant. Anyone with Postman or DevTools can call the endpoint directly. Authorization belongs on the server.</p><h3>The difference in one line</h3><ul><li><strong>BOLA:</strong> right action, <strong>wrong object</strong>.</li><li><strong>BFLA:</strong> <strong>wrong action</strong> for your role.</li></ul><p>The HTTP method doesn’t decide it. BOLA can hit DELETE; BFLA can hit GET.</p><h3>Test yourself</h3><p>Classify each one before reading on. Answers are at the end.</p><ol><li>Alice changes /orders/1001 to /orders/1002 and sees Bob&#39;s order.</li><li>A customer calls POST /admin/users/202/suspend and it works.</li><li>A support agent may suspend users, but only in their own group. They suspend someone outside it.</li><li>A user with no access to role management promotes themselves to admin.</li></ol><h3>How to test for BOLA</h3><ol><li>Create two users, each with their own record, and get both tokens.</li><li>As User A, read A’s record: expect 200.</li><li>As User A, read, update and delete B’s record: expect 403 or 404.</li><li>Log in as B and confirm nothing changed.</li></ol><p>Don’t forget IDs in query params and request bodies, and nested routes like /users/202/orders/7.</p><h3>How to test for BFLA</h3><ol><li>Write down which role may run which function (for example: only admins may suspend users or change roles).</li><li>Run each function as an allowed role: expect success.</li><li>Run it as every other role: expect 403.</li><li>Try alternate routes to the same action, such as a separate role-update endpoint.</li><li>Confirm no side effect happened.</li></ol><blockquote><em>A 403 is a good sign, not proof. The real evidence is that the data didn’t change.</em></blockquote><h3>Quick myth-busting</h3><ul><li><strong>“Valid JWT = authorized.”</strong> A token proves identity, not permission.</li><li><strong>“BOLA only affects GET.”</strong> It hits reads, updates and deletes.</li><li><strong>“BOLA and BFLA can’t overlap.”</strong> One request can break both.</li></ul><h3>The takeaway</h3><p>For every sensitive request, ask two questions:</p><ol><li>May this user access <strong>this object</strong>?</li><li>May this user perform <strong>this function</strong>?</li></ol><p>If your tests only prove the API works, they’re half done. Prove it works <em>only</em> for the right people.</p><h3>Quiz answers</h3><ol><li><strong>BOLA.</strong> Same function, wrong object.</li><li><strong>BFLA.</strong> Customers can’t suspend anyone.</li><li><strong>BOLA.</strong> The trap: the agent <em>may</em> use the function, just not on that user. An /admin URL doesn&#39;t make it BFLA.</li><li><strong>BFLA.</strong> The role-management function itself was unprotected.</li></ol><p>How many did you get right? Share your score, or a BOLA/BFLA bug you’ve found, in the responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f916b0f334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs. GraphQL: When to Use Each and What Problems GraphQL Solves]]></title>
            <link>https://medium.com/@dksoni0812/rest-vs-graphql-when-to-use-each-and-what-problems-graphql-solves-621b8c3fb422?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/621b8c3fb422</guid>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 11:40:54 GMT</pubDate>
            <atom:updated>2026-10-28T11:40:54.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TtbsbmHXvOwPECkO-jsEg.png" /><figcaption>REST vs GraphQL</figcaption></figure><p><em>Understanding API architecture through real-world examples, request/response comparisons, and practical QA testing scenarios.</em></p><h3>Introduction: Why Do We Need GraphQL When REST Already Exists?</h3><p>Imagine you are testing a donor-management platform.</p><p>The application has a dashboard that displays information about a donor, including:</p><ul><li>Donor name and email address</li><li>Total contributions</li><li>Recent donations</li><li>Active pledges</li><li>Campaigns the donor has supported</li></ul><p>The frontend needs all this information to render a single dashboard.</p><p>With a traditional REST API, you might have to call several endpoints:</p><pre>GET /api/v1/donors/101<br>GET /api/v1/donors/101/contributions<br>GET /api/v1/donors/101/pledges<br>GET /api/v1/donors/101/campaigns</pre><p>Each endpoint returns a predefined response structure.</p><p>But what if the dashboard needs only the donor’s name, total contributions, and the three most recent donations?</p><p>Do we really need to retrieve every field returned by those endpoints?</p><p>And what if the frontend needs additional information that isn’t available from the initial request?</p><p>These questions lead us to two important API design challenges:</p><ol><li><strong>Over-fetching:</strong> Receiving more data than the client needs.</li><li><strong>Under-fetching:</strong> Receiving insufficient data from one request and needing additional requests to obtain the information required.</li></ol><p>GraphQL was designed to address these and other data-fetching challenges.</p><p>However, this doesn’t mean REST is outdated or that GraphQL is always the better choice.</p><p>Let’s understand the differences through practical examples.</p><h3>1. What Is REST?</h3><p>REST stands for Representational State Transfer.</p><p>It is an architectural style used to design networked applications. REST APIs commonly expose resources through URLs and use HTTP methods to perform operations.</p><p>For example:</p><pre>GET    /api/v1/donors/101<br>POST   /api/v1/donors<br>PUT    /api/v1/donors/101<br>PATCH  /api/v1/donors/101<br>DELETE /api/v1/donors/101</pre><p>Each endpoint represents a resource or collection of resources.</p><p>The HTTP method determines the operation being requested.</p><h3>Example: Retrieving a donor</h3><p>Request:</p><pre>GET /api/v1/donors/101<br>Authorization: Bearer &lt;access_token&gt;</pre><p>Response:</p><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;phone&quot;: &quot;+1-555-0100&quot;,<br>  &quot;address&quot;: &quot;New York&quot;,<br>  &quot;createdAt&quot;: &quot;2026-01-15T10:30:00Z&quot;,<br>  &quot;status&quot;: &quot;ACTIVE&quot;<br>}</pre><p>Suppose the frontend only needs the donor’s name.</p><p>It still receives the email, phone number, address, creation timestamp, and status because the endpoint returns those fields.</p><p>This is an example of <strong>over-fetching</strong>, assuming the client doesn’t need those additional fields.</p><p>An API can be designed to return a smaller response, but doing so may require additional endpoints, query parameters, or response-shaping capabilities.</p><h3>Example: Retrieving related information</h3><p>Now suppose the dashboard also needs the donor’s three most recent contributions.</p><p>The frontend might call:</p><pre>GET /api/v1/donors/101/contributions?limit=3</pre><p>Response:</p><pre>{<br>  &quot;donorId&quot;: 101,<br>  &quot;contributions&quot;: [<br>    {<br>      &quot;id&quot;: 501,<br>      &quot;amount&quot;: 250,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    },<br>    {<br>      &quot;id&quot;: 502,<br>      &quot;amount&quot;: 100,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    },<br>    {<br>      &quot;id&quot;: 503,<br>      &quot;amount&quot;: 500,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    }<br>  ]<br>}</pre><p>If the dashboard needs donor details, contributions, pledges, and campaign information, it may need several API requests.</p><p>This can introduce additional network round trips and coordination between requests.</p><p>However, an important distinction: <strong>REST does not inherently require multiple requests or excessive responses.</strong> A well-designed REST API can provide aggregated resources, filtering, pagination, and purpose-built endpoints.</p><p>The challenge depends on how the <strong>API is designed.</strong></p><h3>2. What Is GraphQL?</h3><p>GraphQL is a query language for APIs and a runtime for executing those queries against a defined schema.</p><p>Unlike a conventional REST design, where each endpoint generally determines the response structure, GraphQL allows clients to specify which fields they need.</p><p>A GraphQL API commonly exposes a single HTTP endpoint, such as:</p><pre>POST /graphql</pre><p>Clients send queries describing the data they want.</p><h3>Example: Retrieving donor information</h3><p>Suppose we want only the donor’s name and their three most recent contributions.</p><p>A GraphQL query could look like this:</p><pre>query {<br>  donor(id: &quot;101&quot;) {<br>    name<br>    contributions(limit: 3) {<br>      id<br>      amount<br>      currency<br>    }<br>  }<br>}</pre><p>The response contains the requested fields:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;donor&quot;: {<br>      &quot;name&quot;: &quot;John Smith&quot;,<br>      &quot;contributions&quot;: [<br>        {<br>          &quot;id&quot;: &quot;501&quot;,<br>          &quot;amount&quot;: 250,<br>          &quot;currency&quot;: &quot;USD&quot;<br>        },<br>        {<br>          &quot;id&quot;: &quot;502&quot;,<br>          &quot;amount&quot;: 100,<br>          &quot;currency&quot;: &quot;USD&quot;<br>        },<br>        {<br>          &quot;id&quot;: &quot;503&quot;,<br>          &quot;amount&quot;: 500,<br>          &quot;currency&quot;: &quot;USD&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Notice something important.</p><p>The client didn’t request the donor’s email, phone number, address, or creation timestamp.</p><p>Those fields aren’t included in the response.</p><p>The client also requested related contribution information through the same GraphQL operation.</p><p>This can reduce the need for multiple client-side requests.</p><p><strong>The key difference is that GraphQL lets the client specify the response fields, whereas a conventional REST endpoint generally defines the response structure.</strong></p><p>Of course, the GraphQL server must implement the relevant fields and relationships, and authorization must still be enforced.</p><h3>3. Over-Fetching vs. Under-Fetching: Understand the Difference</h3><p>These two concepts are frequently confused in API testing interviews.</p><p>Let’s make them simple.</p><h3>Over-fetching: Receiving more than you need</h3><p>Suppose the frontend requires:</p><pre>{<br>  &quot;name&quot;: &quot;John Smith&quot;<br>}</pre><p>But the REST endpoint returns:</p><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;phone&quot;: &quot;+1-555-0100&quot;,<br>  &quot;address&quot;: &quot;New York&quot;,<br>  &quot;status&quot;: &quot;ACTIVE&quot;<br>}</pre><p>The client receives additional fields it doesn’t need.</p><p>This is over-fetching.</p><p><strong>Potential impact:</strong></p><ul><li>Unnecessary data transfer.</li><li>Additional client-side processing.</li><li>Exposure of fields that should not be available to that client.</li><li>Increased coupling between the client and the API response.</li></ul><p>The security point deserves special attention: if a field contains sensitive information, the server must enforce field-level access controls where necessary. GraphQL’s ability to select fields is not a substitute for authorization.</p><h3>Under-fetching: Not receiving enough data</h3><p>Suppose the dashboard requires:</p><pre>{<br>  &quot;name&quot;: &quot;John Smith&quot;,<br>  &quot;totalContributions&quot;: 850,<br>  &quot;activePledges&quot;: 2<br>}</pre><p>The initial REST request returns only:</p><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;name&quot;: &quot;John Smith&quot;<br>}</pre><p>The frontend then makes additional requests:</p><pre>GET /api/v1/donors/101/contributions/summary<br>GET /api/v1/donors/101/pledges/summary</pre><p>This is an example of under-fetching from the perspective of the initial request.</p><p><strong>Potential impact:</strong></p><ul><li>Additional network round trips.</li><li>Increased response latency.</li><li>More complicated frontend data orchestration.</li><li>More opportunities for partial failures.</li></ul><p>GraphQL can address this by allowing the client to request related information in a single operation, provided the schema supports those fields.</p><h3>A quick memory trick</h3><p>Concept | Meaning | Simple Question</p><p>Over-fetching | Receiving unnecessary data | Am I getting more than I need?</p><p>Under-fetching | Not receiving enough data from the current request | Do I need additional requests to get the rest?</p><p>Remember: These are common API design problems, not limitations that every REST implementation necessarily suffers from.</p><h3>4. When Should You Choose REST?</h3><p>REST is an excellent choice when your application has well-defined resources and predictable operations.</p><p>Consider the following scenarios.</p><h3>Scenario 1: A straightforward CRUD application</h3><p>Suppose you are developing a user-management API.</p><p>You need to:</p><ul><li>Create a user.</li><li>Retrieve user details.</li><li>Update a user.</li><li>Delete a user.</li></ul><p>A REST design is straightforward:</p><pre>POST   /api/v1/users<br>GET    /api/v1/users/101<br>PATCH  /api/v1/users/101<br>DELETE /api/v1/users/101</pre><p>There is no compelling reason to introduce GraphQL solely because it is a newer or more flexible technology.</p><h3>Scenario 2: Public APIs with conventional resource access</h3><p>If external consumers need stable, well-defined resource endpoints, REST can provide a familiar interface with established HTTP semantics.</p><p>Caching, observability, API gateway integration, and access policies can also be relatively straightforward to implement.</p><h3>Scenario 3: File uploads and downloads</h3><p>REST endpoints are often a natural fit for operations involving binary files, document downloads, and conventional upload workflows.</p><p>GraphQL can support file workflows through additional conventions or signed upload URLs, but it doesn’t automatically make these use cases simpler.</p><h3>Scenario 4: Simple integrations between services</h3><p>If one service needs to retrieve a specific resource from another service, a straightforward REST endpoint may be easier to implement, debug, and maintain.</p><p><strong>Practical takeaway:</strong> Don’t introduce GraphQL unless its flexibility solves a real problem for your application.</p><h3>5. When Should You Choose GraphQL?</h3><p>GraphQL becomes particularly attractive when clients need different combinations of data from interconnected resources.</p><h3>Scenario 1: Complex dashboards</h3><p>Imagine that a donor-management platform supports three clients:</p><ul><li>A web dashboard for administrators.</li><li>A mobile application for donors.</li><li>An analytics interface for fundraising teams.</li></ul><p>Each client requires different fields.</p><p>The mobile application might need:</p><pre>query {<br>  donor(id: &quot;101&quot;) {<br>    name<br>    contributions(limit: 5) {<br>      amount<br>      createdAt<br>    }<br>  }<br>}</pre><p>The administrative dashboard might need:</p><pre>query {<br>  donor(id: &quot;101&quot;) {<br>    name<br>    email<br>    status<br>    contributions(limit: 10) {<br>      amount<br>      currency<br>      createdAt<br>    }<br>    pledges {<br>      amount<br>      status<br>    }<br>  }<br>}</pre><p>The same GraphQL schema can support different client requirements without necessarily creating a separate endpoint for every screen.</p><p>The server must still authorize access to every relevant object and field.</p><h3>Scenario 2: Mobile applications with limited bandwidth</h3><p>Mobile clients often benefit from requesting only the information needed to render a screen.</p><p>GraphQL can reduce unnecessary data transfer and combine related data retrieval into fewer requests.</p><p>However, GraphQL does not guarantee fewer requests, faster responses, or lower bandwidth usage. Large queries and inefficient server-side resolvers can create the opposite result.</p><h3>Scenario 3: Rapidly evolving frontend requirements</h3><p>When different teams build different clients against the same backend, GraphQL can provide flexibility in selecting fields.</p><p>Teams can often add or remove fields from their queries without requiring a new backend endpoint for every change.</p><p>This flexibility is valuable when the schema is managed carefully and breaking changes are handled through a deliberate deprecation strategy.</p><h3>6. What Problems Does GraphQL Solve — and What Problems Does It Introduce?</h3><p>GraphQL addresses important data-fetching challenges, but it also introduces architectural considerations.</p><p>Let’s evaluate both sides.</p><h3>Problems GraphQL can help solve</h3><p><strong>1. Excessive data retrieval</strong></p><p>Clients can request specific fields rather than receiving every field exposed by a conventional endpoint.</p><p><strong>2. Multiple client-side requests</strong></p><p>Clients can request related information through a single operation, reducing network round trips when the schema and resolvers support it.</p><p><strong>3. Different frontend requirements</strong></p><p>Different clients can select different fields from a shared schema.</p><p><strong>4. Frontend dependency on endpoint proliferation</strong></p><p>The API can support new combinations of data without requiring a new endpoint for every screen.</p><h3>Problems GraphQL does not automatically solve</h3><p><strong>1. Database query inefficiency</strong></p><p>Consider this query:</p><pre>query {<br>  donors {<br>    id<br>    name<br>    contributions {<br>      id<br>      amount<br>    }<br>  }<br>}</pre><p>If the server loads contributions separately for every donor, it can create the N+1 query problem.</p><p>For example, fetching 100 donors could trigger one database query for donors and another query for each donor’s contributions.</p><p>GraphQL does not automatically optimize database access.</p><p>Solutions can include batching, request-scoped data loaders, efficient joins, and appropriate database query design.</p><p><strong>2. Authorization vulnerabilities</strong></p><p>A client requesting a particular field does not mean it is entitled to see that field.</p><p>The server must enforce access control on relevant objects, fields, and operations.</p><p><strong>3. Expensive queries</strong></p><p>A client could submit a deeply nested query or request a large number of related records.</p><p>Production GraphQL APIs may need query-depth limits, complexity analysis, pagination requirements, rate limiting, timeouts, and resource budgets.</p><p><strong>4. Caching complexity</strong></p><p>REST GET endpoints work naturally with many standard HTTP caching mechanisms.</p><p>GraphQL commonly uses POST requests, although GET queries are also supported by many implementations. Caching strategies may require persisted queries, operation-aware caching, normalized client caches, or other mechanisms.</p><p><strong>5. Monitoring and observability</strong></p><p>With REST, monitoring a specific endpoint often provides a useful starting point.</p><p>With GraphQL, a single endpoint can serve many operations. Effective monitoring should also consider operation names, resolver latency, error rates, and expensive fields.</p><p>GraphQL can therefore improve client-side flexibility while requiring more sophisticated server-side governance.</p><h3>7. How Should QA Engineers Test REST and GraphQL APIs?</h3><p>This is where the architectural differences become particularly important.</p><p>The objective is not simply to verify whether an API returns HTTP 200. The objective is to validate its behavior, data integrity, security, and performance.</p><h3>Testing REST APIs</h3><p>Consider this request:</p><pre>GET /api/v1/donors/101<br>Authorization: Bearer &lt;access_token&gt;</pre><p>A QA engineer should validate:</p><p><strong>Functional testing</strong></p><ul><li>Does the API return the correct donor?</li><li>Are all expected fields present?</li><li>Are data types correct?</li><li>Does the response match the API contract?</li></ul><p><strong>Negative testing</strong></p><ul><li>What happens when the donor ID doesn’t exist?</li><li>What happens when the ID has an invalid format?</li><li>What happens when the request has no authentication token?</li><li>What happens when the user is authenticated but unauthorized?</li></ul><p><strong>Boundary testing</strong></p><ul><li>Are pagination limits enforced?</li><li>Are invalid query parameters handled correctly?</li><li>Are large payloads and unusual values processed safely?</li></ul><p><strong>Security testing</strong></p><ul><li>Can a user access another donor’s financial information?</li><li>Are sensitive fields exposed unnecessarily?</li><li>Are authorization checks enforced consistently across endpoints?</li></ul><h3>Testing GraphQL APIs</h3><p>Now consider:</p><pre>query {<br>  donor(id: &quot;101&quot;) {<br>    name<br>    email<br>    contributions {<br>      amount<br>    }<br>  }<br>}</pre><p>The same categories apply, but GraphQL introduces additional test dimensions.</p><p><strong>1. Schema validation</strong></p><p>Verify that fields, argument types, nullability, and relationships match the published schema.</p><p><strong>2. Field selection</strong></p><p>Request only the donor’s name and verify that the response contains the requested field rather than unrelated fields.</p><p><strong>3. Nested data retrieval</strong></p><p>Verify that the donor’s contributions belong to the correct donor and that pagination behaves as expected.</p><p><strong>4. GraphQL error handling</strong></p><p>A GraphQL response can contain both data and errors.</p><p>For example:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;donor&quot;: null<br>  },<br>  &quot;errors&quot;: [<br>    {<br>      &quot;message&quot;: &quot;Donor not found&quot;<br>    }<br>  ]<br>}</pre><p>The exact behavior depends on the schema and resolver implementation.</p><p>A GraphQL execution error does not necessarily mean the HTTP response itself uses a non-2xx status code. Therefore, checking only the HTTP status is insufficient.</p><p><strong>5. Authorization</strong></p><p>Verify that users cannot access unauthorized objects or sensitive fields by changing IDs or requesting additional fields.</p><p><strong>6. Query complexity and performance</strong></p><p>Test deeply nested queries, large result sets, pagination, rate limits, and resolver performance.</p><h3>A practical GraphQL testing example</h3><p>Using Playwright with TypeScript, you can send a GraphQL query through the API testing interface:</p><pre>import { test, expect } from &#39;@playwright/test&#39;;</pre><pre>test(&#39;should retrieve the requested donor details&#39;, async ({<br>  request,<br>}) =&gt; {<br>  const response = await request.post(<br>    &#39;https://api.example.com/graphql&#39;,<br>    {<br>      headers: {<br>        Authorization: `Bearer ${process.env.API_TOKEN}`,<br>      },<br>      data: {<br>        query: `<br>          query GetDonor($id: ID!) {<br>            donor(id: $id) {<br>              id<br>              name<br>            }<br>          }<br>        `,<br>        variables: {<br>          id: &#39;101&#39;,<br>        },<br>      },<br>    }<br>  );</pre><pre>  expect(response.ok()).toBeTruthy();</pre><pre>  const body = await response.json();</pre><pre>  expect(body.errors).toBeUndefined();<br>  expect(body.data.donor).toMatchObject({<br>    id: &#39;101&#39;,<br>    name: &#39;John Smith&#39;,<br>  });<br>});</pre><p>This example assumes that the API uses the donor(id: ID!) query and returns IDs as strings. Adjust the query, endpoint, and assertions to match the actual schema.</p><p>For production-grade tests, also validate the response schema, authorization behavior, and error handling.</p><h3>8. A Common Interview Question: Does GraphQL Replace REST?</h3><p><strong>No. GraphQL is an alternative API approach, not a universal replacement for REST.</strong></p><p>Consider an application with the following requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6s8p1B6rtBoy-FoNicppYw.png" /></figure><p>These are guidelines rather than strict rules.</p><p>A single application can expose REST endpoints for some operations and GraphQL for others.</p><p>The correct choice depends on client requirements, data relationships, caching needs, operational complexity, security controls, and team expertise.</p><h3>9. Final Takeaways</h3><p>Let’s summarize the most important lessons.</p><ul><li><strong>REST</strong> organizes API interactions around resources and HTTP methods.</li><li><strong>GraphQL</strong> lets clients request specific fields through a schema-defined query language.</li><li><strong>Over-fetching</strong> means receiving unnecessary data.</li><li><strong>Under-fetching</strong> means needing additional requests because the current request doesn’t provide all required data.</li><li>GraphQL can reduce unnecessary data transfer and client-side request orchestration, but it doesn’t guarantee better performance.</li><li>GraphQL introduces its own challenges, including query complexity, resolver inefficiency, caching, and authorization.</li><li>Both approaches require functional, negative, performance, and security testing.</li></ul><h3>My recommendation as a QA engineer</h3><p>Don’t evaluate an API architecture only by how easy it is to send a request or how many endpoints it exposes.</p><p>Evaluate the complete system.</p><p>Ask yourself:</p><ol><li>Does the API return the correct data?</li><li>Does it return only data the client is authorized to access?</li><li>Does it perform well under realistic workloads?</li><li>Can the API evolve without breaking existing clients?</li><li>Can we reliably test, monitor, and troubleshoot it?</li></ol><p>These questions matter much more than whether the application uses REST or GraphQL.</p><p><strong>Remember:</strong> REST structures the interaction around resources; GraphQL gives clients greater control over data selection. Both can be excellent architectural choices when designed and tested properly.</p><p><em>If you are a QA engineer preparing for API testing interviews, try this question:</em></p><p><strong>Your frontend needs information from five related REST endpoints to render a dashboard. Would migrating to GraphQL automatically make the application faster? Why or why not?</strong></p><p>The best answer considers network round trips, resolver efficiency, database access, query complexity, caching, and the actual performance bottleneck.</p><p>Understanding these trade-offs is what separates someone who knows API terminology from someone who understands API architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=621b8c3fb422" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP Tools, Resources & Prompts: The Simplest Way to Understand MCP Server Primitives]]></title>
            <link>https://medium.com/@dksoni0812/mcp-tools-resources-prompts-the-simplest-way-to-understand-mcp-server-primitives-bf1a8a6153c8?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf1a8a6153c8</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 12:22:41 GMT</pubDate>
            <atom:updated>2026-08-17T12:22:41.867Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>If you are learning Model Context Protocol (MCP), there are three words you will see everywhere: Tools, Resources, and Prompts.</strong></p><p>At first, they can feel surprisingly similar.</p><p>After all, all three are exposed by an MCP server and can be discovered by an MCP client.</p><p>So the obvious question is:</p><blockquote><strong><em>When should I use a Tool, a Resource, or a Prompt?</em></strong></blockquote><p>I found the easiest way to understand them is to forget the technical terminology for a moment and think about a <strong>restaurant</strong>.</p><p>Once you understand that analogy, the whole thing becomes much easier.</p><h3>🧠 The One-Minute Mental Model</h3><p>Remember these three words:</p><blockquote><strong><em>Resource = KNOW</em></strong><em> 📚<br></em><strong><em>Tool = DO</em></strong><em> 🛠️<br></em><strong><em>Prompt = GUIDE</em></strong><em> 📝</em></blockquote><p>That’s the entire concept in three words.</p><ul><li><strong>Resource</strong> → gives you information.</li><li><strong>Tool</strong> → performs an action.</li><li><strong>Prompt</strong> → gives you a reusable way to guide an interaction.</li></ul><p>The official MCP SDK documentation describes the same separation: Tools are for actions, Resources expose read-only data, and Prompts are reusable templates. (<a href="https://ts.sdk.modelcontextprotocol.io/?utm_source=chatgpt.com">Model Context Protocol</a>)</p><p>Let’s make this memorable.</p><h3>🍽️ Imagine an MCP Server as a Restaurant</h3><p>Imagine you walk into a restaurant.</p><p>There are three important things you can interact with:</p><h3>📖 The Menu</h3><p>It tells you what’s available.</p><p>That’s similar to an <strong>MCP Resource</strong>.</p><h3>👨‍🍳 The Kitchen</h3><p>It actually prepares something for you.</p><p>That’s similar to an <strong>MCP Tool</strong>.</p><h3>📝 A Predefined Order</h3><p>The restaurant has a predefined “Chef’s Special” workflow you can choose.</p><p>That’s similar to an <strong>MCP Prompt</strong>.</p><p>So:</p><pre>MCP SERVER<br>                 │<br>       ┌─────────┼─────────┐<br>       │         │         │<br>       ▼         ▼         ▼<br>    RESOURCE   TOOL     PROMPT<br>       │         │         │<br>       ▼         ▼         ▼<br>      KNOW      DO      GUIDE</pre><p>Now let’s break each one down.</p><h3>📚 1. MCP Resources — “KNOW”</h3><h3>What is a Resource?</h3><p>A Resource is a way for an MCP server to expose <strong>data or content</strong> to the client/application.</p><p>That data could be:</p><ul><li>Files</li><li>Documents</li><li>Database records</li><li>API responses</li><li>Configuration</li><li>Application state</li><li>Other contextual information</li></ul><p>The MCP SDK documentation explicitly describes Resources as data that clients can read and use as context. (<a href="https://csharp.sdk.modelcontextprotocol.io/concepts/resources/resources.html?utm_source=chatgpt.com">ModelContextProtocol</a>)</p><h3>Think:</h3><blockquote><strong><em>“Here is some information you might need.”</em></strong></blockquote><p>For example:</p><pre>docs://documents/test-plan.pdf</pre><p>or:</p><pre>customer://12345</pre><p>or:</p><pre>github://repository/issues/123</pre><p>The exact URI scheme is application-specific, but the concept remains the same: <strong>the server exposes information that can be read.</strong></p><h3>🧪 QA Example</h3><p>Imagine we build a <strong>QA MCP Server</strong>.</p><p>It could expose:</p><pre>testcase://TC-1001</pre><p>When read, it might return:</p><pre>Test Case: Login with Invalid Password</pre><pre>Steps:<br>1. Open login page<br>2. Enter username<br>3. Enter invalid password<br>4. Click Login</pre><pre>Expected:<br>Error message should be displayed.</pre><p>The Resource didn’t execute anything.</p><p>It simply provided information.</p><p>Therefore:</p><blockquote><strong><em>Resource = KNOW</em></strong></blockquote><h3>🛠️ 2. MCP Tools — “DO”</h3><p>Now imagine you tell the restaurant:</p><blockquote><em>“Prepare my pizza.”</em></blockquote><p>The restaurant has to <strong>do something</strong>.</p><p>That’s an MCP Tool.</p><p>Tools expose callable functions that allow an MCP client/model to ask the server to perform actions. They can perform computations, make API calls, update data, execute operations, and more. (<a href="https://csharp.sdk.modelcontextprotocol.io/concepts/tools/tools.html?utm_source=chatgpt.com">ModelContextProtocol</a>)</p><p>Examples:</p><pre>create_issue()<br>send_email()<br>search_users()<br>run_test()<br>delete_file()<br>create_customer()<br>execute_query()</pre><p>The important word is:</p><h3>ACTION</h3><h3>🧪 QA Example</h3><p>Suppose our QA MCP server exposes:</p><pre>run_playwright_test()</pre><p>Claude could request:</p><pre>run_playwright_test(<br>    testName=&quot;login.spec.ts&quot;<br>)</pre><p>The MCP server actually executes the operation and returns the result.</p><p>For example:</p><pre>Test: Login<br>Status: PASSED<br>Duration: 4.2s</pre><p>Something <strong>happened</strong>.</p><p>Therefore:</p><blockquote><strong><em>Tool = DO</em></strong></blockquote><h3>📝 3. MCP Prompts — “GUIDE”</h3><p>Prompts are probably the most confusing of the three.</p><p>An MCP Prompt is a <strong>reusable prompt template</strong> exposed by the server.</p><p>It helps users start a particular interaction in a consistent way.</p><p>The official documentation describes prompts as reusable templates that clients can expose to users. (<a href="https://csharp.sdk.modelcontextprotocol.io/concepts/prompts/prompts.html?utm_source=chatgpt.com">ModelContextProtocol</a>)</p><p>For example:</p><pre>generate-regression-plan</pre><p>could produce instructions such as:</p><pre>Generate a regression test plan for the following feature.</pre><pre>Include:<br>- Positive scenarios<br>- Negative scenarios<br>- Boundary scenarios<br>- Security scenarios<br>- Integration scenarios</pre><p>The important point:</p><p><strong>The Prompt is providing the instructions/template.</strong></p><p>It isn’t itself the operation that executes your test.</p><p>Therefore:</p><blockquote><strong><em>Prompt = GUIDE</em></strong></blockquote><h3>🎯 The QA Example That Makes Everything Click</h3><p>Let’s build a fictional MCP server for QA.</p><p>It exposes:</p><pre>QA MCP SERVER<br>│<br>├── Resources<br>│   ├── testcase://TC-1001<br>│   ├── requirements://login<br>│   └── api://users<br>│<br>├── Tools<br>│   ├── run_test()<br>│   ├── create_bug()<br>│   └── execute_api()<br>│<br>└── Prompts<br>    ├── generate_test_cases<br>    ├── generate_regression_plan<br>    └── review_test_coverage</pre><p>Now imagine you ask:</p><blockquote><strong><em>“Review the Login feature and execute the regression tests.”</em></strong></blockquote><p>The AI could potentially use all three.</p><h3>Step 1 — Prompt</h3><p>Use:</p><pre>generate_regression_plan</pre><p>This provides a structured way to approach the task.</p><h3>Step 2 — Resources</h3><p>Read:</p><pre>requirements://login</pre><p>and:</p><pre>testcase://TC-1001</pre><p>Now the AI has the required <strong>context</strong>.</p><h3>Step 3 — Tool</h3><p>Execute:</p><pre>run_test()</pre><p>Now the AI can actually <strong>do something</strong>.</p><h3>🔥 Put It Together</h3><pre>USER<br>                  │<br>                  ▼<br>          ┌───────────────┐<br>          │    PROMPT     │<br>          │    GUIDE      │<br>          └───────┬───────┘<br>                  │<br>                  ▼<br>                 AI<br>                  │<br>          ┌───────┴────────┐<br>          │                │<br>          ▼                ▼<br>     RESOURCE           RESOURCE<br>       KNOW               KNOW<br>          │                │<br>          └───────┬────────┘<br>                  ▼<br>                 AI<br>                  │<br>                  ▼<br>                TOOL<br>                 DO<br>                  │<br>                  ▼<br>              Test Result</pre><p>This is where MCP starts becoming really powerful.</p><h3>🧠 The “Employee” Analogy</h3><p>Here’s another analogy that I personally find extremely useful.</p><p>Imagine Claude is a new employee joining your QA team.</p><p>You give the employee three things.</p><h3>📚 Resource = Knowledge</h3><p>You give them:</p><blockquote><em>“Here is our application documentation.”</em></blockquote><blockquote><em>“Here are our test cases.”</em></blockquote><blockquote><em>“Here is our API specification.”</em></blockquote><p>The employee can <strong>KNOW</strong> things.</p><p>That’s:</p><h3>Resource</h3><h3>🛠️ Tool = Capability</h3><p>You give them:</p><blockquote><em>“You can execute Playwright.”</em></blockquote><blockquote><em>“You can create Jira tickets.”</em></blockquote><blockquote><em>“You can call our API.”</em></blockquote><blockquote><em>“You can query the database.”</em></blockquote><p>Now the employee can <strong>DO</strong> things.</p><p>That’s:</p><h3>Tool</h3><h3>📝 Prompt = Working Instructions</h3><p>You tell them:</p><blockquote><em>“Whenever you test a new feature, check positive, negative, boundary, security, and integration scenarios.”</em></blockquote><p>Now they know <strong>HOW you want them to work</strong>.</p><p>That’s:</p><h3>Prompt</h3><h3>🚦 Who Controls What?</h3><p>This is an important concept — and it appears frequently in MCP interview questions.</p><p>The MCP Python SDK documentation summarizes the three primitives with a useful control model: <strong>Prompts are user-controlled, Resources are application-controlled, and Tools are model-controlled.</strong> (<a href="https://py.sdk.modelcontextprotocol.io/protocol/?utm_source=chatgpt.com">MCP Python SDK</a>)</p><p>PrimitiveTypical controlMain purpose📚 ResourceApplication-controlledProvide context/data🛠️ ToolModel-controlledPerform actions📝 PromptUser-controlledStart/use reusable instructions</p><p>This distinction is worth remembering.</p><h3>Prompt</h3><p>The user chooses:</p><blockquote><em>“I want to review this code.”</em></blockquote><h3>Resource</h3><p>The application/client decides what context should be made available:</p><blockquote><em>“Here is the code file.”</em></blockquote><h3>Tool</h3><p>The model can decide:</p><blockquote><em>“I need to run the tests.”</em></blockquote><h3>🤔 Resource vs Tool — The Most Common Confusion</h3><p>Consider:</p><blockquote><em>“Get customer 123.”</em></blockquote><p>You might initially think:</p><blockquote><em>“That’s an API call, so it must be a Tool.”</em></blockquote><p>Not necessarily.</p><p>Think about <strong>what you’re exposing</strong>.</p><p>If you’re exposing read-only customer information as something the client can retrieve:</p><pre>customer://123</pre><p>that’s naturally a <strong>Resource</strong>.</p><p>But if you’re exposing an operation:</p><pre>get_customer(123)</pre><p>that is a <strong>Tool</strong>.</p><p>The difference isn’t simply:</p><blockquote><em>“API = Tool”</em></blockquote><p>Instead, ask:</p><blockquote><strong><em>“Am I exposing data or an operation?”</em></strong></blockquote><h3>Data → Resource</h3><h3>Operation → Tool</h3><h3>🤔 Tool vs Prompt — Another Common Confusion</h3><p>Consider:</p><blockquote><em>“Run regression tests.”</em></blockquote><p>That’s an <strong>action</strong>.</p><p>So:</p><pre>run_regression_tests()</pre><p>would naturally be a <strong>Tool</strong>.</p><p>Now consider:</p><blockquote><em>“Generate a regression testing strategy using our company’s standard approach.”</em></blockquote><p>That can be represented as a <strong>Prompt</strong>.</p><p>The Prompt provides a reusable instruction/template for the interaction.</p><p>So:</p><pre>generate_regression_strategy</pre><p>could be a Prompt.</p><h3>🤔 Resource vs Prompt</h3><p>Consider:</p><blockquote><em>“Here is our Login API documentation.”</em></blockquote><p>That’s information.</p><h3>Resource 📚</h3><p>Now:</p><blockquote><em>“Review the Login API according to our API testing checklist.”</em></blockquote><p>That’s an instruction.</p><h3>Prompt 📝</h3><p>So:</p><pre>Documentation → Resource<br>Instructions → Prompt</pre><h3>🧩 Resource Templates</h3><p>There’s one more concept worth knowing.</p><p>What if you have thousands of documents?</p><p>You don’t want to create:</p><pre>docs://documents/report.pdf<br>docs://documents/invoice.pdf<br>docs://documents/contract.pdf<br>docs://documents/manual.pdf</pre><p>individually.</p><p>You can use a <strong>Resource Template</strong>.</p><p>For example:</p><pre>docs://documents/{documentId}</pre><p>Then:</p><pre>docs://documents/report.pdf<br>docs://documents/invoice.pdf<br>docs://documents/contract.pdf</pre><p>can be resolved dynamically.</p><p>Resource templates are specifically designed for parameterized resource URIs. (<a href="https://blog.modelcontextprotocol.io/posts/2025-07-29-prompts-for-automation/?utm_source=chatgpt.com">Model Context Protocol Blog</a>)</p><p>Think:</p><blockquote><strong><em>Resource = one specific piece of information</em></strong></blockquote><blockquote><strong><em>Resource Template = a pattern for finding many pieces of information</em></strong></blockquote><h3>🐍 A Small Python MCP Example</h3><p>The Python MCP SDK makes these concepts fairly easy to see in code. Its current documentation shows @mcp.tool(), @mcp.resource(), and @mcp.prompt() as the corresponding decorators. (<a href="https://py.sdk.modelcontextprotocol.io/v1/?utm_source=chatgpt.com">MCP Python SDK</a>)</p><p>For example:</p><pre>from mcp.server.fastmcp import FastMCP</pre><pre>mcp = FastMCP(&quot;QA Server&quot;)<br></pre><pre>@mcp.tool()<br>def run_test(test_name: str) -&gt; str:<br>    &quot;&quot;&quot;Run an automated test.&quot;&quot;&quot;<br>    return f&quot;Running test: {test_name}&quot;<br></pre><pre>@mcp.resource(&quot;testcase://{test_id}&quot;)<br>def get_test_case(test_id: str) -&gt; str:<br>    &quot;&quot;&quot;Return test case details.&quot;&quot;&quot;<br>    return f&quot;Test case details for {test_id}&quot;<br></pre><pre>@mcp.prompt()<br>def generate_test_cases(feature: str) -&gt; str:<br>    &quot;&quot;&quot;Generate test scenarios for a feature.&quot;&quot;&quot;<br>    return f&quot;&quot;&quot;<br>    Generate test cases for:</pre><pre>    {feature}</pre><pre>    Include:<br>    - Positive scenarios<br>    - Negative scenarios<br>    - Boundary scenarios<br>    - Security scenarios<br>    &quot;&quot;&quot;</pre><p>Now look at the three definitions:</p><pre>@mcp.tool()<br>       ↓<br>     DO</pre><pre>@mcp.resource()<br>       ↓<br>     KNOW</pre><pre>@mcp.prompt()<br>       ↓<br>    GUIDE</pre><p>That’s the whole concept sitting right there in the code.</p><h3>🧠 The Ultimate Cheat Sheet</h3><p>If you’re preparing for an MCP interview, certification, or simply trying to understand the architecture, memorize this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqiVWrGRcWmiPFBxT16lmQ.png" /></figure><h3>🚀 One Sentence You’ll Never Forget</h3><p>If someone asks you:</p><blockquote><strong><em>“What’s the difference between MCP Tools, Resources and Prompts?”</em></strong></blockquote><p>You can answer:</p><blockquote><strong><em>“Resources give the AI information to KNOW, Tools give the AI capabilities to DO, and Prompts give the user reusable instructions to GUIDE the AI.”</em></strong></blockquote><p>Or the ultra-short version:</p><h3>📚 Resource → KNOW</h3><h3>🛠️ Tool → DO</h3><h3>📝 Prompt → GUIDE</h3><h3>Final Thought</h3><p>As QA engineers, we already use this separation every day — we just don’t always call it MCP.</p><p>Think about a typical automation framework:</p><pre>Requirements / Test Data<br>        ↓<br>      KNOW<br>        ↓<br>   Resources</pre><pre>Automation Actions<br>        ↓<br>       DO<br>        ↓<br>     Tools</pre><pre>Testing Strategy / Instructions<br>        ↓<br>      GUIDE<br>        ↓<br>     Prompts</pre><p>Once you see MCP this way, it stops looking like another AI acronym to memorize and starts looking like a <strong>clean architecture for connecting AI with real-world data, capabilities, and workflows</strong>.</p><p>And honestly, that’s the sweet spot for QA: <strong>AI knows the system, AI can act on the system, and we can define how we want AI to test the system.</strong> 🚀</p><h3>📌 Further Reading</h3><ul><li><a href="https://modelcontextprotocol.io/?utm_source=chatgpt.com">Model Context Protocol — Official Documentation</a></li><li><a href="https://py.sdk.modelcontextprotocol.io/?utm_source=chatgpt.com">MCP Python SDK</a></li><li><a href="https://ts.sdk.modelcontextprotocol.io/?utm_source=chatgpt.com">MCP TypeScript SDK</a></li><li><a href="https://blog.modelcontextprotocol.io/posts/2025-07-29-prompts-for-automation/?utm_source=chatgpt.com">MCP Prompts &amp; Workflow Automation</a></li></ul><p><em>Note: MCP continues to evolve, so SDK APIs and examples can change. The conceptual distinction between Tools, Resources, and Prompts is the part worth locking into memory.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1a8a6153c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Privacy in the Age of LLMs: 3 Proven Strategies to Prevent Leaks]]></title>
            <link>https://medium.com/@dksoni0812/data-privacy-in-the-age-of-llms-3-proven-strategies-to-prevent-leaks-629344d7c94b?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/629344d7c94b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[ai-adoption]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 11:42:24 GMT</pubDate>
            <atom:updated>2025-08-26T12:21:33.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJ4nFslhO44liBcvr7oTUQ.png" /><figcaption>Data Privacy in the age of LLM</figcaption></figure><h3>Introduction</h3><p>The adoption of Large Language Models (LLMs) and AI-powered assistants is skyrocketing across industries. From automating workflows to enhancing productivity, these tools are changing how companies operate. But there’s one barrier holding many organizations back: <strong>data privacy and security concerns</strong>.</p><p>How can enterprises leverage the power of LLMs while ensuring sensitive information doesn’t leak? Let’s explore three proven strategies, backed by real-world examples.</p><h3>1. Hosting Enterprise LLMs on Company Servers</h3><p>Instead of sending prompts and data to public cloud models, enterprises can host LLMs on <strong>private or enterprise-grade infrastructure</strong>. This ensures data remains within the organization’s control.</p><ul><li><strong>Why it matters</strong>: Sensitive information (financial data, IP, customer details) never leaves the company’s secured environment.</li><li><strong>Example</strong>: Microsoft’s <strong>Azure OpenAI Service</strong> allows enterprises to run GPT models in their own Azure cloud tenant, complying with GDPR, HIPAA, and other regulations.</li></ul><p>👉 <strong>Takeaway</strong>: Enterprise hosting = Keep your AI brain <em>in-house</em>.</p><h3>2. Implementing API Gateway Controls</h3><p>An API gateway acts as a <strong>security checkpoint</strong> between users and the LLM. It can filter, redact, or block sensitive fields before data ever reaches the model.</p><ul><li><strong>Why it matters</strong>: Prevents employees from accidentally sharing PII (personally identifiable information), trade secrets, or confidential financial details.</li><li><strong>Example</strong>: Financial institutions use <strong>API gateways (like Kong or Apigee)</strong> to strip out account numbers, credit card details, or social security IDs before queries hit an AI service.</li></ul><p>👉 <strong>Takeaway</strong>: API controls = Filter what goes <em>out</em>.</p><h3>3. Hosting Offline LLMs Locally</h3><p>For industries with <strong>zero tolerance for external data exposure</strong>, LLMs can be deployed fully offline, running on local servers or private clusters.</p><ul><li><strong>Why it matters</strong>: No internet access means zero risk of data being transmitted outside the organization.</li><li><strong>Example</strong>: Defense organizations and healthcare providers often run offline LLMs like <strong>LLaMA or GPT-J</strong> on secured infrastructure to protect classified data or patient records.</li></ul><p>👉 <strong>Takeaway</strong>: Offline hosting = Cut off the <em>internet</em>.</p><h3>Quick Recap</h3><ul><li><strong>Enterprise LLMs</strong> = Keep it <em>in-house</em></li><li><strong>API Controls</strong> = Filter what goes <em>out</em></li><li><strong>Offline LLMs</strong> = Cut off the <em>internet</em></li></ul><p>💡 Easy memory trick: <strong>In-house → Filter → Offline</strong></p><h3>Future Outlook</h3><p>As regulations like <strong>GDPR, HIPAA, and SOC 2</strong> become stricter, enterprises will need to adopt a combination of these strategies. The future of AI in business will depend not just on innovation but also on <strong>trust, compliance, and governance</strong>.</p><h3>Final Thought</h3><p>Which approach do you think your industry needs most: <strong>in-house hosting, API filtering, or offline models</strong>?</p><p>Drop your thoughts in the comments- let’s discuss how to make AI both powerful and safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629344d7c94b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Brains to Workers: Demystifying LLMs, AI Assistants, and AI Agents]]></title>
            <link>https://medium.com/@dksoni0812/from-brains-to-workers-demystifying-llms-ai-assistants-and-ai-agents-404097374f9f?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/404097374f9f</guid>
            <category><![CDATA[ai-applications]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 07:14:58 GMT</pubDate>
            <atom:updated>2025-08-26T07:14:58.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2VjwGjeZwWzQ93JkejAFg.png" /><figcaption>LLM vs AI Assistant vs AI Agent</figcaption></figure><h3>Introduction</h3><p>When you chat with ChatGPT, you’re using an AI Assistant. But behind it lies an LLM. And tomorrow, you might have an AI Agent that books flights and manages your schedule on its own. Confused by these terms? Let’s simplify them.</p><p>In this article, we’ll break down the difference between <strong>LLMs, AI Assistants, and AI Agents</strong> with sticky analogies, real-world examples, and a simple visual that will make it unforgettable.</p><h3>1. LLMs (Large Language Models)</h3><ul><li><strong>What they are</strong>: The <strong>brains</strong> of AI, trained on massive amounts of text. They don’t have goals; they just predict the next word.</li><li><strong>Think of them as</strong>: A <em>knowledge engine</em>.</li><li><strong>Examples</strong>: GPT-5, Claude, Gemini.</li></ul><p>👉 <strong>Analogy</strong>: LLM = A <em>library full of knowledge</em> + a <em>super-fast librarian</em> who can answer questions but won’t take action for you.</p><h3>2. AI Applications / Assistants</h3><ul><li><strong>What they are</strong>: Software built on top of LLMs that solve <strong>specific tasks</strong> or assist humans.</li><li><strong>Think of them as</strong>: Helpful apps powered by LLMs.</li><li><strong>Examples</strong>: ChatGPT app, Grammarly, GitHub Copilot.</li></ul><p>👉 <strong>Analogy</strong>: AI Assistant = A <em>friendly office assistant</em> who uses the library to draft emails, summarize documents, or check grammar.</p><h3>3. AI Agents</h3><ul><li><strong>What they are</strong>: Next level. They can think (LLM), help (assistant), and <strong>act</strong> (tools + autonomy). They set goals, break them into steps, call APIs, run code, browse the web, and deliver results without micromanagement.</li><li><strong>Think of them as</strong>: Autonomous workers.</li><li><strong>Examples</strong>: AutoGPT, LangChain Agents, advanced customer support bots.</li></ul><p>👉 <strong>Analogy</strong>: AI Agent = An <em>employee</em> who not only consults the library and helps you, but also goes out to book tickets, send emails, or manage a project.</p><h3>🎯 Quick Recap (So You’ll Never Forget)</h3><ul><li><strong>LLM = Brain / Library</strong> → <em>Knows</em></li><li><strong>AI Assistant = Helpful App</strong> → <em>Helps</em></li><li><strong>AI Agent = Autonomous Worker</strong> → <em>Acts</em></li></ul><p>💡 Easy memory trick: <strong>Brain → Assistant → Agent</strong></p><h3>Visual Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXSIAW7JeOc-GeTBrHYT4w.png" /></figure><p>The diagram shows the flow: <strong>LLMs (Brains) → AI Assistants (Helpers) → AI Agents (Workers)</strong>.</p><h3>Where We’re Heading</h3><p>LLMs gave us intelligence. Assistants made it useful. Agents are making it autonomous. The future is one where agents could manage tasks end-to-end- from researching investments to booking vacations- while you focus on what matters most.</p><h3>Final Thought</h3><p>Which excites you more- the <strong>brains</strong> (LLMs), the <strong>helpers</strong> (Assistants), or the <strong>workers</strong> (Agents)?</p><p>Drop your thoughts in the comments- let’s spark a conversation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=404097374f9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Playwright Fixtures: From Zero to Hero ]]></title>
            <link>https://medium.com/@dksoni0812/mastering-playwright-fixtures-from-zero-to-hero-2cd10f41f33b?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd10f41f33b</guid>
            <category><![CDATA[fixtures]]></category>
            <category><![CDATA[web-automation]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[playwrights]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 11:40:43 GMT</pubDate>
            <atom:updated>2025-07-31T11:40:43.021Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Transform your test automation game with the power of Playwright fixtures — A complete guide to writing cleaner, more maintainable, and scalable test code.</em></p><h3><strong>🚀 Introduction: Why Fixtures Will Change Your Testing Life</strong></h3><p>If you’ve been writing Playwright tests and find yourself repeating setup code, struggling with test dependencies, or dealing with messy test files, then <strong>fixtures</strong> are about to become your new best friend. Fixtures in Playwright are not just a feature — they’re a paradigm shift that will make your tests more <strong>readable</strong>, <strong>maintainable</strong>, and <strong>powerful</strong>.</p><p>By the end of this article, you’ll understand:</p><ul><li>What fixtures are and why they matter</li><li>How to transform messy tests into clean, reusable components</li><li>Different types of fixtures and when to use them</li><li>Where to organize your fixture files for maximum efficiency</li><li>Advanced patterns that will make you a fixture master</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6_w-jVTEkmya100QLqj4g.png" /><figcaption>Playwright Fixtures</figcaption></figure><h3><strong>🔍 The Problem: Life Before Fixtures</strong></h3><p>Let’s start with a real-world scenario from an e-commerce application. Here’s how most QA Automation engineers write tests initially:</p><pre>import { test, expect } from &quot;@playwright/test&quot;;<br><br>test.beforeEach(&quot;Setup authentication&quot;, async ({ page }) =&gt; {<br>  console.log(&quot;Setting up authentication for each test&quot;);<br>});<br><br>test(&quot;should allow user to view product details&quot;, async ({ page }) =&gt; {<br>  // Repeated setup code for authentication<br>  await page.goto(&quot;/login&quot;);<br>  await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, &quot;testuser@example.com&quot;);<br>  await page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, &quot;SecurePass123!&quot;);<br>  await page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br><br>  // More repeated setup for product data<br>  const productData = {<br>    id: &quot;prod-123&quot;,<br>    name: &quot;Wireless Headphones&quot;,<br>    price: 199.99,<br>  };<br><br>  // Actual test logic<br>  await page.goto(`/products/${productData.id}`);<br>  await expect(page.locator(&#39;[data-testid=&quot;product-name&quot;]&#39;)).toContainText(<br>    productData.name<br>  );<br>  await expect(page.locator(&#39;[data-testid=&quot;product-price&quot;]&#39;)).toContainText(<br>    &quot;$199.99&quot;<br>  );<br>});<br><br>test(&quot;should allow user to add product to cart&quot;, async ({ page }) =&gt; {<br>  // Oh no! Same authentication setup repeated<br>  await page.goto(&quot;/login&quot;);<br>  await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, &quot;testuser@example.com&quot;);<br>  await page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, &quot;SecurePass123!&quot;);<br>  await page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br><br>  // Same product data repeated<br>  const productData = {<br>    id: &quot;prod-123&quot;,<br>    name: &quot;Wireless Headphones&quot;,<br>    price: 199.99,<br>  };<br><br>  // Test logic<br>  await page.goto(`/products/${productData.id}`);<br>  await page.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;);<br>  await expect(page.locator(&#39;[data-testid=&quot;cart-count&quot;]&#39;)).toContainText(&quot;1&quot;);<br>});</pre><h3><strong>Problems with this approach:</strong></h3><ul><li>🔄 <strong>Code duplication</strong> — Authentication and setup repeated in every test</li><li>🐛 <strong>Error-prone</strong> — Easy to make mistakes when copying login credentials</li><li>📈 <strong>Hard to maintain</strong> — Credential changes require updates everywhere</li><li>🧪 <strong>Slow execution</strong> — Repeated authentication for each test</li><li>🎯 <strong>Poor readability — </strong>Test intent gets lost in setup noise</li></ul><h3><strong>✨ The Solution: Playwright Fixtures</strong></h3><p>Fixtures solve all these problems by providing a clean, reusable way to set up test dependencies. Here’s the same tests transformed with fixtures:</p><pre>import { test, expect } from &quot;../fixtures&quot;;<br><br>test(&quot;should allow user to view product details&quot;, async ({<br>  authenticatedPage,<br>  testProduct,<br>}) =&gt; {<br>  await authenticatedPage.goto(`/products/${testProduct.id}`);<br>  await expect(<br>    authenticatedPage.locator(&#39;[data-testid=&quot;product-name&quot;]&#39;)<br>  ).toContainText(testProduct.name);<br>  await expect(<br>    authenticatedPage.locator(&#39;[data-testid=&quot;product-price&quot;]&#39;)<br>  ).toContainText(`$${testProduct.price}`);<br>});<br><br>test(&quot;should allow user to add product to cart&quot;, async ({<br>  authenticatedPage,<br>  testProduct,<br>}) =&gt; {<br>  await authenticatedPage.goto(`/products/${testProduct.id}`);<br>  await authenticatedPage.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;);<br>  await expect(<br>    authenticatedPage.locator(&#39;[data-testid=&quot;cart-count&quot;]&#39;)<br>  ).toContainText(&quot;1&quot;);<br>});</pre><h4><strong>Notice the transformation:</strong></h4><ul><li>✅ <strong>Zero duplication</strong> — Authentication handled by `authenticatedPage` fixture</li><li>✅ <strong>Crystal clear intent</strong> — Tests focus on business logic, not setup</li><li>✅ <strong>Type safety</strong> — Full TypeScript support with proper data types</li><li>✅ <strong>Automatic lifecycle</strong> — Login and cleanup handled automatically</li></ul><h4><strong>📁 Where to Place Your Fixtures: Project Organization</strong></h4><p>Before diving into fixture creation, let’s establish the proper project structure. Here’s the recommended organization:</p><p><strong>Option 1: Single Fixtures File (Recommended for Small Projects)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SECCauNztTo7aLDcSOInng.png" /><figcaption>Option 1: Single Fixtures File</figcaption></figure><p><strong>Option 2: Fixtures Directory (Recommended for Large Projects)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2np6BQcW_xpbEHjvnAaAWw.png" /><figcaption>Option 2: Fixtures Directory</figcaption></figure><h4><strong>Integration with playwright.config.ts</strong></h4><p>Your `playwright.config.ts` doesn’t need special configuration for fixtures, but you can set up test patterns:</p><pre>// playwright.config.ts<br>import { defineConfig } from &quot;@playwright/test&quot;;<br><br>export default defineConfig({<br>  testDir: &quot;./tests&quot;,<br>  // Your fixtures work automatically with any test configuration<br>  use: {<br>    baseURL: &quot;http://localhost:3000&quot;,<br>  },<br>  projects: [<br>    {<br>      name: &quot;auth-tests&quot;,<br>      testMatch: &quot;tests/auth/**/*.spec.ts&quot;,<br>      // Custom fixtures work seamlessly here<br>    },<br>    {<br>      name: &quot;e2e-tests&quot;,<br>      testMatch: &quot;tests/e2e/**/*.spec.ts&quot;,<br>      dependencies: [&quot;auth-tests&quot;], // Run auth tests first<br>    },<br>  ],<br>});</pre><h3><strong>🏗️ Building Your First Fixture</strong></h3><p>Let’s create practical fixtures for a real e-commerce application:</p><h4><strong>Step 1: Create fixtures.ts with Real-World Types</strong></h4><pre>// fixtures.ts<br>import { test as base, expect, Page } from &quot;@playwright/test&quot;;<br><br>// Define realistic fixture types<br>type AuthFixtures = {<br>  authenticatedPage: Page;<br>  adminPage: Page;<br>};<br><br>type DataFixtures = {<br>  testProduct: Product;<br>  testUser: User;<br>};<br><br>type WorkerFixtures = {<br>  apiClient: ApiClient;<br>};<br><br>// Real-world data interfaces<br>interface Product {<br>  id: string;<br>  name: string;<br>  price: number;<br>  category: string;<br>  inStock: boolean;<br>}<br><br>interface User {<br>  id: string;<br>  email: string;<br>  name: string;<br>  role: &quot;customer&quot; | &quot;admin&quot;;<br>}<br><br>interface ApiClient {<br>  baseURL: string;<br>  authToken: string;<br>  get(endpoint: string): Promise&lt;any&gt;;<br>  post(endpoint: string, data: any): Promise&lt;any&gt;;<br>}<br><br>export const test = base.extend&lt;AuthFixtures &amp; DataFixtures, WorkerFixtures&gt;({<br>  // Your fixtures will be implemented here<br>});<br><br>export { expect };</pre><h4><strong>Step 2: Implement Practical Fixtures</strong></h4><pre>export const test = base.extend&lt;AuthFixtures &amp; DataFixtures, WorkerFixtures&gt;({<br>  // Authentication fixture for regular users<br>  authenticatedPage: async ({ page }, use) =&gt; {<br>    // 🔧 SETUP: Login as test user<br>    await page.goto(&quot;/login&quot;);<br>    await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, &quot;testuser@example.com&quot;);<br>    await page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, &quot;SecurePass123!&quot;);<br>    await page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br><br>    // Wait for successful login<br>    await page.waitForURL(&quot;/dashboard&quot;);<br><br>    // 🎯 PROVIDE: Authenticated page to tests<br>    await use(page);<br><br>    // 🧹 CLEANUP: Logout after test<br>    await page.click(&#39;[data-testid=&quot;user-menu&quot;]&#39;);<br>    await page.click(&#39;[data-testid=&quot;logout&quot;]&#39;);<br>  },<br><br>  // Admin authentication fixture<br>  adminPage: async ({ page }, use) =&gt; {<br>    await page.goto(&quot;/admin/login&quot;);<br>    await page.fill(&#39;[data-testid=&quot;admin-email&quot;]&#39;, &quot;admin@example.com&quot;);<br>    await page.fill(&#39;[data-testid=&quot;admin-password&quot;]&#39;, &quot;AdminPass123!&quot;);<br>    await page.click(&#39;[data-testid=&quot;admin-login-button&quot;]&#39;);<br><br>    await page.waitForURL(&quot;/admin/dashboard&quot;);<br>    await use(page);<br><br>    await page.click(&#39;[data-testid=&quot;admin-logout&quot;]&#39;);<br>  },<br><br>  // Test product data fixture<br>  testProduct: async ({}, use) =&gt; {<br>    const product: Product = {<br>      id: &quot;test-product-001&quot;,<br>      name: &quot;Wireless Bluetooth Headphones&quot;,<br>      price: 199.99,<br>      category: &quot;Electronics&quot;,<br>      inStock: true,<br>    };<br>    await use(product);<br>  },<br><br>  // Test user data fixture<br>  testUser: async ({}, use) =&gt; {<br>    const user: User = {<br>      id: &quot;test-user-001&quot;,<br>      email: &quot;testuser@example.com&quot;,<br>      name: &quot;John Doe&quot;,<br>      role: &quot;customer&quot;,<br>    };<br>    await use(user);<br>  },<br><br>  // Worker-scoped API client<br>  apiClient: [<br>    async ({}, use) =&gt; {<br>      // 👥 WORKER SCOPE: Expensive setup shared across tests<br>      const client: ApiClient = {<br>        baseURL: process.env.API_BASE_URL || &quot;http://localhost:3001/api&quot;,<br>        authToken: await getApiAuthToken(),<br>        async get(endpoint: string) {<br>          const response = await fetch(`${this.baseURL}${endpoint}`, {<br>            headers: { Authorization: `Bearer ${this.authToken}` },<br>          });<br>          return response.json();<br>        },<br>        async post(endpoint: string, data: any) {<br>          const response = await fetch(`${this.baseURL}${endpoint}`, {<br>            method: &quot;POST&quot;,<br>            headers: {<br>              Authorization: `Bearer ${this.authToken}`,<br>              &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            },<br>            body: JSON.stringify(data),<br>          });<br>          return response.json();<br>        },<br>      };<br>      await use(client);<br>    },<br>    { scope: &quot;worker&quot; },<br>  ],<br>});<br><br>// Helper function for API authentication<br>async function getApiAuthToken(): Promise&lt;string&gt; {<br>  const response = await fetch(&quot;http://localhost:3001/api/auth/token&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      clientId: process.env.API_CLIENT_ID,<br>      clientSecret: process.env.API_CLIENT_SECRET,<br>    }),<br>  });<br>  const data = await response.json();<br>  return data.accessToken;<br>}</pre><h4><strong>Step 3: Use in Real-World Tests</strong></h4><pre>// tests/products/product-details.spec.ts<br>import { test, expect } from &quot;../../fixtures&quot;;<br><br>test.describe(&quot;Product Details Page&quot;, () =&gt; {<br>  test(&quot;should display correct product information&quot;, async ({<br>    authenticatedPage,<br>    testProduct,<br>  }) =&gt; {<br>    await authenticatedPage.goto(`/products/${testProduct.id}`);<br><br>    await expect(<br>      authenticatedPage.locator(&#39;[data-testid=&quot;product-name&quot;]&#39;)<br>    ).toContainText(testProduct.name);<br>    await expect(<br>      authenticatedPage.locator(&#39;[data-testid=&quot;product-price&quot;]&#39;)<br>    ).toContainText(`$${testProduct.price}`);<br>    await expect(<br>      authenticatedPage.locator(&#39;[data-testid=&quot;product-category&quot;]&#39;)<br>    ).toContainText(testProduct.category);<br>  });<br><br>  test(&quot;should allow adding product to cart&quot;, async ({<br>    authenticatedPage,<br>    testProduct,<br>  }) =&gt; {<br>    await authenticatedPage.goto(`/products/${testProduct.id}`);<br><br>    await authenticatedPage.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;);<br>    await expect(<br>      authenticatedPage.locator(&#39;[data-testid=&quot;success-message&quot;]&#39;)<br>    ).toBeVisible();<br>    await expect(<br>      authenticatedPage.locator(&#39;[data-testid=&quot;cart-count&quot;]&#39;)<br>    ).toContainText(&quot;1&quot;);<br>  });<br>});</pre><pre>// tests/admin/product-management.spec.ts<br>test.describe(&quot;Admin Product Management&quot;, () =&gt; {<br>  test(&quot;should allow admin to create new product&quot;, async ({<br>    adminPage,<br>    apiClient,<br>  }) =&gt; {<br>    const newProduct = {<br>      name: &quot;New Test Product&quot;,<br>      price: 299.99,<br>      category: &quot;Electronics&quot;,<br>    };<br><br>    await adminPage.goto(&quot;/admin/products/new&quot;);<br>    await adminPage.fill(&#39;[data-testid=&quot;product-name&quot;]&#39;, newProduct.name);<br>    await adminPage.fill(<br>      &#39;[data-testid=&quot;product-price&quot;]&#39;,<br>      newProduct.price.toString()<br>    );<br>    await adminPage.selectOption(<br>      &#39;[data-testid=&quot;product-category&quot;]&#39;,<br>      newProduct.category<br>    );<br>    await adminPage.click(&#39;[data-testid=&quot;save-product&quot;]&#39;);<br><br>    // Verify via API<br>    const products = await apiClient.get(&quot;/products&quot;);<br>    const createdProduct = products.find((p) =&gt; p.name === newProduct.name);<br>    expect(createdProduct).toBeTruthy();<br>  });<br>});</pre><h3><strong>🎯 Types of Fixtures: Understanding the Two Scopes</strong></h3><p>Playwright officially supports two types of fixture scopes:</p><h4><strong>1. Test-Scoped Fixtures (Default)</strong></h4><ul><li><strong>When to use:</strong> When you need fresh data for each test</li><li><strong>Lifecycle:</strong> Created before each test, destroyed after each test</li></ul><pre>testUser: async ({}, use) =&gt; {<br>  // Create a fresh user for each test<br>  const user = await createTestUser({<br>    email: `test-${Date.now()}@example.com`,<br>    name: &quot;Test User&quot;<br>  });<br>  await use(user);<br>  // Cleanup user after test<br>  await deleteTestUser(user.id);<br>},</pre><h4><strong>2. Worker-Scoped Fixtures</strong></h4><ul><li><strong>When to use:</strong> For expensive setup that can be shared across tests</li><li><strong>Lifecycle:</strong> Created once per worker, reused across all tests in that worker</li></ul><pre>databaseConnection: [<br>  async ({}, use) =&gt; {<br>    // Expensive database setup once per worker<br>    const db = await setupTestDatabase();<br>    await seedTestData(db);<br>    await use(db);<br>    await teardownTestDatabase(db);<br>  },<br>  { scope: &quot;worker&quot; }<br>],</pre><p><strong>Key Difference:</strong> Test-scoped fixtures run for every test, while worker-scoped fixtures run once per worker process and are shared across multiple tests.</p><h3><strong>🔗 Fixture Dependencies: Building Complex Setups</strong></h3><p>One of the most powerful features of fixtures is dependency injection. Here’s a real-world example:</p><pre>export const test = base.extend&lt;ComplexFixtures&gt;({<br>  // Base fixture - API authentication<br>  apiAuthToken: async ({}, use) =&gt; {<br>    const token = await authenticateWithAPI();<br>    await use(token);<br>  },<br><br>  // Depends on apiAuthToken<br>  userApiClient: async ({ apiAuthToken }, use) =&gt; {<br>    const client = new UserApiClient(apiAuthToken);<br>    await use(client);<br>  },<br><br>  // Depends on userApiClient - creates a test user<br>  createdTestUser: async ({ userApiClient }, use) =&gt; {<br>    const user = await userApiClient.createUser({<br>      email: `test-${Date.now()}@example.com`,<br>      name: &quot;Integration Test User&quot;,<br>      role: &quot;customer&quot;,<br>    });<br>    await use(user);<br>    await userApiClient.deleteUser(user.id);<br>  },<br><br>  // Depends on createdTestUser - logs in as that user<br>  authenticatedUserPage: async ({ page, createdTestUser }, use) =&gt; {<br>    await page.goto(&quot;/login&quot;);<br>    await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, createdTestUser.email);<br>    await page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, &quot;TestPassword123!&quot;);<br>    await page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br>    await page.waitForURL(&quot;/dashboard&quot;);<br>    await use(page);<br>  },<br>});</pre><p><strong>Dependency chain:</strong> `apiAuthToken` → `userApiClient` → `createdTestUser` → `authenticatedUserPage`</p><h3><strong>🏆 Advanced Fixture Patterns</strong></h3><h4><strong>Pattern 1: Parameterized Fixtures</strong></h4><p>Create fixtures that can be configured per test:</p><pre>type TestOptions = {<br>  userRole: &quot;customer&quot; | &quot;admin&quot; | &quot;moderator&quot;;<br>  productCategory: &quot;electronics&quot; | &quot;clothing&quot; | &quot;books&quot;;<br>};<br><br>const test = base.extend&lt;MyFixtures, {}, TestOptions&gt;({<br>  userRole: [&quot;customer&quot;, { option: true }], // Default value<br>  productCategory: [&quot;electronics&quot;, { option: true }],<br><br>  roleBasedUser: async ({ userRole }, use) =&gt; {<br>    const user = await createUserWithRole(userRole);<br>    await use(user);<br>    await deleteUser(user.id);<br>  },<br><br>  categoryProduct: async ({ productCategory }, use) =&gt; {<br>    const product = await createProductInCategory(productCategory);<br>    await use(product);<br>    await deleteProduct(product.id);<br>  },<br>});<br><br>// Usage with different configurations<br>test(&quot;customer can view electronics&quot;, async ({<br>  roleBasedUser,<br>  categoryProduct,<br>}) =&gt; {<br>  // Test logic here<br>}).config({ userRole: &quot;customer&quot;, productCategory: &quot;electronics&quot; });<br><br>test(&quot;admin can manage clothing products&quot;, async ({<br>  roleBasedUser,<br>  categoryProduct,<br>}) =&gt; {<br>  // Test logic here<br>}).config({ userRole: &quot;admin&quot;, productCategory: &quot;clothing&quot; });</pre><h4><strong>Pattern 2: Page Object Fixtures</strong></h4><p>Combine fixtures with page objects for ultimate power:</p><pre>// Page Object Classes<br>class LoginPage {<br>  constructor(private page: Page) {}<br><br>  async goto() {<br>    await this.page.goto(&#39;/login&#39;);<br>  }<br><br>  async loginAs(email: string, password: string) {<br>    await this.page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, email);<br>    await this.page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, password);<br>    await this.page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br>  }<br>}<br><br>class ProductPage {<br>  constructor(private page: Page) {}<br><br>  async goto(productId: string) {<br>    await this.page.goto(`/products/${productId}`);<br>  }<br><br>  async addToCart() {<br>    await this.page.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;);<br>  }<br>}<br><br>// Fixtures using Page Objects<br>loginPage: async ({ page }, use) =&gt; {<br>  const loginPage = new LoginPage(page);<br>  await loginPage.goto();<br>  await use(loginPage);<br>},<br><br>productPage: async ({ page, testProduct }, use) =&gt; {<br>  const productPage = new ProductPage(page);<br>  await productPage.goto(testProduct.id);<br>  await use(productPage);<br>},<br><br>authenticatedProductPage: async ({ loginPage, productPage, testUser }, use) =&gt; {<br>  await loginPage.loginAs(testUser.email, &#39;TestPassword123!&#39;);<br>  await use(productPage);<br>},</pre><h4><strong>Pattern 3: Data-Driven Fixtures</strong></h4><p>Create fixtures that provide realistic test data:</p><pre>testDataSet: async ({}, use) =&gt; {<br>  const data = {<br>    users: {<br>      customer: {<br>        email: &#39;customer@test.com&#39;,<br>        password: &#39;CustomerPass123!&#39;,<br>        role: &#39;customer&#39;<br>      },<br>      admin: {<br>        email: &#39;admin@test.com&#39;,<br>        password: &#39;AdminPass123!&#39;,<br>        role: &#39;admin&#39;<br>      }<br>    },<br>    products: {<br>      electronics: await loadElectronicsProducts(),<br>      clothing: await loadClothingProducts(),<br>      books: await loadBookProducts()<br>    },<br>    paymentMethods: {<br>      validCard: {<br>        number: &#39;4111111111111111&#39;,<br>        expiry: &#39;12/25&#39;,<br>        cvv: &#39;123&#39;<br>      },<br>      expiredCard: {<br>        number: &#39;4111111111111111&#39;,<br>        expiry: &#39;12/20&#39;,<br>        cvv: &#39;123&#39;<br>      }<br>    }<br>  };<br>  await use(data);<br>},</pre><p><strong>🎉 The Benefits: Why Fixtures Are Game-Changers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-dwqzoMynYXkHZo0wCh2Q.png" /><figcaption>Benefits of Fixtures</figcaption></figure><h3><strong>💡 Best Practices: Fixture Mastery Tips</strong></h3><h4><strong>1. Name Fixtures Descriptively</strong></h4><pre>// ❌ Bad<br>data: async ({}, use) =&gt; { ... },<br><br>// ✅ Good<br>authenticatedCustomerUser: async ({}, use) =&gt; { ... },<br>adminUserWithPermissions: async ({}, use) =&gt; { ... },<br>productInElectronicsCategory: async ({}, use) =&gt; { ... },</pre><h4><strong>2. Keep Fixtures Focused</strong></h4><pre>// ❌ Bad - Too many responsibilities<br>everythingYouNeed: async ({}, use) =&gt; {<br>  const user = await createUser();<br>  const product = await createProduct();<br>  const order = await createOrder();<br>  await use({ user, product, order });<br>},<br><br>// ✅ Good - Single responsibility<br>authenticatedUser: async ({}, use) =&gt; { ... },<br>testProduct: async ({}, use) =&gt; { ... },<br>pendingOrder: async ({ authenticatedUser, testProduct }, use) =&gt; { ... },</pre><h4><strong>3. Use Appropriate Scopes</strong></h4><pre>// ❌ Expensive API authentication in test scope<br>apiClient: async ({}, use) =&gt; {<br>  const client = await createApiClientWithAuth();<br>  await use(client);<br>},<br><br>// ✅ Move expensive operations to worker scope<br>apiClient: [<br>  async ({}, use) =&gt; {<br>    const client = await createApiClientWithAuth();<br>    await use(client);<br>  },<br>  { scope: &quot;worker&quot; }<br>],</pre><h4><strong>4. Handle Errors Gracefully</strong></h4><pre>databaseConnection: async ({}, use) =&gt; {<br>  let connection;<br>  try {<br>    connection = await connectToTestDatabase();<br>    await use(connection);<br>  } catch (error) {<br>    console.error(&#39;Database connection failed:&#39;, error);<br>    throw error;<br>  } finally {<br>    if (connection) {<br>      await connection.close();<br>    }<br>  }<br>},</pre><h3><strong>🚀 Real-World Example: Complete E-commerce Test Suite</strong></h3><p>Here’s how you might structure fixtures for a complete e-commerce application:</p><pre>// fixtures/index.ts<br>import { test as base, expect, Page } from &quot;@playwright/test&quot;;<br><br>type EcommerceFixtures = {<br>  // Authentication<br>  customerUser: User;<br>  adminUser: User;<br>  authenticatedCustomerPage: Page;<br>  authenticatedAdminPage: Page;<br><br>  // Products &amp; Inventory<br>  electronicsProduct: Product;<br>  clothingProduct: Product;<br>  outOfStockProduct: Product;<br><br>  // Shopping &amp; Orders<br>  shoppingCart: ShoppingCart;<br>  validPaymentMethod: PaymentMethod;<br>  completedOrder: Order;<br><br>  // API clients<br>  userApiClient: UserApiClient;<br>  productApiClient: ProductApiClient;<br>  orderApiClient: OrderApiClient;<br>};<br><br>type WorkerFixtures = {<br>  databaseConnection: DatabaseConnection;<br>  apiAuthToken: string;<br>};<br><br>export const test = base.extend&lt;EcommerceFixtures, WorkerFixtures&gt;({<br>  // Worker-scoped expensive setup<br>  databaseConnection: [<br>    async ({}, use) =&gt; {<br>      const db = await setupTestDatabase();<br>      await seedInitialData(db);<br>      await use(db);<br>      await cleanupTestDatabase(db);<br>    },<br>    { scope: &quot;worker&quot; },<br>  ],<br><br>  apiAuthToken: [<br>    async ({}, use) =&gt; {<br>      const token = await getServiceAccountToken();<br>      await use(token);<br>    },<br>    { scope: &quot;worker&quot; },<br>  ],<br><br>  // API Clients<br>  userApiClient: async ({ apiAuthToken }, use) =&gt; {<br>    const client = new UserApiClient(apiAuthToken);<br>    await use(client);<br>  },<br><br>  productApiClient: async ({ apiAuthToken }, use) =&gt; {<br>    const client = new ProductApiClient(apiAuthToken);<br>    await use(client);<br>  },<br><br>  orderApiClient: async ({ apiAuthToken }, use) =&gt; {<br>    const client = new OrderApiClient(apiAuthToken);<br>    await use(client);<br>  },<br><br>  // Test Users<br>  customerUser: async ({ userApiClient }, use) =&gt; {<br>    const user = await userApiClient.createUser({<br>      email: `customer-${Date.now()}@test.com`,<br>      name: &quot;Test Customer&quot;,<br>      role: &quot;customer&quot;,<br>    });<br>    await use(user);<br>    await userApiClient.deleteUser(user.id);<br>  },<br><br>  adminUser: async ({ userApiClient }, use) =&gt; {<br>    const user = await userApiClient.createUser({<br>      email: `admin-${Date.now()}@test.com`,<br>      name: &quot;Test Admin&quot;,<br>      role: &quot;admin&quot;,<br>    });<br>    await use(user);<br>    await userApiClient.deleteUser(user.id);<br>  },<br><br>  // Authenticated Pages<br>  authenticatedCustomerPage: async ({ page, customerUser }, use) =&gt; {<br>    await page.goto(&quot;/login&quot;);<br>    await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, customerUser.email);<br>    await page.fill(&#39;[data-testid=&quot;password&quot;]&#39;, &quot;TestPassword123!&quot;);<br>    await page.click(&#39;[data-testid=&quot;login-button&quot;]&#39;);<br>    await page.waitForURL(&quot;/dashboard&quot;);<br>    await use(page);<br>  },<br><br>  authenticatedAdminPage: async ({ page, adminUser }, use) =&gt; {<br>    await page.goto(&quot;/admin/login&quot;);<br>    await page.fill(&#39;[data-testid=&quot;admin-email&quot;]&#39;, adminUser.email);<br>    await page.fill(&#39;[data-testid=&quot;admin-password&quot;]&#39;, &quot;AdminPassword123!&quot;);<br>    await page.click(&#39;[data-testid=&quot;admin-login-button&quot;]&#39;);<br>    await page.waitForURL(&quot;/admin/dashboard&quot;);<br>    await use(page);<br>  },<br><br>  // Test Products<br>  electronicsProduct: async ({ productApiClient }, use) =&gt; {<br>    const product = await productApiClient.createProduct({<br>      name: &quot;Test Wireless Headphones&quot;,<br>      price: 199.99,<br>      category: &quot;electronics&quot;,<br>      stock: 50,<br>    });<br>    await use(product);<br>    await productApiClient.deleteProduct(product.id);<br>  },<br><br>  clothingProduct: async ({ productApiClient }, use) =&gt; {<br>    const product = await productApiClient.createProduct({<br>      name: &quot;Test Cotton T-Shirt&quot;,<br>      price: 29.99,<br>      category: &quot;clothing&quot;,<br>      stock: 100,<br>    });<br>    await use(product);<br>    await productApiClient.deleteProduct(product.id);<br>  },<br><br>  outOfStockProduct: async ({ productApiClient }, use) =&gt; {<br>    const product = await productApiClient.createProduct({<br>      name: &quot;Test Out of Stock Item&quot;,<br>      price: 99.99,<br>      category: &quot;electronics&quot;,<br>      stock: 0,<br>    });<br>    await use(product);<br>    await productApiClient.deleteProduct(product.id);<br>  },<br><br>  // Shopping Cart with items<br>  shoppingCart: async (<br>    { authenticatedCustomerPage, electronicsProduct },<br>    use<br>  ) =&gt; {<br>    await authenticatedCustomerPage.goto(`/products/${electronicsProduct.id}`);<br>    await authenticatedCustomerPage.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;);<br>    await authenticatedCustomerPage.goto(&quot;/cart&quot;);<br><br>    const cart = {<br>      items: [electronicsProduct],<br>      total: electronicsProduct.price,<br>    };<br><br>    await use(cart);<br>  },<br><br>  // Valid payment method<br>  validPaymentMethod: async ({}, use) =&gt; {<br>    const paymentMethod = {<br>      type: &quot;credit_card&quot;,<br>      cardNumber: &quot;4111111111111111&quot;,<br>      expiryMonth: &quot;12&quot;,<br>      expiryYear: &quot;2025&quot;,<br>      cvv: &quot;123&quot;,<br>      holderName: &quot;Test User&quot;,<br>    };<br>    await use(paymentMethod);<br>  },<br><br>  // Completed order<br>  completedOrder: async (<br>    {<br>      authenticatedCustomerPage,<br>      shoppingCart,<br>      validPaymentMethod,<br>      orderApiClient,<br>    },<br>    use<br>  ) =&gt; {<br>    // Navigate to checkout<br>    await authenticatedCustomerPage.goto(&quot;/checkout&quot;);<br><br>    // Fill payment details<br>    await authenticatedCustomerPage.fill(<br>      &#39;[data-testid=&quot;card-number&quot;]&#39;,<br>      validPaymentMethod.cardNumber<br>    );<br>    await authenticatedCustomerPage.fill(<br>      &#39;[data-testid=&quot;expiry-month&quot;]&#39;,<br>      validPaymentMethod.expiryMonth<br>    );<br>    await authenticatedCustomerPage.fill(<br>      &#39;[data-testid=&quot;expiry-year&quot;]&#39;,<br>      validPaymentMethod.expiryYear<br>    );<br>    await authenticatedCustomerPage.fill(<br>      &#39;[data-testid=&quot;cvv&quot;]&#39;,<br>      validPaymentMethod.cvv<br>    );<br><br>    // Complete purchase<br>    await authenticatedCustomerPage.click(&#39;[data-testid=&quot;place-order&quot;]&#39;);<br>    await authenticatedCustomerPage.waitForSelector(<br>      &#39;[data-testid=&quot;order-confirmation&quot;]&#39;<br>    );<br><br>    // Get order details<br>    const orderNumber = await authenticatedCustomerPage<br>      .locator(&#39;[data-testid=&quot;order-number&quot;]&#39;)<br>      .textContent();<br>    const order = await orderApiClient.getOrder(orderNumber);<br><br>    await use(order);<br>  },<br>});</pre><pre>// Example test usage<br>test.describe(&quot;Product Management&quot;, () =&gt; {<br>  test(&quot;customer can view product details&quot;, async ({<br>    authenticatedCustomerPage,<br>    electronicsProduct,<br>  }) =&gt; {<br>    await authenticatedCustomerPage.goto(`/products/${electronicsProduct.id}`);<br><br>    await expect(<br>      authenticatedCustomerPage.locator(&#39;[data-testid=&quot;product-name&quot;]&#39;)<br>    ).toContainText(electronicsProduct.name);<br>    await expect(<br>      authenticatedCustomerPage.locator(&#39;[data-testid=&quot;product-price&quot;]&#39;)<br>    ).toContainText(`$${electronicsProduct.price}`);<br>    await expect(<br>      authenticatedCustomerPage.locator(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;)<br>    ).toBeVisible();<br>  });<br><br>  test(&quot;customer cannot add out of stock product to cart&quot;, async ({<br>    authenticatedCustomerPage,<br>    outOfStockProduct,<br>  }) =&gt; {<br>    await authenticatedCustomerPage.goto(`/products/${outOfStockProduct.id}`);<br><br>    await expect(<br>      authenticatedCustomerPage.locator(&#39;[data-testid=&quot;out-of-stock-message&quot;]&#39;)<br>    ).toBeVisible();<br>    await expect(<br>      authenticatedCustomerPage.locator(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;)<br>    ).toBeDisabled();<br>  });<br>});<br><br>test.describe(&quot;Order Management&quot;, () =&gt; {<br>  test(&quot;customer can complete purchase&quot;, async ({ completedOrder }) =&gt; {<br>    expect(completedOrder.status).toBe(&quot;completed&quot;);<br>    expect(completedOrder.total).toBeGreaterThan(0);<br>    expect(completedOrder.items).toHaveLength(1);<br>  });<br><br>  test(&quot;admin can view order details&quot;, async ({<br>    authenticatedAdminPage,<br>    completedOrder,<br>  }) =&gt; {<br>    await authenticatedAdminPage.goto(`/admin/orders/${completedOrder.id}`);<br><br>    await expect(<br>      authenticatedAdminPage.locator(&#39;[data-testid=&quot;order-status&quot;]&#39;)<br>    ).toContainText(&quot;completed&quot;);<br>    await expect(<br>      authenticatedAdminPage.locator(&#39;[data-testid=&quot;order-total&quot;]&#39;)<br>    ).toContainText(`$${completedOrder.total}`);<br>  });<br>});<br><br>export { expect };</pre><h3><strong>🎯 Conclusion: Your Journey to Fixture Mastery</strong></h3><p>Playwright fixtures are more than just a testing feature — they’re a design pattern that promotes clean, maintainable, and scalable test automation. By mastering fixtures, you’ll:</p><ul><li><strong>Write tests faster</strong> with reusable authentication and data setup</li><li><strong>Maintain codebases easier</strong> with centralized user and product management</li><li><strong>Scale test suites</strong> without drowning in repetitive setup code</li><li><strong>Collaborate better</strong> with self-documenting, business-focused test code</li></ul><h4><strong>Quick Recap Checklist ✅</strong></h4><ul><li>[ ] Understand the two fixture scopes (test-scoped and worker-scoped)</li><li>[ ] Know how to create fixture dependencies for complex workflows</li><li>[ ] Use TypeScript for type-safe user data and API responses</li><li>[ ] Apply descriptive naming that reflects business domains</li><li>[ ] Handle authentication and cleanup properly</li><li>[ ] Choose the right scope for expensive operations</li><li>[ ] Organize fixtures properly in your project structure</li><li>[ ] Compose complex e-commerce scenarios from simple fixtures</li></ul><h4><strong>Next Steps 🚀</strong></h4><p>1. <strong>Start small</strong> — Convert your login flow to an `authenticatedPage` fixture</p><p>2. <strong>Build gradually</strong> — Add user data and product fixtures as you identify patterns</p><p>3. <strong>Share with team</strong> — Create a fixture library for your application domain</p><p>4. <strong>Iterate and improve</strong> — Refactor fixtures as your application evolves</p><p>Remember: The best fixture is one that makes your tests read like business requirements, not technical implementation details. Happy testing! 🎭</p><h3><strong>📚 Additional Resources</strong></h3><p>For in-depth API details and advanced configuration options, see the official Playwright documentation (https://playwright.dev/docs/test-fixtures).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd10f41f33b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed Up Playwright Tests with Storage State Authentication]]></title>
            <link>https://medium.com/@dksoni0812/speed-up-playwright-tests-with-storage-state-authentication-f73cc1a85049?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f73cc1a85049</guid>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[sessionstorage]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 13:04:13 GMT</pubDate>
            <atom:updated>2025-04-07T13:04:13.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*pIuMG7lbWNb2ok3MUXQDxw.png" /><figcaption>Storage State Authentication with Playwright</figcaption></figure><p>When building large-scale test suites using <a href="https://playwright.dev/">Playwright</a>, one common challenge is managing <strong>authentication across multiple spec files</strong> — especially in applications with <strong>role-based access</strong> like admin, editor, or viewer.</p><p>A typical E2E test often begins with a login. While this works for small suites, it quickly becomes inefficient and repetitive when scaling. So how do we fix that?</p><p>Let’s talk about <strong>Storage State Authentication</strong> — a game-changing approach that lets you <strong>store a logged-in session once and reuse it in all your test files</strong>, making your test suite leaner, faster, and more maintainable.</p><h3>🧠 The Problem: Repeated Login Slows Down Everything</h3><p>Imagine this setup:</p><ul><li>100+ spec files</li><li>Each one starts with a login</li><li>Multiple user roles (admin, editor, viewer)</li><li>Every test repeats the same login process</li></ul><p>This results in:</p><ul><li>🔁 Redundant operations</li><li>🐢 Slower test execution</li><li>⚠️ Increased chances of flaky login-related failures</li></ul><h3>✅ The Solution: Use Playwright’s Storage State</h3><p>Instead of logging in on every test, you can:</p><ol><li>Log in <strong>once</strong> for each role.</li><li>Save the session cookies and local storage to a .json file.</li><li>Reuse those session files in every test file for that role.</li></ol><blockquote><em>🎯 Playwright’s </em><a href="https://playwright.dev/docs/auth#session-storage"><em>storageState</em></a><em> API enables this behavior.</em></blockquote><h3>🔧 Step-by-Step Guide</h3><h3>🗂️ Folder Structure</h3><p>playwright/<br>├── auth.setup.mts # Handles login and storage<br>├── config/config.mts # Role configs<br>├── tests/<br>│ ├── admin.spec.mts<br>│ ├── editor.spec.mts<br>│ └── viewer.spec.mts<br>└── playwright.config.mts</p><h3>1. Setup Role-Based Auth</h3><p><strong>auth.setup.mts</strong></p><pre>import { expect, Page, test as setup } from &#39;@playwright/test&#39;;<br>import config, { type Role } from &#39;./configuration/config.mts&#39;;<br><br>async function verifyAndSaveAuthState(role: Role, baseURL: string | undefined, page: Page) {<br>  if (!baseURL) throw new Error(&#39;baseURL is not defined.&#39;);<br><br>  const credentials = config.roles[role];<br>  await page.goto(&#39;/&#39;);<br>  if (!credentials.username || !credentials.password) {<br>      throw new Error(&#39;Username or password not configured&#39;);<br>  }<br>  await page.getByRole(&#39;textbox&#39;, { name: &#39;Email Address&#39; }).fill(credentials.username);<br>  await page.getByRole(&#39;textbox&#39;, { name: &#39;Password&#39; }).fill(credentials.password);<br>  await page.getByRole(&#39;button&#39;, { name: &#39;Sign in&#39; }).click();<br><br>  await expect(page).toHaveTitle(&#39;Home&#39;);<br>}<br><br>Object.entries(config.roles).forEach(([key, role]) =&gt; {<br>  setup(`Authenticate and store state for ${key}`, async ({ page, baseURL }) =&gt; {<br>    await verifyAndSaveAuthState(key as Role, baseURL, page);<br>    console.log(<br>      `✅ Authentication for &quot;${key}&quot; was successful. Saving session state...`,<br>    );<br>    await page.context().storageState({ path: role.authFile });<br>  });<br>});</pre><p>🔐 This logs in once per role and saves session info like cookies and local storage in files such as auth/admin.json , auth/editor.json , and auth/viewer.json</p><h3>2. Configure Projects in playwright.config.mts</h3><pre>projects: [<br>  {<br>    name: &#39;setup&#39;,<br>    testMatch: &#39;auth.setup.mts&#39;,<br>  },<br>  {<br>    name: &#39;chromium&#39;,<br>    use: {<br>        ...devices[&#39;Desktop Chrome&#39;],<br>        storageState: path.resolve(dirname, &#39;auth/admin.json&#39;),<br>    },<br>    dependencies: [&#39;setup&#39;],<br>    },<br>],</pre><p>📦 This ensures your session states are generated before running other tests.</p><h3>3. Reuse Session in Test Files</h3><p><strong>Example: </strong><strong>employeeCRUD.spec.mts</strong></p><pre>import { faker } from &#39;@faker-js/faker&#39;;<br>import { test } from &#39;@playwright/test&#39;;<br>import employeePage from &#39;./employeePage.mts&#39;;<br><br>test.use({ storageState: &#39;playwright/auth/admin.json&#39; });<br><br>test.describe(&#39;Individual employee CRUD operation tests&#39;, () =&gt; {<br>  test.beforeEach(async ({ page }) =&gt; {<br>    await page.goto(&#39;/&#39;);<br>  });<br><br>  // Test each CRUD operation separately for better isolation<br>  test(&#39;should create a new individual employee&#39;, async ({ page }) =&gt; {<br>    const { firstName, lastName } =<br>      await employeePage.addIndividualEmployee(page);<br>    await employeePage.validateEmployeeName(<br>      page,<br>      `${firstName} ${lastName}`,<br>    );<br>  });<br>});</pre><p>🚀 Your test starts in an authenticated state — no login steps required.</p><h3>💡 Why This Pattern Rocks</h3><p>✅ <strong>Speed</strong> — Skip login every time<br>✅ <strong>DRY Code</strong> — Centralized login logic<br>✅ <strong>Stability</strong> — Reduces flaky tests<br>✅ <strong>Scalability</strong> — Easily add more roles</p><h3>🛡️ Best Practices</h3><ul><li><strong>Isolate Roles</strong>: Store each role’s session in separate files (admin.json, editor.json, etc.)</li><li><strong>Keep Credentials Safe</strong>: Use environment variables, not hard-coded secrets</li><li><strong>Handle Expiry</strong>: Regenerate sessions in CI pipelines regularly</li><li><strong>Use </strong><strong>.env or Config Files</strong>: Centralize user credentials and base URLs</li></ul><h3>📌 Final Thoughts</h3><p>Playwright’s <strong>Storage State Authentication</strong> is a must-have when scaling your E2E tests — especially for applications with multiple user roles. It reduces redundancy, enhances test performance, and keeps your suite maintainable.</p><p>If you’re still logging in on every test, now’s the time to level up!</p><p><strong>🧭 References:</strong></p><ul><li><a href="https://playwright.dev/docs/auth#session-storage">Playwright Docs — Session Storage</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f73cc1a85049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Context Clicks: Handling Repeated Elements in Playwright]]></title>
            <link>https://medium.com/@dksoni0812/mastering-context-clicks-handling-repeated-elements-in-playwright-f50df9da7794?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50df9da7794</guid>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playwright-community]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 07:02:26 GMT</pubDate>
            <atom:updated>2025-03-31T07:02:26.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_BrtreZhBfwOtrahW4HMQ.png" /><figcaption>Handling of repeated elements in playwright</figcaption></figure><p>Automation testing is all about precision, efficiency, and reusability. One of the common challenges in test automation is handling repeated elements dynamically. In this article, we will explore how Playwright can be leveraged to efficiently interact with repeated elements using a real-world example from <strong>SauceDemo</strong>.</p><h3>Understanding the Scenario</h3><p>SauceDemo provides a sample e-commerce platform where multiple products are listed, each with an <strong>Add to Cart</strong> button. The goal is to automate the process of selecting a specific product and clicking its associated <strong>Add to Cart</strong> button, ensuring that we interact with the correct element dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrPigd3WN9q5gKuKbjVVTQ.png" /><figcaption>Workflow</figcaption></figure><h3>Why Playwright?</h3><p>Playwright is a modern automation framework that supports multi-browser testing, offers powerful selectors, and provides built-in capabilities for handling dynamic elements. Its <strong>flexible</strong> <strong>locators</strong> allow us to precisely target elements without relying on <strong>fragile XPath expressions</strong>.</p><h3>Automating “Add to Cart” for a Specific Product</h3><p>Let’s write a Playwright script in TypeScript to automate adding a specific product to the cart.</p><h3>Step 1: Set Up Playwright</h3><p>Ensure you have Playwright installed in your project. If not, install it using:</p><pre>npm install @playwright/latest</pre><h3>Step 2: Write the Playwright Script</h3><pre>test(&#39;Handle repeated elements and perform context-click in Playwright&#39;, async () =&gt; {<br>  const browser = await chromium.launch({ headless: false });<br>  const page = await browser.newPage();<br>  <br>  // Navigate to Sthe auceDemo login page<br>  await page.goto(&#39;https://www.saucedemo.com/&#39;);<br>  <br>  // Log in with demo credentials<br>  await page.fill(&#39;#user-name&#39;, &#39;standard_user&#39;);<br>  await page.fill(&#39;#password&#39;, &#39;secret_sauce&#39;);<br>  await page.click(&#39;#login-button&#39;);<br>  <br>  // Wait for the inventory page to load<br>  await page.waitForSelector(&#39;.inventory_item&#39;);<br>  <br>  // Locate the item with a specific name and click its &quot;Add to Cart&quot; button<br>  const itemName = &#39;Sauce Labs Backpack&#39;;<br>  const item = page.locator(&#39;.inventory_item&#39;).filter({ hasText: itemName });<br>  const addToCartButton = item.locator(&#39;button:has-text(&quot;Add to cart&quot;)&#39;);<br>  await addToCartButton.click();<br>  console.log(`Added &#39;${itemName}&#39; to cart`);<br>  <br>  // Close browser<br>  await browser.close();<br>});</pre><h3>Step 3: Understanding the Code</h3><ol><li><strong>Login to SauceDemo:</strong> We enter the username and password, then click the login button.</li><li><strong>Wait for Product List:</strong> We ensure the page loads completely before proceeding.</li><li><strong>Find the Target Product:</strong> We use Playwright’s locator with .filter({ hasText: itemName }) to identify the exact product.</li><li><strong>Click “Add to Cart”:</strong> Using locator(&#39;button:has-text(&quot;Add to cart&quot;)&#39;), we ensure that we click the correct button within the specific product card.</li></ol><h3>Advanced Enhancements</h3><p>To make the script more dynamic and reusable, we can convert it into a function:</p><pre>async function addItemToCart(page, productName) {<br>  const item = page.locator(&#39;.inventory_item&#39;).filter({ hasText: productName });<br>  await item.locator(&#39;button:has-text(&quot;Add to cart&quot;)&#39;).click();<br>  console.log(`Added &#39;${productName}&#39; to cart`);<br>}</pre><p>Now, you can simply call await addItemToCart(page, &#39;Sauce Labs Bike Light&#39;); for any product dynamically.</p><h3>Best Practices for Handling Repeated Elements in Playwright</h3><ul><li><strong>Use </strong>locator().filter()<strong> Instead of XPath</strong>: Playwright provides modern ways to handle elements dynamically.</li><li><strong>Ensure Elements Are Loaded</strong>: Use await page.waitForSelector() before interacting with elements.</li><li><strong>Implement Reusable Functions</strong>: Modularizing your functions improves maintainability.</li><li><strong>Use Assertions to Validate Actions</strong>: Add checks using expect() from Playwright Test to verify elements are added to the cart.</li></ul><h3>Conclusion</h3><p>Handling repeated elements efficiently is crucial in test automation. Playwright’s robust locator strategies make it seamless to interact with dynamic elements without relying on <strong>brittle</strong> <strong>selectors</strong>. By leveraging techniques like filter(), locator(), and reusable functions, we can build scalable and reliable automation scripts.</p><p>Try implementing this approach in your Playwright framework and enhance your automation capabilities today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50df9da7794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Environment Configuration in Playwright: A Comprehensive Guide]]></title>
            <link>https://medium.com/@dksoni0812/effective-environment-configuration-in-playwright-a-comprehensive-guide-c003e63c59dd?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c003e63c59dd</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 14:01:17 GMT</pubDate>
            <atom:updated>2025-02-28T14:15:36.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtgygCOkTyzKliSV5XxSww.jpeg" /></figure><p>When working with Playwright, configuring environments effectively ensures smooth execution of tests across different setups. In this article, we will explore various ways to handle environment variables and URL configurations in Playwright, covering:</p><ol><li><strong>Project setup for multi-environment handling</strong></li><li><strong>Environment file (.env) management</strong></li><li><strong>Using </strong>baseURL<strong> for default configurations</strong></li><li><strong>Handling multiple URLs in different test cases</strong></li><li><strong>Leveraging the JS ternary operator for dynamic </strong>baseURL<strong> assignment</strong></li></ol><h3>1. Setting Up Projects for Multi-Environment Handling</h3><p>Playwright allows the creation of multiple projects within playwright.config.ts, which can be configured for different environments. This enables executing tests across multiple setups efficiently.</p><h3>Example Configuration:</h3><pre>import { defineConfig } from &#39;@playwright/test&#39;;<br><br>export default defineConfig({<br>  projects: [<br>    {<br>      name: &#39;staging&#39;,<br>      use: {<br>        baseURL: &#39;https://staging.example.com&#39;,<br>      },<br>    },<br>    {<br>      name: &#39;production&#39;,<br>      use: {<br>        baseURL: &#39;https://www.example.com&#39;,<br>      },<br>    },<br>  ],<br>});ty</pre><p>In this setup, running npx playwright test --project=staging will execute tests against the staging environment, while npx playwright test --project=production will run against production.</p><h3>2. Managing Environment Variables Using .env File</h3><p>Instead of hardcoding URLs, you can use environment variables stored in a .env file.</p><h3>Example .env File:</h3><pre>BASE_URL=https://staging.example.com<br>API_KEY=your_api_key_here</pre><p>To load these variables in Playwright, install the dotenv package and update your configuration:</p><pre>import { defineConfig } from &#39;@playwright/test&#39;;<br>import dotenv from &#39;dotenv&#39;;<br><br>dotenv.config();<br><br>export default defineConfig({<br>  use: {<br>    baseURL: process.env.BASE_URL,<br>  },<br>});</pre><p>Now, Playwright will dynamically pick the baseURL from the .env file.</p><h3>3. Utilizing baseURL in Playwright for Default Configurations</h3><p>Playwright provides a baseURL option that automatically prefixes all page.goto() requests, simplifying test maintenance.</p><h3>Example:</h3><pre>await page.goto(&#39;/dashboard&#39;); // Resolves to https://staging.example.com/dashboard</pre><p>This ensures consistency without requiring full URLs in every test.</p><h3>4. Handling Different URL Configurations in Various Test Cases</h3><p>Some tests may require different URLs based on scenarios. In such cases, testOptions.ts can be customized.</p><h3>Example testOptions.ts:</h3><pre>export const testOptions = {<br>  env1: {<br>    baseURL: &#39;https://env1.example.com&#39;,<br>  },<br>  env2: {<br>    baseURL: &#39;https://env2.example.com&#39;,<br>  },<br>};</pre><p>Inside your test:</p><pre>import { test } from &#39;@playwright/test&#39;;<br>import { testOptions } from &#39;../testOptions&#39;;<br><br>test(&#39;navigate to different environment&#39;, async ({ page }) =&gt; {<br>  const environment = process.env.ENV || &#39;env1&#39;;<br>  const baseURL = testOptions[environment].baseURL;<br><br>  await page.goto(`${baseURL}/login`);<br>});</pre><p>Now, setting ENV=env2 before running the test will use the corresponding URL.</p><h3>5. Using JS Ternary Operator for Dynamic baseURL Assignment</h3><p>For a simpler conditional assignment of baseURL, you can use the JS ternary operator.</p><pre>import { defineConfig } from &#39;@playwright/test&#39;;<br><br>const baseURL = process.env.ENV === &#39;staging&#39;<br>  ? &#39;https://staging.example.com&#39;<br>  : &#39;https://www.example.com&#39;;<br><br>export default defineConfig({<br>  use: { baseURL },<br>});</pre><p>This approach eliminates the need for extra configuration files, making it easier to manage environment-based URLs.</p><h3>Conclusion</h3><p>By implementing these techniques, you can configure Playwright to handle multiple environments efficiently. Leveraging .env files, baseURL, and conditional logic simplifies test execution across various setups. A well-structured configuration enhances test maintainability and reduces redundant code, leading to a more scalable automation framework.</p><p><strong>Happy testing with Playwright!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c003e63c59dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Test Automation: Integrating WebdriverIO with TestRail]]></title>
            <link>https://medium.com/@dksoni0812/streamlining-test-automation-integrating-webdriverio-with-testrail-88a63cdb538c?source=rss-7726a9e5db4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a63cdb538c</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[testrail]]></category>
            <category><![CDATA[webdriverio]]></category>
            <category><![CDATA[reporting]]></category>
            <dc:creator><![CDATA[Dhrumil Soni]]></dc:creator>
            <pubDate>Sun, 19 May 2024 18:57:03 GMT</pubDate>
            <atom:updated>2024-05-19T19:23:40.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced software development environment, ensuring efficient and reliable testing processes is crucial. This article explores the integration of WebdriverIO, a powerful test automation framework, with TestRail, a comprehensive test management tool. By combining these two solutions, teams can streamline their testing workflows, foster collaboration, and ultimately deliver high-quality software products more efficiently.</p><h3>Understanding WebdriverIO</h3><p><a href="https://webdriver.io/">WebdriverIO</a> is a powerful and flexible JavaScript-based test automation framework for web applications. It enables teams to write automated tests that simulate real user interactions, such as clicking buttons, filling forms, and verifying content across various browsers and platforms. With its modular architecture and extensibility, WebdriverIO provides a scalable and maintainable solution for automating web application testing.</p><h3>Understanding TestRail</h3><p><a href="https://www.testrail.com/">TestRail</a> is a comprehensive web-based test management tool that facilitates the entire software testing lifecycle. It offers features for organizing and managing test cases, tracking test execution progress, and generating detailed reports. With its centralized repository and user-friendly interface, TestRail fosters collaboration among team members and stakeholders, ensuring transparency and traceability throughout the testing process.</p><h3>The Need for Integration</h3><p>Consider a scenario where your team is working on a complex web application with numerous features and functionalities. As the codebase grows, the number of automated tests written with WebdriverIO also increases. This manual effort not only consumes valuable time and resources but also introduces the risk of human error, potentially leading to inaccurate or outdated test reports.</p><h3>Integrating WebdriverIO with TestRail:</h3><p>By integrating WebdriverIO with TestRail, teams can seamlessly synchronize test execution results from WebdriverIO directly into TestRail. This integration eliminates the need for manual updates, ensuring that test results are accurately and promptly reflected in the corresponding test cases within TestRail.</p><h4><strong>Configuration</strong></h4><p>The first thing you need is to enable the TestRail API so that report can communicate with TestRail and push the test results. To do so, log into your TestRail account and go to Administration &gt; Site Settings &gt; API and make sure you click the checkbox near Enable API.</p><pre>npm i --save-dev @wdio/testrail-reporter</pre><p>Add testrail reporter to your <strong>wdio.conf.ts</strong> file</p><pre>export const config: Options.Testrunner = {<br>    // ...<br>    reporters:<br>        [<br>            [&#39;testrail&#39;, {<br>                projectId: 1,<br>                suiteId: 1,<br>                domain: &#39;xxxxx.testrail.io&#39;,<br>                username: &#39;TESTRAIL_USERNAME&#39;,<br>                apiToken: &#39;TESTRAIL_API_TOKEN&#39;,<br>                runName: &#39;name for the test run&#39;,<br>                oneReport: true,<br>                includeAll: false<br>                caseIdTagPrefix: &#39;&#39; // used only for multi-platform Cucumber Scenarios<br>            }<br>        ]<br>    ],<br>    // ...<br>}</pre><h4>Understanding of above testrail options</h4><blockquote>projectId: ID of the testrail project.</blockquote><p>This is the unique identifier for the TestRail project you want to associate your test results with. Open your project in TestRail, and observe the URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po3BtJ-ILl0tdfzmr6iWMQ.png" /><figcaption>TestRail Project Dashboard</figcaption></figure><p>From the above image, the Project Name is “TestExample,” and you can see “P23” beside the project name, which suggests the project ID is 23.</p><blockquote>suiteId: ID of the suite</blockquote><p>This is the unique identifier for the test suite within the specified project. A test suite is a collection of related test cases.</p><p>Open your “Test Suites &amp; Cases” section under the project in TestRail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxhzgF-r47eqzUkaf9CYZg.png" /><figcaption>TestRail: Test cases in TestSuite</figcaption></figure><p><strong>Two ways:</strong></p><ol><li>From the image above, you can see “S82” next to the suite name, indicating that the suite ID is 82.</li><li>Check the URL when you open a specific test suite: https://tech.testrail.io/index.php?/suites/view/82&amp;group_by=cases:section_id&amp;group_order=asc&amp;display_deleted_cases=0 From the above URL, you can get your suite ID, which is 82.</li></ol><blockquote>domain: Domain of your testrail instance, e.g. your-domain.testrail.io.</blockquote><blockquote>username: Username of your testrail instance.</blockquote><blockquote>apiToken: API token of your testrail instance.</blockquote><blockquote>runName: Custom name for the test run.</blockquote><blockquote>oneReport: Create a single test run.</blockquote><blockquote>includeAll: Include all tests in suite in test run.</blockquote><h4>Generation of apiToken in the TestRail</h4><ol><li>Go to “My Settings”</li><li>Navigate to “API Keys”</li><li>Click on “Add Key”</li><li>Add “Name” of the Key and Click “Generate Key”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgyYeNmZ40nSpPkXNEoahQ.png" /><figcaption>API Configurations: Add API Key Name</figcaption></figure><p>5. After key is getting generated, make sure to store at someplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHGcX3PHgXdm6-DuzEXC7g.png" /><figcaption>API Configurations: Generation of API Key in the TestRail</figcaption></figure><p>6. Now Click on “+ Add Key” button.</p><p>7. Do not forgot to “Save Settings”.</p><p>After making changes as per above explanation, <strong>testrail</strong> reporter configuration in <strong>wdio.conf.ts</strong> look like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am1g1hLTgDA_XTws6RWcVw.png" /><figcaption>wdio.conf.ts - testrail report configuration</figcaption></figure><h4>Mapping of TestRail test case with WDIO Testcase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9suKWIBRhpt1Z-yBfw3woA.png" /></figure><p>We have three test cases in our suite which having IDs C29729, C29731, and C29732.</p><p>Add TestRail’s test case ID to the WebDriverIO test description. e.g.</p><pre>it(&quot;C29732 Website Main Pages: Verify the Headers options available in the Home Page Footer.&quot;, async()=&gt; { </pre><pre>it(&quot;C29731 Website Main Pages: Verify About Us page opens error-free&quot;, async () =&gt; {</pre><pre>it(&quot;C29729 Website Main Pages: Verify Landing Page opens error-free&quot;, async () =&gt; {</pre><p>So mapping is Done. Now, you all set to update your test results through Automation test execution in the testrail test run.</p><h4>TestRun Inside the TestRail before Automation Test Execution:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdFKX7CkVdYTBxhBpr4QJw.png" /><figcaption>TestRun- “TestExample” in TestRail</figcaption></figure><p>Now, run automation command to execute tests:</p><blockquote>npx wdio wdio.conf.ts — spec ./test/specs/aboutus_test.ts</blockquote><h4><strong>Execution Logs:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArBniUTyw9QFvkxMYipS2g.png" /><figcaption>Test Execution Logs</figcaption></figure><h4><strong>TestRail Execution:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCRz9uY9HFjiRoeaoWDQEg.png" /><figcaption>TestRail — Test Report Execution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ajJGTsuhWL6vNlxzvLdwg.png" /><figcaption>TestRail — Individual Test Execution with detailed logs</figcaption></figure><p>After execution completes, it automatically updates the test result in the TestRun.</p><h3>Best Practices and Considerations</h3><ul><li><strong>Secure Handling of API Keys</strong>: Ensure that API tokens and sensitive information are securely stored and never committed to version control systems. Consider using environment variables or secure storage solutions.</li><li><strong>Documentation and Knowledge Sharing</strong>: Maintain clear documentation of automated tests and their corresponding test cases in TestRail</li><li><strong>Test Case Organization</strong>: Organize test cases in TestRail based on application modules, features, or other logical groupings to enhance maintainability and reporting.</li><li><strong>Continuous Integration and Delivery</strong>: Integrate the WebdriverIO and TestRail integration into your continuous integration and delivery pipeline for seamless and automated testing processes.</li></ul><h3>Common Challenges and Troubleshooting</h3><ul><li>Ensure that your API token is valid and has the necessary permissions to interact with TestRail.</li><li>Double-check the project and suite IDs to ensure they are correct and match your TestRail instance.</li><li>If you encounter authentication errors, verify that your username and domain are correct and up-to-date.</li></ul><h3><strong>Conclusion:</strong></h3><p>By integrating WebdriverIO with TestRail, teams can unlock the full potential of test automation and streamline their testing processes. This integration empowers teams to scale their automated testing efforts, maintain traceability, foster collaboration, and ultimately deliver high-quality software products more efficiently. Embrace the power of this integration and elevate your software testing practices to new heights.</p><p><strong>References</strong>:</p><ul><li><a href="https://webdriver.io/docs/wdio-testrail-reporter">https://webdriver.io/docs/wdio-testrail-reporter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a63cdb538c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>