<?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 Saptarshi Deb on Medium]]></title>
        <description><![CDATA[Stories by Saptarshi Deb on Medium]]></description>
        <link>https://medium.com/@sap7deb?source=rss-7759187d2c6b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0aWaZVX6TMwxmnNXT9ab-w.jpeg</url>
            <title>Stories by Saptarshi Deb on Medium</title>
            <link>https://medium.com/@sap7deb?source=rss-7759187d2c6b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:34:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sap7deb/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[Stop Using Map<String, Object> in Cucumber: Type-Safe Scenario Context for Cucumber JVM]]></title>
            <link>https://medium.com/@sap7deb/stop-using-map-string-object-in-cucumber-type-safe-scenario-context-for-cucumber-jvm-3d8a64b54fd1?source=rss-7759187d2c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8a64b54fd1</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[cucumber]]></category>
            <dc:creator><![CDATA[Saptarshi Deb]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 15:21:38 GMT</pubDate>
            <atom:updated>2026-06-25T15:21:38.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Using Map&lt;String, Object&gt; in Cucumber: A Type-Safe Scenario Context Library for Java</h3><p>A cleaner, safer, and reusable approach to sharing state between Cucumber step definitions</p><h3>Introduction</h3><p>If you’ve built more than a few Cucumber automation frameworks, you’ve probably written some version of this:</p><pre>public class ScenarioContext {<br>    private final Map&lt;String, Object&gt; context = new HashMap&lt;&gt;();<br><br>    public void set(String key, Object value) {<br>        context.put(key, value);<br>    }<br><br>    public Object get(String key) {<br>        return context.get(key);<br>    }<br>}</pre><p>At first, it feels simple.</p><p>Then the framework grows.</p><p>Suddenly you have:</p><ul><li>Hundreds of context keys</li><li>Casting everywhere</li><li>Runtime ClassCastExceptions</li><li>String typos causing failures</li><li>Duplicate context implementations across projects</li><li>Complex dependency injection wiring</li></ul><p>After building multiple automation frameworks over the years, I noticed the same pattern repeating again and again.</p><p>That’s why I created:</p><h4><a href="https://github.com/sap7deb/cucumber-scenario-context?utm_source=chatgpt.com">cucumber-scenario-context GitHub Repository</a></h4><p>A lightweight Java library that provides:</p><ul><li>Type-safe context storage</li><li>Cucumber integration</li><li>PicoContainer support</li><li>Automatic lifecycle management</li><li>Cleanup hooks</li><li>Framework-independent core module</li></ul><h3>The Problem</h3><p>Most Cucumber projects need to share data between steps.</p><p>Example:</p><pre>Scenario: Create a user<br><br>Given a new user is created<br>When the user updates their profile<br>Then the profile update succeeds</pre><p>The user object created in the first step must be accessible in later steps.</p><p>Most frameworks solve this using:</p><pre>Map&lt;String, Object&gt;</pre><p>Typical Implementation</p><pre>context.put(&quot;user&quot;, user);<br><br>User user = (User) context.get(&quot;user&quot;);</pre><p>Problems:</p><p>❌ Manual casting</p><p>❌ Runtime failures</p><p>❌ String-based keys</p><p>❌ No compile-time safety</p><p>❌ Boilerplate repeated in every project</p><h3>Traditional vs Type-Safe Context</h3><h4>Traditional Approach</h4><pre>context.put(&quot;response&quot;, response);<br><br>Response response =<br>    (Response) context.get(&quot;response&quot;);</pre><h4>Using cucumber-scenario-contextKey&lt;T&gt;</h4><p>A type-safe identifier.</p><pre>Key&lt;String&gt; USERNAME =<br>    Key.key(&quot;username&quot;, String.class);</pre><p>No casting.</p><p>No magic strings.</p><p>Compile-time type safety.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*czuNDEsC0h40GPiB6pUrpg.png" /></figure><h3>Core Design</h3><h4>Type-Safe Keys</h4><p>Instead of:</p><pre>context.put(&quot;username&quot;, &quot;alice&quot;);</pre><p>Use:</p><pre>Key&lt;String&gt; USERNAME =<br>        Key.key(&quot;username&quot;, String.class);</pre><p>Store value:</p><pre>context.add(USERNAME, &quot;alice&quot;);</pre><p>Retrieve value: No casting required.</p><pre>String user = context.get(USERNAME);</pre><h3>Complexity Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6mmZ73tojjiR9WbdFcsFg.png" /></figure><h3>Basic Usage</h3><h4>Define Keys</h4><p>Create a central key registry.</p><pre>public final class ContextKeys {<br><br>    public static final Key&lt;String&gt; USERNAME =<br>            Key.key(&quot;username&quot;, String.class);<br><br>    public static final Key&lt;User&gt; USER =<br>            Key.key(&quot;user&quot;, User.class);<br><br>    private ContextKeys() {}<br>}</pre><h4>Store Values</h4><pre>context.add(ContextKeys.USERNAME, &quot;alice&quot;);</pre><h4>Retrieve Values</h4><pre>String username =<br>        context.get(ContextKeys.USERNAME);</pre><h4><strong>Check</strong> <strong>Existence</strong></h4><pre>if(context.contains(ContextKeys.USERNAME)) {<br>    // proceed<br>}</pre><h3>Remove Value</h3><pre>context.remove(ContextKeys.USERNAME);</pre><h3>Clear Context</h3><pre>context.clear();</pre><h3>Integration</h3><h4>Maven Dependency</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.github.sap7deb&lt;/groupId&gt;<br>    &lt;artifactId&gt;cucumber-scenario-context&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>The library integrates seamlessly with Cucumber and PicoContainer, providing a fresh context for every scenario.</p><h3>Real-World API Testing Example</h3><p>Consider a user creation API test.</p><h4>Step 1: Create User</h4><pre>@When(&quot;a user is created&quot;)<br>public void createUser() {<br>Response response =<br>        userApi.createUser();<br>    context.add(<br>        ContextKeys.CREATE_USER_RESPONSE,<br>        response<br>    );<br>}</pre><h4>Step 2: Validate Response</h4><pre>@Then(&quot;user creation should succeed&quot;)<br>public void validateResponse() {<br><br>    Response response =<br>        context.get(<br>            ContextKeys.CREATE_USER_RESPONSE<br>        );<br><br>    assertEquals(<br>        201,<br>        response.statusCode()<br>    );<br>}</pre><p>The response object is shared across step definitions without any casting or string-based lookups.</p><h3>Advantages Over Traditional Implementations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJw9QEEoZC3mhYSIWtobmw.png" /></figure><h3>When Should You Use It?</h3><p>This library is particularly useful when:</p><ul><li>Building Cucumber JVM frameworks</li><li>Using PicoContainer for dependency injection</li><li>Sharing API responses, domain objects, or test data between steps</li><li>Standardizing framework design across multiple projects</li><li>Reducing custom framework code</li></ul><h3>Conclusion</h3><p>Most Cucumber frameworks eventually reinvent a scenario context implementation. Unfortunately, many rely on Map&lt;String, Object&gt;, resulting in casting, string keys, and unnecessary boilerplate.</p><p>cucumber-scenario-context provides a reusable, type-safe alternative that keeps step definitions clean, improves maintainability, and eliminates an entire class of runtime errors.</p><p><strong>Repository:</strong><br><a href="https://sap7deb.github.io/cucumber-scenario-context/"> GitHub — cucumber-scenario-context</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8a64b54fd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Cypress Tests with cy.session()]]></title>
            <link>https://medium.com/@sap7deb/one-login-to-rule-them-all-streamlining-cypress-tests-with-cy-session-951288b7bfcf?source=rss-7759187d2c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/951288b7bfcf</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[cypress]]></category>
            <dc:creator><![CDATA[Saptarshi Deb]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 15:46:22 GMT</pubDate>
            <atom:updated>2024-10-22T05:56:34.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxpknZGzE52gtldrimjD8A.jpeg" /></figure><p>In modern web application testing, speed and efficiency are essential. One common bottleneck in end-to-end testing with Cypress is the need to log in multiple times across different tests. Each login process can slow down test execution and reduce efficiency, especially when running large test suites. Fortunately, Cypress offers a solution in the form of cy.session(), which allows you to log in once and reuse that session across multiple tests. In this blog, we&#39;ll walk through how to implement cy.session() to make your Cypress tests faster and more efficient.</p><h4>The Problem: Redundant Logins in Tests</h4><p>Imagine you have multiple tests that require users to be logged in. For each test, you might have the login steps repeated at the beginning, leading to unnecessary duplication and wasted time. Even if you move the login process to a beforeEach() hook, you still find that Cypress logs in for every test. This is a problem when the actual functionality being tested has nothing to do with the login process.</p><pre>beforeEach(() =&gt; {<br>  cy.visit(&#39;/login&#39;);<br>  cy.get(&#39;#username&#39;).type(&#39;test&#39;);<br>  cy.get(&#39;#password&#39;).type(&#39;test&#39;);<br>  cy.get(&#39;button&#39;).click();<br>});</pre><h4>The Solution: cy.session()</h4><p>Cypress provides the cy.session() command to store and reuse session data (cookies, local storage, and session storage) across tests. This makes it possible to log in once and reuse that session throughout your test suite. This is how you can implement it:</p><ol><li><strong>Define the Session in a Custom Command</strong><br>First, move the login logic to a custom Cypress command. This will help streamline your code and make it more reusable.</li></ol><pre>Cypress.Commands.add(&#39;login&#39;, (username, password) =&gt; {<br>  cy.visit(&#39;/login&#39;);<br>  cy.get(&#39;#username&#39;).type(username);<br>  cy.get(&#39;#password&#39;).type(password);<br>  cy.get(&#39;button&#39;).click();<br>});</pre><p>2. <strong>Implement </strong><strong>cy.session()</strong><br>Now, use the cy.session() command to ensure that the session is stored and reused in subsequent tests. The session is identified by an ID, which in this case could be the username.</p><pre>cy.session([username, password], () =&gt; {<br>  cy.login(username, password);<br>});</pre><p>With this setup, Cypress will store the session after the first login and reuse it for all subsequent tests. No need to log in again!</p><p>3. <strong>Reusing the Session Across Tests</strong> You can now reuse the stored session in your test suite, ensuring that Cypress uses the same session data across different tests.</p><pre>it(&#39;should display the welcome message after login&#39;, () =&gt; {<br>  cy.session([username, password], () =&gt; {<br>    cy.visit(&#39;/&#39;);<br>    cy.contains(&#39;Welcome&#39;);<br>  });<br>});</pre><p>4. <strong>Cross-Spec Session Persistence</strong> By default, cy.session() will store the session only within a specific spec file. However, Cypress offers an option to cache the session across different spec files by using the cacheAcrossSpecs: true option. This is particularly useful when your test suite spans multiple files.</p><pre>cy.session([username, password], () =&gt; {<br>  cy.login(username, password);<br>}, {<br>  cacheAcrossSpecs: true<br>});</pre><p>This will allow the session to persist even when running tests across different spec files, further improving test execution speed.</p><h4>Handling Multiple Users and Sessions</h4><p>If your test suite requires testing with different users, cy.session() can handle that as well. By assigning unique session IDs based on the username and password, you can maintain separate sessions for each user across your tests.</p><pre>cy.session([user1], () =&gt; {<br>  cy.login(user1.username, user1.password);<br>});<br><br>cy.session([user2], () =&gt; {<br>  cy.login(user2.username, user2.password);<br>});</pre><p>This flexibility allows you to simulate different user roles or scenarios without repeatedly logging in, speeding up your entire test process.</p><h4>Conclusion</h4><p>The cy.session() command is a powerful tool for improving the performance of Cypress tests by reducing redundant logins and storing session data. By implementing this feature, you can significantly speed up your test execution and make your code more maintainable. This becomes even more useful when dealing with large test suites or multiple user roles.</p><p>Make sure to explore the official Cypress documentation for cy.session() to uncover additional options and capabilities. Implementing best practices like these will ensure that your end-to-end testing is both efficient and scalable.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951288b7bfcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Automation Best Practices: Streamlining Software Quality]]></title>
            <link>https://medium.com/@sap7deb/testing-automation-best-practices-streamlining-software-quality-e269bb17d72c?source=rss-7759187d2c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e269bb17d72c</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[automation-tools]]></category>
            <category><![CDATA[software-test-automation]]></category>
            <category><![CDATA[automation-testing]]></category>
            <dc:creator><![CDATA[Saptarshi Deb]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 07:22:56 GMT</pubDate>
            <atom:updated>2024-04-17T06:11:36.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48YNjo1K9DzC4SX4B0CRIg.png" /></figure><p><em>Automated testing has revolutionised the landscape of software development, empowering teams to expedite testing processes while maintaining the highest standards of quality.</em></p><p><em>In this blog post, we’ll delve into some essential practices to maximise the effectiveness of your test automation endeavours. From strategising to execution and maintenance, these practices are geared towards optimising your testing workflow and elevating the overall quality of your software products. Throughout this exploration, we’ll illustrate these best practices within the context of automation using TypeScript Cypress.</em></p><h3>1. Crafting a Strategic Foundation</h3><p>Before embarking on your automation journey, laying down a robust strategy is paramount. Define clear objectives and discern what aspects of your testing process warrant automation. Engage with key stakeholders such as Product Managers, Business Analysts, and UX Designers to glean insights into critical functionalities and user requirements.</p><h3>2. Strategic Test Set Organisation</h3><p>Efficiently organise your tests into logical sets based on functionality or application modules. This structured approach facilitates seamless test management and execution as your test suite expands.</p><p>As an example, let’s consider the <strong>“Student Registration”</strong> functionality (test suite), which includes tests such as <strong>“Creating a new Student Information”</strong> and <strong>“Adding students to a specific program unit”</strong>.</p><p>And here is an example of usage <strong>describe()</strong> to define the “Test set” and <strong>it()</strong> to define the “Test case” in Cypress:</p><pre>describe(&#39;Student Registration&#39;, () =&gt; {<br>  it(&#39;Create new student information&#39;, () =&gt; {<br>    // Test scenario code<br>  });<br><br>  it(&#39;Add student to a specific program unit&#39;, () =&gt; {<br>    // Test scenario code<br>  });<br>});</pre><h3>3. Comprehensive Test Scenario Descriptions</h3><p>Thoroughly outline each test scenario, delineating steps and expected outcomes before diving into code implementation. This proactive approach streamlines test development by providing a clear roadmap of testing objectives.</p><h3>4. Leveraging Preconditions and Postconditions</h3><p>Leverage setup and teardown mechanisms like before(), after(), beforeEach(), and afterEach() to ensure test environment readiness and cleanliness, fostering test reliability and independence.</p><pre>describe(&#39;Student Registration&#39;, () =&gt; {<br>  before(() =&gt; {<br>    createRegistration(student.name, student.age);<br>  });<br><br>  after(() =&gt; {<br>    deleteExcursion(student.name);<br>  });<br><br>  it(&#39;Add student to a specific program unit&#39;, () =&gt; {<br>    // Test scenario code<br>  });<br>});</pre><h3>5. Automating Pre and Postconditions with API Calls</h3><p>Utilise API endpoints to automate setup and cleanup tasks, ensuring consistency and efficiency across your testing processes.</p><pre>export function createRegistration(studentName: string) {<br>  cy.request({<br>    method: &#39;POST&#39;,<br>    url: &#39;https://www.test&#39;,<br>    headers: { &#39;X-API-KEY&#39;: &#39;test key&#39; },<br>    body: {<br>      type: studentName,<br>    },<br>  });<br>}</pre><h3>6. Enhancing Element Identification</h3><p>Augment HTML elements with data-testid attributes to facilitate precise element identification within automated tests, bolstering test accuracy and resilience to UI changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5Sk8de6C_kqJDBFYUQmtA.png" /></figure><pre>addStudentName(value: string) {<br>  cy.findByTestId(&#39;student-id&#39;).type(value);<br>}</pre><h3>7. Effective Page Object Pattern Implementation</h3><p>Employ the Page Object pattern to encapsulate UI elements and actions within dedicated objects, promoting test readability, maintainability, and scalability.</p><h4>Why you should consider adopting the Page Object pattern in test automation:</h4><ul><li>Utilise the Page Object pattern when dealing with a sophisticated UI featuring numerous pages or elements necessitating frequent testing interactions.</li><li>Implement the pattern when there’s a requirement to reuse elements or actions across multiple tests or test suites.</li><li>Embrace the Page Object pattern if you anticipate regular UI updates, aiming to consolidate all UI-related changes in one accessible location for simplified maintenance.</li></ul><h4>Page Object pattern may not be necessary in the below situations:</h4><ul><li>For applications boasting a straightforward UI with minimal pages or elements requiring limited interaction during testing.</li><li>When developing one-off or ad-hoc tests that do not demand future maintenance or reuse.</li><li>In scenarios where time constraints dictate the need for swiftly created tests, overlooking long-term maintenance or scalability concerns.</li></ul><h3>8. Leveraging Inheritance for Shared Page Elements</h3><p>Utilise inheritance to streamline the management of shared page elements across multiple page objects, fostering code modularity and organisation.</p><p>We can create a <strong>base page object that contains the common elements</strong>. Then, we can create child page objects for specific pages that inherit from the base page object. This helps to make our test code more modular and organised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfjJCJrtnfgeLqxhdt6pmQ.png" /></figure><h3>9. Grouping Shared Components for Reusability</h3><p>It is vital to identify is similar elements appear on different pages, such as headers, footers, sidebars, hamburger menus</p><p>By identifying these shared components and keeping them in a separate files, as in the point above, we can <strong>avoid repeating the same code across different page objects</strong>. Instead, we write methods to interact with these shared elements just once. This approach not only saves time and effort but also makes our test code more efficient, maintainable, and reusable.</p><h3>10. Developing Reusable Helper Methods</h3><p>Create reusable helper methods for frequently performed tasks, such as authentication, to encapsulate logic and promote code reuse across tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*3OOSw44wNq6pesrChVy37Q.png" /><figcaption>Folders structure</figcaption></figure><h3>11. Logging Test Details for Debugging</h3><p>Augment test execution with comprehensive logging to facilitate efficient debugging and troubleshooting, enabling swift resolution of test failures.</p><pre> addStudent(value: string) {<br>  cy.findByTestId(&#39;student-name&#39;).type(value);<br>  cy.log(`The &quot;${value}&quot; name is added to the studentName`);<br> }</pre><h3>12. Organising Test Data for Efficiency</h3><p>Centralise and categorise test data into dedicated files to promote reusability and maintainability, facilitating streamlined test data management and updates.</p><pre>{<br> &quot;student&quot;: {<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;surname&quot;: &quot;Doe&quot;,<br>  &quot;email&quot;: &quot;johndoe@test.test&quot;,<br> }</pre><h3>13. Prioritising Regular Maintenance</h3><p>Commit to regular review and upkeep of automated tests to ensure alignment with evolving application requirements and sustained effectiveness.</p><p>By embracing these 13 best practices, you can unlock the full potential of test automation, empowering your team to deliver high-quality software with speed and confidence. Embrace automation, streamline your testing processes, and embark on a journey towards software excellence!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e269bb17d72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating Webcam Access in Playwright: Testing Web Apps with Mocked Media Stream and Device]]></title>
            <link>https://medium.com/@sap7deb/simulating-webcam-access-in-playwright-testing-web-apps-with-mocked-media-stream-and-device-f403dbbcb166?source=rss-7759187d2c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f403dbbcb166</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[mediastream]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[webcam]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Saptarshi Deb]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 10:07:14 GMT</pubDate>
            <atom:updated>2023-04-20T10:40:46.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oia4Pf4Ya4oDy_4xkZGcKg.jpeg" /></figure><p>It can be difficult to test a web application that needs access to the webcam when there isn’t a physical device available. Fortunately, online applications that require camera access may be tested with the use of the Playwright test automation framework.</p><p>We’ll go through how to set up Playwright browser parameters to imitate a webcam and device in this blog article.</p><p>Step 1: Installing Playwright</p><p>To get started, you’ll need to install Playwright. You can do this by opening a command prompt or terminal on your machine and typing the following command:</p><pre>npm install -g playwright</pre><p>Step 2: Creating a Playwright configuration file</p><p>Next, make a new file in your project directory called “playwright.config.js”. The Playwright configuration options will be in this file. Here is an illustration of a configuration file that has the options required to simulate a webcam and device:</p><pre>const { devices } = require(&#39;playwright&#39;);<br><br>module.exports = {<br>    projects: [<br>        {<br>            name: &#39;chromium&#39;,<br>            use: {<br>                ...devices[&#39;Desktop Chrome&#39;],<br>                launchOptions: {<br>                    args: [&#39;--disable-web-security&#39;,<br>                        &#39;--use-fake-ui-for-media-stream&#39;,<br>                        &#39;--use-fake-device-for-media-stream&#39;<br>                    ],<br>                }<br>            },<br>        },<br>    ],<br>};</pre><p>The “Desktop Chrome” device settings are being used to create the Playwright project “chromium” in this configuration file. Additionally, we are providing the browser options “ — use-fake-ui-for-media-stream” and “ — use-fake-device-for-media-stream” that are required to impersonate a webcam and device.</p><p>Step 3: Writing the Playwright test script</p><p>You may now create a Playwright test script to test the web application after installing the configuration file. Here is an example test script that launches a browser, accesses the web application, authorises webcam use, and checks to see if the programme is operating as intended:</p><pre>const { chromium } = require(&#39;playwright&#39;);<br><br>describe(&#39;Web application with webcam access&#39;, () =&gt; {<br>    let browser;<br><br>    beforeAll(async () =&gt; {<br>        browser = await chromium.launch({<br>            headless: false,<br>            timeout: 60000,<br>        });<br>    });<br><br>    afterAll(async () =&gt; {<br>        await browser.close();<br>    });<br><br>    it(&#39;should access webcam and function correctly&#39;, async () =&gt; {<br>        const context = await browser.newContext({<br>            ...devices[&#39;Desktop Chrome&#39;],<br>            viewport: null,<br>        });<br>        const page = await context.newPage();<br>         await page.goto(&#39;https://webcamtests.com/&#39;);<br>         await page.locator(&quot;#webcam-launcher&quot;).waitFor({state:&quot;visible&quot;})<br>         await page.click(&quot;#webcam-launcher&quot;)<br>    });<br>});</pre><p>In this test script, a Chromium browser is launched, a new context is created, the web application is navigated to, and the application is interacted with to test its functionality. In order to make sure that the application is being tested in a realistic context, we are also using the “Desktop Chrome” device settings.</p><p>Step 4: Running the Playwright test</p><p>To run the Playwright test, open a command prompt or terminal in your project directory and type the following command:</p><pre>npx playwright test</pre><p>This command will run the test script and output the results to the console. When the test runs you can see that a mock camera output has been displayed in the area where your real webcam output was expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzDmsY9gAqAaGD5HkL9ttg.png" /></figure><p>Conclusion</p><p>When a physical device is not available, testing web applications that require access to the webcam might be challenging. To imitate webcam access and test web applications with a mocked media stream and device, Playwright and the — use-fake-ui-for-media-stream and — use-fake-device-for-media-stream browser options can be used.</p><p>In the above example i have used playwright as the testing tool but as this is configuration for the browser, i believe this could also be used with other UI testing automation tools</p><p>Please Refer to this for more information</p><p><a href="https://stackoverflow.com/questions/52095416/how-can-i-correctly-provide-a-mock-webcam-video-to-chrome">https://stackoverflow.com/questions/52095416/how-can-i-correctly-provide-a-mock-webcam-video-to-chrome</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f403dbbcb166" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Automation Framework for validation of Kafka messages with in Microservices]]></title>
            <link>https://medium.com/@sap7deb/test-automation-framework-for-validation-of-kafka-messages-with-in-microservices-794506d47e18?source=rss-7759187d2c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/794506d47e18</guid>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <dc:creator><![CDATA[Saptarshi Deb]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 07:19:26 GMT</pubDate>
            <atom:updated>2022-09-08T07:19:26.126Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of this article, we would try to understand how we can test the Kafka messages between two or more microservices. But lets try to understand what is Kafka and how it is used to communicate between microservices</p><h3>What is Kafka</h3><p>Kafka is a distributed event store and stream-processing platform. It is an open-source system developed by the Apache Software Foundation written in Java and Scala</p><p>Apache Kafka is an open-source message broker that provides high throughput, high availability, and low latency. Apache Kafka can be used either on its own or with the additional technology from Confluent. Confluent Kafka provides additional technologies that sit on top of Apache Kafka.</p><p>For more details on Kafka and its’s workflow and why is it needed, please refer to the below links</p><p><a href="https://technically.substack.com/p/whats-kafka-and-what-does-confluent">https://technically.substack.com/p/whats-kafka-and-what-does-confluent</a><br><a href="https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works">https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works</a></p><h3>How to create a Kafka event and message</h3><p>If you have read above articles, you should now have some understanding on how Kafka works. The basic workflow of Kafka looks like the below image.</p><p>We have Producers which publish messages to Kafka topics into various Partitions. Then we have Consumers which consume these messages from those specific Topics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mqn-zVEl1dNMj5h8bufX7w.png" /></figure><p>For us to create a framework for testing Kafka messages we must first see how we can produce a simple message.</p><p>Here we are using Java 11 and Gradle and the build tool (you can also use maven)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCq4RVv1QGMLKrONGebFXA.png" /></figure><h4>Dependencies:</h4><pre>implementation group: &#39;org.apache.kafka&#39;, name: &#39;kafka-clients&#39;, version: &#39;3.0.0&#39;<br><br>implementation group: &#39;org.apache.avro&#39;, name: &#39;avro&#39;, version: &#39;1.11.0&#39;</pre><p>Below is the sample code to generate a Kafka message and publish it to a topic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIuFSxyWk90Yp-S5yRHL1g.png" /></figure><p>Here if you see you have defined some properties, these are Kafka config properties where we have to define the bootstrap server, the schema registry, the Avro Serializer that we are using. All these config related service would be running in docker which is we will discuss later</p><h3>What is Apache Avro</h3><p>Avro is a language-independent serialization library. To do this Avro uses a schema which is one of the core components. It stores the schema in a file for further data processing.</p><p>Reference: <a href="https://avro.apache.org/docs/">https://avro.apache.org/docs/</a></p><p>We need to create an Avro schema file in <strong>.avsc</strong> format. For the above example create a <strong>movies.avsc</strong> file</p><pre>{<br>     &quot;type&quot;: &quot;record&quot;,<br>     &quot;namespace&quot;: &quot;com.app&quot;,<br>     &quot;name&quot;: &quot;Movie&quot;,<br>     &quot;version&quot;: &quot;1&quot;,<br>     &quot;fields&quot;: [<br>       { &quot;name&quot;: &quot;movie_name&quot;, &quot;type&quot;: [&quot;null&quot;,&quot;string&quot;], &quot;doc&quot;: &quot;Name of Movie&quot; },<br>       { &quot;name&quot;: &quot;genre&quot;, &quot;type&quot;: [&quot;null&quot;,&quot;string&quot;], &quot;doc&quot;: &quot;Genre of Movie&quot; }<br>     ]<br>}</pre><p>This would be the Kafka schema for the Topic. To make to simple for us to use the schema, we can generate a POJO class for the above json schema Avro, Add the following task in build.gradle</p><pre>import com.github.davidmc24.gradle.plugin.avro.GenerateAvroJavaTask</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8k4Y4E1V_ug2q5GnwbT1Q.png" /></figure><p>Then run the below gradle command</p><pre>./gradlew generateAvro</pre><p>This task would generate the Java classes from the <strong><em>.avsc</em></strong> files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SsLBqF1CIGRp9qT-3ZwOvQ.png" /></figure><h3>How to run Kafka locally</h3><p>We can do this using docker. We have created a docker-compose with all the dependencies. Please refer below</p><p><a href="https://github.com/sap7deb/kafka-validation-framework-/blob/main/docker-compose.yml">https://github.com/sap7deb/kafka-validation-framework-/blob/main/docker-compose.yml</a></p><p>Run the command</p><pre>docker-compose -f &quot;docker-compose.yml&quot; up -d</pre><p>Do a docker ps and see if all the container are running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbu_8jBzMBhsgrwcSkcmMQ.png" /></figure><p>Once all the image are up and running, open <a href="http://localhost:9021/clusters">http://localhost:9021</a><br>You should see the <a href="https://docs.confluent.io/platform/current/control-center/index.html">control-center</a> dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oa3It-pCUQfM-RJnbircCQ.png" /></figure><p>This is where you can see all the topic that are created and messages that are published</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR6Z6Q5zrkR0C6X7WF6JEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQFYYRs9jjIsyNPV5_sAlw.png" /></figure><p>Now lets run the Producers, as you might have noticed that in the Producer we have used the Topic name <strong><em>movies </em></strong>in the code and used Movies class which was generated using Avro to create the message</p><pre>Movie movie = new Movie();<br>movie.setMovieName(&quot;Batman&quot;);<br>movie.setGenre(&quot;Fiction&quot;);</pre><p>Once the message is published, topic gets automatically created and can be seen in control-center</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNtzeG9InhCX6ylUNxPtHg.png" /></figure><p>The message that is published can also be seen here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2DQwtMIxPiqi8eV4YMVtg.png" /></figure><h3>How to consume the message</h3><p>We can do this with Kafka consumers. Now that we have successfully published a message, we should also be able to consume it so as to complete the communication between services.</p><p>Below is the sample code for Kafka consumer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUwIwGPDjLWajjszPHJ9Bg.png" /></figure><p>For consumption of messages we need consumer group, each consumer can connect to a consumer group retrieve messages for a specific topic. In this example we are consuming from the topic <strong><em>movies</em></strong> in which we have published</p><h3>How to create a Test Automation Framework</h3><p>Now that we have successfully created a Kafka producer and consumer, we can use that same thing to create a framework to validate the messages.</p><p>Lets us consider a scenario where we have two microservices, 1st service publishes a specific message to Topic A, the 2nd service consumes the message from that topic, processes the data and then publishes a new message to Topic B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZflC4qK-rNT_b_eS2nrtGg.png" /></figure><p>Lets say, we want to do validation on the 2nd service, in this case we can create a framework where we publish a message to Topic A and then consume the messages from topic B and validate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfp8VYw2tdUTgQe3Ofzw3A.png" /></figure><p>We have used cucumber with kafka-client to create the framework. You can clone this Github repo to get the framework<br><a href="https://github.com/sap7deb/kafka-validation-framework">https://github.com/sap7deb/kafka-validation-framework</a></p><h3>How to define the Producer and Consumers</h3><p>We have used a cucumber feature file define the scenarios and steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nSFCKAFPthM3ZrYx2oH1A.png" /></figure><p>In the <strong>Given</strong> steps we create the message to to be published</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHR7b69ZjwXT2kBj-orLWQ.png" /></figure><p>We use the Kafka producer to publish the message in <strong>When</strong> step. This published the message to the topic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q6BmCQX6sGm8PctPvw8GA.png" /></figure><p>And then consume and validate the message in the <strong>Then</strong> step. We start consuming messages from the topic and assert the vales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miFiKfo6-YDY-6MEFNVAIg.png" /></figure><p>Once the step are defined for the scenario, we would use a <strong><em>Runner</em></strong> to execute the feature files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGi5R1QSzDGI-cpN0DlsBw.png" /></figure><h3>How to run the Tests</h3><p>To run the tests we added a Gradle task <em>kafkaTests</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*mwCDLeObza-TywO5JIhyRg.png" /></figure><p>On triggering the task, we can see the scenarios getting run and it generates a html report under Reports folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIEYnd7BjxfAikBmFQagsA.png" /></figure><p>You can also specify a particular Partition in which the message would get published on that Topic and also assign a key for that message. Doing that might be helpful as there might be a lot of messages coming into that Topic at that point of time as it might be used by multiple services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TFBZWGBYcREXUanHhqy6w.png" /></figure><p>Similarly you have to configure your consumer to consume messages from specific partition and then use the <strong><em>Key</em></strong> value to filter out messages for validation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFmhxt-60-nffTbj30fcXA.png" /></figure><p>This is just to provide an idea on how to setup a framework for event driven microservices. The framework can always be modified o fit you use-case.</p><p>I hope you’ve enjoyed the article, and if you’ve found it useful, please feel free to share with others or leave a comment.</p><p><strong>Source Code</strong>: <a href="https://github.com/sap7deb/kafka-validation-framework">https://github.com/sap7deb/kafka-validation-framework</a></p><h4>Reference Links:</h4><p><a href="https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/">https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/</a><br><a href="https://technically.substack.com/p/whats-kafka-and-what-does-confluent">https://technically.substack.com/p/whats-kafka-and-what-does-confluent</a><br><a href="https://en.wikipedia.org/wiki/Apache_Kafka">https://en.wikipedia.org/wiki/Apache_Kafka</a><br><a href="https://docs.confluent.io/platform/current/control-center/index.html">https://docs.confluent.io/platform/current/control-center/index.html</a><br><a href="https://www.baeldung.com/java-apache-avro">https://www.baeldung.com/java-apache-avro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794506d47e18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>