<?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 Douglas Cardoso on Medium]]></title>
        <description><![CDATA[Stories by Douglas Cardoso on Medium]]></description>
        <link>https://medium.com/@douglas.dcm?source=rss-834bb8ca859b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mx3X_w9or_s1IfjYLhUbbg.jpeg</url>
            <title>Stories by Douglas Cardoso on Medium</title>
            <link>https://medium.com/@douglas.dcm?source=rss-834bb8ca859b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:22:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@douglas.dcm/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[Guará Framework Tutorial: Masterclass (Primeiro Código) ]]></title>
            <link>https://medium.com/@douglas.dcm/guar%C3%A1-framework-tutorial-masterclass-primeiro-c%C3%B3digo-780cbb7239d9?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/780cbb7239d9</guid>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[guara-framework]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Sun, 24 May 2026 05:26:42 GMT</pubDate>
            <atom:updated>2026-05-24T05:26:42.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_xZwbsLhCgIU9AyQL2wCw.png" /></figure><p>Fala, devs! Beleza?</p><p>Se você trabalha com automação de testes ou QA, sabe o parto que é manter a documentação em Gherkin (BDD) e o código de automação real em sincronia. O resultado? Quase sempre vira um monstro técnico, cheio de seletores poluídos que ninguém fora do time de QA consegue ler.</p><p>Para acabar com esse problema, eu gravei um vídeo prático mostrando o poder do framework <strong>Guará</strong>. Dá uma olhada em como um cenário de negócio se transforma direto em código Python fluído, legível e elegante.</p><p>Neste episódio da nossa série semanal, a gente vai direto ao ponto em: <strong>Guará Framework Tutorial: Masterclass (Primeiro Código)</strong>.</p><h4>🎥 Dá o play no tutorial completo</h4><p>Para ver o passo a passo da implementação e entender como aplicar isso no seu dia a dia, assiste aí:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeBv_X777Xtg%3Fstart%3D7%26feature%3Doembed%26start%3D7&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeBv_X777Xtg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeBv_X777Xtg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c163e30fda5dc45934eb62cf3194076/href">https://medium.com/media/5c163e30fda5dc45934eb62cf3194076/href</a></iframe><p>(Se o player não carregar por aqui, sem problemas: é só <a href="https://www.youtube.com/watch?v=eBv_X777Xtg&amp;t=7s">clicar neste link para ver direto no YouTube</a></p><h4>💻 O Código na Prática (Sem Enrolação)</h4><p>Para você ver que não é conversa fiada, saca só como o Guará deixa a estrutura do teste limpa:</p><pre>def test_add_product_to_cart(app: Application):<br>    (    <br>        app.given(OpenedSauceDemo, url=&quot;https://www.saucedemo.com/&quot;)<br>        .when(ClientLogin, with_username=&quot;standard_user&quot;, with_password=&quot;secret_sauce&quot;)<br>        .then(it.IsEqualTo, True)<br><br>        .when(AddProductToCart)<br>        .then(it.IsEqualTo, &quot;1&quot;)<br>        <br>        .when(OpenCart)<br>        .then(it.Contains, &quot;Your Cart&quot;)<br><br>        .when(CheckProductQuantity)<br>        .then(it.IsEqualTo, &quot;1&quot;)<br>    )</pre><p>Adeus código espaguete! Com essa abordagem, o seu próprio teste já serve como a documentação viva do sistema enquanto testa de verdade.</p><ul><li>🖥️ <a href="https://guara.readthedocs.io/en/latest/">Documentação do projeto</a></li><li>🍿 <a href="https://www.youtube.com/playlist?list=PLR5jeODwvciLIUX8M4jvWKJa6Z4Ua50fQ">Playlist completa (Guará: Do Zero ao Avançado)</a></li></ul><p>O que achou dessa estrutura? Já passou raiva tentando sincronizar BDD com código antes? Deixa seu comentário aqui embaixo para a gente trocar uma ideia!</p><p>Lembrando que tem vídeo novo sobre isso <strong>toda terça-feira, às 12h (meio-dia)</strong>. Bora codar! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=780cbb7239d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Gherkin to Source Code Without Losing the Business Language]]></title>
            <link>https://medium.com/@douglas.dcm/from-gherkin-to-source-code-without-losing-the-business-language-05577fafa540?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/05577fafa540</guid>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[page-transactions]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 03:48:57 GMT</pubDate>
            <atom:updated>2026-06-12T01:48:23.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtKrKunSN4aofT0NMJ4Rqw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ddealmeida?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dan DeAlmeida</a> on <a href="https://unsplash.com/photos/clear-toy-marble-with-reflection-of-seashore-Qr0Dvl8YQtU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Picture this: you are a software developer building an education platform and you receive from the product owner some requirements written in Business Language (Gherkin). You need to implement these scenarios in Python.</p><p>Probably you will start creating <em>models</em> and <em>service</em> modules. You will create some classes to represent the entities described in the scenarios like <em>Student</em>, <em>Course</em>, and <em>Subject</em>. You will add conditionals and loops in the entity classes to control the business logic and restrict paths in the code:</p><pre># Enroll a student in a course<br>if course.status == &quot;active&quot; and student.course == None:<br>    student.course = course<br>raise BusinessError(&quot;Student already in a course&quot;)</pre><p>Also, you will create a class to represent the persistence layer (database) and methods like <em>list_students</em>, <em>get_course_by_name</em> and <em>create_student</em> to add, delete, update end return data from database.</p><p>You, probably, will create facades to group the classes in a logical sequence, add more <em>if’s</em>, <em>else’s</em> and loops to control the code flow.</p><p>At the end of the sprint, you have a scenario implemented and tested.</p><p>There is nothing wrong with its style of implementation. It is a common process. However, something loses the importance in this process: the <strong>business scenario</strong> itself.</p><p>In this article I’ll showcase a behavior-driven development that converts business languages directly to executable code. The intention is to keep the implementation closer to the business language and promote the code to the source-of-truth.</p><h4>Gherkin Scenarios for the Education Platform</h4><p>Going back to the fictional (not much) story. Here are some scenarios an education platform could have:</p><pre>Feature: Student GPA and approval<br><br>  Scenario: Student is approved when GPA is 7 or higher and all subjects are passed<br>    Given a student named &quot;John&quot; is enrolled in the &quot;Computer Science&quot; course<br>    And the course has the subjects &quot;Math&quot;, &quot;Physics&quot;, and &quot;Programming&quot;<br>    And the student has the following grades:<br>      | Subject     | Grade |<br>      | Math        | 7     |<br>      | Physics     | 8     |<br>      | Programming | 9     |<br>    When the system calculates the student&#39;s GPA<br>    Then the GPA should be 8<br>    And the student status should be &quot;Approved&quot;<br><br>Feature: Student enrollment in course subjects<br><br>  Scenario: Student cannot enroll in a subject from another course<br>    Given a student named &quot;Carlos&quot; is enrolled in the &quot;Medicine&quot; course<br>    And the subject &quot;Algorithms&quot; belongs to the &quot;Computer Science&quot; course<br>    When the student tries to enroll in the subject &quot;Algorithms&quot;<br>    Then the enrollment should be rejected<br>    And the system should show the message &quot;Students can only enroll in subjects from their own course&quot;<br><br>Feature: Student enrollment in a course<br><br>  Scenario: Student enrolls in an active course<br>    Given a course named &quot;Architecture&quot; is active<br>    When a student named &quot;Julia&quot; tries to enroll in the &quot;Architecture&quot; course<br>    Then the enrollment should be accepted<br>    And the system should show the message &quot;Student enrolled in course&quot;<br><br>Feature: Course cancellation<br><br>  Scenario: Students cannot enroll in a canceled course<br>    Given a course named &quot;Architecture&quot; has been canceled by the general coordinator<br>    When a student named &quot;Julia&quot; tries to enroll in the &quot;Architecture&quot; course<br>    Then the enrollment should be rejected<br>    And the system should show the message &quot;Canceled courses cannot accept new enrollments&quot;</pre><p>They are pretty, readable, easy to understand, and find inconsistencies. Now a possible implementation as described in the previous story. It was simplified for the sake of this article. Let us look at a more traditional implementation.</p><pre># Entities<br>class Course:<br>    def __init__(self, course_id, name):<br>        self.course_id = course_id<br>        self.name = name<br>        self.is_canceled = False<br><br><br>class Student:<br>    def __init__(self, student_id, name):<br>        self.student_id = student_id<br>        self.name = name<br>        self.course = None<br><br><br># Application<br>class UniversityService:<br>    def __init__(self):<br>        self.courses = {}<br>        self.students = {}<br><br>    def create_course(self, course_id, name):<br>        self.courses[course_id] = Course(course_id, name)<br><br>    def create_student(self, student_id, name):<br>        self.students[student_id] = Student(student_id, name)<br><br>    def cancel_course(self, course_id):<br>        course = self.courses.get(course_id)<br><br>        if course is None:<br>            raise ValueError(&quot;Course not found&quot;)<br><br>        course.is_canceled = True<br><br>    def enroll_student_in_course(self, student_id, course_id):<br>        student = self.students.get(student_id)<br>        course = self.courses.get(course_id)<br><br>        if student is None:<br>            raise ValueError(&quot;Student not found&quot;)<br><br>        if course is None:<br>            raise ValueError(&quot;Course not found&quot;)<br><br>        if course.is_canceled:<br>            raise ValueError(&quot;Canceled courses cannot accept new enrollments&quot;)<br><br>        student.course = course<br><br><br># Scenario: Students cannot enroll in a canceled course<br>service = UniversityService()<br><br>service.create_course(&quot;C1&quot;, &quot;Architecture&quot;)<br>service.create_student(&quot;S1&quot;, &quot;Julia&quot;)<br>service.cancel_course(&quot;C1&quot;)<br><br>try:<br>    service.enroll_student_in_course(&quot;S1&quot;, &quot;C1&quot;)<br>    print(&quot;Unexpected result: student enrolled in a canceled course&quot;)<br>except ValueError as e:<br>    print(e)</pre><p>It was done in a traditional style. Notice the technical references like <em>service</em> and the preconditions and business logic spread in many <em>ifs</em> in the code. We forgot to represent the system behavior in a simple and explicit way.</p><p>The scenario was spread into many pieces and it may be hard to put all of them together when we need to understand the code in the future.</p><p>Consider that more features will be integrated into the code and more <em>if/else</em> will be introduced to control the business logic and new flows.</p><p>In summary, the scenario cannot be read as it was presented by the business team. It is hard to validate that the system is doing what it should do without proper unit tests and careful code review.</p><p>We can try to test its integration with Python <a href="https://behave.readthedocs.io/en/latest/">Behave</a> to bring the explicit behavior back to the game, but it may be hard to do it without coming up against technical stuff like services.</p><p>The system works, but it is hard to prove that it behaves as expected just by reading the code.</p><p>At this point, the development team and business one are not talking the same language anymore. There is a translation from business language to production code (technical stuff).</p><h4>Behavior-driven development</h4><p>Now, using the framework <a href="https://guara.readthedocs.io/en/latest/">Guará</a> to represent the scenarios directly in the code. <strong>The code now tells the story.</strong></p><p>For example, the scenario <em>Student enrollment in a course</em> can be written like this:</p><pre>from guara.application import Application<br><br>eduapp = Application()<br><br>(<br>    eduapp.given(IsActiveCourse, course_id=course_id)<br>    .and_(IsNotStudentInACouse, student_id=student_id)<br>    .when(<br>        EnrollStudentInCourse,<br>        student_id=student_id,<br>        course_id=course_id,<br>    )<br>    .then(it.IsEqualTo, &quot;Student enrolled in course&quot;)<br>)</pre><p>The preconditions <em>IsActiveCourse</em> and <em>IsNotStudentInACourse</em> are now explicit and are at the higher level of the code. Not buried in the methods in form of <em>if</em> conditionals. The precondition and action classes have single responsibilities.</p><pre>from guara.transaction import AbstractTransaction<br><br>class IsActiveCourse(AbstractTransaction):<br>    def do(self, course_id):<br>        print(f&quot;Checking the status of course {course_id}&quot;)<br>        status = database.courses.get_status(course_id=course_id)<br>        if status == &quot;Active&quot;:<br>            return True<br>        raise CourseCanceledException(&quot;Course canceled&quot;)<br><br><br>class IsNotStudentInACourse(AbstractTransaction):<br>    def do(self, student_id):<br>        print(f&quot;Checking if student in a course&quot;)<br>        course = database.student.get_course()<br>        if course:<br>            raise StudentException(&quot;Student already in a course&quot;)<br><br><br>class EnrollStudentInCourse(AbstractTransaction):<br>    def do(self, student_id, course_id):<br>        print(f&quot;Enrolling student {student_id} in course {course_id}&quot;)<br>        status = database.enroll_course(course_id, student_id)<br>        return &quot;Student enrolled in course&quot;</pre><p>In the end, it is easier to compare the code against the scenario steps and assert they are present in the code.</p><pre>import argparse<br>from guara.transaction import Application<br>from guara import it<br><br>eduapp = Application()<br><br>def main():<br>    parser = argparse.ArgumentParser()<br><br>    parser.add_argument(&quot;--action&quot;, required=True)<br>    parser.add_argument(&quot;--student-id&quot;)<br>    parser.add_argument(&quot;--course-id&quot;)<br><br>    args = parser.parse_args()<br><br>    if args.action == &quot;enroll_course&quot;:<br>        try:<br>            (<br>                eduapp.given(HasCourse, course_id=args.course_id)<br>                .and_(IsActiveCourse, course_id=args.course_id)<br>                .and_(HasStudent, student_id=args.student_id)<br>                .and_(IsNotStudentEnrolledInCourse, student_id=args.student_id)<br>                .when(<br>                    EnrollStudentInCourse,<br>                    student_id=args.student_id,<br>                    course_id=args.course_id,<br>                )<br>                .asserts(it.IsTrue)<br>            )<br>        except Exception as e:<br>            print(str(e))<br>            app.undo()<br><br># Calling the CLI            <br>python edu.py enroll-course --course-id 10 --student-id 1324</pre><h4>Benefits</h4><ul><li>The production code is now the source of truth</li><li>It can be compared directly to the business scenarios</li><li>The responsibilities are encapsulated in dedicated classes</li><li>It is possible to undo operations easily once the framework is based on the Command Pattern (GoF)</li><li>It is easy to add more behavior to the code without changing other classes</li><li>The classes are reusable</li><li>It hides the technical stuff. They still exist, but now the actions are first-class citizens</li></ul><h4>Points of attention</h4><ul><li>It is not a one-size-fits-all style. It is necessary to evaluate if the system under development will benefit from this code style</li><li>Makes more sense when the scenarios are defined in Gherkin language; otherwise, it will be necessary to translate the requirement to code as done in the traditional implementation</li></ul><h4>Conclusion</h4><p>The important difference is that the source code still reads almost like the original Gherkin scenario. Instead of hiding business rules inside technical layers, we keep them visible and explicit in the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05577fafa540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if your code spoke the same language as your business?]]></title>
            <link>https://medium.com/@douglas.dcm/what-if-your-code-spoke-the-same-language-as-your-business-b9c359a88ef5?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9c359a88ef5</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[gherkin-language]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[modeling]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 06:31:38 GMT</pubDate>
            <atom:updated>2026-04-08T06:31:38.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FuYjhXeG97vQ2vtP_e_sw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Jordan</a> on <a href="https://unsplash.com/photos/choose-your-words-tiles-POMpXtcVYHo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The <a href="https://agilealliance.org/glossary/three-amigos/">Three Amigos</a> pattern states that people from business, development, and testing perspectives “should collaborate to define what to do, and agree on how they know when it is done correctly”. However, in most IT solutions, there is still a gap between the language spoken by business stakeholders, developers, and testers. This gap leads to miscommunication, ambiguity, and misunderstandings. In practice, there is always a <strong>translation step</strong> — converting business ideas, use cases, and user stories into production and testing artifacts (i.e., source code).</p><blockquote>But what if this translation step didn’t exist?</blockquote><p>What if we could use the <strong>same language</strong> to describe the business, implement the system, and validate it?</p><p>I started exploring a testing framework called <a href="https://guara.readthedocs.io/en/latest/">Guará,</a> which is based on a simple idea:</p><blockquote>Break your system into small actions (transactions) and validate their results.</blockquote><p>With this approach, you begin writing tests like this:</p><pre>app.given(UserLoggedIn) \<br> .when(Search, product=&quot;notebook&quot;) \<br> .then(ReportChart) \<br> .expects(IsEqualTo, 1)</pre><p>Now the code reads like a story. However, the real breakthrough came when I extended this idea into a <strong>business-oriented language</strong>. So, instead of using generic words like <em>given</em>, <em>when</em>, and <em>then </em>(the Gherkin style), I asked:</p><blockquote>How would a finance professional describe their processes?</blockquote><p>The answer led to something like this:</p><pre>fin_app.account_with(HasBalance) \<br> .execute(BuyAsset, symbol=&quot;AAPL&quot;, amount=2000) \<br> .settles(UpdatePortfolio) \<br> .reconciles(ExpectedPortfolio, 20)</pre><p>Now we are speaking the language of the business. This is no longer just test code — it is <strong>executable business logic</strong>.</p><p>One of the most powerful aspects of this approach is that the same building blocks used to describe behavior can also be used to implement it.</p><p>For example, a transaction like <em>BuyAsset</em> can be implemented as:</p><pre>class BuyAsset(AbstractTransaction):<br>  def do(self, symbol, amount):<br>    DataBase.balance -= amount</pre><p>Here, a specific amount is deducted from the customer’s balance and the same transaction can be reused across multiple scenarios — in both tests and production flows — improving consistency, readability, and maintainability. Hence, your tests are no longer just validations. They become <strong>living documentation of the system</strong>.</p><h3>How the Framework Works (Simple View)</h3><p>At its core, the framework is built on three simple concepts:</p><p>* <strong>Transactions</strong> → small units of work (e.g., <em>BuyAsset</em>)<br>* <strong>Application</strong> → orchestrates execution (the runner)<br>* <strong>Assertions</strong> → validate results</p><p>The flow works like this:</p><p>* <em>given / when / then</em> → execute transactions<br>* <em>asserts / expects</em> → validate outcomes</p><p>All of this is coordinated by the <em>Application</em> class.</p><h3>Extending to a Ubiquitous Language (Finance Example)</h3><p>The real power of this approach is that it can be extended into a <strong>domain-specific language</strong>. For example, in finance:</p><p>* <em>given</em> → <em>account_with, portfolio_with, positioned_with</em><br>* <em>when → execute, trade</em><br>* <em>then → settles, result_in</em><br>* <em>asserts → reconciles, balances</em></p><p>This transforms technical steps into <strong>business expressions</strong>. In a simple example:</p><pre>from guara.transaction import Application, AbstractTransaction<br>from guara import it<br><br><br># Extends the framework to financial domain<br>class FinancialApplication(Application):<br>    def __init__(self, driver=None):<br>        super().__init__(driver)<br><br><br>    def account_with(self, transaction, **kwargs):<br>        super().given(transaction, **kwargs)<br>        return self<br>    <br>    <br>    def execute(self, transaction, **kwargs):<br>        super().when(transaction, **kwargs)<br>        return self<br>    <br>    <br>    def settles(self, transaction, **kwargs):<br>        super().then(transaction, **kwargs)<br>        return self<br>    <br>    <br>    def reconciles(self, assertion, expected):<br>        super().asserts(assertion, expected)<br>        return self<br>    <br><br># Transactions that can be used in production and testing code<br>class BuyAsset(AbstractTransaction):<br>    def do(self, symbol, amount):<br>        DataBase.balance -= amount<br><br><br># Custom assertions derive from base ones, but using the finance terms<br>class ExpectedPortfolio(it.IsEqualTo):<br>    def __init__(self):<br>        super().__init__()<br><br><br># The domain language used in production code<br>def main():<br>    fin_app = FinancialApplication()<br>    (<br>        fin_app.account_with(HasBalance)<br>        .execute(BuyAsset, symbol=&quot;AAPL&quot;, amount=2000)<br>        .settles(UpdatePortfolio)<br>    )<br><br><br># The domain language used in testing<br>def test_extend_ubiquitous_language():<br>    fin_app = FinancialApplication()<br>    (<br>        fin_app.account_with(HasBalance)<br>        .execute(BuyAsset, symbol=&quot;AAPL&quot;, amount=2000)<br>        .settles(UpdatePortfolio)<br>        .reconciles(ExpectedPortfolio, 20)<br>    )</pre><p>What started as a testing pattern becomes something much bigger: <strong>a way to write software that mirrors real-world thinking</strong>. Instead of <strong>writing code and then explaining</strong> it you <strong>write code that is the explanation</strong>.</p><h3>Final Thought</h3><p>If your code cannot be understood by the business, you are building a system only part of the team can see. But if your code speaks the language of the business… you are not just writing software, you are modeling reality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9c359a88ef5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Page Transactions and Page Object Model]]></title>
            <link>https://medium.com/@douglas.dcm/page-transactions-and-page-object-model-645974e6f870?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/645974e6f870</guid>
            <category><![CDATA[page-transactions]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:45:38 GMT</pubDate>
            <atom:updated>2025-02-03T05:45:38.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Colorful mosaic in geometric forms" src="https://cdn-images-1.medium.com/max/1024/0*8PWVXgDxm7xutTVP" /><figcaption>Photo by <a href="https://unsplash.com/@gpthree?utm_source=medium&amp;utm_medium=referral">George Pagan III</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I wrote <a href="https://medium.com/python-in-plain-english/page-transactions-as-a-new-way-to-organize-your-testing-automation-3b9dd91c3092"><strong>Page Transactions as a new way to organize your testing automation</strong></a>, focusing on simplicity, readability and flexibility. Now, I present a structured comparison of Page Transactions (<strong>PT</strong>) and Page Objects Model (<strong>POM</strong>) explaining the pros and cons of each pattern. At the end I give some tips to migrate from POM to PT in simple steps.</p><p>To whom that is not familiar with POM, in a nutshell, it is a design pattern used in testing automation where the objects on a UI page are represented as methods in a class and where each class represents the UI page itself.</p><p>The comparison takes into account aspects like <strong>maintainability</strong>, <strong>reusability</strong>, <strong>readability</strong> and <strong>simplicity</strong>. Lets start with POM which is a popular pattern in test automation.</p><h3>Page Objects Model</h3><h4>Code maintainability</h4><p>✅ Separates locators from tests ✅ Easy to update elements</p><p>❌ Still tightly coupled with page structure ❌ If UI changes, all affected pages must be updated</p><h4>Reusability</h4><p>✅ Page classes can be reused across multiple tests</p><p>❌ Interactions are page-specific, not user-flow based</p><h4>Readability and Simplicity</h4><p>✅ Test cases look clean with method calls</p><p>❌ Requires writing multiple classes for different pages, which can add complexity</p><h4>Scalability</h4><p>✅ Works well for large projects with many pages</p><p>❌ Harder to manage when dealing with workflows spanning multiple pages</p><h4>Test maintenance effort</h4><p>✅ If a locator changes, it only needs to be updated in one place</p><p>❌ If the user workflow changes, tests might need significant updates</p><h4>Suitability for UI testing</h4><p>✅ Well-suited for UI automation with Selenium and similar tools</p><p>❌ Not ideal for non-UI scenarios (e.g., REST API testing)</p><h3>Page Transactions</h3><h4>Code maintainability</h4><p>✅ Transactions focus on user actions rather than elements, reducing maintenance</p><p>❌ Requires a different mindset for those used to POM</p><h4>Reusability</h4><p>✅ Highly reusable since transactions are user-action based</p><p>❌ If UI structure changes drastically, transactions might need updates</p><h4>Readability &amp; Simplicity</h4><p>✅ Tests read like human instructions, improving clarity ✅ Reduces WebDriver calls in test script</p><p>❌ Requires defining multiple transaction classes for different actions</p><h4>Scalability</h4><p>✅ Works well for large applications, especially where user flows span multiple pages</p><p>❌ Slightly more setup is needed compared to POM</p><h4>Test maintenance effort</h4><p>✅ Less maintenance required since tests are written based on <strong>actions</strong> rather than UI elements</p><p>❌ If a transaction is reused across many tests, fixing one issue could impact multiple tests</p><h4>Suitability for UI testing</h4><p>✅ Works for UI, API, and asynchronous testing</p><p>❌ Less common in traditional UI automation frameworks</p><h3>Analysis</h3><p><strong>PT</strong> focuses on user workflows, making it more maintainable and scalable. It allows for better test organization and is more suitable for different types of automation (Web UI, API, Desktop UI). Tests written in PT are more readable, making them accessible to non-technical stakeholders. If your project involves <strong>complex user workflows</strong> across multiple pages, <strong>Page Transactions is the better approach</strong>.</p><p><strong>POM is still a great choice</strong> for teams already familiar with traditional UI testing methods, and it provides a structured way to manage page elements. If you need <strong>simple UI structure representation</strong>, POM works well.</p><p>So, no pattern is best or worst. It depends on the characteristics of a given project. However,<strong> if the project fits better with PT pattern, but is already implemented in POM, it is possible to migrate from POM to PT</strong> following these tips.</p><h3>Tips for Migrating from POM to PT</h3><p>Moving from <strong>POM</strong> to <strong>PT</strong> requires shifting from <strong>page-centric automation</strong> to <strong>user action-centric automation</strong>. Below are key steps and examples to help with the transition.</p><ol><li><strong>Identify User Transactions</strong>: In POM, page objects represent pages. In PT, it focus on transactions like Login, Logout, Submit Form, Change Language, Navigate to a Page.<strong> </strong>Instead of writing separate methods for every element on a page, create classes for each transaction.</li><li><strong>Convert POM Methods to PT Transactions: </strong>Check bellow a POM Example (Before Migration). The test login to a page, informs the user and password of a user and checks if the Dashboard page is displayed. There is a <strong>LoginPage</strong> class which hosts the methods to interact with the components of the page, like <strong>username</strong> field.</li></ol><pre>from selenium.webdriver.common.by import By<br><br>class LoginPage:<br>    def __init__(self, driver):<br>        self.driver = driver<br>        self.username = (By.ID, &quot;username&quot;)<br>        self.password = (By.ID, &quot;password&quot;)<br>        self.login_button = (By.ID, &quot;login&quot;)<br><br>    def enter_username(self, user):<br>        self.driver.find_element(*self.username).send_keys(user)<br><br>    def enter_password(self, pwd):<br>        self.driver.find_element(*self.password).send_keys(pwd)<br><br>    def click_login(self):<br>        self.driver.find_element(*self.login_button).click()</pre><pre>def test_login():<br>    driver = webdriver.Chrome()<br>    login_page = LoginPage(driver)<br><br>    login_page.enter_username(&quot;user1&quot;)<br>    login_page.enter_password(&quot;password1&quot;)<br>    login_page.click_login()<br><br>    assert &quot;Dashboard&quot; in driver.title</pre><p>PT Example (After Migration). Now, the <strong>LoginTransaction</strong> class represents the whole login action which adds the user name, password and submit them.</p><pre>from guara.transaction import AbstractTransaction<br><br>class LoginTransaction(AbstractTransaction):<br>    def __init__(self, driver):<br>        super().__init__(driver)<br><br>    def do(self, username, password):<br>        self._driver.find_element(By.ID, &quot;username&quot;).send_keys(username)<br>        self._driver.find_element(By.ID, &quot;password&quot;).send_keys(password)<br>        self._driver.find_element(By.ID, &quot;login&quot;).click()<br>        return self._driver.title</pre><pre>from guara.transaction import Application<br>from guara import it<br>from selenium import webdriver<br><br>def test_login():<br>    driver = webdriver.Chrome()<br>    app = Application(driver)<br><br>    app.at(LoginTransaction, username=&quot;user1&quot;, password=&quot;password1&quot;).asserts(<br>      it.Contains, &quot;Dashboard&quot;<br>    )</pre><p><strong>Benefits of the PT Approach</strong></p><ul><li><strong>Less boilerplate code</strong> as no needs for page-specific methods in tests</li><li><strong>Readable test cases</strong> once tests describe actions in plain English</li><li><strong>Easier maintenance </strong>as UI changes don’t break all related test methods</li></ul><p>4. <strong>Additional Refactoring for Other Pages</strong>: for example changing Language Transaction, instead of:</p><pre>class HomePage:<br>    def click_language_button(self):<br>        self.driver.find_element(By.ID, &quot;language&quot;).click()</pre><p>Use</p><pre>class ChangeLanguageTransaction(AbstractTransaction):<br>    def __init__(self, driver):<br>        super().__init__(driver)<br><br>    def do(self, language):<br>        self._driver.find_element(By.ID, f&quot;lang-{language}&quot;).click()<br>        return self._driver.find_element(By.TAG_NAME, &quot;body&quot;).text</pre><p>Test case:</p><pre>app.at(ChangeLanguageTransaction, language=&quot;pt&quot;).asserts(<br>  it.Contains, &quot;Página inicial&quot;<br>)</pre><p><strong>5. Gradual Migration Strategy</strong>:</p><ul><li>Start with frequently changing tests</li><li>Convert one transaction at a time</li><li>Keep old POM code until full migration is complete</li></ul><h3>Conclusion</h3><p>PT is a new pattern, but demonstrates good qualities when compared against POM that is a widely used pattern in test automation. It in some situations PT fits better and can be used as an alternative to POM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645974e6f870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Page Transactions as a new way  to organize your testing automation]]></title>
            <link>https://python.plainenglish.io/page-transactions-as-a-new-way-to-organize-your-testing-automation-3b9dd91c3092?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b9dd91c3092</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unicorns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 00:44:25 GMT</pubDate>
            <atom:updated>2025-01-27T12:00:44.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Page Transactions as a new way to organize your testing automation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JLCFQNz0MkIa3Fiq" /><figcaption>Photo by <a href="https://unsplash.com/@matcfelipe?utm_source=medium&amp;utm_medium=referral">Mateus Campos Felipe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Scarlet_ibis">Scarlet ibis (Guará)</a></p><p>The scarlet ibis, sometimes called red ibis (Eudocimus ruber), is a species of ibis in the bird family Threskiornithidae. It inhabits tropical South America and part of the Caribbean. In form, it resembles most of the other twenty-seven extant species of ibis, but its remarkably brilliant scarlet coloration makes it unmistakable. It is one of the two national birds of Trinidad and Tobago, and its Tupi–Guarani name, guará, is part of the name of several municipalities along the coast of Brazil.</p><h3>The pattern</h3><p><strong>Guará</strong> is the Python implementation of the design pattern <strong>Page Transactions</strong>. It is more of a programming pattern than a tool. As a pattern, it can be bound to any driver other than Selenium including the ones used to Linux, Window and Mobile automation.</p><p>The intent of this pattern is to simplify test automation. It was inspired by Page Objects, App Actions, and Screenplay. Page Transactions focus on the operations (transactions) a user can perform on an application, such as Login, Logout, or Submit Forms.</p><p>This initiative was born to improve the readability, maintainability and flexibility of automation testing code without the need for new automation tools or the necessity of many abstractions to build human-readable statements. Another concern was to avoid binding the framework to specific automation tools, like Selenium, leaving the testers free to choose their preferred ones. No new plugin nor new knowledge is required to start using Guará with Helium, Dogtail, PRA Python, Playwright or whatever tool you like or need.</p><p><strong>It is worth to say again:</strong></p><blockquote>Guará is the Python implementation of the design pattern Page Transactions. It is more of a programming pattern than a tool.</blockquote><p>Guará leverages the <strong>Command Pattern (GoF)</strong> to group user interactions, like pressing buttons or filling texts, into transactions. Despite I’m calling it a framework, it is not a new tool.</p><p>Instead of focusing on UI elements like buttons, check boxes or text areas, it emphasizes the <strong>user journey</strong>. The complexity is abstracted into these transactions, making the test statements feels like plain English. Testers also have the flexibility to extend assertions to custom ones that are not provided by the framework.</p><h3>The Framework in action</h3><p>This simple implementation mimics the user switching languages in a Web Page:</p><pre>from selenium import webdriver<br>from guara.transaction import Application<br>from guara import it, setup<br>import home <br><br>def test_language_switch():<br>    app = Application(webdriver.Chrome())<br>    <br>    # Open the application<br>    app.at(setup.OpenApp, url=&quot;https://example.com/&quot;)<br>    <br>    # Change language and assert<br>    app.at(home.ChangeToPortuguese).asserts(it.IsEqualTo, &quot;Conteúdo em Português&quot;)<br>    app.at(home.ChangeToEnglish).asserts(it.IsEqualTo, &quot;Content in English&quot;)<br>    <br>    # Close the application<br>    app.at(setup.CloseApp)</pre><p>Each user transaction is grouped into its own class (e.g., <strong>ChangeToPortuguese</strong>) which inherits from <strong>AbstractTransaction</strong>. The tester just has to override the <strong>do</strong> method and the framework does the work.</p><pre>from guara.transaction import AbstractTransaction<br><br>class ChangeToPortuguese(AbstractTransaction):<br>    def do(self, **kwargs):<br>        self._driver.find_element(By.CSS_SELECTOR, &quot;.btn-pt&quot;).click()<br>        return self._driver.find_element(By.CSS_SELECTOR, &quot;.content&quot;).text</pre><p>The tester can check the the transactions and assertions in the logs after run the tests:</p><pre>test_demo.py::test_language_switch <br>2025-01-24 21:07:10 INFO Transaction: setup.OpenApp<br>2025-01-24 21:07:10 INFO  url: https://example.com/<br>2025-01-24 21:07:14 INFO Transaction: home.ChangeToPortuguese<br>2025-01-24 21:07:14 INFO Assertion: IsEqualTo<br>2025-01-24 21:07:14 INFO  Actual Data: Conteúdo em Português<br>2025-01-24 21:07:14 INFO  Expected: Conteúdo em Português<br>2025-01-24 21:07:14 INFO Transaction: home.ChangeToEnglish<br>2025-01-24 21:07:14 INFO Assertion: IsEqualTo<br>2025-01-24 21:07:14 INFO  Actual Data: Content in English<br>2025-01-24 21:07:14 INFO  Expected: Content in English<br>2025-01-24 21:07:14 INFO Transaction: setup.CloseApp</pre><p>The tester can also use fixtures like setup and tear down to initiate and finish the tests. Remember, it is not a new tool, so you can use pytest or unittesting features without any problem.</p><h3>Why use Guará?</h3><p>Each class represents a complete user transaction, improving code re-usability. Also, the code is written in plain English, making it easier for non-technical collaborators to review and contribute.</p><p>Custom assertions can be created and shared by testers. Additionally, Guará can be integrated with any non-Selenium tool.</p><p>Page Transactions can automate REST APIs, unit tests, desktop, and mobile tests. As a side effect of the Command Pattern, the framework can even be used in product development.</p><h3>Using Guará</h3><p>Setting up Guará is simple:</p><ol><li>Install Guará with the command</li></ol><pre>pip install guara</pre><p>2. Build your transactions using the <strong>AbstractTransaction</strong> class.</p><p>3. Invoke the transactions using the <strong>Application</strong> runner and its methods <strong>at</strong> and <strong>asserts</strong>.</p><p>3. Execute tests with detailed logging with Pytest:</p><pre>python -m pytest -o log_cli=1 --log-cli-level=INFO</pre><p>For more examples, check out the <a href="https://github.com/douglasdcm/guara/blob/main/docs/TUTORIAL.md">tutorial</a>.</p><h3>Conclusion</h3><p><strong>Guará</strong> is a new way testers can organize their code making it simple to read, maintain and integrate with any automation driver. It improves the collaboration between testers and non-technical members. Testers can also extend it building and sharing new assertions.</p><p><a href="https://github.com/douglasdcm/guara/tree/main">Try Guará today!</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b9dd91c3092" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/page-transactions-as-a-new-way-to-organize-your-testing-automation-3b9dd91c3092">Page Transactions as a new way  to organize your testing automation</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Refactoring to Patterns]]></title>
            <link>https://python.plainenglish.io/python-refactoring-to-patterns-1ca71be08a60?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca71be08a60</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[desing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[books]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 01:46:40 GMT</pubDate>
            <atom:updated>2025-01-06T04:29:28.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O88y8CI3cWn1quZllqI_A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@phofilmfan?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Patrick Ho</a> on <a href="https://unsplash.com/photos/man-in-yellow-shirt-climbing-on-brown-concrete-building-during-daytime-5Elh_y6gBdM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>I’ll keep this brief to save your time — here’s the TL;DR:</p><blockquote><a href="https://github.com/douglasdcm/refactoring-to-patterns/blob/main/code_smells_table.py">This table in Python</a> contains a list of code smells and the design patterns that address them.</blockquote><pre>class CodeSmells:<br>    Duplicated_Code = [<br>        form_template_method,<br>        introduce_polymorphic_creation_with_factory_method,<br>        chain_constructors,<br>        replace_one__many_distinctions_with_composite,<br>        extract_composite,<br>        unify_interfaces_with_adapter,<br>        introduce_null_object,<br>    ]<br>    Long_Method = [<br>        compose_method,<br>        move_accumulation_to_collecting_parameter,<br>        replace_conditional_dispatcher_with_command,<br>        move_accumulation_to_visitor,<br>        replace_conditional_logic_with_strategy,<br>    ]<br>    Conditional_Complexity = [  # Complicated conditonal logic<br>        replace_conditional_logic_with_strategy,<br>        move_emblishment_to_decorator,<br>        replace_state_altering_conditionals_with_state,<br>        introduce_null_object,<br>    ]<br>    Primitive_Obssession = [<br>        replace_type_code_with_class,<br>        replace_state_altering_conditionals_with_state,<br>        replace_conditional_logic_with_strategy,<br>        replace_implict_tree_with_composite,<br>        replace_implicit_language_with_interpreter,<br>        move_emblishment_to_decorator,<br>        encapsulate_composite_with_builder,<br>    ]<br>    # Lack of &quot;information hiding&quot; [Parnas]<br>    Indecent_Exposure = [encapsulate_classes_with_factory]<br>    # The logic/responsibility is sprawled in multiple places<br>    # (classes, methods)<br>    Solution_Sprawl = [move_creation_knowledge_to_factory]<br>    # [Fowler and Beck] Interfaces of classes different,<br>    # but classes are similar<br>    Alternative_Classes_with_Different_Interfaces = unify_interfaces_with_adapter<br>    # [Fowler and Beck] A class the doesn&#39;t do enough to pay itself<br>    Lazy_Class = [inline_singleton]<br>    Large_Class = [<br>        replace_conditional_dispatcher_with_command,<br>        replace_state_altering_conditionals_with_state,<br>        replace_implict_tree_with_composite,<br>    ]<br>    Switch_Statements = [  # Complicated switches<br>        replace_conditional_dispatcher_with_command,<br>        move_accumulation_to_visitor,<br>    ]<br>    # Code that do the same with different types or quantity of data<br>    # (similar to duplication)<br>    Combination_Explostion = [replace_implicit_language_with_interpreter]<br>    # The same problem being solved in many ways in the system<br>    # (similar to duplication)<br>    Oddball_Solutions = [unify_interfaces_with_adapter]</pre><h3>The Journey</h3><p>After nearly a year of effort, I’ve finally completed my self-imposed goal of writing all the refactoring examples from the book <a href="https://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351"><em>Refactoring to Patterns</em> by Joshua Kerievsky</a> in Python. This book broadened my understanding of how to apply design patterns in production code.</p><p><a href="https://github.com/douglasdcm/refactoring-to-patterns/tree/main/src">Each example</a> includes a brief explanation of the original code and its context, followed by the refactored code and the benefits gained through the refactoring. For instance, <a href="https://github.com/douglasdcm/refactoring-to-patterns/blob/main/src/compose_method.py">the refactoring to “Compose Method”</a> transforms difficult-to-read code into a simple, streamlined implementation.</p><p>Lets get this example and examine the original code.</p><pre># Original code<br># It is not easy to understand the code<br>def add(element):<br>    readonly = False<br>    size = 0<br>    elements = []<br>    if not readonly:<br>        new_size = size + 1<br>        if new_size &gt; len(elements):<br>            new_elements = []<br>            for i in range(size):<br>                new_elements[i] = elements[i]<br>            elements = new_elements<br>        size += 1<br>        elements[size] = element</pre><p>It is possible to see that the code is not easy to understand. It has many nested conditions and loops. Now lets go to the refactored code.</p><pre># Code Refactored<br># The new code has meaningfull names for blocks of code and is not nested.<br># The Compose Method is a refactoring to simplificate the code<br>def at_capacity(new_size, elements):<br>    new_size &gt; len(elements)<br><br><br>def grow(size):<br>    new_elements = []<br>    for i in range(size):<br>        new_elements[i] = elements[i]<br>    elements = new_elements<br><br><br>def add_elements(elements, element, size):<br>    size += 1<br>    elements[size] = element<br><br><br>def add_refac(element):<br>    readonly = False<br>    if readonly:<br>        return<br>    if at_capacity:<br>        grow()<br>    add_elements(element)</pre><p>The idea of the refactoring is reduce the complication with meaningful methods and remove the nested branches. Notice it was necessary to extract blocks of code to methods.</p><p>While working through the book and writing the examples, I had to interpret UML diagrams and understand the mechanics in detail. This required intense focus and mental effort. Many times, I had to rebuild the examples from scratch because converting code from Java to Python is not straightforward. Native Python doesn’t support cyclic imports, constructor overloads, or interfaces well, so some adaptations were necessary. I added comments to these areas to help future consultation of the code.</p><p>Through this process, I realized my previous understanding of design patterns was mostly theoretical and limited to trivial scenarios. For example, while I understood that “Polymorphism” addresses development problems, the book <a href="https://github.com/douglasdcm/refactoring-to-patterns/blob/main/src/introduce_polymorphic_creation_with_factory_method.py">showed its application in test automation</a> by abstracting the setup phase and reusing the remaining test implementation.</p><p>Here are both versions of the code. The difference between the original and new code is the setup of the test.</p><pre># Original code<br># Similar methods differs from the object instantiation.<br># All the rest is the same<br>class TestCase:<br>    pass<br><br><br>class DOMBuilder:<br>    def __init__(self, orders) -&gt; None:<br>        pass<br><br>    def calc(self):<br>        return 42<br><br><br>class XMLBuilder:<br>    def __init__(self, orders) -&gt; None:<br>        pass<br><br>    def calc(self):<br>        return 42<br><br><br>class DOMTest(TestCase):<br>    def run_dom_test(self):<br>        expected = 42<br>        builder = DOMBuilder(&quot;orders&quot;)  # different object created<br>        assert builder.calc() == expected<br><br><br>class XMLTest(TestCase):<br>    def run_xml_test(self):<br>        expected = 42<br>        builder = XMLBuilder(&quot;orders&quot;)  # different object created<br>        assert builder.calc() == expected<br><br><br># Code refactored<br># The instantiation of the DOMBuilder or XMLBuilder is the only difference<br># in both tests.<br># It was created an OutputBuilder like an interface for both classes<br># (it is not necessary given that Python uses duck type).<br># In TestCase a new method called &quot;create_builder&quot; was introduced to be<br># implemented by the children classes.<br># This is the step executed in runtime for each type of test. This is the<br># polymorphism. When both tests (DOMTest and XMLTest) are executed,<br># the instance returned from the &quot;create_builder&quot; depends on the<br># implementation. Is can be DOMBuilder or XMLBuilder.<br>class OutputBuilder:<br>    def calc(self):<br>        raise NotImplementedError()<br><br><br>class DOMBuilderRefac(OutputBuilder):<br>    def calc(self):<br>        return 42<br><br><br>class XMLBuilderRefac(OutputBuilder):<br>    def calc(self):<br>        return 42<br><br><br>class TestCaseRefac:<br>    def create_builder(self):<br>        raise NotImplementedError()<br><br>    def run_test(self):<br>        expected = 42<br>        builder = self.create_builder()  # different object created<br>        assert builder.calc() == expected<br><br><br>class DOMTestRefac(TestCaseRefac):<br>    def create_builder(self) -&gt; OutputBuilder:<br>        return DOMBuilderRefac()<br><br><br>class XMLTestRefac(TestCaseRefac):<br>    def create_builder(self):<br>        return XMLBuilderRefac()<br><br><br>def run():<br>    dom_tc = DOMTestRefac()<br>    dom_tc.run_test()<br><br>    xml_tc = XMLTestRefac()<br>    xml_tc.run_test()</pre><p>The “Visitor” pattern was the most difficult for me to understand. I read about the pattern in the <em>Design Patterns</em> book before attempting the refactoring. It was only after seeing the original (unrefactored) <a href="https://github.com/douglasdcm/refactoring-to-patterns/blob/main/src/move_accumulation_to_visitor.py">code being transformed into the new version</a> that I realized the pattern isn’t as complex as it initially seems. Essentially, the pattern decouples classes from their methods. Again, both codes for comparison. The implementation of the pattern is “by the book”.</p><pre># Original code<br># The TextExtractor has lots of conditons to handle Nodes, like StringNode<br># The idea ofthe rectoring is distribute the logic into Visitor classes<br><br><br># Interface<br>class Node:<br>    pass<br><br><br>class LinkTag(Node):<br>    pass<br><br><br>class Tag(Node):<br>    pass<br><br><br>class StringNode(Node):<br>    pass<br><br><br>class TextExtractor:<br>    def extract_text(self, nodes: list[Node]):<br>        result = []<br>        for node in nodes:<br>            if isinstance(node, StringNode):<br>                result.append(&quot;string&quot;)<br>            elif isinstance(node, LinkTag):<br>                result.append(&quot;linktag&quot;)<br>            elif isinstance(node, Tag):<br>                result.append(&quot;tag&quot;)<br>            else:<br>                result.append(&quot;other&quot;)<br>        return result<br><br><br># Code refactored<br># Interface (the visitor)<br>class NodeVisitorRefac:<br>    def visit_link_tag(self, node):<br>        return &quot;linktag&quot;<br><br>    def visit_tag(self, node):<br>        return &quot;tag&quot;<br><br>    def visit_string_node(self, node: object):<br>        return &quot;string&quot;<br><br><br>class NodeRefac:<br>    def accept(self, node: NodeVisitorRefac):<br>        pass<br><br><br>class LinkTagRefac(NodeRefac):<br>    def accept(self, node: NodeVisitorRefac):<br>        return node.visit_link_tag(self)<br><br><br>class TagRefac(NodeRefac):<br>    def accept(self, node: NodeVisitorRefac):<br>        return node.visit_tag(self)<br><br><br>class StringNodeRefac(NodeRefac):<br>    def accept(self, node: NodeVisitorRefac):<br>        return node.visit_string_node(self)<br><br><br># The concret visitor<br>class TextExtractorVisitorRefac(NodeVisitorRefac):<br>    def extract_text(self, nodes: list[NodeRefac]):<br>        result = []<br>        for node in nodes:<br>            result.append(node.accept(self))<br>        return result<br><br><br>def run_refac():<br>    # The original object calling its method<br>    result1 = TextExtractor().extract_text([StringNode()])<br>    # The new object accepting visitors<br>    result2 = TextExtractorVisitorRefac().extract_text([StringNodeRefac()])<br>    return result1, result2</pre><h3>Conclusion</h3><p>I highly recommend the book to everyone. The first time I read it, I found it boring and difficult to grasp the concepts just by following static code examples. However, when you actively write the code, the ideas gradually come to life. Errors will occur, and addressing them requires understanding the underlying concepts. This process transforms theory into practice and solidifies your knowledge.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca71be08a60" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-refactoring-to-patterns-1ca71be08a60">Python: Refactoring to Patterns</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python CLI system with Kinde authentication]]></title>
            <link>https://python.plainenglish.io/python-cli-with-kinde-authentication-588bd46d64b3?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/588bd46d64b3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[terminal-commands]]></category>
            <category><![CDATA[kinde]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 01:45:46 GMT</pubDate>
            <atom:updated>2024-04-27T14:04:36.596Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python CLI System with Kinde Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CYeBk_azj1c2sxpIPSajQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Xavi Cabrera</a> on <a href="https://unsplash.com/photos/yellow-red-blue-and-green-lego-blocks-kn-UmDZQDjM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Hi, how are you? This is one of my experiments again. Now I built a CLI application in Python and integrated it with the authentication tool called <a href="https://kinde.com/">Kinde</a> to manage the user permissions and allow them to perform just the granted operations. I have to say that it was not an easy task even after reading the <a href="https://kinde.com/docs/">Kinde documentation</a> many times and go deeper with its <a href="https://github.com/kinde-starter-kits/python-starter-kit">Python Starter Kit</a>. At the end, and after many hours of investigation, the solution was simple.</p><h3>CLI System overview</h3><p>To exercise my Python and design skills I created <a href="https://github.com/douglasdcm/tdd_detroid/tree/architecture">this repository</a> where I listed some requirements I think a system of a university would have. For example, students would be able to enroll to disciplines and set their grades. I started doing a <a href="https://github.com/douglasdcm/tdd_detroid/blob/main/architecture.odp">design upfront in diagrams</a> to understand the domains and features of the system. One of them was the necessity to distinguish the operations the coordinators of the university could do, but the students couldn’t and vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNC_hrISq_saUXnjCLbLEA.png" /><figcaption>Architecture overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTU1ywkX4m5pwlRWUCUjIg.png" /><figcaption>Student allowed actions</figcaption></figure><p>I did some <a href="https://github.com/douglasdcm/tdd_detroid?tab=readme-ov-file#exploration">research</a> and found many interesting authentication tools I could integrate with my system. Kinde was the selected one. It has a Python Starter Kit that is very helpful to check the initial setup and play around with the tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gKU3JoKuteSAdmZOerCEw.png" /><figcaption>Login page of the Flask app</figcaption></figure><h3>Kinde overview</h3><p>The tool is simple. The user setup an account, in my case it was a <a href="https://app.kinde.com/auth/cx/_:nav&amp;m:register&amp;psid:b0a79bbfa8ab473e930b6a52de12ecf4">free one</a>, creates an application in the preferable programming language or framework, there is a huge list of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*hz7x9H3dmI56rjOB4eyNGA.png" /><figcaption>Kinde SDKs</figcaption></figure><p>The user uses the provided <em>client_id</em> and <em>client_secret</em> to connect to the Python Starter Kit with the Kinde application. I used the Starter Kit as-is, so it is built in Flask. The user runs the Flask server and goes to home page. There, she is requested to sign-in or sign-up with her credential (email, for example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*2-xvdsE-HV6B_CfAjKo7HQ.png" /><figcaption>Home page of Flask app</figcaption></figure><p>The credential is validated by the Kinde application, if it is OK one numerical code is sent to the user email. The user has to inform the code in the sign in page and, if it works, the control is sent back to the Flask app. A simple flow to protect my CLI system. At this point, the user can perform the allowed operations by REST API while her connection is valid. When the connection is broken, for a logout, for example, the Flask app blocks the user operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iMyDNRrhYaXJUwFx1dBiA.png" /><figcaption>The user can get its details while connected</figcaption></figure><h3>Integration with my CLI system</h3><p>One of my self-imposed requirements was that the university system would have to be operated by CLI (not by a Web page).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiuZ3P8v_Ix7JG5xFRCeXg.png" /><figcaption>Authentication process with Kinde</figcaption></figure><p>It made the things harder for me, because I had to figure out how to use the Flask app session, that was in the server side, with my Ubuntu terminal, that was on the client side. If it was a Web page, everything would be straightforward as Flask works very well with it. The interesting part of the process was the issues <a href="https://github.com/kinde-starter-kits/python-starter-kit/issues/16">1</a>, <a href="https://github.com/kinde-starter-kits/python-starter-kit/issues/15">2</a> and <a href="https://github.com/kinde-starter-kits/python-starter-kit/issues/13">3</a> found and reported in Kinde Starter Kit repository. I feel happy to help the community!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*MgfG9fP1JwecwEPXKSmVrw.png" /><figcaption>Commands of the university CLI system</figcaption></figure><p>One the challenges was to figure out how to get the Kinde token after the user signed in the credentials in the sign-in page (remember, using the email and the numerical code). The Starter Kit has a login page where the user token is provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TH-mRaDIj9o-ZR0NtDio-A.png" /><figcaption>User token after login with email and numerical code</figcaption></figure><p>So, one step was done. But, for my surprise, this user token could be used in a small range of <a href="https://kinde.com/api/docs/#kinde-management-api">Kinde endpoints</a>. For example, to check if the user is logged in. To get the user permissions I would need a different administrative token. That was the painful part. <a href="https://www.postman.com/">Postman</a> helped a lot in the investigation. The response is the token I can use to get the list of all users from my Kinde application, the organizations, the roles and its permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*znFa8Zh8exyWN79-AZTxpA.png" /><figcaption>Token received after investigation</figcaption></figure><p>This is the Postman request to get the API token converted to cURL. Notice I had to send the <em>client_id</em> and the <em>client_secret</em> in the body request<em>.</em></p><pre>curl - location &#39;https://mydomain.kinde.com/oauth2/token&#39; \<br> - header &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br> - header &#39;Accept: application/json&#39; \<br> - data-urlencode &#39;audience=https://mydomain.kinde.com/api&#39; \<br> - data-urlencode &#39;grant_type=client_credentials&#39; \<br> - data-urlencode &#39;client_id=1q2w3e4r5t&#39; \<br> - data-urlencode &#39;client_secret=5t4r3e2w1q &#39;</pre><p>To make my CLI system work with Kinde, I had to make pure requests to my Flask app and to Kinde API. So, I couldn’t use the <a href="https://kinde.com/docs/developer-tools/python-sdk/">Kinde Python SDK</a> in client side. After suffer to understand the fragments of examples from the Kinde documentation, I was able to use the administrative token to get the list of all users assigned in my Kinde application. With this list, it was easy to get the user roles and use them in my CLI functions to check the user role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*TJewt3qiWCVfOYJGHfrWyQ.png" /><figcaption>Wrapper Python class to get all roles of a given user</figcaption></figure><pre>// Response with an example of a role<br>{<br>    &quot;code&quot;: &quot;OK&quot;,<br>    &quot;roles&quot;: [<br>        {<br>            &quot;id&quot;: &quot;018f1075-cde4-ab55-af1b-84b3e2b47ac2&quot;,<br>            &quot;key&quot;: &quot;student&quot;,<br>            &quot;name&quot;: &quot;student&quot;<br>        }<br>    ],<br>    &quot;message&quot;: &quot;Success&quot;<br>}</pre><p>With the <em>key</em> and/or <em>name</em> of each role, it was also easy to check the user role details. This is the role configured for a specific user in Kinde application. I set the user as <em>student</em> and <em>coordinator</em> just for test. In an ideal world, each user would have just one role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*N4Ufb8WZ3yF2YeVIvWbVIg.png" /></figure><p>This is the output of one of the commands after validating the user authentication and roles. This is one command supposed to be executed just by coordinators of the university that show each course, their disciplines and the accumulated grade (gpa) of each student.</p><pre>python cli.py list-courses<br>List of courses:<br>{<br>    &quot;adm&quot;: {<br>        &quot;students&quot;: [],<br>        &quot;subjects&quot;: [<br>            &quot;management&quot;<br>        ]<br>    },<br>   &quot;geography&quot;: {<br>        &quot;students&quot;: [],<br>        &quot;subjects&quot;: [<br>            &quot;minerals&quot;<br>        ]<br>    },<br>    &quot;mat&quot;: {<br>        &quot;students&quot;: [<br>            {<br>                &quot;gpa&quot;: 8.0,<br>                &quot;grades&quot;: [<br>                    {<br>                        &quot;5626b408430457b4b93950d81cce2953&quot;: 7<br>                    },<br>                    {<br>                        &quot;b78010c74efe5f148562c1f3bad22285&quot;: 9<br>                    }<br>                ],<br>                &quot;name&quot;: &quot;douglas&quot;<br>            },<br>            {<br>                &quot;gpa&quot;: 0.0,<br>                &quot;grades&quot;: [],<br>                &quot;name&quot;: &quot;maria&quot;<br>            }<br>        ],<br>        &quot;subjects&quot;: [<br>            &quot;calculus&quot;,<br>            &quot;algebra&quot;,<br>            &quot;analysis&quot;,<br>            &quot;geometry&quot;<br>        ]<br>    },<br>   &quot;port&quot;: {<br>        &quot;students&quot;: [],<br>        &quot;subjects&quot;: []<br>    }<br>}</pre><p>Now I set the same user just as a <em>student</em>. So, it cannot list the details of the courses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Szu-TnvCUj5c9QoGAT_iVg.png" /><figcaption>User is just a student</figcaption></figure><p>This is the returned error in the client side.</p><pre>python cli.py list-courses<br>Traceback (most recent call last):<br>  File &quot;/home/douglas/repo/tdd_detroid/cli.py&quot;, line 332, in &lt;module&gt;<br>    cli()<br>  File &quot;/home/douglas/repo/tdd_detroid/venv/lib/python3.11/site-packages/click/core.py&quot;, line 1157, in __call__<br>    return self.main(*args, **kwargs)<br>           ^^^^^^^^^^^^^^^^^^^^^^^^^^<br>  File &quot;/home/douglas/repo/tdd_detroid/venv/lib/python3.11/site-packages/click/core.py&quot;, line 1078, in main<br>    rv = self.invoke(ctx)<br>         ^^^^^^^^^^^^^^^^<br>  File &quot;/home/douglas/repo/tdd_detroid/venv/lib/python3.11/site-packages/click/core.py&quot;, line 1688, in invoke<br>    return _process_result(sub_ctx.command.invoke(sub_ctx))<br>                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>  File &quot;/home/douglas/repo/tdd_detroid/venv/lib/python3.11/site-packages/click/core.py&quot;, line 1434, in invoke<br>    return ctx.invoke(self.callback, **ctx.params)<br>           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>  File &quot;/home/douglas/repo/tdd_detroid/venv/lib/python3.11/site-packages/click/core.py&quot;, line 783, in invoke<br>    return __callback(*args, **kwargs)<br>           ^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>  File &quot;/home/douglas/repo/tdd_detroid/cli.py&quot;, line 86, in list_courses<br>    __check_coordenator_role(user_id)<br>  File &quot;/home/douglas/repo/tdd_detroid/cli.py&quot;, line 46, in __check_coordenator_role<br>    raise NonValidOperation(f&quot;The user need to be a &#39;{Roles.COORDINATOR}&#39;.&quot;)<br>src.exceptions.NonValidOperation: The user need to be a &#39;coordinator&#39;.</pre><p>The next step is to remove the sign-in/sign-up page make it be done through the CLI. Maybe an issue to other posts.</p><h3>Conclusion</h3><p>The process to integrate Kinde and a CLI system was not easy and had some issues on the path, but the persistence won :)</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588bd46d64b3" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-cli-with-kinde-authentication-588bd46d64b3">Python CLI system with Kinde authentication</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Web Crawlers with Caqui: Boosting Speed with Multi-Processing]]></title>
            <link>https://medium.com/@douglas.dcm/speed-up-your-web-crawlers-at-90-148f3ca97b6?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/148f3ca97b6</guid>
            <category><![CDATA[webdriver]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 10:14:24 GMT</pubDate>
            <atom:updated>2023-09-15T17:30:14.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8sUd1LLl4jrWlqsdDx7mQ.jpeg" /><figcaption>source: Photo by <a href="https://unsplash.com/@maicoamorim?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maico Amorim</a> on <a href="https://unsplash.com/photos/SJWPKMb9u-k?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Welcome back! In this article, we will explore a new chapter of the <a href="https://github.com/douglasdcm/caqui"><strong>Caqui</strong></a> library. This time, we will focus on leveraging Caqui to boost the speed of your web crawler. By implementing a multi-processing approach, we can achieve remarkable results. So, let’s dive in!</p><h3>Harnessing the Power of Multi-Processing</h3><p>The Caqui library is designed to utilize asynchronous calls to web drivers, enabling execution in multiple threads. However, we can further optimize its performance by employing multiple processes. To demonstrate this, we have utilized the Python multiprocessing library.</p><h3>The Results</h3><p>By creating a sub-process for each CPU in the system and executing asynchronous calls, we can collect data in parallel. The chart below showcases the time taken in seconds for a crawler to retrieve the complete content of 156 pages from four different websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*6APuFR7GweX2x768aUAKYg.png" /><figcaption>Velocity of a crawler in seconds. Source: author</figcaption></figure><p>Lets take a look on all experiment. The complete code is available <a href="https://github.com/douglasdcm/job-conqueror/blob/multiprocessing/src/controller.py"><strong>here</strong></a>.</p><h4>Experiment (I)</h4><p>The most basic execution of the crawler using a single thread.</p><p>The starting point is to create a single thread to schedule the task in the <em>__schedule_tasks</em> function that receives the company data and an <a href="https://docs.python.org/3/library/asyncio-sync.html#asyncio.Semaphore"><em>asyncio.Semaphore</em></a>. The semaphore is configured to a maximum concurrency of 1 for now.</p><pre>MAX_THREAD_CONCURRENCY = 1<br>semaphore_threads = asyncio.Semaphore(MAX_THREAD_CONCURRENCY)<br><br>def __overwrite(company=None, semaphore=None):<br>    if asyncio.get_event_loop().is_closed() is True:<br>        loop = asyncio.new_event_loop()<br>        asyncio.set_event_loop(loop)<br>    loop = asyncio.get_event_loop()<br>    try:<br>        loop.run_until_complete(__schedule_tasks(company, semaphore))<br>    finally:<br>        loop.run_until_complete(loop.shutdown_asyncgens())<br>        loop.close()<br>        return True</pre><h4>Experiment (II)</h4><p>Running the crawler with three threads setting the <em>MAX_THREAD_CONCURRENCY = 3</em>, without multiprocessing. The elapsed time is similar to (I), as one slow website prolongs the execution.</p><h4>Experiment (III)</h4><p>Introducing a single sub-process, resulting in a 50% reduction in time. Adding the following code with a <em>MAX_PROCESS_CONCURRENCY = 1</em> and a new <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Semaphore">Semaphore for multiprocesses</a>.</p><pre>MAX_PROCESS_CONCURRENCY = 1<br><br>def overwrite(database_string, companies):<br>    try:<br>        semaphore = Semaphore(MAX_PROCESS_CONCURRENCY)<br>        processes = [<br>            Process(<br>                target=__overwrite,<br>                args=(<br>                    company,<br>                    semaphore,<br>                ),<br>            )<br>            for company in companies<br>        ]<br><br>        for process in processes:<br>            process.start()<br><br>        for process in processes:<br>            process.join()<br>    finally:<br>        return True</pre><h4>Experiment (IV)</h4><p>Utilizing three sub-processes (<em>MAX_PROCESS_CONCURRENCY = 3</em>), yielding a noticeable improvement, albeit not as significant as (III).</p><h4>Experiment (V)</h4><p>You may remember Caqui uses the <em>desiredCapabilities</em> to configure the session. Enabling headless mode for the web driver, leading to another 50% reduction in time.</p><pre>CAPABILITIES = {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;browserName&quot;: &quot;anydriver&quot;,<br>        &quot;acceptInsecureCerts&quot;: True,<br>        &quot;goog:chromeOptions&quot;: {&quot;extensions&quot;: [], &quot;args&quot;: [&quot;--headless&quot;]},<br>    }<br>}<br><br>_session = await asynchronous.get_session(DRIVER_URL, CAPABILITIES)<br>_base_objects = BaseObjects(_session)<br></pre><h4>Experiment (VI) and (VII)</h4><p>Configuring the web driver to use the “eager” Load Strategy and leveraging all available CPUs. This further decreases the time spent. On average, the web crawler can retrieve the body content from each page in less than 1 second.</p><pre>CAPABILITIES = {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;browserName&quot;: &quot;anydriver&quot;,<br>        &quot;acceptInsecureCerts&quot;: True,<br>        &quot;pageLoadStrategy&quot;: &quot;eager&quot;,<br>        &quot;goog:chromeOptions&quot;: {&quot;extensions&quot;: [], &quot;args&quot;: [&quot;--headless&quot;]},<br>    }<br>}</pre><p>Compared to Experiment (I), this represents a staggering 90% increase in velocity, achieved through simple implementation and configuration.</p><h4>Parallel UI Testing with Caqui</h4><p>In addition to speeding up web crawlers, Caqui can also be used for parallel UI testing. By integrating it with pytest and pytest-asyncio-cooperative, tests can be executed in parallel using multiple threads. The installation and configuration process is straightforward. For more information, refer to the plugin documentation.</p><h4>Challenges Faced</h4><p>During our experiments, we conducted all tests on our local machine, employing the Chrome web driver and saving data in a PostgreSQL database running within a local Docker container. The setup worked flawlessly in all scenarios. However, when we switched to multiprocessing and attempted to save data in a remote database, we encountered an issue where some data was lost. Although we did not investigate this further, we suspect that the crawler was sending data to the database faster than our internet connection could handle.</p><h3>Conclusion</h3><p>By leveraging Caqui with multi-processing, you can significantly enhance the speed of your crawler and UI tests. However, it is crucial to be mindful of potential drawbacks that the multi-processing strategy may introduce.</p><p>Incorporating these tips and techniques into your web crawling endeavors will undoubtedly yield impressive results. So, go ahead and supercharge your web crawlers with Caqui!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=148f3ca97b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run Asynchronous Calls Against WebDrivers]]></title>
            <link>https://medium.com/better-programming/run-asynchronous-calls-to-webdrivers-e16b98b26fd9?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e16b98b26fd9</guid>
            <category><![CDATA[winium]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[webdriver]]></category>
            <category><![CDATA[scraping]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 03:46:42 GMT</pubDate>
            <atom:updated>2023-06-13T16:05:39.966Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introducing Caqui: a powerful tool for web scraping that is constantly evolving</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*etLLcjcbLSJ8TH5DYCaJig.png" /><figcaption>Caqui. Image credit: Author</figcaption></figure><p>Recently, I was looking for Python libraries capable of executing asynchronous commands in WebDrivers, such as <a href="https://chromedriver.chromium.org/downloads">ChromeDriver</a> or <a href="https://firefox-source-docs.mozilla.org/testing/geckodriver/index.html">GeckoDriver</a>. Unfortunately, none of them worked, so I decided to create my own library. Hence, <a href="https://github.com/douglasdcm/caqui">Caqui</a> was born.</p><p>I’ve used it in another <a href="https://github.com/douglasdcm/job-conqueror">personal project</a> to search for over 2,000 job openings on over 200 recruitment websites. I reduced the time by at least 30% from the synchronous version to the asynchronous one, just by using three concurrent instances of WebDrivers. I still managed to create <a href="https://github.com/douglasdcm/caqui">Caqui</a> as an agnostic library that, in addition to executing commands in WebDrivers, runs commands in Winium, and tests Windows applications without installing anything additional. I’ll tell you a little more about it.</p><p>I experimented with Jmeter to test a Desktop application a few years ago. I talk more about the experiment in this <a href="https://medium.com/@douglas.dcm/testing-windows-apps-with-http-rest-b4e8f80f8b7e">article</a>, so I won’t go on too long here. But basically, the experiment was to run Winium commands remotely using REST API to test the Windows Calculator. I used this knowledge to make <a href="https://github.com/douglasdcm/caqui">Caqui</a> run commands on <a href="https://github.com/2gis/Winium.Desktop">Winium</a> and WebDrivers, as described above. For this to work, it was necessary that the WebDriver be raised as a server, and its URL be used in your product, for example, a crawler.</p><p>Let’s take <a href="https://chromedriver.chromium.org/downloads">ChromeDriver</a> as an example. Did you know you can run it as an ordinary shell script? By doing this, a server is raised, and it listens for requests on port 9999.</p><pre>./chromedriver --port=9999<br>Starting ChromeDriver 113.0.5672.63 (0e1a4471d5ae5bf128b1bd8f4d627c8cbd55f70c-refs/branch-heads/5672@{#912}) on port 9999<br>Only local connections are allowed.<br>Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.<br>ChromeDriver was started successfully.</pre><p>The next sample script, found <a href="https://github.com/douglasdcm/caqui/blob/main/sample.py">here</a>, opens five instances of WebDriver in headless mode and grabs all links from webpages, 40 in total, in 2 seconds.</p><pre># It opens the WebDriver, navigate to a page and get all links<br>import asyncio<br>import time<br>from caqui import synchronous, asynchronous<br>from os import getcwd<br>from tests.constants import PAGE_URL<br><br>BASE_DIR = getcwd()<br><br>MAX_CONCURRENCY = 5  # number of webdriver instances running<br>all_anchors = []<br>semaphore = asyncio.Semaphore(MAX_CONCURRENCY)<br><br><br>async def get_all_links():<br>    async with semaphore:<br>        driver_url = &quot;http://127.0.0.1:9999&quot;<br>        capabilities = {<br>            &quot;desiredCapabilities&quot;: {<br>                &quot;browserName&quot;: &quot;chrome&quot;,<br>                &quot;marionette&quot;: True,<br>                &quot;acceptInsecureCerts&quot;: True,<br>                &quot;pageLoadStrategy&quot;: &quot;normal&quot;,<br>                &quot;goog:chromeOptions&quot;: {&quot;extensions&quot;: [], &quot;args&quot;: [&quot;--headless&quot;]},<br>            }<br>        }<br><br>        session = await asynchronous.get_session(driver_url, capabilities)<br>        await asynchronous.go_to_page(<br>            driver_url,<br>            session,<br>            PAGE_URL,<br>        )<br><br>        all_anchors = []<br>        for i in range(4):<br>            i += 1<br>            locator_value = f&quot;//a[@id=&#39;a{i}&#39;]&quot;<br>            locator_type = &quot;xpath&quot;<br>            anchors = []<br><br>            anchors = await asynchronous.find_elements(<br>                driver_url, session, locator_type, locator_value<br>            )<br>            all_anchors.extend(anchors)<br><br>        texts = []<br>        for anchor in all_anchors:<br>            text = await asynchronous.get_property(driver_url, session, anchor, &quot;href&quot;)<br>            texts.append(text)<br><br>        for text in texts:<br>            print(f&quot;Link found &#39;{text}&#39;&quot;)<br><br>        synchronous.close_session(driver_url, session)<br><br><br># Reference: https://stackoverflow.com/questions/48483348/how-to-limit-concurrency-with-python-asyncio<br>async def main():<br>    number_of_websites = range(10)<br>    tasks = [asyncio.ensure_future(get_all_links()) for number in number_of_websites]<br>    await asyncio.gather(*tasks)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    start = time.time()<br>    loop = asyncio.get_event_loop()<br>    try:<br>        loop.run_until_complete(main())<br>    finally:<br>        loop.run_until_complete(loop.shutdown_asyncgens())<br>        loop.close()<br>        end = time.time()<br>        print(f&quot;Found 40 links&quot;)  # 10 websites with 4 links each<br>        print(f&quot;Time: {end-start:.2f} sec&quot;)</pre><p>Output:</p><pre>(venv) douglas@douglas:~/repo/caqui$ python sample.py <br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Link found &#39;http://any1.com/&#39;<br>Link found &#39;http://any2.com/&#39;<br>Link found &#39;http://any3.com/&#39;<br>Link found &#39;http://any4.com/&#39;<br>Found 40 links<br>Time: 2.07 sec</pre><p>This was a tremendous performance boost, especially for my data scraping projects.</p><p>Not to mention the possibility of running remote commands, initially with <a href="https://github.com/2gis/Winium.Desktop">Winium</a>, to test Windows applications. Returning to the experiment with <a href="https://jmeter.apache.org/">Jmeter</a>, at that time, I was able to remotely test a .Net application that ran on Windows Server and was constantly updated. Doing it this way, the testing team didn’t need to maintain multiple local instances of the application on an unapproved operating system (we used Windows 10).</p><p>It was possible to update the application on a shared Windows Server and leave <a href="https://github.com/2gis/Winium.Desktop">Winium</a> running on this server and do the tests on our local machines with <a href="https://jmeter.apache.org/">Jmeter</a>. Now, with <a href="https://github.com/douglasdcm/caqui">Caqui</a>, it tends to be simpler as we’re not using a performance testing tool to make GUI tests. <a href="https://github.com/douglasdcm/caqui">Caqui</a> is a simple collection of functions, like get_element, click, and other ones that make the work much easier.</p><p>Here is an example of the execution against Winium. Again, the WebDriver needs to be running as a server on Windows OS.</p><pre>.\Winium.Desktop.Driver.exe --port=9999</pre><p>The code can be gotten from <a href="https://github.com/douglasdcm/caqui/blob/main/sample-winium.py">here</a>:</p><pre># Simple example of usage of caqui with Windows Calculator<br># It opens the Calculator and clicks the number &quot;8&quot;<br># Test works just i Windows environment. Tested with Windows 10<br>from caqui import synchronous<br><br><br>def main():<br>    driver_url = &quot;http://127.0.0.1:9999&quot;<br>    capabilities = {<br>        &quot;capabilities&quot;: {&quot;firstMatch&quot;: [{}], &quot;alwaysMatch&quot;: {}},<br>        &quot;desiredCapabilities&quot;: {<br>            &quot;debugConnectToRunningApp&quot;: &quot;false&quot;,<br>            &quot;app&quot;: &quot;C:/windows/system32/calc.exe&quot;,<br>        },<br>    }<br>    session = synchronous.get_session(driver_url, capabilities)<br>    element = synchronous.find_element(<br>        driver_url, session, locator_type=&quot;name&quot;, locator_value=&quot;Eight&quot;<br>    )<br><br>    synchronous.click(driver_url, session, element)<br>    synchronous.close_session(driver_url, session)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXKdYd9exzVjmAPZIhehlw.png" /><figcaption>Test opens Windows Calculator and clicks on number 8. Image credit: Author</figcaption></figure><h3>Conclusion</h3><p><a href="https://github.com/douglasdcm/caqui">Caqui</a> is an agnostic library that can run asynchronous and synchronous commands against WebDrivers and Winium using the same set of functions. It is a powerful tool for web scraping and is constantly evolving. Hence all help is welcome :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e16b98b26fd9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/run-asynchronous-calls-to-webdrivers-e16b98b26fd9">Run Asynchronous Calls Against WebDrivers</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with PyScript, Postgres and K8S]]></title>
            <link>https://medium.com/@douglas.dcm/playing-with-pyscript-postgres-and-k8s-55690f0cd4da?source=rss-834bb8ca859b------2</link>
            <guid isPermaLink="false">https://medium.com/p/55690f0cd4da</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[pyscript]]></category>
            <category><![CDATA[postgrest]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Douglas Cardoso]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 03:24:26 GMT</pubDate>
            <atom:updated>2023-02-15T03:24:26.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jLSxNQvNqsYr02VB_wr96A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@artturijalli?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artturi Jalli</a> on <a href="https://unsplash.com/photos/g5_rxRjvKmg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve talked in other posts about my hobby of experimenting with technologies that interest me. This time I spent some time experimenting with <a href="https://pyscript.net/">PyScript</a>. I have to say that I decided to study PyScript, because I’m a no-no with JavaScript and <strong>I wanted to know if using PyScript it would be possible to get the same results I get when using JavaScript</strong>. So, in my tests I used pure Python to develop an application that integrates front-end, back-end and some database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wh8tTJJKDuQNvXK1nm2NRg.png" /><figcaption>Front-end, back-end and database</figcaption></figure><p>As the experiment progressed, I added a few more ingredients to the mix: PostgREST, Docker, and Kubernetes. In case you’re curious, I left the code in this <a href="https://github.com/douglasdcm/tdd_detroid">repository</a> that is constantly updated. For each new experiment I created a separate branch and as the process is dynamic (I do several experiments simultaneously), it may be that the tests in some of them are not passing. I’m trying to keep at least the master branch stable. If you have any questions, feel free to ask me there. Without further ado, let’s get to the results:</p><h4>1 — PyScript + Sqlite</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LUOOYA9GYckklBHar7TUA.png" /><figcaption>PyScript calling Python code in “core”</figcaption></figure><p>In the first version of the application, I developed (in Python) some functions that would be the business logic of the system (core). This core would integrate with a <a href="https://www.sqlite.org/index.html">Sqlite</a> database to persist entered data. Through PyScript I made the calls directly to these functions without using the REST API. Basically, in HTML I import the functions according to the <a href="https://docs.pyscript.net/latest/tutorials/getting-started.html#importing-the-needed-libraries">PyScript documentation</a> that communicate with the database. With this initial configuration, it was possible to perform all data integration and persistence, however, data is lost with each page update (refresh). <strong>This scenario can be interesting for small projects that are not concerned with data persistence or for prototyping</strong>, since the implementation is very fast and straightforward without the need to create REST API for front-end communication with the back-end and database. data.</p><h4>2 — PyScript + Postgres</h4><p>In this second test, I simply replaced Sqlite with <a href="https://www.postgresql.org/">Postgres</a> making the necessary adaptations and corrections. For example, adding username and password in my functions. To my surprise, the simple substitution didn’t work, because PyScript uses Pyodide which, in turn, doesn’t support sockets. See more details in the <a href="https://pyodide.org/en/stable/usage/faq.html#how-can-i-load-external-files-in-pyodide">Pyodide documentation</a>. <strong>Thus, the Python functions that the HTML called could not open a connection to the database</strong>. This did not happen with Sqlite, because, as far as I understand, PyScript creates a virtual environment and creates the Sqlite database (data file) in it. No need for sockets. This then led me to the next experiment.</p><h4>3 — PyScript + PostgREST</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4R3EMAp_6u2rOd4OOb6gSQ.png" /><figcaption>PyScrpit saving data using PostgREST</figcaption></figure><p><a href="https://postgrest.org/en/stable/#">PostgREST</a> is a server that provides a native REST API for Postgres. In other words, it is not necessary to create your own API to make the UI communicate with the database. As I couldn’t make the calls directly through HTML, I momentarily replaced front-end and back-end integration via the PostgREST REST API. This time the core functions were not being used. Just direct UI calls to PostgREST using Pyodide. <strong>This worked very well and was relatively simple, however the application’s business logic (core) was not used</strong>, so any data passed to the API would have to be handled at the highest level function and not by a specialist class. <strong>This configuration is interesting for its simplicity and can be used for prototyping or systems that don’t have any business rules</strong>. Remembering that the data is persisted in Postgres, so nothing is lost. But, in my case, I needed to use business rules, so I evolved my tests.</p><h4>4 — PyScript + PostgREST (requests)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6hGmB6xLAql197KhWxIug.png" /><figcaption>Core saving data using PostgREST</figcaption></figure><p>In this new configuration, I removed all the core functions that connected directly to the database and replaced them with PostgREST REST calls. I used Python’s “requests” library. One detail about my application is that it was primarily made as a command line application (CLI). Until this moment, PyScript was not yet in use, as the main interface was the user terminal. That configuration (PostgREST in the core) worked great for the CLI application, but again failed in the UI. This error could not be debugged, because neither the “console” nor the “network” tab of the browser showed any error that gave any clue. But, what if we change the “requests” library to “pyodide”?</p><h4>5 — PyScript + PostgreST (Pyodide)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_znD45_CozufyPLgRZJp1Q.png" /><figcaption>Core saving data using Pyodide</figcaption></figure><p>When I replaced the “requests” library with <a href="https://pyodide.org/en/stable/">Pyodide</a> in the core (yes, here I am using Pyodide in my back-end) the <strong>UI calls worked and the data was persisted to the database</strong>. However, since Pyodide cannot be installed via “pip” in my virtual environment, I haven’t found a way to make my unit tests work. They all broke from not finding the “pyodide” library. Now things work, but at the cost of <strong>not being able to be tested by unit tests</strong>. Again, it can be an interesting setup for systems that don’t have many business rules and it’s feasible to only have UI tests. But, that’s not my case, I have a lot of business rules and I need my unit tests. And if…</p><h4>6 — PyScript + Flask + PostgREST (requests)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUeQZps4v4o-mhJe1ZxLxg.png" /><figcaption>PyScript calling route “do” to save data</figcaption></figure><p>My application already runs with <a href="https://flask.palletsprojects.com/en/2.2.x/">flask</a>, but so far I was just making my HTML communicate directly with my back-end without REST API in this part. So my flask server only had the “/” route for home page rendering. When I added new routes on the flask server and had the PyScript functions call it, everything worked. Now, I have HTML that doesn’t use JavaScript, I have Python functions that communicate with the back-end (via flask), this back-end communicates with the database (via PostgREST) ​​and the data is persisted. <strong>This all works, but note that it was necessary to add a few more components to not have JavaScript in the UI</strong>. Between one test and another, I went a little further and tried Docker integration.</p><h4><strong>7 — PyScript + Docker</strong></h4><p>In this configuration, almost nothing changes, apart from having to create the <a href="https://www.docker.com/">Docker</a> images on my own,<strong> the application remains the same</strong>. It even makes it simpler to test the UI. The next step was Kubernetes.</p><h4>8 — PyScript + Kubernetes</h4><p>Here I needed to make some adjustments to the application to make it work on <a href="https://kubernetes.io/">Kubernetes</a>. I’m using a single Pod with multiple containers that communicate natively over “localhost” within the Pod. I needed to change the host in the URLs to a DNS and expose the ports of all containers via Services (this was more of a hack than a configuration I would use in production). <strong>Having this DNS, I was able to change my “hosts” file to point to 127.0.0.1 when testing through Docker or to “$(minikube ip)” when testing through Kubernetes</strong>.</p><h4>Conclusion</h4><p>I confess that I wasn’t entirely happy with the result, because it wasn’t as simple as calling Python functions from PyScript. That said, I think PyScript has great potential, but it’s not production ready. That’s what their <a href="https://pyscript.net/">documentation</a> says.</p><blockquote>Please be advised that PyScript is very alpha and under heavy development. There are many known issues, from usability to loading times, and you should expect things to change often. We encourage people to play and explore with PyScript, but at this time we do not recommend using it for production.</blockquote><p>If socket support is added to Pyodide I think things would be simpler. The fact that I was able to make it work with Docker and Kubernetes without huge additional configurations made me happy even though PyScript is not recommended for production.</p><p>Tell me in the comments what you think about these experiments! Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55690f0cd4da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>