<?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 Suryakanta Mohapatra on Medium]]></title>
        <description><![CDATA[Stories by Suryakanta Mohapatra on Medium]]></description>
        <link>https://medium.com/@suryakanta.dev?source=rss-ff77cba6ac2b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HtTIRT8gkEBxpD8oJWKyqQ.jpeg</url>
            <title>Stories by Suryakanta Mohapatra on Medium</title>
            <link>https://medium.com/@suryakanta.dev?source=rss-ff77cba6ac2b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:07:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suryakanta.dev/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[From Fragile Locators to Unbreakable Tests: Semantic Similarity with Sentence Embeddings]]></title>
            <link>https://medium.com/@suryakanta.dev/from-fragile-locators-to-unbreakable-tests-semantic-similarity-with-sentence-embeddings-110a10fe75ea?source=rss-ff77cba6ac2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/110a10fe75ea</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[ai-test-automation]]></category>
            <dc:creator><![CDATA[Suryakanta Mohapatra]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 22:55:48 GMT</pubDate>
            <atom:updated>2026-01-26T22:55:48.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CeA4pjfA2N-z2yCP6rC8Q.png" /></figure><p>For years, UI test automation has been plagued by fragile locators. A single change to an HTML ID, class name, or button text can break dozens of tests overnight. Teams waste countless hours maintaining xPaths and CSS selectors that depend on the exact structure of the markup.</p><p>What if your tests could <strong>understand the meaning</strong> behind elements instead of relying on their exact appearance?</p><p>That’s exactly what <strong>semantic similarity with sentence embeddings</strong> enables — and it’s one of the most powerful, accessible, and fully open-source ways to make your UI tests truly resilient today.</p><h3>The Core Idea: Meaning, Not Markup</h3><p>Sentence embedding models (like <em>all-MiniLM-L6-v2 </em>from the Sentence Transformers library) take any piece of text — a button label, aria-label, title, or even your natural language description — and convert it into a dense numerical vector (typically 384 dimensions).</p><p>These vectors live in a high-dimensional space where <strong>semantically similar phrases are close together</strong>, even if the wording is different.</p><p>For example:</p><ul><li>“Add Sauce Labs Backpack to cart”</li><li>“Add to bag”</li><li>“Purchase this item”</li><li>“Añadir al carrito” (Spanish)</li></ul><p>All produce vectors pointing in nearly the same direction because they share the same intent.</p><p>We measure closeness using <strong>cosine similarity</strong> — a score from -1 to 1, where values near 1 indicate a strong semantic match.</p><p>This turns element location into a <strong>semantic search problem</strong>: extract candidate texts from the page, embed them, embed your intent, and pick the closest match above a confidence threshold.</p><p>No more breaking when text changes slightly. No more failing on localization. No more hunting for dynamic IDs.</p><h3>Why This Technique Stands Out</h3><ul><li><strong>Fully local &amp; fast</strong>: Runs on CPU in milliseconds, no API keys or internet required.</li><li><strong>Lightweight</strong>: The model is only ~80MB.</li><li><strong>Deterministic</strong>: No randomness like with LLMs.</li><li><strong>Zero training needed</strong>: Pre-trained on general language, works out-of-the-box for most UI text.</li><li><strong>Highly resilient</strong>: Survives redesigns, A/B tests, and dynamic content.</li></ul><h3>Core Concept: Turning Words into “Meaning Vectors”</h3><p>Modern AI models (like <em>all-MiniLM-L6-v2</em>) take any sentence or phrase — such as a button’s visible text, aria-label, or your natural language description — and convert it into a fixed-length numerical vector. These vectors are positioned in a high-dimensional “vector space” where semantically similar texts are close together.</p><p>To illustrate, imagine embedding this word set:</p><pre>[&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;juice&quot;, &quot;jam&quot;,<br> &quot;car&quot;, &quot;truck&quot;, &quot;bike&quot;, &quot;parts&quot;, &quot;petrol&quot;, &quot;diesel&quot;, &quot;road&quot;,<br> &quot;dog&quot;, &quot;cat&quot;, &quot;wolf&quot;, &quot;pet&quot;, &quot;veterinary&quot;, &quot;animals&quot;]</pre><p>When reduced to 2D using t-SNE or UMAP, you’d clearly see three clusters: fruits, vehicles, and animals — even though no clustering algorithm was explicitly told the categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-QDxlZcnG_SdAb-m6KBeSA.png" /><figcaption>2D graph showing clusters</figcaption></figure><p>Here’s the code to generate such a visualization yourself:</p><pre>from sentence_transformers import SentenceTransformer<br>from sklearn.manifold import TSNE<br>import plotly.express as px<br><br># 1. Load the model and your words<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>words = [&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;juice&quot;, &quot;jam&quot;,<br>         &quot;car&quot;, &quot;truck&quot;, &quot;bike&quot;, &quot;parts&quot;, &quot;petrol&quot;, &quot;diesel&quot;, &quot;road&quot;,<br>         &quot;dog&quot;, &quot;cat&quot;, &quot;wolf&quot;, &quot;pet&quot;, &quot;veterinary&quot;, &quot;animals&quot;]<br><br># 2. Convert words to vectors (embeddings)<br>embeddings = model.encode(words)<br><br># 3. Reduce 384 dimensions to 2D using t-SNE<br>tsne = TSNE(n_components=2, perplexity=3, random_state=42, init=&#39;pca&#39;, learning_rate=&#39;auto&#39;)<br>vis_dims = tsne.fit_transform(embeddings)<br><br># 4. Create an interactive scatter plot<br>fig = px.scatter(x=vis_dims[:, 0], y=vis_dims[:, 1], text=words,<br>                 color=vis_dims[:, 0], color_continuous_scale=&#39;Viridis&#39;)<br>fig.update_traces(textposition=&#39;top center&#39;)<br>fig.update_layout(<br>  plot_bgcolor=&#39;plum&#39;, <br>  paper_bgcolor=&#39;plum&#39;,               <br>  width=800, height=480, <br>  margin=dict(l=20, r=20, t=40, b=20),# Outer margin area<br>  # This section draws the axis lines<br>  xaxis=dict(showline=True, linewidth=1, linecolor=&#39;black&#39;, mirror=False),<br>  yaxis=dict(showline=True, linewidth=1, linecolor=&#39;black&#39;, mirror=False),<br>)<br>fig.show()</pre><p>In UI testing, this clustering means “Add to cart”, “Add to bag”, and “Purchase item” naturally group together — allowing your test to find the right element even if the exact text changes. To find the best match, we compute <strong>cosine similarity</strong> — essentially the angle between vectors. A score close to 1 means high similarity (same intent); close to 0 means unrelated.</p><h3>How the Model Works</h3><p>The all-MiniLM-L6-v2 is a distilled version of BERT, fine-tuned specifically for <strong>sentence-level similarity</strong> using siamese networks (training pairs of similar/dissimilar sentences). It’s tiny (~80MB), runs fast on CPU, and outperforms larger models on semantic tasks.</p><p>In your test:</p><ol><li>Extract text + context from all candidate elements (buttons, links, etc.).</li><li>Encode them (and your intent description) into vectors.</li><li>Find the candidate with the highest cosine similarity.</li><li>If above a threshold (e.g., 0.4), interact with it via a robust Playwright locator.</li></ol><p>This makes tests survive:</p><ul><li>Text changes (“Add to cart” → “Add to basket”)</li><li>Localization</li><li>Dynamic attributes</li><li>Minor redesigns</li></ul><p>It’s deterministic, fully local, and needs no training data from your app — the pre-trained model already “understands” language meaning.</p><p>In UI testing context, it turns element location into a <strong>semantic search problem</strong>, much like how search engines find relevant pages.</p><p>Start with this technique — it’s the biggest quick win for reducing flakiness while keeping things simple and open-source! 🚀</p><h3>Full Runnable Example with Playwright</h3><p>Here’s a complete implementation that works reliably on <a href="https://www.saucedemo.com/">sauce-demo</a> website</p><pre>from playwright.sync_api import sync_playwright<br>from bs4 import BeautifulSoup<br>from sentence_transformers import SentenceTransformer, util<br>import torch<br><br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br>def find_by_semantics(current_page, description: str, threshold: float = 0.35):<br>    html = current_page.content()<br>    soup = BeautifulSoup(html, &#39;html.parser&#39;)<br><br>    candidates = []<br>    elements = soup.find_all([&#39;button&#39;, &#39;a&#39;, &#39;input&#39;, &#39;div&#39;, &#39;span&#39;, &#39;label&#39;, &#39;h1&#39;, &#39;h2&#39;, &#39;h3&#39;, &#39;h4&#39;, &#39;img&#39;])<br><br>    for elem in elements:<br>        text = elem.get_text(strip=True)<br>        attrs = &#39; &#39;.join([<br>            str(v) if not isinstance(v, list) else &#39; &#39;.join(v)<br>            for k, v in elem.attrs.items()<br>            if k in [&#39;id&#39;, &#39;class&#39;, &#39;aria-label&#39;, &#39;title&#39;, &#39;role&#39;, &#39;placeholder&#39;, &#39;alt&#39;, &#39;data-test&#39;] and v<br>        ])<br>        if text or attrs:<br>            candidate_str = f&quot;{elem.name} | Text: {text} | Attributes: {attrs}&quot;<br>            candidates.append((candidate_str, elem, text.strip()))<br><br>    if not candidates:<br>        raise ValueError(&quot;No candidate elements found on the page.&quot;)<br><br>    print(f&quot;Found {len(candidates)} candidate elements. Encoding...&quot;)<br><br>    candidate_texts = [c[0] for c in candidates]<br>    desc_embedding = model.encode(description, convert_to_tensor=True)<br>    candidate_embeddings = model.encode(candidate_texts, convert_to_tensor=True)<br><br>    similarities = util.cos_sim(desc_embedding, candidate_embeddings)[0]<br>    best_idx = torch.argmax(similarities).item()<br>    best_score = similarities[best_idx].item()<br><br>    print(f&quot;Best match score: {best_score:.3f} → {candidate_texts[best_idx][:200]}&quot;)<br><br>    if best_score &lt; threshold:<br>        raise ValueError(f&quot;No good match found. Best score {best_score:.3f} &lt; threshold {threshold}&quot;)<br><br>    matched_elem = candidates[best_idx][1]<br>    visible_text = candidates[best_idx][2]<br><br>    # Playwright locator with fallbacks<br>    if visible_text:<br>        locator = current_page.get_by_text(visible_text, exact=False).first<br>        if locator.is_visible(timeout=1000):<br>            return locator<br>        return current_page.locator(f&quot;:has-text(&#39;{visible_text}&#39;)&quot;).first<br><br>    if matched_elem.get(&#39;aria-label&#39;):<br>        return current_page.get_by_label(matched_elem[&#39;aria-label&#39;])<br>    if matched_elem.get(&#39;alt&#39;):<br>        return current_page.get_by_alt_text(matched_elem[&#39;alt&#39;])<br><br>    # Ultimate selector fallback<br>    if matched_elem.get(&#39;id&#39;):<br>        selector = f&quot;#{matched_elem[&#39;id&#39;]}&quot;<br>    elif matched_elem.get(&#39;class&#39;):<br>        class_list = matched_elem[&#39;class&#39;]<br>        selector = matched_elem.name + &quot;.&quot; + &quot;.&quot;.join(class_list)<br>    else:<br>        selector = matched_elem.name<br><br>    return current_page.locator(selector).first<br><br># Full demo script<br>with sync_playwright() as p:<br>    browser = p.chromium.launch(headless=False)<br>    page = browser.new_page()<br>    page.goto(&quot;https://www.saucedemo.com/&quot;)<br><br>    page.fill(&quot;#user-name&quot;, &quot;standard_user&quot;)<br>    page.fill(&quot;#password&quot;, &quot;secret_sauce&quot;)<br>    page.click(&quot;#login-button&quot;)<br>    page.wait_for_load_state(&quot;networkidle&quot;)<br><br>    add_btn = find_by_semantics(page, &quot;Add to cart button for Sauce Labs Backpack&quot;)<br>    add_btn.click()<br><br>    cart = find_by_semantics(page, &quot;shopping cart link or badge&quot;)<br>    cart.click()<br><br>    print(&quot;Semantic technique completed successfully!&quot;)<br>    browser.close()</pre><h3>Final Thoughts</h3><p>Semantic similarity with sentence embeddings marks a fundamental shift from <strong>syntactic</strong> (markup-dependent) to <strong>semantic</strong> (intent-driven) test automation.</p><p>Your tests no longer break because of superficial UI changes — they start understanding the page like a human tester.</p><p>And the best part? You can implement this <strong>today</strong> with fully open-source tools, zero cost, and no vendor lock-in.</p><p>This is the biggest quick win for dramatically reducing test flakiness while keeping everything simple, fast, and reliable.</p><p>Start experimenting — the era of locator maintenance hell is over.</p><p>Happy testing! 🚀</p><p><strong>References</strong>:</p><ul><li>Sentence Transformers library and models: <a href="https://www.sbert.net/">https://www.sbert.net/</a></li><li>all-MiniLM-L6-v2 model: <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2</a></li><li>Original Sentence-BERT paper: Reimers, Nils, and Iryna Gurevych. “Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks.” EMNLP-IJCNLP 2019. <a href="https://arxiv.org/abs/1908.10084">https://arxiv.org/abs/1908.10084</a></li><li>Playwright Python documentation: <a href="https://playwright.dev/python/">https://playwright.dev/python/</a></li></ul><p>Want to stay updated on the latest in AI-powered test automation, self-healing techniques, and making flaky tests a thing of the past? Follow me on <a href="https://www.linkedin.com/in/suryakmo/">LinkedIn</a> for more practical deep dives and code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=110a10fe75ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shift-Left iOS Testing with Focus Flows]]></title>
            <link>https://eng.lyft.com/shift-left-ios-testing-with-focus-flows-c9e050bd2095?source=rss-ff77cba6ac2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e050bd2095</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[shift-left-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Suryakanta Mohapatra]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 17:19:03 GMT</pubDate>
            <atom:updated>2022-10-12T17:19:03.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1aMbIhVcgrTnY_RK1ATJg.png" /></figure><h3><strong>Pain Points of Traditional Automated UI Tests</strong></h3><p>Creating a great modern-day software product requires a shift-left approach to testing by ensuring faster, more frequent, and earlier testing. <a href="https://en.wikipedia.org/wiki/Shift-left_testing">Shift-left testing</a> is <em>an approach to software testing and system testing in which testing is performed earlier in the lifecycle (i.e., moved left on the project timeline)</em>. The current standard of automated mobile testing is less effective in implementing the shift-left approach due to some inherent challenges such as <strong>time </strong>and <strong>flakiness </strong>of test executions.</p><p>Most automated tests complete some irrelevant steps in order to reach the application state where the real assertions happen. Let’s explore an example of testing the <a href="https://www.lyft.com/rider/lyftpass">Lyft Pass</a><strong> </strong>details<strong> </strong>screen of the Lyft Rider app. The test sequence is as follows:</p><ol><li>Log in</li><li>Tap the hamburger menu</li><li>Tap payment</li><li>Select a Lyft Pass</li><li>Verify behavior on the Lyft Pass details page</li></ol><p>In the above example, the test controller must execute all the pre-conditional steps before finally testing the Lyft Pass<strong> </strong>details<strong> </strong>screen, even if they are of little to no relevance. These pre-conditional UI steps increase the time of execution and its flakiness. If the test fails, there is a high probability that the cause of failure is something other than what the test is verifying.</p><p>One way to address these issues would be to remove the pre-conditional UI steps and focus only on the flow that the test cares about. Removing the pre-conditional steps would allow the tests to execute in less time compared to when executing the full test flow. It would also bring down the flakiness because the test would no longer be impacted by these steps, and the failure would be limited to the actual assertion of the test.</p><h3>Focus Flows: The Panacea</h3><p>We introduced the concept of Focus Flows to address the above concerns. A Focus Flow is a mini application that’s independent of other modules and compiles a smaller (“focused”) flow of a specific product feature. It runs in a reduced environment which carries both the session state (configs, feature flags, service state, user account) and device state (device settings, simulated locations, stored values) that is expected for the feature to function properly.</p><p>Let us take an example of the same Lyft Pass scenario. The Focus Flow starts the application right from the Lyft Pass<strong> </strong>details<strong> </strong>screen without going through any of the previous steps such as login, the hamburger menu, payment, etc. It has the same device and session state as that of a real-life Lyft Pass scenario. This reduces the time spent on executing the test tremendously and fixes the flakiness that may have otherwise been caused by the pre-conditional test steps. Since the flow depends on only a subset of the app’s features, we can use it to test a small piece of the app without waiting for the whole application to be compiled.</p><p>Now that we’ve introduced Focus Flows, let’s take a closer look at how traditional UI tests compare to Focus Flows, assuming that we have a page-driven framework available for our automation which uses <em>XCUITest</em> to run the tests. In order to keep things simple, this post limits the discussion to only Focus Flows, and does not go deeper into test framework details.</p><p>Let’s take the same example of the Lyft Pass<strong> </strong>details page verification<strong>. </strong>Lyft Pass is a promo code given by an organization to their employees that covers all or a portion of the cost of their rides. The traditional flow to reach the Lyft Pass details screen requires the controller to pass through steps 1 through 9 as depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4C4QMKduU3liayFE6AEqCA.png" /><figcaption>Traditional Test Flow To Verify Lyft Pass Details</figcaption></figure><h3>Traditional Automated UI Tests</h3><p>The code for the traditional way of automating the above scenario would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b20118a7c1ef8d5de002e1d879a9b7/href">https://medium.com/media/94b20118a7c1ef8d5de002e1d879a9b7/href</a></iframe><p>As we can see from the above code snippet, the automated test:</p><ol><li>Logs in</li><li>Navigates to the payment section</li><li>Taps the Lyft Pass</li><li>Verifies that the details of the Lyft Pass are loaded and rendered</li></ol><p>The primary goal of the test is to verify that the Lyft Pass details are loaded correctly. Due to the limitations of the traditional setup, the test has to navigate through many unrelated steps like logging in, navigating to payment<em>,</em> etc., which increases the test execution time and could introduce flakiness. Consider the following scenarios:</p><ol><li>Lyft Pass details page works but logging in fails</li><li>Lyft Pass details page works but the hamburger menu button is broken</li><li>Lyft Pass details page verification takes 2 seconds to load and test, but getting there takes 30 seconds</li></ol><p><strong>Pre-Assertion Failures: </strong>In scenarios 1 and 2, the test fails for reasons that have nothing to do with the Lyft Pass details page. These pre-assertion failures increase the overall flakiness of the test.</p><p><strong>Pre-Assertion Delays</strong>: Scenario 3 spends a greater percentage of time on the steps that the test does not intend to verify than it does on the screen actually being tested.</p><h3>Focus Flow Automated UI Tests</h3><p>In contrast, the code below shows a Focus Flow test in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ace66d1299e00c4798e8428941e0f3f9/href">https://medium.com/media/ace66d1299e00c4798e8428941e0f3f9/href</a></iframe><p>As shown by the above code snippet, the test does not go through all the previously required steps such as logging in and navigating to payments. The Focus Flow starts the app right from the Lyft Pass details screen by providing the module with all of its necessary configuration, removing the need for the previous screens in the test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WY5-1UkfBBLpCI9q0cgYEw.png" /><figcaption>Focus Flow Enabled Test Flow To Verify Lyft Pass Details</figcaption></figure><h3><strong>How to Design Flow-Based UI Tests</strong></h3><p>Our apps are built leveraging what we call a Flow Architecture (more details in <a href="https://www.scottberrevoets.com/2021/10/14/ios-architecture-at-lyft/">this post</a>). At a high level, rather than depending on one monolithic router to drive the entire application, this architecture relies on a set of smaller, composable routers. Each router encapsulates a Flow, which is what Focus Flows are built on top of.</p><p>Creating features in isolation like this allowed us to split Focus Flows out of the main application for rapid iteration and testing. At Lyft, we <a href="https://www.youtube.com/watch?v=-u40WqvdRsg">utilize Bazel</a> to provide application targets for each Focus Flow, but a similar result for UI tests could be achieved through some other mechanism for jumping to specific features (such as a menu, deeplinks, etc.). When doing so, it’s important that the destination screen is injected with any required state such as authentication, location information, and feature flags. The specifics of how this is implemented will vary by architecture, but we were able to extend our dependency injection system to allow for customization from both tests and Focus Flows. Here’s an example of how we initialize a Focus Flow for testing purposes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/847058a9814c13c8c8ca3ef9457d9b31/href">https://medium.com/media/847058a9814c13c8c8ca3ef9457d9b31/href</a></iframe><h3>Performance Analysis</h3><p>We executed the Lyft Pass details scenario using both the traditional and Focus Flow automations. The results showed that the Focus Flow approach outperformed the traditional test automation both in terms of speed and reliability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ACWpRKFfGX9sVbraqyIXCA.png" /><figcaption>Performance Comparison Between Traditional and Focus Flow Tests</figcaption></figure><h3>Takeaways</h3><p>Running our tests with Focus Flows has reduced execution time and flakiness by enabling us to skip irrelevant steps in test scenarios. Although Focus Flows provide an excellent tool for iterating and testing quickly and reliably, they haven’t replaced our smoke tests or end-to-end test suite since they’re focused on smaller features of the app while smoke tests are focused on broader end-to-end workflows. Nonetheless, Focus Flows have been an excellent addition to our testing strategy, and help us to quickly deliver features with the best possible quality.</p><h3>Acknowledgments</h3><p>Special thanks to <a href="https://www.linkedin.com/in/gonzalolarralde/">Gonzalo Larralde</a> for introducing me to Focus Flows. Thanks to <a href="https://www.linkedin.com/in/edricta/">Edric Ta</a>, <a href="https://www.linkedin.com/in/patelchhaya/">Chhaya Patel</a> and <a href="https://www.linkedin.com/in/gowthamjs/">Gowtham J S</a> for the support reviewing this article!</p><p><em>We are looking for talented engineers like you. If you’re interested in mobile test engineering, check out our </em><a href="https://www.lyft.com/careers"><em>careers page</em></a><em>.</em></p><p><em>Happy testing!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e050bd2095" width="1" height="1" alt=""><hr><p><a href="https://eng.lyft.com/shift-left-ios-testing-with-focus-flows-c9e050bd2095">Shift-Left iOS Testing with Focus Flows</a> was originally published in <a href="https://eng.lyft.com/">Lyft Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticating REST services behind AWS API Gateway]]></title>
            <link>https://medium.com/@suryakanta.dev/authenticating-rest-services-behind-aws-api-gateway-5ddad8b1f187?source=rss-ff77cba6ac2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ddad8b1f187</guid>
            <category><![CDATA[api-test-automation]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[restassured]]></category>
            <dc:creator><![CDATA[Suryakanta Mohapatra]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 07:55:01 GMT</pubDate>
            <atom:updated>2021-09-14T07:56:17.921Z</atom:updated>
            <content:encoded><![CDATA[<p>I am sure many of you have experience in working with APIs secured behind AWS API gateway. In order for us to do a rest call to those APIs, it must be supplemented with an authentication token in the header. Usually, when such calls are invoked from mobile/web applications the token is generated by AWS Amplify. AWS Amplify has SDKs for each of these platforms. But in this article, I will put focus on how to deal with authentication while performing automated API testing in a Java-based test framework.</p><p>Let me explain the context.</p><p>I have a set of REST APIs secured behind API Gateway. All these APIs need to be tested from an automation test framework(Java-based) using the Rest-Assured library. In order for my test scripts to make REST calls to any of these APIs, the call should be well authenticated with an authorization token. The authorization token is provided by AWS Cognito which stores a pool of users who have already signed up to access the resources. To make it look simple, the below image shows how AWS Cognito helps in authenticating for Mobile/ Web Client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*Ja8ZsBa--iHK2Nv-tesvwg.png" /><figcaption>Authentication using AWS Cognito</figcaption></figure><p>Now we will see how to get authenticated when the authorization is initiated from a Java test script. The authentication token is generated once per test execution session and can be used in the header to make REST calls for all the APIs as defined in the test script. The below image gives a clear idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkLHWKK7eHEwQzFMzaZlsw.png" /><figcaption>API Testing with authorization token from Cognito User Pool</figcaption></figure><p>As we can see from the above image, every test in the test suite extends to a common parent test called Base Test. The Base-Test is responsible for dealing with both setup(all prerequisites before the test starts) and teardown(clean up after test execution is over). As every test down the lane in the test suite require the Authorization token in the header before attempting to make REST calls, it is obvious to initialize the auth token right in the setup(@BeforeSuite) method of the Base Test. To make the overall framework well organized, we should have a separate utility class to fetch the token which is called inside the BaseTest Setup method. The Fetch_Token_Utility class looks something like follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f6105b74aada77ca4ba555c0807a2c6/href">https://medium.com/media/0f6105b74aada77ca4ba555c0807a2c6/href</a></iframe><p>As you can see, I have used some of the AWS libraries functions to use the following attributes, which are needed to fetch the authorization token from Cognito.</p><ul><li>AWS &lt;accessKey&gt; of the user</li><li>AWS &lt;secretKey&gt; of the user</li><li>&lt;userName&gt; of the user in the Cognito user pool</li><li>&lt;password&gt; of the user in the Cognito user pool</li><li>&lt;clientId&gt; of the App client present in Cognito user pool</li></ul><p>We have to make sure the enable password_based_authentication flow in the Cognito App Client settings by checking it in order for the above method to work. Refer to the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZwTpiA0Frv-B5ADH-Ft7g.png" /><figcaption>enabling username and password-based authentication in Cognito</figcaption></figure><p>The list of Maven dependencies to use the AWS libraries are:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>  &lt;artifactId&gt;aws-java-sdk&lt;/artifactId&gt;<br>  &lt;version&gt;1.11.360&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>  &lt;artifactId&gt;aws-java-sdk-core&lt;/artifactId&gt;<br>  &lt;version&gt;1.11.360&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>  &lt;artifactId&gt;aws-java-sdk-cognitoidp&lt;/artifactId&gt;<br>  &lt;version&gt;1.11.360&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Once we have the above FetchTokenUtility class, the tests and BaseTest will look something like below:</p><pre>public class APITestFeatureA extends APIBaseTest {<br>    @Test(groups = {&quot;arts-api&quot;, &quot;client_ops&quot;, &quot;orchestrator&quot;})<br>    public void testFunctionA(ITestContext context, Method method){<br>        &lt;Code&gt;<br>    }<br><br>    @Test(groups = {&quot;arts-api&quot;, &quot;client_ops&quot;, &quot;orchestrator&quot;})<br>    public void testFunctionB(ITestContext context, Method method){<br>        &lt;Code&gt;<br>    }<br>}</pre><pre>public class APIBaseTest {<br>    <br>    @BeforeSuite<br>    public void setUpAgent(){<br>        RestAssured.<em>baseURI </em>= EnvironmentParams.<em>API_BASE_URI</em>;<br>        headers.put(&quot;Authorization&quot;, &quot;Bearer &quot;+FetchTokenUtility.getToken());<br>    }<br>    <br>    @AfterSuite<br>    public void tearDown(){<br>        &lt;CleanUp code&gt;<br>    }<br>    <br>}</pre><p>With all these setups, when we run the tests, every REST call header will contain an authentication token to access secured APIs further. There are multiple ways of getting authentication tokens from the Cognito user pool such as SRP-based, custom authentication, etc. But we have explored the username and password way of authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ddad8b1f187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting Personal Identifiable Information with LexNLP]]></title>
            <link>https://medium.com/cisco-fpie/protecting-personal-identifiable-information-with-lexnlp-c5da752562bf?source=rss-ff77cba6ac2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5da752562bf</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Suryakanta Mohapatra]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 20:12:48 GMT</pubDate>
            <atom:updated>2021-03-26T20:12:48.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aloi3LBUY-bJE7MnniOTJw.png" /></figure><p>It is no wonder companies are taking stringent measures to make sure they are fully compliant towards EU’s General Data Protection Regulations (<a href="https://gdpr-info.eu/"><em>GDPR</em></a>) which protects privacy of Personally Identifiable Information(<a href="https://en.wikipedia.org/wiki/Personal_data"><em>PII</em></a>) of EU residents, a lot more stricter regulations are coming sooner than later such as California Privacy Right Act in 2023, SAFE DATA Act by the end of 2021. Hence protecting PII is becoming a matter of paramount importance to businesses.</p><p>On the other hand, it is quite burdensome for humans to verify each and every public medium at their disposal to check if it contains PII. Hence, in this article we will delve deeper to understand how to retrieve textual information from an image by Optical Character Recognition(<a href="https://en.wikipedia.org/wiki/Optical_character_recognition">OCR</a>)<em> </em>and how to use a Natural Language Processing Library called <a href="https://lexpredict-lexnlp.readthedocs.io/en/latest/"><em>LexNLP</em></a><em> </em>to process the extracted text to check if it contains any PII. This is the output of a recent hackathon I participated.</p><p>So, to give a high-level overview, first we will walk through <a href="https://en.wikipedia.org/wiki/Optical_character_recognition"><em>OCR</em></a>, its application and at the end we will see how <a href="https://lexpredict-lexnlp.readthedocs.io/en/latest/"><em>LexNLP</em></a> helps to detect presence of PII. In order to tie everything together we’ll write a simple python script that helps extract text and checks for PII. All these are exposed via a Flask web application for the convenience of user interactivity.</p><p><strong>Optical Character Recognition</strong></p><p>Optical Character Recognition or <a href="https://en.wikipedia.org/wiki/Optical_character_recognition"><em>OCR</em></a> is a technology that helps detect the presence of textual information in an image and extract the machine encoded text from it which the computer understands. Detecting text information through automated processes is not as trivial as it appears to humans. Behind the scenes is a series of complicated processes involving image processing and implementation of other complex algorithms which finally extracts the text. To the computer the processed image contains only matrix of white and black dots. Extraction involves multiple phases such as Despeckle, Binarisation, Line removal, Layout analysis, script recognition, segmentation, and normalization, Matrix matching and post processing. We will keep these jargons out of scope of this article for simplicity.</p><p>Here in this article, we will stick to <a href="https://pypi.org/project/pytesseract/"><em>PyTesseract</em></a> library to retrieve text from an image. This is a wrapper for Google’s Tesseract-OCR engine. There are other libraries also that can be used such as Pyocr.</p><p><strong>Natural Language Processing</strong></p><p>Although this is a vast field in itself which primarily involves with interaction between computers and human language in order to process and analyze large amount of natural language data, here we will use this technology via an open-source library called <a href="https://lexpredict-lexnlp.readthedocs.io/en/latest/"><em>LexNLP</em></a> to extract PII from a textual content.</p><p><strong>Technology stack we will use</strong></p><p>For this project, we are going to use the following</p><ul><li><a href="https://pypi.org/project/pytesseract/"><em>PyTesseract</em></a> for Optical Character Recognition</li><li><a href="https://flask.palletsprojects.com/en/1.1.x/"><em>Flask</em></a> web framework for OCR server</li><li><a href="https://pillow.readthedocs.io/en/stable/"><em>Pillow</em></a> library for image manipulation</li><li><a href="https://lexpredict-lexnlp.readthedocs.io/en/latest/"><em>LexNLP</em></a> for extracting PII</li></ul><p><strong>Getting our hands dirty</strong></p><p>Enough of this explanations, now let’s build the real thing which in layman’s term will provide us with a web page that allows a user to upload an image, snapshot or scanned photo to the server and get back information from the image along with any <a href="https://en.wikipedia.org/wiki/Personal_data"><em>PII</em></a> that may be present.</p><p>Initially we are going to install all the prerequisite for this project. Then we will develop the flask framework needed for ease of user interaction.</p><p>We will use <a href="https://pypi.org/project/pip/"><em>pip</em></a> to install software packages. Install pip by following the below steps:</p><p>Manually download the get-pip.py from <a href="https://bootstrap.pypa.io/get-pip.py">here</a> or use curl command to do so.</p><pre>curl <a href="https://bootstrap.pypa.io/get-pip.py">https://bootstrap.pypa.io/get-pip.py</a> -o get-pip.py</pre><p>Then, navigate to the folder where get-pip.py is downloaded and run the following command to install pip</p><pre>python get-pip.py</pre><p>Now we are ready to install <a href="https://pypi.org/project/pipenv/"><em>pipenv</em></a> using the following command</p><pre>pip install pipenv</pre><p>pipenv creates and manages virtual environment for our project. Now, since we have <a href="https://pypi.org/project/pipenv/"><em>pipenv</em></a>, let’s create a directory and kick-start by following command. We use python3 system link here.</p><pre>mkdir lexnlp-extraction &amp;&amp; cd lexnlp-extraction &amp;&amp; pipenv install –three</pre><p>Activate virtual environment by the command</p><pre>pipenv shell</pre><p>Now we can install all packages/ dependencies by pip install command. As we know we have dependencies on <a href="https://pypi.org/project/pytesseract/"><em>pytesseract</em></a> for OCR functions and <a href="https://pypi.org/project/Pillow/"><em>Pillow</em></a> for image manipulation, lets install both of them now.</p><pre>pipenv install pytesseract Pillow</pre><p>The most important dependency to install is lexNLP which provides the core functionality to fetch the PII from the supplied text. Follow the below steps to install lexNLP:</p><p>Clone the lexNLP git repo to your local folder and install by pipenv install command</p><pre>git clone <a href="https://github.com/LexPredict/lexpredict-lexnlp.git">https://github.com/LexPredict/lexpredict-lexnlp.git</a></pre><pre>cd lexpredict-lexnlp</pre><pre>pipenv install</pre><p>The above steps install lexNLP library which provides arrays of features, but we will focus on <a href="https://lexpredict-lexnlp.readthedocs.io/en/docs-0.1.6/modules/extract_en_pii.html"><em>lexNLP-PII</em></a> feature.</p><p>And the last but not the least is to install flask framework. Follow the below command</p><pre>pipenv install flask</pre><p>As we have installed all the prerequisites, now it’s high time we create the necessary scripts. Should you need to learn flask before moving ahead feel free to visit <a href="https://flask.palletsprojects.com/en/1.1.x/quickstart/#quickstart"><em>here</em></a>.</p><p>Before writing the scripts, let us see how the framework layout looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*zD2A4ax1F5VgNW-PsJx0ag.png" /><figcaption>Framework Layout</figcaption></figure><ul><li><em>app.py</em><strong> : </strong>Kick starts flask server and contains necessary routes.</li><li><em>ocr_extraction.py </em><strong>: </strong>Handles the extraction of text from the image</li><li><em>lexnlp_extraction.py</em><strong> : </strong>This file handles the extraction of PII</li><li><em>template/</em><strong> : </strong>Folder contains all the html files</li><li>static/uploads/ : Folder contains all uploaded images</li><li><em>index.html</em> : Starting page with which the application starts</li><li><em>upload.html</em> : Lets user upload the image file and shows result</li></ul><p>Let’s define the content of <em>ocr_extraction.py</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9d55da4fd9a9d1cb60d4da9b58fad86/href">https://medium.com/media/f9d55da4fd9a9d1cb60d4da9b58fad86/href</a></iframe><p>The above script takes charge of opening the image by using Image class of Pillow library and then extracts the text by using <strong><em>image_to_string()</em></strong> function of pytesseract.</p><p>lexnlp_extraction.py is another file which defines a method to extracts the list of PII from the supplied text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c296d6f77bfee3707a20f66b96ed5b39/href">https://medium.com/media/c296d6f77bfee3707a20f66b96ed5b39/href</a></iframe><p>app.py is the file which literally starts the flask application. Here is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6e6866c156cabbed5157e17078fd05/href">https://medium.com/media/7a6e6866c156cabbed5157e17078fd05/href</a></iframe><p>The <em>upload_page()</em> functions is called when image is uploaded from the HTML page. And the uploaded image is stored in the <em>static/uploads/</em> folder. Similarly, the HTML files are stored in <em>templates/</em> folder. So, we have to manually create both these folders and keep the HTML (shown below) files in the <em>template/</em> folder.</p><p>The index.html file is pointed by default(basic route) as the home page. index.html has hyperlink for upload.html. Below is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9710d233c1fbbb747edf05e0b039790e/href">https://medium.com/media/9710d233c1fbbb747edf05e0b039790e/href</a></iframe><p>And at last, the upload.html is responsible for submitting the image via POST method and renders the result/ response from app.py. Below is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fd72714264e5ebc2f8ae9c39b1527b9/href">https://medium.com/media/0fd72714264e5ebc2f8ae9c39b1527b9/href</a></iframe><p>Now we are ready to run the app. All we have to do is go to the virtual environment in the same directory by running the command:</p><pre>pipenv shell <br>flask run</pre><p>The server should start with the following message:</p><pre>* Environment: production</pre><pre>WARNING: This is a development server. Do not use it in a production deployment.</pre><pre>Use a production WSGI server instead.</pre><pre>* Debug mode: off</pre><pre>* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)</pre><p>Go to the browser and load the above displayed URL(127.0.0.1:5000) and we should see the following page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*U7Btf_wFMLcWEuTFIM1UYQ.png" /><figcaption>127.0.0.1:5000</figcaption></figure><p>When clicked upload link, it should show the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwpzSCnFSyE-89-DZNevvQ.png" /><figcaption>127.0.0.1:5000/upload</figcaption></figure><p>In the upload page, we have to upload an image which we intend to fetch the text and PII from by clicking choose File button and then selecting the file in local folder and then we need to click upload button, which shows the extracted text and PII.</p><p>Below are the results when tried with different images such as color handwritten scanned image, scanned Black and White handwritten image and digitally written black and white screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ToyxXg5BeE_srMaLIsj_w.png" /><figcaption>Result for Screenshot Image of digitally written document</figcaption></figure><p>The above result is for screenshot image of digitally written document, which fetches the result(both text and PII such as SSN and Phone) accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dxc98PAnCo5t-KiHDNAs9g.png" /><figcaption>Result for Black and White scanned Image of handwritten document</figcaption></figure><p>The above result is for black and white scanned image of handwritten document, which poorly fetched the SSN where 1 is misinterpreted as ‘(‘ and hence no PII was detected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxW5NaGvI05-rcA3l-a_UQ.png" /><figcaption>Result for Color scanned Image of handwritten document</figcaption></figure><p>The above result is for color scanned image of handwritten document, which is quite similar to the previous one, the difference being “<em>Live en”</em> vs “<em>Live tn”. </em>Moreover, it is worth the effort to contribute to LexNLP to include information like medical record, tax record ..etc in their PII scope.</p><p>The chances of getting better accuracy in fetching text is highly dependent on how better contrast does the image have. This area definitely needs further analysis and testing. The primary purpose of this article is to bring and demonstrate my learning from a hackathon which may help the beginners trying to get into this field.</p><p><strong>Conclusion</strong>:</p><p>Although we have achieved a lot in this project, still we could have included PDF file in the text extraction process for which we could use PyPDF2 library and rest of the process works same. Pytesseract and LexNLP are great opens source libraries for OCR and PII detection which would be greatly useful in multiple use cases to make sure PII privacy is well complied.</p><p>The source code of the project can be accessed at <a href="https://github.com/suryak-cs/PII-LexNLP.git">GitHub</a></p><blockquote><strong>Reference and Credits</strong></blockquote><p>[1]Robley Gori — PyTesseract — Simple Python Optical Character Recognition <a href="https://stackabuse.com/pytesseract-simple-python-optical-character-recognition">https://stackabuse.com/pytesseract-simple-python-optical-character-recognition</a></p><p>[2]Extracting Personally-Identifiable Information(PII) — <a href="https://lexpredict-lexnlp.readthedocs.io/en/docs-0.1.6/modules/extract_en_pii.html">https://lexpredict-lexnlp.readthedocs.io/en/docs-0.1.6/modules/extract_en_pii.html</a></p><p>[3]GitHub Tesseract — <a href="https://github.com/tesseract-ocr/tesseract">https://github.com/tesseract-ocr/tesseract</a></p><p>[4]<a href="https://pypi.org/project/pytesseract/">https://pypi.org/project/pytesseract/</a></p><p>[5]Word cloud from <a href="https://www.wordclouds.com/">https://www.wordclouds.com/</a></p><p>[6]Icons in the cover image from <a href="https://icons8.com/">https://icons8.com/</a>. See below.</p><ul><li><a href="https://icons8.com/icons/set/identity-theft">Identity theft Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/order-delivered">Order delivered Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/sim-card">Sim card Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/mastercard-credit-card">Mastercard credit card Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/fingerprint">Fingerprint Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/password-window">Password window Icons - Free Download, PNG and SVG</a></li><li><a href="https://icons8.com/icons/set/birth-date">Birth date Icons - Free Download, PNG and SVG</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5da752562bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cisco-fpie/protecting-personal-identifiable-information-with-lexnlp-c5da752562bf">Protecting Personal Identifiable Information with LexNLP</a> was originally published in <a href="https://medium.com/cisco-fpie">cisco-fpie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>