<?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 Oliver Holmes on Medium]]></title>
        <description><![CDATA[Stories by Oliver Holmes on Medium]]></description>
        <link>https://medium.com/@oliver-holmes?source=rss-b958a182104b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WJjUlWqlKPMrNvapw0c_rA.jpeg</url>
            <title>Stories by Oliver Holmes on Medium</title>
            <link>https://medium.com/@oliver-holmes?source=rss-b958a182104b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:14:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oliver-holmes/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[Python Prefect: A Guide To Your First Steps]]></title>
            <link>https://medium.com/@oliver-holmes/prefect-a-guide-to-your-first-steps-58550baf5c3a?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/58550baf5c3a</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[task-runners]]></category>
            <category><![CDATA[perfect]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 12:20:26 GMT</pubDate>
            <atom:updated>2024-09-24T00:41:08.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgO4id9J4iCSxVykVsHmWA.jpeg" /><figcaption>Your first steps on this jounery</figcaption></figure><p>Python Prefect is an open-source workflow orchestration tool that simplifies the process of building, running, and monitoring data pipelines.</p><blockquote>Designed by engineers for engineers.</blockquote><p>Prefect allows you to focus on writing code that delivers value rather than managing the complexities of workflow orchestration. This article will guide you through the initial steps of getting started with Prefect, including stepup, understanding key concepts, and creating your first flow.</p><p>For this guide I’m going to use UV for package management: <a href="https://github.com/astral-sh/uv">https://github.com/astral-sh/uv</a></p><h3>Prerequisites</h3><ul><li>Python 3.12</li><li>Prefect 3.0.3</li><li>The UV package manager: <a href="https://github.com/astral-sh/uv">https://github.com/astral-sh/uv</a></li></ul><h3>Prefect Concepts</h3><p>Before diving into coding, lets look at some Prefect concepts:</p><h4>Flows</h4><p>A <strong>Flow</strong> is the primary unit of work in Prefect. It represents an orchestrated pipeline of tasks. Think of it as a workflow that defines how tasks are connected and executed.</p><h4>Tasks</h4><p>A <strong>Task</strong> is a single unit of work within a flow. Tasks are Python functions that perform specific actions, such as data processing, API calls, or computations.</p><h4>Parameters</h4><p><strong>Parameters</strong> allow you to make your flows dynamic by passing data into them at runtime. This makes your flows flexible and reusable.</p><h4>States</h4><p><strong>States</strong> represent the current status of a flow or task. Common states include Pending, Running, Completed, and Failed. States help you monitor and manage the execution of your workflows.</p><p>A full list can be found at: <a href="https://docs.prefect.io/3.0/develop/manage-states">https://docs.prefect.io/3.0/develop/manage-states</a></p><h3>Setup</h3><p>Initialise the project, install prefect and activate your virtual envionment:</p><pre>uv init .<br>uv add prefect<br>source .venv/bin/activate</pre><h3>Your First Prefect Flow</h3><p>Let’s create a simple Prefect flow using the virtual environment you’ve set up.</p><h4>Step 1: Create a Python Script</h4><p>Create a file named my_first_flow.py in your project directory:</p><pre>touch my_first_flow.py</pre><h4>Step 2: Write the Flow Code</h4><p>Open my_first_flow.py in your preferred text editor and add the following code:</p><pre>from prefect import task, flow<br><br>@task<br>def say_hello(name):<br>    print(f&quot;Hello, {name}!&quot;)<br><br>@task<br>def add_numbers(x, y):<br>    return x + y<br><br>@task<br>def display_result(result):<br>    print(f&quot;The result is {result}&quot;)<br><br>@flow<br>def my_first_flow():<br>    say_hello(&quot;World&quot;)<br>    result = add_numbers(5, 7)<br>    display_result(result)<br><br>if __name__ == &quot;__main__&quot;:<br>    my_first_flow()</pre><h4>Step 3: Open Prefect server to see results</h4><p>Run a local server to view runs with:</p><pre>prefect server start    </pre><p>This will run the server and you should see:</p><pre> ___ ___ ___ ___ ___ ___ _____ <br>| _ \ _ \ __| __| __/ __|_   _| <br>|  _/   / _|| _|| _| (__  | |  <br>|_| |_|_\___|_| |___\___| |_|  <br><br>Configure Prefect to communicate with the server with:<br><br>    prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api<br><br>View the API reference documentation at http://127.0.0.1:4200/docs<br><br>Check out the dashboard at http://127.0.0.1:4200</pre><p>If all goes well you should be able to navigate to the dashboard at: <a href="http://127.0.0.1:4200/dashboard">http://127.0.0.1:4200/dashboard</a> and see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zP5b66_rR0krXFbvhE59Qw.png" /></figure><h4>Step 4: Run your flow and see the result</h4><p>Open a new terminal in your project and run:</p><pre>source .venv/bin/activate<br>python my_first_flow.py </pre><p>You should get back something like:</p><pre>20:53:33.716 | INFO    | prefect.engine - Created flow run &#39;sassy-starling&#39; for flow &#39;my-first-flow&#39;<br>20:53:33.717 | INFO    | prefect.engine - View at http://127.0.0.1:4200/runs/flow-run/5f68a8a9-cd88-4fb5-9280-0c913f565703<br>20:53:33.761 | INFO    | Task run &#39;say_hello-fe3&#39; - Created task run &#39;say_hello-fe3&#39; for task &#39;say_hello&#39;<br>Hello, World!<br>20:53:33.776 | INFO    | Task run &#39;say_hello-fe3&#39; - Finished in state Completed()<br>20:53:33.797 | INFO    | Task run &#39;add_numbers-e4a&#39; - Created task run &#39;add_numbers-e4a&#39; for task &#39;add_numbers&#39;<br>20:53:33.799 | INFO    | Task run &#39;add_numbers-e4a&#39; - Finished in state Completed()<br>20:53:33.815 | INFO    | Task run &#39;display_result-766&#39; - Created task run &#39;display_result-766&#39; for task &#39;display_result&#39;<br>The result is 12<br>20:53:33.817 | INFO    | Task run &#39;display_result-766&#39; - Finished in state Completed()<br>20:53:33.832 | INFO    | Flow run &#39;sassy-starling&#39; - Finished in state Completed()</pre><p>You can see we were able to get the results back as “Hello, World!” and “The result is 12”.</p><p>You can see you runs on <a href="http://127.0.0.1:4200/runs">http://127.0.0.1:4200/runs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkhrGoo0GITxl4lwU1qdfw.png" /></figure><p>Run it again a few times to see the runs accumulate on this page.</p><h4>Step 5: Update the flow to have a parameterised method</h4><p>Update my_first_flow.py to:</p><pre>from prefect import task, flow<br><br>@task<br>def say_hello(name):<br>    print(f&quot;Hello, {name}!&quot;)<br><br>@task<br>def add_numbers(x, y):<br>    return x + y<br><br>@task<br>def display_result(result):<br>    print(f&quot;The result is {result}&quot;)<br><br>@flow<br>def my_parameterized_flow(name: str = &quot;World&quot;, x: int = 5, y: int = 7):<br>    say_hello(name)<br>    result = add_numbers(x, y)<br>    display_result(result)<br><br>if __name__ == &quot;__main__&quot;:<br>    my_parameterized_flow(name=&quot;Oliver&quot;, x=10, y=20) # Or your own name :)</pre><p>Run: python my_first_flow.py again and check: <a href="http://127.0.0.1:4200/flows">http://127.0.0.1:4200/flows</a></p><p>You should see your new flow my-parameterized-flow and click on it to see the last run.</p><h4><strong>GitHub Repo</strong></h4><ul><li><a href="https://github.com/OliverAHolmes/code-examples/tree/main/prefect-uv">https://github.com/OliverAHolmes/code-examples/tree/main/prefect-uv</a></li></ul><h4>References</h4><ul><li><a href="https://github.com/astral-sh/uv">https://github.com/astral-sh/uv</a></li><li><a href="https://docs.prefect.io/3.0/get-started/quickstart">https://docs.prefect.io/3.0/get-started/quickstart</a></li><li><a href="https://docs.prefect.io/3.0/develop/manage-states">https://docs.prefect.io/3.0/develop/manage-states</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58550baf5c3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerised Testing: Running FastAPI Database Tests Locally with Docker & PostgreSQL]]></title>
            <link>https://python.plainenglish.io/containerised-testing-running-fastapi-database-tests-locally-with-docker-postgresql-e02095c93061?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e02095c93061</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 05:47:00 GMT</pubDate>
            <atom:updated>2023-10-08T02:31:26.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVmN596J8rAkAzi2FE2v7w.png" /></figure><h3>Why set up a containerized testing environment</h3><p>In today’s era of rapid software development, ensuring the robustness and reliability of applications is paramount. One of the most critical aspects of this reliability is the art of testing, especially when databases are involved. Traditional database testing methods often require developers to set up a separate database environment, configure it, and sometimes even populate it with mock data. This approach is not only time-consuming but also introduces potential discrepancies between development, testing, and production environments. Enter the world of containerized testing.</p><p>Containerized testing offers an elegant solution to these challenges. By encapsulating the entire environment, including the application, its dependencies, and the database, within Docker containers, we can achieve consistent and reproducible testing environments. This ensures that our tests run the same way every time, regardless of where they’re executed.</p><p>In this guide, we’ll delve deep into setting up a local testing environment for a FastAPI application using Docker. We’ll specifically use PostgreSQL as our database of choice, given its widespread use and robust feature set. By the end of this tutorial, you’ll be equipped with the knowledge to run your FastAPI database tests in a local, containerized environment, ensuring accuracy and efficiency in your testing process.</p><h3>Prerequisites</h3><p>Before diving into the tutorial, ensure you’re equipped with the following:</p><ol><li>Basic Understanding of Python: Since FastAPI is a modern, fast (high-performance) web framework for building APIs with Python, you should be familiar with Python syntax and basic programming concepts.</li><li>Familiarity with FastAPI: While we’ll cover the specifics related to testing, having prior knowledge about building APIs with FastAPI would be beneficial.</li><li>Docker Knowledge: You should understand the basics of Docker, such as what containers are, how to build Docker images, and how to run containers. If you’re new to Docker, consider going through Docker’s <a href="https://docs.docker.com/get-started/">official Getting Started guide</a>.</li><li>PostgreSQL Basics: Understand the fundamentals of PostgreSQL databases, including how to create databases, tables, and run basic SQL queries.</li><li>Development Environment: Ensure you have the following tools installed:</li></ol><ul><li>Python 3.11</li><li>Docker</li><li>Local PostgreSQL client</li></ul><h3>Implementation</h3><h4>Create docker-compose.yml</h4><p>In this example I’ve created a docker to test the Postgres database and a docker to run the project locally for development.</p><ol><li>posgres-dev: Is for local development and includes a persistant data store called volumes which will maintain data between testing sessions.</li><li>posgres-test: Is only for running unit tests and doesn’t include a persistent data store as we want a fresh database for each test run.</li></ol><pre>version: &quot;3.8&quot;<br><br>services:<br>  postgres-dev:<br>    image: postgres:16<br>    volumes:<br>      - pgdata:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_DB: devdb<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: password<br>    ports:<br>      - 5432:5432<br>  postgres-test:<br>    image: postgres:16<br>    environment:<br>      POSTGRES_DB: testdb<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: password<br>    ports:<br>      - 5433:5432<br>volumes:<br>  pgdata:</pre><h4>Create SQL Model</h4><p>In this example I have create a User model for the API routes to use. This model with also be used to create the database tables.</p><pre>from typing import Optional<br>from datetime import datetime as dt<br>from sqlmodel import Field, SQLModel, Column, String<br><br><br>class User(SQLModel, table=True):<br>    &quot;&quot;&quot;Represents a user stored in the database.&quot;&quot;&quot;<br><br>    __tablename__ = &quot;user&quot;<br>    id: Optional[int] = Field(default=None, primary_key=True, index=True)<br>    username: str = Field(<br>        description=&quot;Username for the user.&quot;,<br>    )<br>    email: str = Field(<br>        sa_column=Column(String, unique=True, index=True),<br>        description=&quot;Email address of the user.&quot;,<br>    )<br>    full_name: Optional[str] = Field(<br>        description=&quot;Full name of the user.&quot;,<br>    )<br>    hashed_password: str = Field(<br>        description=&quot;Hashed password for the user.&quot;,<br>    )<br>    created_at: dt = Field(<br>        default_factory=dt.utcnow,<br>        description=&quot;Timestamp of when the user was registered.&quot;,<br>    )</pre><h4>Create Route</h4><p>This is one example route, if you would like to see a full list of CRUD routes please check the examples in the repository listed at the end of the article.</p><pre>&quot;&quot;&quot;<br>FastAPI router for handling User operations.<br><br>This module contains endpoints for creating, retrieving, updating, and deleting users.<br>&quot;&quot;&quot;<br><br>from fastapi import APIRouter, HTTPException<br>from pydantic import BaseModel<br>from db import SessionLocal<br>from models import User<br><br>router = APIRouter(prefix=&quot;/users&quot;)<br><br>@router.post(&quot;/&quot;)<br>async def create_user(user: User):<br>    &quot;&quot;&quot;<br>    Create a new user.<br><br>    Parameters:<br>        user (User): The user to create.<br><br>    Returns:<br>        dict: Confirmation message and user_id of the created user.<br>    &quot;&quot;&quot;<br><br>    session = SessionLocal()<br><br>    db_user = User(**user.dict())<br>    session.add(db_user)<br><br>    session.commit()<br>    user_id = db_user.id<br><br>    session.close()<br><br>    return {&quot;message&quot;: &quot;User created successfully&quot;, &quot;user_id&quot;: user_id}</pre><h4>Create Tests for routes</h4><p>This is a unit test for the route, in this test I use the test client provided by FastAPI and test the create user route. Again for a full list of example tests please checkout the repository listed at the end of the article.</p><pre>from fastapi import status<br>from fastapi.testclient import TestClient<br>from main import app<br>from db import SessionLocal<br>from models import User<br><br>client = TestClient(app)<br><br><br>def test_create_user():<br>    # Creating a new user<br>    response = client.post(<br>        &quot;/users/&quot;,<br>        json={<br>            &quot;username&quot;: &quot;testuser&quot;,<br>            &quot;email&quot;: &quot;test@email.com&quot;,<br>            &quot;full_name&quot;: &quot;Test User&quot;,<br>            &quot;hashed_password&quot;: &quot;hashedpassword123&quot;,  # In a real-world scenario, this should be hashed<br>        },<br>    )<br>    assert response.status_code == status.HTTP_200_OK<br>    assert response.json()[&quot;message&quot;] == &quot;User created successfully&quot;<br>    user_id = response.json()[&quot;user_id&quot;]<br><br>    # Validate database<br>    db = SessionLocal()<br>    db_user = db.query(User).filter(User.id == user_id).first()<br>    assert db_user is not None<br>    db.close()</pre><h4>Configure database settings for testing</h4><p>Set up the database config for local development and testing:</p><ol><li>Get the environment variable and use it to decide what database to use:<br>if settings.ENV == “testing”</li><li>Techinally we should have a fresh database for the tests, but just is case if we’re using a test environment we drop all the current tables:<br>SQLModel.metadata.drop_all(engine)</li></ol><pre>&quot;&quot;&quot;Module for database setup and utilities using SQLModel and SQLAlchemy.&quot;&quot;&quot;<br><br>from sqlmodel import create_engine, SQLModel<br>from sqlalchemy.orm import sessionmaker<br>from config import settings<br><br><br>if settings.ENV == &quot;testing&quot;:<br>    SQLALCHEMY_DATABASE_URL = &quot;postgresql://user:password@localhost:5433/testdb&quot;<br>else:<br>    SQLALCHEMY_DATABASE_URL = &quot;postgresql://user:password@localhost:5432/devdb&quot;<br><br>engine = create_engine(SQLALCHEMY_DATABASE_URL)<br><br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br><br><br>def create_db():<br>    &quot;&quot;&quot;Creates a new database if it doesn&#39;t exist, and removes it if we are in testing mode.&quot;&quot;&quot;<br><br>    if settings.ENV == &quot;testing&quot;:<br>        SQLModel.metadata.drop_all(engine)<br><br>    # Create tables if they don&#39;t exist<br>    SQLModel.metadata.create_all(engine)<br><br><br>def get_db():<br>    &quot;&quot;&quot;Gets a new database session and closes it when done.<br><br>    Yields:<br>        Session: a new database session<br>    &quot;&quot;&quot;<br><br>    session = SessionLocal()<br>    try:<br>        yield session<br>    finally:<br>        session.close()</pre><h4>Run with code coverage</h4><p>Run these commands to use the docker to test the routes we constructed:</p><ol><li>docker-compose up -d postgres-test<br>This command will start a service named postgres-test defined in a docker-compose.yml file. The -d flag will run it in detached mode, meaning the service will run in the background.</li><li>wait-for-postgres.sh<br>This is a bash script that waits until the conatiner is ready to run. It’s used as a buffer to ensure the postgres-test container is up and running before the tests are run. This is a simple way to deal with potential race conditions, the should be replaced for the type of database you are using. For an example of what this script does check the repository link provided at the end of this article.</li><li>export ENV=testing: This sets an environment variable named ENV with the value testing. <br>pytest tests -x -vv --cov=. --cov-report=term-missing: This is a command to run tests using pytest. Here&#39;s the breakdown of the flags:<br>-x: Stop the test run after the first failure.<br>-vv: Increase verbosity of the test output.<br>--cov=.: Measure coverage over the current directory.<br>--cov-report=term-missing: Display the coverage report in the terminal and show lines that are missing coverage.<br>docker-compose stop postgres-test:stops the postgres-test service.</li><li>docker-compose rm -f postgres-test:After stopping the postgres-test service, this command removes the container. The -f flag forces the removal without asking for confirmation.</li></ol><pre>docker-compose up -d postgres-test<br>wait-for-postgres.sh<br>export ENV=testing &amp;&amp; pytest tests -x -vv --cov=. --cov-report=term-missing<br>docker-compose stop postgres-test<br>docker-compose rm -f postgres-test</pre><h3>Conclusion</h3><p>In the realm of software development, the rapid and ever-evolving landscape demands not just innovative solutions but also reliable and efficient approaches to address potential challenges.</p><p>The guide presented above provides a method for setting up a containerized testing environment using FastAPI and Docker with PostgreSQL, although you could use the same method for any other framework or programming language paired with any other type of datatbase.</p><p>The steps delineated above encapsulate the essence of a modern development workflow, placing emphasis on repeatability, scalability, and maintainability. They ensure that every test is conducted in a pristine environment, minimizing external interference and the chances of inconsistencies. Furthermore, leveraging Docker and its capabilities ensures that our testing infrastructure remains as agile and adaptable as the applications it tests.</p><p>In essence this is method to minimise breaking changes and bullet proof your development life cycle, happy hacking!</p><blockquote><em>GitHub Repo</em></blockquote><p><a href="https://github.com/OliverAHolmes/fastapi-docker-postgresql-test-example">GitHub - OliverAHolmes/fastapi-docker-postgresql-test-example: This demonstrates how to test FastAPI endpoints reliant on a PostgreSQL database.</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e02095c93061" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/containerised-testing-running-fastapi-database-tests-locally-with-docker-postgresql-e02095c93061">Containerised Testing: Running FastAPI Database Tests Locally with Docker &amp; PostgreSQL</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[Mocking Data for FFLib in Apex for Salesforce]]></title>
            <link>https://medium.com/better-programming/mocking-data-for-fflib-in-apex-for-salesforce-a8f0453c1a9?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f0453c1a9</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 09:40:10 GMT</pubDate>
            <atom:updated>2022-05-04T10:15:19.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>Speed up your unit tests by mocking data for FFLib Apex selectors!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1NuWM94i5y1SIwhtD-goA.jpeg" /></figure><h4>Why do we want to mock our FFLib Apex Unit Tests?</h4><p>We want to keep our flow state and one of the principles used to keep us in a flow state is to get continuous clear and immediate feedback. In software development we are lucky to have structured methodologies to create testable blocks of code that keep us safe.</p><p>The part of that last paragraph that is important is the word: <em>“immediate”. </em>The faster these tests run and the easier it is to run then the better development experience you’re going to have.</p><p>If you want to get some more information on the concept of a mocking data in Apex before jumping into FFLib mocking checkout this Trailhead:</p><p><a href="https://trailhead.salesforce.com/en/content/learn/modules/unit-testing-on-the-lightning-platform/mock-stub-objects">Unit Testing on the Lightning Platform</a></p><h4>When to mock and when not to mock!</h4><p>The short answer is that we mock selectors that use the <a href="https://github.com/apex-enterprise-patterns/fflib-apex-common">FFLib Apex Common</a> Library for DML operations.</p><p>At our organisation we have two types of Apex tests:</p><ul><li><strong>Unit Tests: </strong><br>For domain logic, these don’t interact with the database, instead we mock the a Selectors, this means they only test the logic of the methods. These are typically used for methods in a Controller class or a Service class.</li><li><strong>Integration Tests: </strong><br>For methods that interact with the database using DML operations or for attaining object schemas. These are typically used for Selector methods, but can sometimes include a service method for object schemas.</li></ul><h4>Create a global date</h4><p>It’s good to set up a global data or DateTime for your tests.</p><p>If you set up a global dateTime then you know that your time will be consistent when your tests are run. This can be useful in case your tests start run at a min before midnight and then following tests in your test set to run on the next day. This has caused issues in the past so to prevent issues set a global test dateTime or Date with:</p><pre>static Date todaysDate = Date.today();</pre><h4>First set up the test data</h4><p>The difference between a Salesforce object that has been saved in the database and one that hasn’t is simple — if it’s been saved in the database it has an Id.</p><p>FFLib has a great way of mocking the Id for an object so it can be treated like an object that has been saved to the database even though it hasn’t, hence making it a mocked object.</p><p>To create a mocked object we use the method:</p><pre>fflib_IDGenerator.generate(sObject.SObjectType);</pre><p>This gives it an Id when it’s initialized even though it exists only in memory. We now have our test set up with some mocked data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd0404496ea139cb846f48dd6cea31a8/href">https://medium.com/media/cd0404496ea139cb846f48dd6cea31a8/href</a></iframe><h4>Let’s create the test</h4><p>For creating the test we’ll use the pattern:</p><ul><li>Set up</li><li>Create mocks</li><li>Given</li><li>When</li><li>Then</li></ul><p><strong>Set up</strong></p><p>Create an instance of the test object in a list:</p><pre>Contact testContact = testContact();<br>List&lt;Contact&gt; testContactsList = new List&lt;Contact&gt; {testContact};<br>Set&lt;Id&gt; testContactsSet = new Set&lt;Id&gt;{testContact.Id};</pre><p><strong>Create mocks</strong></p><p>Set up the mock selectors:</p><pre>fflib_ApexMocks mocks = <strong>new</strong> fflib_ApexMocks();</pre><pre>ContactSelector contactSelectorMock = <br>(ContactSelector) mocks.mock(ContactSelector.class);</pre><p><strong>Given</strong></p><p>Test up the mocks to return the mocked data:</p><pre>mocks.startStubbing();</pre><pre>mocks.when(contactSelectorMock.sObjectType())<br>.thenReturn(Contact.SObjectType);</pre><pre>mocks.when(contactSelectorMock.selectById(testContactsSet))<br>.thenReturn(testContactsList);</pre><pre>mocks.stopStubbing();</pre><pre>Application.Selector.setMock(contactSelectorMock);</pre><p><strong>When</strong></p><p>Run the test and get the result:</p><pre><em>Test</em>.startTest();</pre><pre>List&lt;Contact&gt; result = ConatctController.getContacts(contactId);</pre><pre><em>Test</em>.stopTest();</pre><p><strong>Then</strong></p><p>Verify that the mocked selector worked and check that the method returned the correct result:</p><pre>((ContactSelector) mocks.verify(contactSelectorMock)).selectById(testContactsSet);</pre><pre><em>System</em>.assertEquals(1, result.size(), &#39;Check that the record returned.&#39;);</pre><pre><em>System</em>.assertEquals(testContactsList[0].Id, result[0].Id, &#39;Check correct Contact Id returned.&#39;);</pre><pre>System.assertEquals( 9  todaysDate,  10  result[0].Date_Created__c,  11  &#39;Check record created on the correct date.&#39; 12);</pre><h4>Put it all together</h4><p>This is a code example of what a Unit Test that utilizes the FFLib mocks would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/189f42129e2b537da0d6b780cb288e41/href">https://medium.com/media/189f42129e2b537da0d6b780cb288e41/href</a></iframe><h4>Final thoughts</h4><p>Unit tests save lives! That’s a bit dramatic, but they can save code. When writing Unit Tests keep in mind that you’re not just looking to get 100% code coverage, which you should aim for, Unit Tests should be written in a way that tests the logic. Make sure that you write tests that don’t just test the code but test the logic.</p><p>If you’re really brave you can take a Test Driven Design approach:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJv2uxzhPFl4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJv2uxzhPFl4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJv2uxzhPFl4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a77cdc33e136abd9d482eabe86244d/href">https://medium.com/media/35a77cdc33e136abd9d482eabe86244d/href</a></iframe><p>Write the tests while you’re creating the logic. With mocking data and knowing the result of the method there should be nothing standing in your way!</p><p>Good luck with mocking.</p><blockquote>References</blockquote><ul><li><a href="https://andyinthecloud.com/2016/06/26/working-with-apex-mocks-matchers-and-unit-of-work/">https://andyinthecloud.com/2016/06/26/working-with-apex-mocks-matchers-and-unit-of-work/</a></li><li><a href="https://github.com/apex-enterprise-patterns/fflib-apex-common">https://github.com/apex-enterprise-patterns/fflib-apex-common</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f0453c1a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/mocking-data-for-fflib-in-apex-for-salesforce-a8f0453c1a9">Mocking Data for FFLib in Apex for Salesforce</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[ 5 Tips to to improve your ability to develop software]]></title>
            <link>https://thedailycommit.com/5-tips-to-to-improve-your-ability-to-develop-software-545b1132d8cf?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/545b1132d8cf</guid>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[commitment]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 06:01:07 GMT</pubDate>
            <atom:updated>2022-04-05T06:01:07.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5JSWes38UjdpAJPm7dzuQ.jpeg" /></figure><p>These are tips that have improved my ability to provide software solutions to organisation&#39;s and I hope they will be useful for you too!</p><pre>· <a href="#b15d">1. Fall in love with learning.</a><br>· <a href="#e02a">2. Understand flow state.</a><br>· <a href="#966a">3. Test your code.</a><br>· <a href="#937d">4. Create your own tools.</a><br>· <a href="#cd9f">5. Write notes.</a></pre><h3>1. Fall in love with learning.</h3><p>I’m a researcher at heart and I love to learn and it’s helped me become a better software developer. I’ve found on my learning journey that when I learn something new I serendipitously find it useful within a few weeks despite not planning on using it immediately.</p><p>Some things I have found useful for my learning process are:</p><ul><li>Get enough sleep.</li><li>Write about what you’ve learnt.</li><li>Make learning a daily habit.</li></ul><h3>2. Understand flow state.</h3><p><a href="https://www.headspace.com/articles/flow-state">Flow state</a> is state in which you can create with a fluidity between your body and mind. I think flow state should be one of the first things taught in software development. Once you understand flow state you can look at tools and processes to enable you to reach and maintain flow state. Flow state has improved my development experience and has been one of the keys to enjoying the daily commit.</p><h3>3. Test your code.</h3><p>Your code is not complete unless it’s being tested. There are many different types of software testing methods, the two I lean on the most are <a href="https://en.wikipedia.org/wiki/Unit_testing">unit tests</a> and end-to-end integration tests. A tool I’ve recently been using for end-to-end testing is <a href="https://playwright.dev/">Playwright</a>, here is an article I wrote on using Playwright for that I used for a project: <a href="https://medium.com/automate-salesforce-manual-steps-in-scratch-orgs-with-playwright-4d8f1adbaac1">Automate Salesforce Scratch Orgs with Playwright</a>.</p><h3>4. Create your own tools.</h3><p>One of the greatest things about being a software developer is the ability to create whatever software you need to create. I have often felt that being a software developer allows me to feel freer in a software driven world. With enough time and budget we could create a replica of the entire world as a cloud hosted service, although I imagine it would be a lot of time.</p><p>This means we can make tools for ourselves. A couple of examples of tools you could create for yourself are plugins for your code editor or automating common tasks that you perform as a part of your process. I wrote the article <a href="https://medium.com/make-your-own-cli-with-javascript-node-js-ea2675a37b08">Make your own CLI with Javascript &amp; Node.js!</a> where I show an example of building a CLI tool that you could use to automate tasks.</p><h3>5. Write notes.</h3><p>Be in the habit of writing notes, write notes everyday. There are so many advantages to writing notes, but the main two for me are; I can’t remember everything and I love to save code snippets.</p><p>It’s hard for most people to remember everything and creating notes helps my remember through the process of writing them and gives me a way to extend my long term memory and give it keyword search capabilities. Also keeping code snippets of methods and functions that I’ve used for the development of some systems that I can use on other systems is something I’ve found invaluable.</p><p>I also recommend writing notes in <a href="https://www.markdownguide.org/">Markdown</a>:</p><ul><li>As a developer it’s good to know Markdown in general because it’s what you should be using to keep your documentation.</li><li>It’s plain text and could be stored in a git repository.</li><li>It has the ability to store and display code snippets in different languages and makes it easy to copy and paste them.</li><li>I use a combination of <a href="https://notable.app/">Notable</a> and <a href="https://www.dendron.so/">Dendron</a>.</li></ul><blockquote>Any feedback is always appreciated, <br>enjoy committing your daily code everyone!!! <br>⌨️ ⌨️ ⌨️️</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545b1132d8cf" width="1" height="1" alt=""><hr><p><a href="https://thedailycommit.com/5-tips-to-to-improve-your-ability-to-develop-software-545b1132d8cf">🖐 5 Tips to to improve your ability to develop software</a> was originally published in <a href="https://thedailycommit.com/">The Daily Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own CLI with Javascript & Node.js!]]></title>
            <link>https://thedailycommit.com/make-your-own-cli-with-javascript-node-js-ea2675a37b08?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2675a37b08</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 10:50:06 GMT</pubDate>
            <atom:updated>2022-03-27T10:50:06.787Z</atom:updated>
            <content:encoded><![CDATA[<p>One piece of advise that I give new software engineers is; If you can’t find a tool to automate a process you need and you can’t find one that already exists, then build one <strong>yourself</strong>.</p><p>You have the ability to build your own awesome CLI with <strong>Node.js</strong> that could automate any process that you currently do manually.</p><h3>What you need to have</h3><ul><li>A basic understanding of <a href="https://nodejs.org/">J</a>avascript.</li><li>A basic understanding of <a href="https://nodejs.org/">Node.js</a>.</li><li>A unix based terminal.</li><li>A text editor, I’m going to use <a href="https://code.visualstudio.com/">VS Code</a> in this example.</li></ul><h3>Set this thing up</h3><p>We’re going to create your project directory, initialise <strong>Node.js</strong> and add the files you’ll need to have for your project to be compatible with the command line:</p><ol><li>Step up your environment by opening your terminal and entering the following command and completing the prompt:<br>mkdir myAwesomeCLI &amp;&amp; cd myAwesomeCLI &amp;&amp; npm init<br>This will make your project directory, open that directory and initialise your Node.js project.</li><li>Create a bin directory and an index file, you will be what your project will need for your command line tool, with this command:<br>mkdir bin &amp;&amp; touch bin/index.js</li><li>Write the <em>shebang</em> to your index file, the shebang will tell your file that it can be run as a script in a terminal tools: <br>echo &#39;#!/usr/bin/env node&#39; &gt; bin/index.js</li><li>If you have the VSCode command set up open your project with code . or open your project in your preferred text editor.</li><li>Navigate to bin/index.js, add console.log(&quot;Hello World!&quot;);under your your shebang, if you’re using VSCode then you should see something like this:</li></ol><figure><img alt="Example of open index.js file with {Hello World!}." src="https://cdn-images-1.medium.com/max/1024/1*HDS_QaCD0O31doWOn1RXlg.png" /><figcaption>Example of open index.js file with {Hello World!}.</figcaption></figure><h3>Install and run this thing</h3><p>We’re going to set your project to be able to be installed <strong>globally</strong>, install it <strong>globally</strong> and the test the installation by running it:</p><ol><li>Map your bin directory in your package JSON by adding the following definition:<br>&quot;bin&quot;: { <br> &quot;myawesomecli&quot;: &quot;./bin/index.js&quot; <br> }<br>Example of an example package.json below.</li><li>In your terminal in your project directory run: npm install --global .</li><li>Test to see if your installation by typing the name of the project , in this case: myawesomecli and it should print “Hello World!” to the screen.</li></ol><figure><img alt="Example of JSON package definition." src="https://cdn-images-1.medium.com/max/1022/1*p9fOvoRL_urlrVLX02AsPg.png" /><figcaption>Example of JSON package definition.</figcaption></figure><blockquote>You’ve made a CLI tool, how awesome are you!!! 🎉🎉🎉</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2675a37b08" width="1" height="1" alt=""><hr><p><a href="https://thedailycommit.com/make-your-own-cli-with-javascript-node-js-ea2675a37b08">Make your own CLI with Javascript &amp; Node.js!</a> was originally published in <a href="https://thedailycommit.com/">The Daily Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Salesforce Scratch Orgs with Playwright]]></title>
            <link>https://thedailycommit.com/automate-salesforce-manual-steps-in-scratch-orgs-with-playwright-4d8f1adbaac1?source=rss-b958a182104b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8f1adbaac1</guid>
            <category><![CDATA[salesforce-automation]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[sfdx]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[playwright-community]]></category>
            <dc:creator><![CDATA[Oliver Holmes]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 11:38:50 GMT</pubDate>
            <atom:updated>2022-03-07T13:32:18.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDUIalT_uFR_ubQtD24Wcg.jpeg" /></figure><h3>Why use Playwright?</h3><p>There are many tools available for testing and automation in multiple different programming languages. And it’s important to choose the tool that is right for your project.</p><p>The reasons I chose playwright for my project:</p><ul><li>It’s Node based and available on NPM and SFDX projects are Node based projects.</li><li>The code generation tool; <a href="https://playwright.dev/docs/codegen">codegen</a>, was the best tool I’d used to date.</li><li>It executed processes that didn’t reply on the use of div and class css inspectors and could search for and click on buttons based on properties.</li><li>It is available in multiple programming languages which makes it a technology that is portable across multiple projects.</li><li>Rich documentation that was easy to understand and follow.</li><li>Ability to watch the automation with the addition of a flag to the command ( — headed).</li></ul><p>Other testing and automation libraries I assessed and compared Playwright to:</p><ul><li><a href="https://developers.google.com/web/tools/puppeteer">Puppeteer</a></li><li><a href="https://selenium-python.readthedocs.io/">Selenium</a></li><li><a href="https://jestjs.io/">Jest</a></li><li><a href="https://www.cypress.io/">Cypress</a></li></ul><p>I judged each framework primarily:</p><ul><li>Documentation</li><li>Portability</li><li>Code generation</li><li>Ability to integrate into current project</li></ul><p>Here is an example of a comparison between Playwright and Selenium: <br><a href="https://www.youtube.com/watch?v=jUIzMsqifYE&amp;ab_channel=Testopic">https://www.youtube.com/watch?v=jUIzMsqifYE&amp;ab_channel=Testopic</a></p><h3>Challenges Automating a SFDX Project</h3><p>The three man challenges I had automating manual steps in an SFDX project were:</p><ul><li>Logging in to the scratch org and bypassing Multi-factor Authentication (MFA).</li><li>Recording automations without relying on class or div css selectors.</li><li>Some page elements require wait times for loading.</li></ul><h3>The Solution</h3><blockquote><strong><em>Get past the MFA!</em></strong></blockquote><p>I needed to bypass the MFA and I knew that SFDX already had the capability to create a front door link with the command sfdx force:org:open. The command however also opened the link in a browser, so I decided to see if I could generate the link without opening the link and disrupting the process. I used sfdx force:org:display, and compared the details outputted by the command against the link created by the open command. I found that the link was formed from the <em>Instance Url</em> and <em>Access Token. </em>I created a script that scraped the display command for the data and constructed the front door url for use as authentication to the Salesforce Scratch Org and also returned the orgs URL to be able to navigate around the Org once authenticated.</p><blockquote><strong><em>Record what I need to automate and automate!</em></strong></blockquote><p>I used Playwrights native interaction recorder to record the manual steps that I needed to automate: <a href="https://playwright.dev/docs/codegen">https://playwright.dev/docs/codegen</a>. To start with I created navigation tabs to add to the home page. It’s something I was doing manually before and it seem like a good place to start the test. I noticed that Salesforce took too long to load data in some places and I need to add a delay to, here is an example:</p><pre>await <em>page</em>.locator(‘[aria-label=”Available\\ Items”] &gt;&gt; text=All’).click({delay: 1000});</pre><p>To run the automations I added the script to retrieve the SFDX front door url to my tests and run:</p><pre>npx playwright tests</pre><p>Or I can add the --headed, flag so I can watch the automation run in case of any required debugging.</p><p>And there you go, we have created a Playwright integration to automate and test features on a Scratch Org!!! 🎉🎉🎉</p><h3>Example GitHub Repo:</h3><p><a href="https://github.com/OliverAHolmes/salesforce-playwright">https://github.com/OliverAHolmes/salesforce-playwright</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8f1adbaac1" width="1" height="1" alt=""><hr><p><a href="https://thedailycommit.com/automate-salesforce-manual-steps-in-scratch-orgs-with-playwright-4d8f1adbaac1">Automate Salesforce Scratch Orgs with Playwright</a> was originally published in <a href="https://thedailycommit.com/">The Daily Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>