<?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 Ifedayo Adesiyan on Medium]]></title>
        <description><![CDATA[Stories by Ifedayo Adesiyan on Medium]]></description>
        <link>https://medium.com/@theifedayo?source=rss-fe4ff6aa03c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z4KVqa92TTLpt3wdE7adpA.jpeg</url>
            <title>Stories by Ifedayo Adesiyan on Medium</title>
            <link>https://medium.com/@theifedayo?source=rss-fe4ff6aa03c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:11:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theifedayo/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[How to Upgrade AWS EKS Node Groups Without Downtime (Step-by-Step Guide)]]></title>
            <link>https://theifedayo.medium.com/how-to-upgrade-aws-eks-node-groups-without-downtime-step-by-step-guide-618b90d1b462?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/618b90d1b462</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 07:23:30 GMT</pubDate>
            <atom:updated>2025-09-23T07:23:30.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nl1j5tg19M70tldmXXDQ5w.png" /></figure><p>Upgrading Kubernetes node groups is key for better performance, scaling, and cost savings. But doing it carelessly can cause downtime. If you’re running on <a href="https://aws.amazon.com/pm/eks/?trk=e7f000d4-cfc4-4eea-92ac-432e764869ec&amp;sc_channel=ps&amp;ef_id=CjwKCAjwisnGBhAXEiwA0zEOR15YWZdqWxUJ-_Yu0C41o4G7HgmY7CqAwbSHZw0H1Eh8fsRmZW0K0xoCTDQQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!669047416746!e!!g!!amazon%20eks!20433874212!155230227787&amp;gad_campaignid=20433874212&amp;gbraid=0AAAAADjHtp-yw3bRR6eig8cDE18WXOMhd&amp;gclid=CjwKCAjwisnGBhAXEiwA0zEOR15YWZdqWxUJ-_Yu0C41o4G7HgmY7CqAwbSHZw0H1Eh8fsRmZW0K0xoCTDQQAvD_BwE"><strong>Amazon EKS</strong></a><strong> (Elastic Kubernetes Service), </strong>AWS’s managed Kubernetes platform, this process becomes easier, but you still need a careful approach.</p><p>This guide walks you through a safe, step-by-step upgrade (using an example of moving from t3.small to t3.medium in EKS) without any disruption to your workloads.</p><h3>Prerequisites</h3><p>Make sure your apps have more than one <a href="https://sematext.com/glossary/kubernetes-replica/#:~:text=Kubernetes%20replicas%20are%20clones%20that,an%20increase%20in%20node%20pressure">replica</a>, you can access the cluster with kubectl or your cloud CLI, and you understand how node pools/node groups work</p><p>In this tutorial, I’ll demonstrate upgrading from an AWS t3.small node to t3.medium node. You’ll notice commands use a — kubeconfig =kubeconfig.yaml flag. This explicitly points kubectl to the correct Kubernetes cluster configuration file, which is useful when managing multiple clusters or when your kubeconfig isn’t in the default location (~/.kube/config)</p><h3>Step 1: Ensure Your Deployment Has Multiple Replicas</h3><p>Check that your Deployments or <a href="https://spacelift.io/blog/statefulset-vs-deployment">StatefulSets</a> run more than one replica, this redundancy keeps apps available during rolling updates.</p><pre>#deployment.yml<br>spec: <br>  replicas: 3</pre><p>You can confirm by running the command below:</p><pre>kubectl --kubeconfig=kubeconfig.yaml get deploy</pre><pre>NAME            READY   UP-TO-DATE   AVAILABLE   AGE<br>test-api        3/3     3            3           12d</pre><ul><li><strong>NAME</strong> → The deployment name (test-api).</li><li><strong>READY (3/3)</strong> → Shows replicas: 3 <a href="https://kubernetes.io/docs/concepts/workloads/pods/">pods</a> are <em>ready</em> out of 3 desired replicas.</li><li><strong>UP-TO-DATE (3)</strong> → Number of replicas that match the latest Deployment spec.</li><li><strong>AVAILABLE (3)</strong> → Number of replicas actually available to serve traffic</li><li><strong>AGE (12d)</strong> → How long the Deployment has existed.</li></ul><p>So the <strong>replica count is reflected in the READY column</strong> (3/3). If your Deployment was set to 5 replicas, you’d see 5/5 here when all are ready.</p><p>If replicas = 1, scale up before starting the upgrade by running</p><pre>kubectl --kubeconfig=kubeconfig.yaml scale deployment test-api --replicas=3</pre><h3>Step 2: Edit the Node Group / Instance Type</h3><p><strong>Add new EC2 instances</strong> with the t3.medium type (either by updating the existing node group or creating a new one).</p><p><strong>Join them to your cluster</strong> using your EKS configuration (this happens automatically if you update the node group, or manually if you create new nodes).</p><p><strong>Label the new nodes</strong> (e.g., node-type=medium) so you can target <a href="https://kubernetes.io/docs/concepts/workloads/">workloads</a> with nodeSelector or nodeAffinity. This ensures pods are scheduled onto the new t3.medium nodes first, before draining the old t3.small ones.</p><pre>kubectl --kubeconfig=kubeconfig.yaml label nodes test-api-new-instance instance-type=t3.medium</pre><p>This command applies a label to a Kubernetes node. Specifically, it adds (or updates) the label instance-type=t3.medium on the node named test-api-new-instance.</p><p>These are the current 2 instances we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr1LUyzWrt0jybMPH2sRqA.png" /><figcaption>list of available nodes</figcaption></figure><p>i-036xxxxxxxxxx49ab is the t3.small node we will like to take out.</p><h3><strong>Step 3: Use nodeSelector or Affinity</strong></h3><p>Now that you’ve added new <strong>EC2 </strong><strong>t3.medium instances </strong>to your EKS cluster, you want Kubernetes to place your workloads on them instead of the older <strong>t3.small instances</strong>.</p><p>Each EC2 instance in the cluster gets a label that includes its instance type. For example, a t3.medium EC2 will have:</p><pre>kubernetes.io/instance-type=t3.medium</pre><p>By updating your Deployment with a nodeSelector, you instruct Kubernetes to run your pods only on the t3.medium EC2 instances:</p><pre># deployment.yml<br>spec:<br>  template:<br>    spec:<br>      nodeSelector:<br>        kubernetes.io/instance-type: t3.medium</pre><h3>Step 4: Trigger a rolling update</h3><p>Once the new nodes are ready and labeled, restart your Deployment to shift workloads:</p><pre>kubectl --kubeconfig=kubeconfig.yaml -n production rollout restart deployment test-api</pre><p>Kubernetes will then:</p><ul><li>Spin up new pods on t3.medium nodes</li><li>Wait for them to be Ready</li><li>Gradually terminate old pods running on t3.small nodes</li></ul><h3>Step 5: Drain &amp; remove old nodes</h3><p>Once your application is fully running on the new nodes, clean up the old ones by draining them:</p><pre>kubectl --kubeconfig=kubeconfig.yaml drain i-036xxxxxxxxxx49ab --ignore-daemonsets --delete-emptydir-data</pre><p>This gracefully evicts pods from the old node while ignoring system <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/">DaemonSets</a>. After the node is drained, you can safely terminate the <strong>t3.small</strong> EC2 instance from the AWS console or CLI.</p><h3><strong>Conclusion</strong></h3><p>Upgrading EKS node groups safely ensures better performance and cost efficiency without downtime. With careful scaling, labeling, and draining, your workloads move smoothly to the new instances.</p><h4>Additional Resources</h4><p><a href="https://docs.aws.amazon.com/eks/latest/userguide/worker.html">Maintain nodes yourself</a> with self-managed nodes</p><p><a href="https://medium.com/@shyam.rughani30/create-a-eks-cluster-and-node-groups-dfc3ad03df8e">Create a EKS Cluster</a> and Node Groups</p><p>If you encounter any issues following this guide, migrating or upgrading your node groups, feel free to reach me on <a href="https://www.linkedin.com/in/ifedayo-adesiyan-76732616b/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=618b90d1b462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production-Ready Vault Deployment on EC2: A Detailed Guide]]></title>
            <link>https://theifedayo.medium.com/production-ready-vault-deployment-on-ec2-a-detailed-guide-7bf30f74373b?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf30f74373b</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[secrets]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 14:26:27 GMT</pubDate>
            <atom:updated>2024-07-31T14:26:27.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1e50WUFyIgspqreOzgQ0w.png" /></figure><p><a href="https://www.vaultproject.io/">HashiCorp Vault</a> is a powerful tool designed for securely managing secrets and protecting sensitive data. It provides a unified interface to access secrets and protect sensitive data using a variety of methods such as encryption, access control, and dynamic secrets generation. Vault is widely used in modern infrastructure to ensure that sensitive information, like API keys, passwords, and certificates, is handled securely and accessed only by authorized entities.</p><p>This guide aims to walk you through the process of deploying a production-ready HashiCorp Vault server on an AWS EC2 instance. The goal is to help you set up a secure, highly available, and scalable Vault environment that meets the needs of a production system.</p><h3>Prerequisites</h3><p>Before deploying HashiCorp Vault on an AWS EC2 instance, several prerequisites need to be addressed:</p><p><strong>AWS Account Setup</strong>: Ensure you have an active AWS account. This is necessary for <a href="https://www.geeksforgeeks.org/amazon-ec2-creating-an-elastic-cloud-compute-instance/">creating and managing EC2 instances</a> and other AWS resources.</p><p><strong>SSH Key Pair Creation</strong>: <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-key-pairs.html">Create an SSH ke</a>y pair <a href="https://99robots.com/how-to-ssh-to-ec2-instance-on-aws/">to securely access your EC2 instances</a>. This key pair will be used to establish an SSH connection to your instance.</p><p><strong>Security Group Configuration</strong>: Configure a security group for your EC2 instance to allow inbound traffic on necessary ports, such as port 8200 for Vault and port 22 for SSH access.</p><h3>Installing Vault</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ9NlHONcX9gTHda2nJ8Rw.png" /></figure><p>To manage your EC2 instance, you’ll need to connect to it via SSH. Open your terminal and use the following command, replacing /path/to/your-key.pem with the path to your SSH key file and your-ec2-public-dns with the public DNS address of your EC2 instance:</p><pre># ssh -i /path/to/your-key.pem ubuntu@your-ec2-public-dns<br>ssh -i tutorial-key.pem ubuntu@ec2-34-254-186-220.eu-west-1.compute.amazonaws.com</pre><p>This command establishes a secure connection to your EC2 instance using the provided key for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBSjOSsqZKPdi48Z8gO-XA.png" /></figure><p>Now you have gained entry into your ec2 instance.</p><p>First, ensure your package index is up-to-date to avoid installation issues using:</p><pre>sudo apt-get update</pre><p>This refreshes the list of available packages and their versions.</p><h4>Installing Necessary Packages</h4><p>Vault installation requires some basic tools like unzip. Install them using:</p><pre>sudo apt-get install -y unzip</pre><p>This command installs the unzip utility, which is needed to extract the Vault binary.<br>Next, download the latest version of Vault from the official HashiCorp release page. As of July 31, 2024, the <a href="https://developer.hashicorp.com/vault/install">latest version</a> is 1.17.2. Replace the version number with the latest release if necessary:</p><pre>wget https://releases.hashicorp.com/vault/1.17.2/vault_1.17.2_linux_amd64.zip</pre><p>This command fetches the Vault binary in a zip archive.<br>Extract the downloaded zip file and move the Vault binary to a directory included in your system’s PATH:</p><pre>unzip vault_1.17.2_linux_amd64.zip</pre><pre>sudo mv vault /usr/local/bin/</pre><p>This extracts the vault binary and moves it to /usr/local/bin, making it accessible from anywhere in your terminal.</p><p>To ensure Vault is installed correctly, check its version:</p><pre>vault --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPDvr8_LqsdYJayotODkpg.png" /><figcaption>vault — version output</figcaption></figure><h3>Configuring Vault</h3><p>To start configuring Vault, first create a directory to store the configuration file:</p><pre>sudo mkdir /etc/vault</pre><p>Next, create and edit the Vault configuration file:</p><pre>sudo nano /etc/vault/vault.hcl</pre><p>This opens a new file in the Nano text editor where you can define your Vault configuration.<br>In the vault.hcl file, specify the storage backend. For a simple setup, use the file storage backend, which stores data locally:</p><pre>storage &quot;file&quot; {<br>  path = &quot;/mnt/vault/data&quot;<br>}</pre><p>This configuration tells Vault to store its data in the /mnt/vault/data directory. Make sure this directory exists and is writable by the Vault process.</p><p>We will verify the directory /mnt/vault exists and that the Vault process has the correct permissions to write to it using the following commands:</p><pre>sudo mkdir -p /mnt/vault<br>sudo chown vault:vault /mnt/vault<br>sudo chmod 700 /mnt/vault</pre><p>Next, set up a listener to handle incoming requests.</p><p>For an EC2 instance, port 8200 is not open by default, you’ll need to check and modify the security group settings to ensure that port 8200 is open.</p><p>Find your instance and select the security group; click on the Inbound rules tab, and then click the Edit inbound rules button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofiFHkZAnVAqkSz2Yazv9w.png" /></figure><p>To add a rule for port 8200, click Add rule, set Type to Custom TCP Rule, set Port range to 8200, set Source to 0.0.0.0/0 (for open access) or specify a custom IP range for more restricted access, and click Save rules</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkL0U5u-sV1A9mYMiZS9jw.png" /></figure><p>For production environments, it’s crucial to use TLS to secure communications. To set up TLS certificates for Vault, you can either generate self-signed certificates or obtain certificates from a Certificate Authority (CA). Here’s an example configuration for a TLS listener:</p><pre>listener &quot;tcp&quot; {<br>  address     = &quot;0.0.0.0:8200&quot;<br>  tls_cert_file = &quot;/etc/vault/vault-cert.pem&quot;<br>  tls_key_file  = &quot;/etc/vault/vault-key.pem&quot;<br>}</pre><p>Replace /etc/vault/vault-cert.pem and /etc/vault/vault-key.pem with the paths to your TLS certificate and key files. This setup ensures that Vault communicates securely over HTTPS.</p><p>To enable the Vault web UI, add the following line to the configuration file:</p><p>ui = true</p><p>This setting allows access to Vault’s user interface via a web browser, which can be accessed at https://&lt;your-ec2-public-dns&gt;:8200.</p><p>The disable_mlock = true setting in Vault&#39;s configuration disables the use of memory locking, which normally prevents Vault&#39;s sensitive data from being swapped to disk, potentially reducing security but improving compatibility in environments where memory locking is not available</p><p>Here is a minimal example of a vault.hcl configuration file:</p><pre># vault.hcl<br>storage &quot;file&quot; {<br>  path = &quot;/mnt/vault/data&quot;<br>}<br><br>listener &quot;tcp&quot; {<br>  address     = &quot;0.0.0.0:8200&quot;<br>  # tls_cert_file = &quot;/etc/vault/vault-cert.pem&quot;<br>  # tls_key_file  = &quot;/etc/vault/vault-key.pem&quot;<br>  tls_disable = 1<br><br>ui = true<br>disable_mlock = true</pre><p>This configuration includes the basic setup for storage, disabled TLS connection, enabling the UI, and disabling memory locking. Ensure that all file paths and other settings match your actual environment.</p><p>With these configurations in place, Vault will be set up to run securely and provide its secret management capabilities through a web interface.</p><h3>Starting Vault as a Service</h3><p>To manage Vault as a systemd service, create a service file for Vault:</p><pre>sudo nano /etc/systemd/system/vault.service</pre><p>This will open a new file in the Nano text editor where you’ll define how Vault should be managed.<br>Add the following content to the vault.service file:</p><pre>[Unit]<br>Description=HashiCorp Vault Service- A tool for managing secrets<br>Documentation=https://www.vaultproject.io/<br>Requires=network-online.target<br>After=network-online.target<br><br>[Service]<br>User=vault<br>Group=vault<br>ExecStart=/usr/local/bin/vault server -config=/etc/vault/vault.hcl<br>ExecReload=/bin/kill -HUP $MAINPID<br>KillMode=process<br>Restart=on-failure<br>LimitNOFILE=65536<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Here’s what each section does:</p><p>[Unit]: Defines the service description and dependencies.<br>[Service]: Configures the service to run as the vault user, start Vault with the specified configuration file, and handle restarts and reloads.<br>[Install]: Configures the service to start at boot.</p><p>Ensure that the vault user and group exist or adjust the User and Group fields accordingly. You might need to create these if they don’t exist:</p><pre>sudo useradd --system --home /etc/vault vault</pre><p>After creating the service file, reload the systemd configuration to recognize the new service:</p><pre>sudo systemctl daemon-reload</pre><p>Enable the Vault service to start automatically at boot and then start it:</p><pre>sudo systemctl enable vault<br>sudo systemctl start vault</pre><p>Verify that the Vault service is running correctly:</p><pre>sudo systemctl status vault</pre><p>This displays the current status of the Vault service, including whether it is active, and provides logs for troubleshooting if necessary.</p><p>By following these steps, you will have Vault running as a managed systemd service, making it easier to handle restarts, automatic starts, and other service management tasks.</p><h3>Initializing and Unsealing Vault</h3><p>Initialization is the first step in setting up Vault. It generates the encryption keys and the initial root token.</p><p>Before initializing, we need to run:</p><pre>export VAULT_ADDR=&#39;http://&lt;your private IPv4 address&gt;:8200&#39;<br>export DBUS_SESSION_BUS_ADDRESS=$XDG_RUNTIME_DIR/bus</pre><p><strong>export VAULT_ADDR=&#39;http://172.31.4.123:8200&#39;</strong> sets the environment variable VAULT_ADDR to the URL of the Vault server, specifying where Vault commands should be directed.</p><p><strong>export DBUS_SESSION_BUS_ADDRESS=$XDG_RUNTIME_DIR/bus</strong>sets the DBUS_SESSION_BUS_ADDRESS environment variable to the path of the DBus session bus address, helping avoid issues with runaway DBus processes.</p><p>To initialize Vault, run:</p><pre>vault operator init</pre><p>This will output several pieces of important information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-AyVMU3lfOLlnhhjy_j4w.png" /><figcaption>vault operator init output</figcaption></figure><p><strong>Unseal Keys</strong>: You will receive multiple unseal keys. These keys are used to unseal the Vault server after it has been started.<br><strong>Root Token</strong>: The initial root token allows you to authenticate and configure Vault.<br><strong>Important</strong>: Save these unseal keys and root token in a secure location. They are critical for accessing and managing your Vault instance.</p><p>Once Vault is initialized, it will be sealed. You need to unseal it using the unseal keys provided during initialization. Use the following command to unseal Vault:</p><pre>vault operator unseal &lt;Unseal Key 1&gt;<br>vault operator unseal &lt;Unseal Key 2&gt;<br>vault operator unseal &lt;Unseal Key 3&gt;</pre><p>You need to enter a majority of the unseal keys to unseal Vault. The exact number depends on your configuration, but typically it’s three out of five.</p><p>You can also do this via the Vault web UI. Open a web browser and navigate to:</p><pre>http://&lt;your-ec2-public-dns&gt;:8200</pre><p>Replace &lt;your-ec2-public-dns&gt; with the public DNS name or IP address of your EC2 instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E6RehZyCgH66sP2KW9GfQ.png" /></figure><p>Ensure that the unseal keys and root token are stored securely:</p><p><strong>Unseal Keys</strong>: Store them in a safe place, such as a secure password manager or a hardware security module (HSM).<br><strong>Root Token</strong>: This token provides full access to Vault, so it should be treated with the highest level of security. Store it in a secure, encrypted location and use it only as needed.</p><p>Once you put in three correct keys, you’ll be redirected to sign in. Use the root token obtained during initialization to sign in:</p><ol><li>Enter the root token in the login prompt.</li><li>Click “Sign in” to access the Vault dashboard.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7FiezDKRjZD9wbAUrWpkQ.png" /><figcaption>vault sign in UI</figcaption></figure><p>The Vault UI provides a user-friendly interface for managing secrets, policies, and configurations. From here, you can perform administrative tasks and configure Vault according to your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXQAjS3o8D9IwPY0lcLeQA.png" /></figure><h3>Securing Vault Deployment</h3><h4>Enabling TLS for secure communication</h4><p>To ensure that communication with Vault is secure, you should enable TLS (Transport Layer Security). This encrypts the data transmitted between clients and the Vault server, protecting it from eavesdropping and tampering.</p><ol><li><strong>Obtain TLS Certificates</strong>: Acquire or generate a TLS certificate and private key. You can use a certificate authority (CA) or a self-signed certificate for testing purposes.</li><li><strong>Configure TLS in Vault</strong>: Update the Vault configuration file (/etc/vault/vault.hcl) to enable TLS:</li></ol><pre>listener &quot;tcp&quot; {<br>  address     = &quot;0.0.0.0:8200&quot;<br>  tls_cert_file = &quot;/etc/vault/vault-cert.pem&quot;<br>  tls_key_file  = &quot;/etc/vault/vault-key.pem&quot;<br>}</pre><p>Replace the file paths with the locations of your TLS certificate and key. This ensures that Vault uses HTTPS for secure communication.</p><p>3<strong>. Restart Vault</strong>: Apply the new configuration by restarting the Vault service:</p><pre>sudo systemctl restart vault</pre><h4>Using Consul or Another Backend for High Availability (HA)</h4><p>For production environments, it’s crucial to ensure high availability and fault tolerance. Consul is a popular choice for Vault’s high-availability backend, but other options like etcd or a cloud-based database can also be used.</p><ol><li><a href="https://netcloud24.com/index.php?rp=/knowledgebase/13/How-to-Install-Consul-Server-on-Ubuntu-22.04.html"><strong>Install Consul</strong></a>: Follow the <a href="https://developer.hashicorp.com/consul/docs/install">Consul installation guide</a> to set up Consul on your infrastructure.</li><li><strong>Configure Vault to Use Consul</strong>: Update the Vault configuration file to use Consul as the storage backend:</li></ol><pre>storage &quot;consul&quot; {<br>  address = &quot;127.0.0.1:8500&quot;<br>  path    = &quot;vault/&quot;<br>}</pre><p>Replace 127.0.0.1:8500 with your Consul server address.</p><p><strong>3. Restart Vault</strong>: Restart Vault to apply the new backend configuration:</p><pre>sudo systemctl restart vault</pre><h4>Configuring Auto-Unseal with AWS KMS</h4><p>Auto-unseal is a feature that allows Vault to automatically unseal itself using a cloud provider’s key management service (KMS). For AWS, this means using AWS KMS to manage the encryption keys.</p><ol><li><strong>Create a KMS Key</strong>: In the AWS Management Console, create a new KMS key for Vault.</li><li><strong>Configure Vault for Auto-Unseal</strong>: Update the Vault configuration file to use AWS KMS:</li></ol><pre>seal &quot;awskms&quot; {<br>  kms_key_id = &quot;arn:aws:kms:region:account-id:key/key-id&quot;<br>}</pre><p>Replace arn:aws:kms:region:account-id:key/key-id with the ARN of your KMS key.</p><p><strong>3. Restart Vault</strong>: Apply the configuration by restarting Vault:</p><pre>sudo systemctl restart vault</pre><h4>Setting Up Regular Backups</h4><p>Regular backups are essential for disaster recovery and data protection.</p><ol><li><strong>Plan Backup Strategy</strong>: Decide on the frequency and method of backups (e.g., daily snapshots).</li><li><strong>Backup Storage</strong>: Store backups in a secure and durable location, such as Amazon S3 or another cloud storage service.</li><li><strong>Automate Backups</strong>: Use cron jobs or other scheduling tools to automate the backup process. For example, create a script to copy the Vault data directory to your backup location and schedule it with cron.</li><li><strong>Test Restores</strong>: Regularly test backup restores to ensure that backups are valid and that you can recover data as needed.</li></ol><h4>Implementing Monitoring and Alerting</h4><p>Monitoring and alerting are crucial for maintaining the health and security of your Vault deployment.</p><ol><li><strong>Enable Vault Metrics</strong>: Vault provides a built-in metrics endpoint that you can enable in the configuration file:</li></ol><pre>telemetry {<br>  dogstatsd_addr = &quot;127.0.0.1:8125&quot;<br>  disable_hostname = true<br>}</pre><p>This configuration sends metrics to a monitoring service like Datadog.</p><p><strong>2. Set Up Monitoring</strong>: Use a monitoring tool such as Prometheus, Grafana, or Datadog to collect and visualize metrics from Vault.</p><p><strong>3. Configure Alerts</strong>: Set up alerts for critical metrics, such as high error rates or low disk space, to ensure timely responses to potential issues.</p><p><strong>4. Review Logs</strong>: Regularly review Vault logs for any unusual activity or errors. Configure log rotation and retention policies to manage log files efficiently.</p><p>By implementing these security measures, you ensure that your Vault deployment is robust, highly available, and resilient against potential issues, providing reliable secret management for your organization.</p><h3>Conclusion</h3><p>In this guide, we’ve covered the essential steps for deploying a production-ready HashiCorp Vault server on AWS EC2, including initialization, unsealing, and configuring Vault for secure and high-availability operations. Emphasizing security and reliability is crucial for protecting sensitive data and maintaining system integrity. We encourage you to explore Vault’s advanced features and best practices further to optimize and secure your secret management infrastructure effectively.</p><h4>Additional Resources</h4><p><a href="https://cloudvisor.co/blog/how-to-connect-an-ec2-instance-using-ssh/">How to Connect an EC2 Instance Using SSH</a></p><p><a href="https://developer.hashicorp.com/vault/tutorials/getting-started/getting-started-install">Vault CLI tutorial</a></p><p><a href="https://developer.hashicorp.com/vault/tutorials/auto-unseal/autounseal-aws-kms">Auto-Unseal with AWS KMS</a></p><p><a href="https://www.cloudthat.com/resources/blog/a-guide-on-configuring-backup-for-amazon-ec2-instances-using-aws-backup-service">A Guide on Configuring Backup for Amazon EC2 Instances using AWS Backup Service</a></p><p>If you encounter any issues following this guide or setting up Vault in production, feel free to contact me on <a href="https://www.linkedin.com/in/ifedayo-adesiyan-76732616b/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf30f74373b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Unit Testing in Go]]></title>
            <link>https://theifedayo.medium.com/a-comprehensive-guide-to-unit-testing-in-go-c292f20670b0?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c292f20670b0</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 09:51:50 GMT</pubDate>
            <atom:updated>2023-11-28T09:51:50.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing is a cornerstone of software development, and in the Go programming language, it’s no different. Go’s simplicity and testing framework makes it a fantastic choice for writing clean and effective unit tests.</p><p>In this comprehensive guide, we will dive deep into the world of unit testing in Go. We will cover everything from the basics of writing and organizing test functions to advanced testing patterns, integration with external tools, best practices, and test coverage analysis. By the end of this tutorial, you will have a solid understanding of unit testing in Go and be well-equipped to write robust and maintainable Go applications.</p><h3>Prerequisite</h3><p>Before we start exploring unit testing in Go, you should have a basic understanding of the Go programming language. If you’re new to Go, consider going through the official <a href="https://tour.golang.org/welcome/1">Go Tour</a> to get familiar with its syntax and features.</p><p>Additionally, you should have Go installed on your system. You can download and install it from the <a href="https://golang.org/dl/">official Go website</a>.</p><p>Note: This tutorial was carried out using Go version 1.21</p><h3>Testing fundamentals</h3><p>In Go, test functions are regular functions with a specific naming convention. To create a test for a function, you should name the test function as Test&lt;FunctionName&gt; in a file ending with _test.go. Let&#39;s create a simple Go program with a corresponding test file to demonstrate this:</p><p>Open your terminal, and create a folder, let’s call it tests</p><pre>mkdir tests</pre><p>Navigate into the folder</p><pre>cd tests</pre><p>Open the folder with your text editor and create two files main.go and main_test.go. main.go will contain the logic of your application and main_test.go will contain its test.</p><p>Run the command below to initialize a new module, which is a self-contained unit of code with its own versioning information and dependencies.</p><pre>go mod init github.com/&lt;your_github_username&gt;/tests</pre><h3>Writing effective test cases</h3><p>Let’s imagine we are working on a simple banking application, and we have a function that calculates the balance after a withdrawal. We will create a function to help with withdrawing money. The Withdraw function will take it in two numbers (current balance and amount) as arguments and check if the amount to be withdrawn is less than current balance, if it passes, the amount can be withdrawn. A corresponding test is added to test if you can withraw an amount.</p><p>Add the following code into main.go and main_test.go.</p><pre>// main.go<br>package main<br><br>import &quot;fmt&quot;<br><br>func Withdraw(currentBalance, amount int) int {<br>    if amount &gt; currentBalance {<br>        fmt.Println(&quot;Insufficient funds.&quot;)<br>        return currentBalance<br>    }<br><br>    newBalance := currentBalance - amount<br>    fmt.Printf(&quot;Withdrawal of %d successful. New balance: %d\n&quot;, amount, newBalance)<br>    return newBalance<br>}<br><br>func main() {<br>    currentBalance := 1000<br>    withdrawalAmount := 200<br><br>    newBalance := Withdraw(currentBalance, withdrawalAmount)<br>    fmt.Printf(&quot;Remaining balance: %d\n&quot;, newBalance)<br>}</pre><p>Now, let’s write a unit test for the Withdraw function</p><pre>// main_test.go<br>package main<br><br>import &quot;testing&quot;<br><br>func TestWithdraw(t *testing.T) {<br>    // Test case 1: Sufficient funds<br>    initialBalance := 1000<br>    withdrawalAmount := 200<br>    expectedBalance := 800<br><br>    result := Withdraw(initialBalance, withdrawalAmount)<br>    if result != expectedBalance {<br>        t.Errorf(&quot;Withdraw(%d, %d) expected %d, but got %d&quot;, initialBalance, withdrawalAmount, expectedBalance, result)<br>    }<br><br>    // Test case 2: Insufficient funds<br>    initialBalance = 100<br>    withdrawalAmount = 200<br>    expectedBalance = 100<br><br>    result = Withdraw(initialBalance, withdrawalAmount)<br>    if result != expectedBalance {<br>        t.Errorf(&quot;Withdraw(%d, %d) expected %d, but got %d&quot;, initialBalance, withdrawalAmount, expectedBalance, result)<br>    }<br>}</pre><p>In this example, we have a Withdraw function that takes the current balance and the withdrawal amount as parameters and returns the new balance after the withdrawal. The unit test checks two scenarios: one where there are sufficient funds and another where there are insufficient funds. The test cases include expected results, and the test will fail if the actual results don&#39;t match the expectations.</p><p>This demonstrates how unit testing can be applied to ensure that a function, in this case, the withdrawal logic, behaves as expected in different scenarios.</p><p>To run the test, use the go test command in your terminal:</p><pre>go test</pre><p>This will execute all the test functions in _test.go files in the current directory and report the results. In this case, it should pass without any errors.</p><pre>[output]<br>Withdrawal of 200 successful. New balance: 800<br>Insufficient funds.<br>PASS<br>ok      github.com/theifedayo/tests     1.570s</pre><p>In a case where there is a failure, we have:</p><pre>[output]<br>Withdrawal of 100 successful. New balance: 900<br>Insufficient funds.<br>--- FAIL: TestWithdraw (0.00s)<br>    main_test.go:13: Withdraw(1000, 100) expected 800, but got 900<br>FAIL<br>exit status 1<br>FAIL    github.com/theifedayo/tests     0.307s</pre><p>You can also provide various command-line flags to customize test execution. For example, to run tests in verbose mode, use:</p><pre>go test -v</pre><pre>[output]<br>=== RUN   TestWithdraw<br>Withdrawal of 200 successful. New balance: 800<br>Insufficient funds.<br>--- PASS: TestWithdraw (0.00s)<br>PASS<br>ok      github.com/theifedayo/tests     0.780s</pre><p>This displays detailed information about each test function being run.</p><h3>Table-driven tests</h3><p>Table-driven tests are a way to run the same test logic with multiple sets of input data. This is especially useful when you want to ensure that your function behaves correctly across various inputs.</p><p>Let’s refactor the previous code using table-driven testing:</p><pre>package main<br><br>import &quot;testing&quot;<br><br>func TestWithdraw(t *testing.T) {<br>    testCases := []struct {<br>        name           string<br>        initialBalance int<br>        withdrawal     int<br>        expectedBalance int<br>    }{<br>        {&quot;Sufficient funds&quot;, 1000, 200, 800},<br>        {&quot;Insufficient funds&quot;, 100, 200, 100},<br>        // Add more test cases as needed<br>    }<br><br>    for _, tc := range testCases {<br>        t.Run(tc.name, func(t *testing.T) {<br>            result := Withdraw(tc.initialBalance, tc.withdrawal)<br>            if result != tc.expectedBalance {<br>                t.Errorf(&quot;%s: Withdraw(%d, %d) expected %d, but got %d&quot;, tc.name, tc.initialBalance, tc.withdrawal, tc.expectedBalance, result)<br>            }<br>        })<br>    }<br>}</pre><p>In the code above, we defined a struct called testCase that holds the input parameters (initialBalance, withdrawal) and the expected result (expectedBalance).</p><p>We created a slice of test cases (testCases) using the testCase struct. We used a loop (for _, tc := range testCases) to iterate through each test case. For each test case, we used t.Run(tc.name, ...) to create a sub-test with a name based on the test case&#39;s name.</p><p>Inside the sub-test, we call the Withdraw function with the input parameters and check if the result matches the expected result. If not, an error is reported.</p><pre>[output]<br>Withdrawal of 200 successful. New balance: 800<br>Insufficient funds.<br>PASS<br>ok      github.com/theifedayo/tests     0.659s</pre><h3>Using the Go testing package and the testing command</h3><p>In Go, the testing package provides a framework for writing and running tests. It includes functions and types for test management, error reporting, and more. Let&#39;s explore some of the key components of the testing package:</p><h3>The testing.T Type</h3><p>The *testing.T type is a testing handle that provides methods for reporting test failures and logging test status. You&#39;ve already seen it in action in the previous example when we used t.Errorf to report an error.</p><h3>Test functions</h3><p>Test functions are functions that start with Test and take a single argument of type *testing.T. These functions are automatically discovered and executed when you run go test.</p><h3>Test Main Functions</h3><p>In some cases, you may need to perform setup or teardown operations before and after running tests. You can define a test main function in your test file to achieve this:</p><pre>func TestMain(m *testing.M) {<br>    // Setup code here<br>    exitCode := m.Run()<br>    // Teardown code here<br>    os.Exit(exitCode)<br>}</pre><p>It is a special function used in testing to customize the setup and teardown of test suites. The m.Run() function runs all the test functions and returns an exit code, which you can use for cleanup or reporting. In database testing below, we will see how to use TestMain to setup and tear down a database.</p><h3>Mocking and stubbing techniques for Go testing</h3><p>Mocking and stubbing are essential techniques in unit testing that allows you to isolate the code under test from external dependencies or collaborators. In Go, you can use libraries like testify/mock or hand-crafted techniques to create mocks and stubs.</p><h3>Using testify/mock</h3><p>Let’s consider a scenario where you want to test a function that interacts with an external API. You don’t want your tests to actually make HTTP requests during testing. Instead, you can use mocking to simulate the API responses.</p><p><a href="https://pkg.go.dev/github.com/stretchr/testify/mock">testify/mock</a> is a popular mocking library for Go. To use it, you&#39;ll need to install the package:</p><pre>go get github.com/stretchr/testify/mock</pre><p>We will demonstrate a common testing pattern in Go, where mock objects are used to isolate and control the behavior of external dependencies during unit testing. This approach ensures that the tested function’s behavior can be verified independently of external services. We use testify/mock to mock an HTTP client. Delete all the code in main.go and main_test.go file.</p><p>In this structure, the main.go file contains our application&#39;s main logic, including the main function that initiates the application, and the FetchData function that fetches data from an external source. The main_test.go file contains the unit tests for the FetchData function, along with the necessary mocking for the HTTP client.</p><pre>// main.go<br>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>)<br>// HTTPClient is an interface for making HTTP requests.<br>type HTTPClient interface {<br>    Do(req *http.Request) (*http.Response, error)<br>}<br>func main() {<br>    client := &amp;http.Client{}<br>    data, err := FetchData(client)<br>    if err != nil {<br>        fmt.Println(&quot;Error:&quot;, err)<br>        return<br>    }<br>    fmt.Println(&quot;Data:&quot;, data)<br>}<br>func FetchData(client HTTPClient) (string, error) {<br>    req, _ := http.NewRequest(&quot;GET&quot;, &quot;https://api.publicapis.org/entries&quot;, nil)<br>    resp, err := client.Do(req)<br>    if err != nil {<br>        return &quot;&quot;, err<br>    }<br>    defer resp.Body.Close()<br>    // Read and process the response here<br>    return &quot;data&quot;, nil<br>}</pre><pre>// main_test.go<br><br>package main<br><br>import (<br> &quot;net/http&quot;<br> &quot;net/http/httptest&quot;<br> &quot;testing&quot;<br> &quot;github.com/stretchr/testify/assert&quot;<br> &quot;github.com/stretchr/testify/mock&quot;<br>)<br>// MockHTTPClient is a mock implementation of HTTPClient.<br>type MockHTTPClient struct {<br>   mock.Mock<br>}<br><br>func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) {<br>   args := m.Called(req)<br>   return args.Get(0).(*http.Response), args.Error(1)<br>}<br><br>func TestFetchData(t *testing.T) {<br>   // Create a new instance of the mock HTTP client<br>   mockClient := new(MockHTTPClient)<br>   // Configure the expected behavior of the mock<br>   mockClient.On(&quot;Do&quot;, mock.Anything).Return(<br>    httptest.NewRecorder().Result(), nil,<br>   )<br>   data, err := FetchData(mockClient)<br>   // Assert that the function behaved as expected<br>   assert.NoError(t, err)<br>   assert.Equal(t, &quot;data&quot;, data)<br>   // Assert that the expected method was called with the expected arguments<br>   mockClient.AssertExpectations(t)<br>}</pre><p>In the code above, we defined an HTTPClient interface and a MockHTTPClient struct that implements the interface. We used github.com/stretchr/testify/mock to create mock expectations and verified that the FetchData function interacts with the HTTP client as expected.</p><h3>Stubbing</h3><p>When testing functions that involve external dependencies, such as file I/O, database access, or external APIs, it’s crucial to avoid interacting with these dependencies directly during tests. Stubbing is a technique that replaces these external dependencies with controlled and predictable substitutes.</p><p>When dealing with database access, a similar approach can be taken to stub the database interactions. We define an interface DBHandler and its real implementation RealDBHandler. The function DataProcessorDB takes a DBHandler as a parameter and executes a database query using this interface. In the test, we use MockDBHandler to simulate database query execution, allowing us to control the result returned during testing.</p><pre>// database_access.go<br>package main<br><br>type DBHandler interface {<br>   ExecuteQuery(query string) (string, error)<br>}<br><br>type RealDBHandler struct{}<br><br>func (r *RealDBHandler) ExecuteQuery(query string) (string, error) {<br>   // Actual database query execution logic<br>   return &quot;real result&quot;, nil<br>}<br><br>func DataProcessorDB(handler DBHandler, query string) (string, error) {<br> result, err := handler.ExecuteQuery(query)<br> if err != nil {<br>    return &quot;&quot;, err<br> }<br>   return result, nil<br>}</pre><pre>// database_access_test.go]<br>package main<br><br>import (<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br> &quot;github.com/stretchr/testify/mock&quot;<br>)<br><br>// MockDBHandler is a mock implementation of DBHandler.<br>type MockDBHandler struct {<br> mock.Mock<br>}<br><br>// ExecuteQuery implements the ExecuteQuery method for the mock.<br>func (m *MockDBHandler) ExecuteQuery(query string) (string, error) {<br> args := m.Called(query)<br> return args.String(0), args.Error(1)<br>}<br><br>func TestDataProcessorDB(t *testing.T) {<br> mockHandler := new(MockDBHandler)<br><br> // Configure the expected behavior of the mock<br> mockHandler.On(&quot;ExecuteQuery&quot;, &quot;SELECT * FROM data&quot;).Return(&quot;stubbed result&quot;, nil)<br><br> result, err := DataProcessorDB(mockHandler, &quot;SELECT * FROM data&quot;)<br><br> assert.NoError(t, err)<br> assert.Equal(t, &quot;stubbed result&quot;, result)<br><br> mockHandler.AssertExpectations(t)<br>}</pre><p>Passing the test, we’ve seen that the mock object isolates the DataProcessorDB function and verifies its behavior without interacting with a real database, using the mocked DBHandler to control and observe its interactions. The DataProcessorDB function correctly calls the ExecuteQuery method on the provided DBHandler with the expected query. The function handles the returned result and error appropriately. The expectations set on the mock, specifically the call to ExecuteQuery with the query &quot;SELECT * FROM data,&quot; are met during the execution of the test.</p><h3>Integrating external testing frameworks and tools</h3><p>While Go’s built-in testing framework is powerful, you may encounter situations where you want to use external testing frameworks or tools to supplement your testing efforts. Here are a few popular ones:</p><h3>Ginkgo and Gomega</h3><p><a href="https://onsi.github.io/ginkgo/">Ginkgo</a> is a BDD-style “Behavior Driven Development” testing framework for Go, and <a href="https://onsi.github.io/gomega/">Gomega</a> is a matcher library that works well with Ginkgo. These tools provide a more expressive way to write and read tests, making them suitable for complex and behavior-driven testing scenarios.</p><p>To use Ginkgo and Gomega, you’ll need to install them:</p><pre>go get github.com/onsi/ginkgo/ginkgo</pre><pre>go get github.com/onsi/gomega/...</pre><p>We define a suite using Describe and provide a description for the suite. Inside the suite, we register all specs using It. Each spec describes a specific test case. Within each spec, we perform the test and make assertions using Expect. These assertions are used to check if the actual results match the expected results.</p><p>Then, you can write Ginkgo tests by deleting all the code in main_test.go and adding this:</p><pre>// main_test.go<br>package main<br><br>import (<br> &quot;testing&quot;<br><br> . &quot;github.com/onsi/ginkgo&quot;<br> . &quot;github.com/onsi/gomega&quot;<br>)<br><br><br>// Define a suite and its description<br>var _ = Describe(&quot;My Suite&quot;, func() {<br> // Register a spec<br> It(&quot;should withdraw correctly&quot;, func() {<br>  currentBalance := 100<br>  amount := 30<br><br>  result := Withdraw(currentBalance, amount)<br>  Expect(result).To(Equal(currentBalance - amount))<br> })<br><br> // Register another spec<br> It(&quot;should handle insufficient funds&quot;, func() {<br>  currentBalance := 20<br>  amount := 30<br><br>  result := Withdraw(currentBalance, amount)<br>  Expect(result).To(Equal(currentBalance))<br> })<br>})<br><br>func TestMain(t *testing.T) {<br>   RegisterFailHandler(Fail)<br>   RunSpecs(t, &quot;My Suite&quot;)<br>}</pre><p>By structuring your tests in this way, you ensure that the Ginkgo framework recognizes and runs your test specs. When you run your tests, you should see the output indicating that the specs were executed, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTlMSzIpXxy5xKVaIYKzlA.png" /></figure><p>Random Seed: 1696315016 indicates that a specific seed value (1696315016 in this case) was used to initialize the random number generator. If you were to run the same suite of tests again with the same seed, you would get the same sequence of random events or values. This can be useful for reproducibility in testing or simulations where you want the same set of random inputs to be used during each run for consistent results.</p><h3>Testify</h3><p><a href="https://pkg.go.dev/github.com/stretchr/testify">Testify</a> is a set of libraries that provide additional testing utilities and assertions. It includes tools for mocking, assertions, and more.</p><p>To use Testify, install the package:</p><pre>go get github.com/stretchr/testify</pre><p>Here’s how to use Testify’s assertions:</p><pre>package main<br><br>import (<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br><br>func TestWithdraw(t *testing.T) {<br> t.Run(&quot;Withdrawal with Sufficient Funds&quot;, func(t *testing.T) {<br>  currentBalance := 1000<br>  withdrawalAmount := 200<br>  expectedBalance := 800<br><br>  result := Withdraw(currentBalance, withdrawalAmount)<br><br>  assert.Equal(t, expectedBalance, result, &quot;Expected balance after withdrawal does not match.&quot;)<br> })<br><br> t.Run(&quot;Withdrawal with Insufficient Funds&quot;, func(t *testing.T) {<br>  currentBalance := 100<br>  withdrawalAmount := 200<br>  expectedBalance := currentBalance<br><br>  result := Withdraw(currentBalance, withdrawalAmount)<br><br>  assert.Equal(t, expectedBalance, result, &quot;Expected balance after withdrawal does not match.&quot;)<br> })<br>}</pre><h3>Test cleanup</h3><p>Sometimes, you need to perform cleanup operations after a test or test suite is complete. The func TestMain(m *testing.M) function in your test code allows you to set up and tear down resources or perform any necessary setup before and after running all your tests. This is useful when you have a common setup and teardown logic that needs to be executed once for multiple test functions in your package.</p><pre>// main_test.go<br>....<br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br> &quot;testing&quot;<br>)<br><br>func TestMain(m *testing.M) {<br> // Setup code here<br> fmt.Println(&quot;Setting up...&quot;)<br><br> // Run all the tests<br> exitCode := m.Run()<br><br> // Teardown code here<br> fmt.Println(&quot;Tearing down...&quot;)<br><br> // Exit with the appropriate exit code<br> os.Exit(exitCode)<br>}<br><br>func TestWithdraw(t *testing.T) {<br> t.Run(&quot;Withdrawal with Sufficient Funds&quot;, func(t *testing.T) {<br>....</pre><p>After the setup code, m.Run() is called to execute all the test functions in your package. The exitCode variable captures the return value of m.Run().</p><pre>[output]<br>Setting up...<br>=== RUN   TestWithdraw<br>=== RUN   TestWithdraw/Sufficient_funds<br>Withdrawal of 200 successful. New balance: 800<br>=== RUN   TestWithdraw/Insufficient_funds<br>Insufficient funds.<br>--- PASS: TestWithdraw (0.00s)<br>    --- PASS: TestWithdraw/Sufficient_funds (0.00s)<br>    --- PASS: TestWithdraw/Insufficient_funds (0.00s)<br>PASS<br>Tearing down...<br>ok      github.com/theifedayo/tests     1.069s</pre><h3>API handler testing</h3><h3>Request validation</h3><p>When testing API handlers, validating the correctness of incoming requests is crucial. This ensures that the handler processes valid inputs and rejects invalid ones. Let&#39;s consider a simple example using the popular testing framework testing and the assertion library github.com/stretchr/testify/assert:</p><p>We will consider a scenario where an HTTP handler CreateUserHandler processes incoming JSON requests to create user entities. We want to ensure that valid requests result in a successful response (HTTP Status 201), while invalid requests return an appropriate error status (HTTP Status 400).</p><pre>// main.go<br>package main<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;net/http&quot;<br>)<br><br>type User struct {<br> Name  string `json:&quot;name&quot;`<br> Email string `json:&quot;email&quot;`<br>}<br><br>func CreateUserHandler(w http.ResponseWriter, r *http.Request) {<br> var newUser User<br><br> decoder := json.NewDecoder(r.Body)<br> err := decoder.Decode(&amp;newUser)<br> if err != nil {<br>  http.Error(w, &quot;Invalid JSON&quot;, http.StatusBadRequest)<br>  return<br> }<br><br> // Assuming a successful user creation<br> // Set the appropriate status code<br> w.WriteHeader(http.StatusCreated)<br><br> // Prepare the response JSON<br> response := map[string]interface{}{<br>  &quot;status&quot;:  &quot;success&quot;,<br>  &quot;message&quot;: &quot;User created successfully&quot;,<br>  &quot;user&quot;:    newUser,<br> }<br><br> // Set the response headers<br> w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br> // Write the response JSON<br> json.NewEncoder(w).Encode(response)<br>}</pre><p>Now, let’s write a unit test for the CreateUserHandler function:</p><pre>// main_test.go<br>package main<br><br>import (<br> &quot;bytes&quot;<br> &quot;net/http&quot;<br> &quot;net/http/httptest&quot;<br> &quot;testing&quot;<br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestCreateUserHandler_ValidRequest(t *testing.T) {<br> payload := []byte(`{&quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john@example.com&quot;}`)<br> req, err := http.NewRequest(&quot;POST&quot;, &quot;/create-user&quot;, bytes.NewBuffer(payload))<br> assert.NoError(t, err)<br><br> rr := httptest.NewRecorder()<br> handler := http.HandlerFunc(CreateUserHandler)<br><br> handler.ServeHTTP(rr, req)<br><br> assert.Equal(t, http.StatusCreated, rr.Code)<br>}<br><br>func TestCreateUserHandler_InvalidRequest(t *testing.T) {<br> // Simulating an invalid JSON request<br> payload := []byte(`{&quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john@example.com&quot;`)<br> req, err := http.NewRequest(&quot;POST&quot;, &quot;/create-user&quot;, bytes.NewBuffer(payload))<br> assert.NoError(t, err)<br><br> rr := httptest.NewRecorder()<br> handler := http.HandlerFunc(CreateUserHandler)<br><br> handler.ServeHTTP(rr, req)<br><br> assert.Equal(t, http.StatusBadRequest, rr.Code)<br>}</pre><p>In the TestCreateUserHandler_ValidRequest test, a valid JSON payload is sent in a POST request to &quot;/create-user&quot;. The test asserts that the HTTP response code is http.StatusCreated (201), indicating that the user creation was successful.</p><p>In the TestCreateUserHandler_InvalidRequest test, an intentionally malformed JSON payload is sent. The test asserts that the HTTP response code is http.StatusBadRequest (400), indicating that the server correctly detected and rejected the invalid request.</p><pre>[output]<br>=== RUN   TestCreateUserHandler_ValidRequest<br>--- PASS: TestCreateUserHandler_ValidRequest (0.00s)<br>=== RUN   TestCreateUserHandler_InvalidRequest<br>--- PASS: TestCreateUserHandler_InvalidRequest (0.00s)<br>PASS<br>ok      github.com/theifedayo/tests     0.729s</pre><p>The tests verified that the CreateUserHandler can appropriately handle both valid and invalid HTTP requests, returning the expected status codes in each case.</p><h3>Response format</h3><p>Ensuring the correct format of the response is equally important. This involves validating the structure and content of the HTTP response generated by the API handler. To write the unit test for response format checks if the handler generates a response in the expected format, we import json with &quot;encoding/json&quot;, then add TestCreateUserHandler_ValidRequest_ResponseFormat</p><pre>// main_test.go<br>...<br> assert.Equal(t, http.StatusBadRequest, rr.Code)<br>}<br><br>func TestCreateUserHandler_ValidRequest_ResponseFormat(t *testing.T) {<br> payload := []byte(`{&quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john@example.com&quot;}`)<br> req, err := http.NewRequest(&quot;POST&quot;, &quot;/create-user&quot;, bytes.NewBuffer(payload))<br> assert.NoError(t, err)<br><br> rr := httptest.NewRecorder()<br> handler := http.HandlerFunc(CreateUserHandler)<br><br> handler.ServeHTTP(rr, req)<br><br> assert.Equal(t, http.StatusCreated, rr.Code)<br><br> var response map[string]interface{}<br> err = json.Unmarshal(rr.Body.Bytes(), &amp;response)<br> assert.NoError(t, err)<br><br> assert.Contains(t, response, &quot;status&quot;)<br> assert.Equal(t, &quot;success&quot;, response[&quot;status&quot;])<br>}<br></pre><p>Now we test for when a valid JSON request to create a user is sent to the “/create-user” endpoint, the CreateUserHandler function responds with an HTTP status code of http.StatusCreated (201) and returns a JSON response with a &quot;status&quot; field set to &quot;success,&quot; indicating that the user creation was successful.</p><pre>[output]<br>=== RUN   TestCreateUserHandler_ValidRequest<br>--- PASS: TestCreateUserHandler_ValidRequest (0.00s)<br>=== RUN   TestCreateUserHandler_InvalidRequest<br>--- PASS: TestCreateUserHandler_InvalidRequest (0.00s)<br>=== RUN   TestCreateUserHandler_ValidRequest_ResponseFormat<br>--- PASS: TestCreateUserHandler_ValidRequest_ResponseFormat (0.00s)<br>PASS<br>ok      github.com/theifedayo/tests     1.459s</pre><h3>Database testing</h3><p>Testing a database in Go typically involves setting up a test database, performing database operations within test functions, and ensuring that the expected results match the actual results. Below is a simple example of testing a database in Go using the popular testing framework testing and the sql package.</p><p>Firstly, we install the SQLite driver with:</p><pre>go get github.com/mattn/go-sqlite3</pre><p>Let’s consider a scenario where you have a database table for users, and you want to test basic CRUD (Create, Read, Update, Delete) operations.</p><pre>// db.go<br>package db<br><br>import (<br> &quot;database/sql&quot;<br> _ &quot;github.com/mattn/go-sqlite3&quot; // SQLite driver<br>)<br><br>// User represents a user in the database.<br>type User struct {<br> ID   int<br> Name string<br> Age  int<br>}<br><br>type UserRepository struct {<br> db *sql.DB<br>}<br><br>func NewUserRepository(db *sql.DB) *UserRepository {<br> return &amp;UserRepository{db: db}<br>}<br><br>func (ur *UserRepository) CreateUser(user *User) error {<br> _, err := ur.db.Exec(&quot;INSERT INTO users (name, age) VALUES (?, ?)&quot;, user.Name, user.Age)<br> return err<br>}<br><br>func (ur *UserRepository) CreateUser(user *User) error {<br> result, err := ur.db.Exec(&quot;INSERT INTO users (name, age) VALUES (?, ?)&quot;, user.Name, user.Age)<br> if err != nil {<br>  return err<br> }<br><br> lastInsertID, err := result.LastInsertId()<br> if err != nil {<br>  return err<br> }<br><br> user.ID = int(lastInsertID)<br> return nil<br>}<br><br>func (ur *UserRepository) UpdateUser(user *User) error {<br> _, err := ur.db.Exec(&quot;UPDATE users SET name = ?, age = ? WHERE id = ?&quot;, user.Name, user.Age, user.ID)<br> return err<br>}<br><br>func (ur *UserRepository) DeleteUser(userID int) error {<br> _, err := ur.db.Exec(&quot;DELETE FROM users WHERE id = ?&quot;, userID)<br> return err<br>}</pre><p>Now, let’s write tests for the UserRepository functions:</p><pre>// db_test.go<br>package db<br><br>import (<br> &quot;database/sql&quot;<br> &quot;testing&quot;<br> &quot;os&quot;<br>)<br><br>const testDBFile = &quot;./test.db&quot;<br><br>func TestMain(m *testing.M) {<br> setupDatabase()<br> code := m.Run()<br> teardownDatabase()<br> os.Exit(code)<br>}<br><br>func setupDatabase() {<br> db, err := sql.Open(&quot;sqlite3&quot;, testDBFile)<br> if err != nil {<br>  panic(err)<br> }<br><br> _, err = db.Exec(`<br>  CREATE TABLE IF NOT EXISTS users (<br>   id INTEGER PRIMARY KEY AUTOINCREMENT,<br>   name TEXT,<br>   age INTEGER<br>  )<br> `)<br> if err != nil {<br>  panic(err)<br> }<br><br> userRepository = NewUserRepository(db)<br>}<br><br>func teardownDatabase() {<br> os.Remove(testDBFile)<br>}<br><br>var userRepository *UserRepository<br><br>func TestUserRepository_CreateUser(t *testing.T) {<br> user := &amp;User{Name: &quot;John Doe&quot;, Age: 25}<br><br> err := userRepository.CreateUser(user)<br> if err != nil {<br>  t.Fatalf(&quot;Error creating user: %v&quot;, err)<br> }<br><br> if user.ID == 0 {<br>  t.Fatal(&quot;User ID not assigned after creation&quot;)<br> }<br><br> // Fetch the user from the database to verify<br> fetchedUser, err := userRepository.GetUser(user.ID)<br> if err != nil {<br>  t.Fatalf(&quot;Error fetching user: %v&quot;, err)<br> }<br><br> if fetchedUser.Name != user.Name || fetchedUser.Age != user.Age {<br>  t.Fatalf(&quot;Mismatch in user data. Expected: %v, Got: %v&quot;, user, fetchedUser)<br> }<br>}<br><br>// Similar test functions for GetUser, UpdateUser, and DeleteUser can be implemented.</pre><p>The TestMain function is used to set up and tear down the test database. It creates an SQLite in-memory database for testing purposes.</p><p>Each test function is designed to test a specific method of the UserRepository. For example, TestUserRepository_CreateUser tests the CreateUser function.</p><p>The test functions uses the testing framework’s t.Fatalf method to report errors. If any assertion fails, the test will stop execution, and the error message will be displayed.</p><p>The setupDatabase and teardownDatabase functions ensure that the test database is properly initialized before running tests and removed after the tests are complete. Remember that the in-memory SQLite database is created and used for testing, and it is independent of any external database connections. The test database is created, used, and removed during the test run, ensuring isolation between test cases.</p><pre>[output]<br>=== RUN   TestUserRepository_CreateUser<br>--- PASS: TestUserRepository_CreateUser (0.00s)<br>PASS<br>ok      github.com/theifedayo/tests     0.408s</pre><p>We have demonstrated a basic example, real-world scenarios might involve more complex interactions, especially if your database operations are part of a larger system. Consider using tools like github.com/DATA-DOG/go-sqlmock for more advanced database testing, especially if you want to mock database responses.</p><h3>Browser testing</h3><p>Testing in the browser with Go typically involves testing web applications, ensuring that the frontend interacts correctly with the backend. There are various tools and libraries in the Go ecosystem that can assist in testing browser-based applications. One popular tool is chromedp, a headless Chrome browser driver for Go.</p><p>Here’s how you write a simple test for a web application using chromedp:</p><p>First, you need to install the necessary packages:</p><pre>go get -u github.com/chromedp/chromedp</pre><p>Now, let’s consider a simple web application that displays a greeting message based on user input. We will write tests that involves starting a headless Chrome browser, navigating to the web application, and checking if the greeting message is displayed correctly.</p><pre>// main.go<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br>)<br><br>func greetHandler(w http.ResponseWriter, r *http.Request) {<br> name := r.URL.Query().Get(&quot;name&quot;)<br> if name == &quot;&quot; {<br>  name = &quot;Guest&quot;<br> }<br><br> message := fmt.Sprintf(&quot;Hello, %s!&quot;, name)<br><br> // Wrap the message in an HTML element with ID &quot;greeting&quot;<br> htmlResponse := fmt.Sprintf(`&lt;div id=&quot;greeting&quot;&gt;%s&lt;/div&gt;`, message)<br> fmt.Fprint(w, htmlResponse)<br>}<br><br>func main() {<br> http.HandleFunc(&quot;/greet&quot;, greetHandler)<br> http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>Make sure you run the server with:</p><pre>go run main.go</pre><p>Navigate to any web browser of your choice with URL: localhost:8080/greet?name=John. You should have something like this displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7RTb67gGGkyFLnFnCldyQ.png" /></figure><p>Now, let’s write a test for this web application using chromedp. We will test that the greeting message is as expected Hello, John!:</p><pre>// main_test.go<br>package main<br><br>import (<br> &quot;context&quot;<br> &quot;testing&quot;<br> &quot;time&quot;<br><br> &quot;github.com/chromedp/cdproto/page&quot;<br> &quot;github.com/chromedp/chromedp&quot;<br>)<br><br>func TestGreetHandler(t *testing.T) {<br> // Start a headless Chrome browser<br> ctx, cancel := chromedp.NewContext(context.Background())<br> defer cancel()<br><br> // Create a timeout context to avoid indefinite waits<br> timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)<br> defer cancel()<br><br> // Open the browser and navigate to the web application<br> err := chromedp.Run(timeoutCtx, chromedp.Navigate(&quot;http://localhost:8080/greet?name=John&quot;))<br> if err != nil {<br>  t.Fatalf(&quot;Failed to navigate: %v&quot;, err)<br> }<br><br> // Wait for the greeting message to appear<br> err = chromedp.Run(timeoutCtx, chromedp.WaitVisible(&quot;#greeting&quot;))<br> if err != nil {<br>  t.Fatalf(&quot;Failed to wait for greeting message: %v&quot;, err)<br> }<br><br> // Extract the text content of the greeting message<br> var greetingText string<br> err = chromedp.Run(timeoutCtx, chromedp.TextContent(&quot;#greeting&quot;, &amp;greetingText))<br> if err != nil {<br>  t.Fatalf(&quot;Failed to get greeting text content: %v&quot;, err)<br> }<br><br> // Check if the greeting message is as expected<br> expectedGreeting := &quot;Hello, John!&quot;<br> if greetingText != expectedGreeting {<br>  t.Errorf(&quot;Expected greeting: %s, Got: %s&quot;, expectedGreeting, greetingText)<br> }<br>}</pre><p>The chromedp library is used to control a headless Chrome browser. The TestGreetHandler function starts a headless Chrome browser, navigates to the web application, and interacts with the page to check if the greeting message is displayed correctly. chromedp.WaitVisible is used to wait until the element with the ID &quot;greeting&quot; becomes visible on the page. chromedp.TextContent is used to extract the text content of the element with the ID &quot;greeting.&quot; Finally, the test compares the extracted greeting message with the expected greeting.</p><p>Run the test; you should have an output similar to:</p><pre>[output]<br>=== RUN   TestGreetHandler<br>--- PASS: TestGreetHandler (0.47s)<br>PASS<br>ok      github.com/theifedayo/tests     0.703s</pre><p>Keep in mind that the success or failure of the test depends on whether the actual behavior of the web application matches the expectations set in the test. If the web application is running and accessible at the specified URL, and if the greeting message is as expected, the test should pass. If there are issues, such as the web application not being reachable, the element not becoming visible, or the text content not matching expectations, the test will fail.</p><p>Remember to start the web application (main.go) before running the tests. If the application is not running, the tests that interact with it will likely fail.</p><h3>Test coverage analysis in Go</h3><p>Test coverage analysis is an essential aspect of testing in Go. It helps you identify which parts of your code are covered by tests and which are not. To generate coverage reports, you can use the built-in go test -cover command:</p><pre>go test -cover</pre><p>This command will display the coverage percentage.</p><p>We will develop our banking application to be more robust by adding GetBalance, Transfer and Deposit function. In main.go and main_test.go, let us add the following functions:</p><pre>// main.go<br>package main<br><br>import &quot;errors&quot;<br><br>// Account represents a bank account.<br>type Account struct {<br> Balance int<br>}<br><br>// Deposit adds funds to the account.<br>func (a *Account) Deposit(amount int) {<br> a.Balance += amount<br>}<br><br>// Withdraw deducts funds from the account, returns an error if insufficient funds.<br>func (a *Account) Withdraw(amount int) error {<br> if amount &gt; a.Balance {<br>  return errors.New(&quot;insufficient funds&quot;)<br> }<br> a.Balance -= amount<br> return nil<br>}<br><br>// GetBalance returns the current balance of the account.<br>func (a *Account) GetBalance() int {<br> return a.Balance<br>}<br><br>// Transfer transfers funds from one account to another.<br>func Transfer(sender *Account, receiver *Account, amount int) error {<br> if err := sender.Withdraw(amount); err != nil {<br>  return err<br> }<br> receiver.Deposit(amount)<br> return nil<br>}</pre><pre>// main_test.go<br>package main<br><br>import (<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestDeposit(t *testing.T) {<br> account := &amp;Account{Balance: 100}<br> account.Deposit(50)<br> assert.Equal(t, 150, account.Balance)<br>}<br><br>func TestWithdraw(t *testing.T) {<br> account := &amp;Account{Balance: 100}<br> err := account.Withdraw(50)<br> assert.NoError(t, err)<br> assert.Equal(t, 50, account.Balance)<br><br> // Test insufficient funds<br> err = account.Withdraw(100)<br> assert.Error(t, err)<br> assert.Equal(t, 50, account.Balance)<br>}<br><br>func TestGetBalance(t *testing.T) {<br> account := &amp;Account{Balance: 100}<br> balance := account.GetBalance()<br> assert.Equal(t, 100, balance)<br>}<br><br>func TestTransfer(t *testing.T) {<br> sender := &amp;Account{Balance: 100}<br> receiver := &amp;Account{Balance: 50}<br><br> err := Transfer(sender, receiver, 25)<br> assert.NoError(t, err)<br> assert.Equal(t, 75, sender.Balance)<br> assert.Equal(t, 75, receiver.Balance)<br><br> // Test insufficient funds in sender&#39;s account<br> err = Transfer(sender, receiver, 100)<br> assert.Error(t, err)<br> assert.Equal(t, 75, sender.Balance)<br> assert.Equal(t, 75, receiver.Balance)<br>}</pre><p>Check the test coverage for this code with:</p><pre>go test -cover</pre><pre>[output]<br>PASS<br>coverage: 100.0% of statements<br>ok      github.com/theifedayo/tests     0.345s</pre><p>Removing the TestTransfer function from out test file and running go test -cover again, we have test coverage of only 60%:</p><pre>[output]<br>PASS<br>coverage: 60.0% of statements<br>ok      github.com/theifedayo/tests     0.345s</pre><p>A better approach to checking our test coverage is to have the test results displayed graphically, highlighting the lines of code that are covered (or not covered) by tests. Run the command below to calculate the coverage percentage and have a profile of it:</p><pre>go test -coverprofile=coverage.out</pre><p>After the output is returned, a file coverage.out is created, which will help display the results in a web browser. Run the command below to have the results displayed in browser:</p><pre>go tool cover -html=coverage.out</pre><p>The results are rendered as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3uZ8jLBCSYkzAyJtnBXSg.png" /></figure><p>We see the Transfer function is not covered in our test and displayed with the red ink.</p><p>Aim for high coverage, but keep in mind that 100% coverage is not always practical or necessary, especially for large scale systems.</p><h3>Automated testing in CI</h3><p>In a CI environment, automated testing is crucial to ensure that code changes do not introduce regressions and that the application functions as expected. Here’s a general process for integrating testing into CI pipelines:</p><p>Define testing scripts — Write testing scripts that cover different aspects of your application, including unit tests, integration tests, and end-to-end tests. In Go, you can use the testing package for unit tests, and tools like go test for running tests.</p><p>Configure CI tool — Configure your CI tool (e.g., Jenkins, GitHub Actions, GitLab CI)to execute the testing scripts whenever code changes are pushed to the repository or when pull requests are created.</p><p>GitHub Actions is a CI/CD service provided by GitHub. It allows you to automate workflows directly within your GitHub repository. We will create GitHub Actions workflow for a Go project (/.github/workflows/go.yml). This workflow will run tests on every push to the main branch using GitHub Actions.</p><pre># /.github/workflows/go.yml<br>name: Go CI<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v2<br><br>    - name: Set up Go<br>      uses: actions/setup-go@v2<br>      with:<br>        go-version: 1.21<br><br>    - name: Run tests<br>      run: go test -v ./...</pre><p>Commit and push your project changes to Github, it will trigger the jobs in yaml file.</p><p>Include linters and code quality checks — Integrate tools like <a href="https://golangci-lint.run/">golangci-lint</a> to perform linting and static code analysis. These checks help maintain code quality and identify potential issues early in the development process.</p><p>Consider Docker for isolation — If your application involves dependencies like databases, consider using Docker containers to isolate your tests. This ensures that tests are consistent and do not rely on the state of external systems.</p><h3>Best practices for unit testing in Go</h3><p>Writing effective unit tests in Go requires following best practices to ensure your tests are maintainable, reliable, and efficient:</p><p>Keep tests close to the code — Place test files in the same package directory as the code they test. This makes it easier to maintain tests and ensures that private functions can be tested.</p><p>Use clear test function names — Choose descriptive names for your test functions that clearly indicate what is being tested. This helps with test documentation and debugging.</p><p>Minimize test dependencies — Keep test dependencies to a minimum. If possible, avoid external dependencies and use mocking or stubbing techniques when necessary.</p><p>Keep tests simple and isolated — Each test should focus on a specific aspect of the code and be isolated from other tests. Avoid test dependencies between different tests.</p><p>Use table-driven tests — As mentioned earlier, use table-driven tests to cover multiple input scenarios with the same test logic.</p><p>Document your tests — Write clear comments in your test code to explain the purpose of the test and any relevant information.</p><p>Run tests regularly — Make running tests a part of your development workflow. Continuous integration (CI) tools can automate this process.</p><p>Monitor code coverage — Use tools like go test -cover to monitor test coverage. Aim for high code coverage to ensure that most of your code is tested.</p><h3>Conclusion</h3><p>In this comprehensive guide to unit testing in Go, we’ve covered everything from the basics of writing test functions to advanced testing patterns, mocking, integration with external tools, best practices, and test coverage analysis. Unit testing is a crucial skill for every Go developer, as it ensures the reliability and maintainability of your code.</p><p>As you continue to build and maintain your Go applications, remember to write clear, concise tests that comprehensively cover your code. Prioritize testing not only to catch bugs but also to document and validate the expected behavior of your software. With diligent testing practices, you’ll enhance the quality and robustness of your Go applications, making them more reliable and easier to maintain in the long run.</p><p>You can read more about testing in <a href="https://pkg.go.dev/testing">Go’s official documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c292f20670b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ACID in Database Engineering]]></title>
            <link>https://theifedayo.medium.com/understanding-acid-in-database-engineering-5abf9259cdc5?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5abf9259cdc5</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 12:41:15 GMT</pubDate>
            <atom:updated>2023-09-10T12:41:15.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*RPSh5hhQRbzRpz9SZDj1ug.png" /></figure><p>In software engineering, ensuring data consistency and reliability is paramount. One foundational concept that helps achieve this is ACID, which stands for <strong>Atomicity, Consistency, Isolation, and Durability</strong>. ACID properties provide a set of guarantees that define how database transactions should behave to maintain data integrity. In this article, we’ll delve into each ACID property, explain its significance, and provide practical code examples using a popular relational database management system, PostgreSQL.</p><h4>Transaction</h4><p>A transaction is a sequence of one or more database operations (such as queries, inserts, updates, or deletes) that are treated as a single, indivisible unit of work. The primary purpose of a transaction is to ensure data integrity by guaranteeing that a series of related database changes either all succeed or all fail, leaving the database in a consistent state.</p><p>The lifespan of a transaction refers to the duration during which a transaction is active and can make changes to the database. Transactions have a well-defined beginning and end.</p><ol><li>Start of a Transaction: A transaction begins when it is initiated explicitly by the application or when a specific operation is performed that automatically starts a transaction (e.g., the execution of an SQL statement like BEGIN or START TRANSACTION).</li><li>Execution of Database Operations: During its lifespan, a transaction can execute various database operations. These operations can include reading data from the database, modifying existing data, or adding new data.</li><li>End of a Transaction: A transaction ends when one of the following occurs:</li></ol><ul><li><em>A successful completion</em>: If all database operations within the transaction are executed successfully, the transaction is typically committed. Committing a transaction makes all its changes permanent and durable in the database.</li><li><em>An error or failure</em>: If any operation within the transaction encounters an error or failure, the transaction is rolled back. Rolling back a transaction ensures that none of its changes are applied to the database, leaving it in its original state.</li></ul><h3>Atomicity</h3><p>Imagine you’re transferring money from one bank account to another online. This operation involves two steps: deducting the money from one account and adding it to the other. Now, if something goes wrong in between, we want to ensure that neither account is left in an inconsistent state.</p><p>This is what we call “atomicity.” It ensures that a series of database operations either all succeed or, if one fails, everything is rolled back to its original state. Think of it as an <strong>all-or-nothing</strong> rule for transactions.</p><p>Suppose you have a banking application, and you want to transfer $100 from User A’s account to User B’s account. Here’s how you can ensure atomicity using SQL commands in PostgreSQL</p><pre>-- Start a transaction<br>BEGIN;<br><br>-- Step 1: Deduct $100 from User A&#39;s account<br>UPDATE accounts SET balance = balance - 100 WHERE account_id = &#39;UserA&#39;;<br><br>-- Step 2: Add $100 to User B&#39;s account<br>UPDATE accounts SET balance = balance + 100 WHERE account_id = &#39;UserB&#39;;<br><br>-- Commit the transaction if both steps succeed<br>COMMIT;<br><br>-- Rollback the transaction if any step fails<br>ROLLBACK;</pre><p>By following this approach, we guarantee that money transfers are atomic operations. Either the entire transfer occurs successfully, leaving both accounts updated, or nothing changes if any part of the transfer fails. This ensures data consistency and prevents partial or erroneous updates in the database.</p><h3>Consistency</h3><p>Imagine a library where books have unique ISBN numbers, and no two books should have the same number. Now, if someone tries to add a book with a duplicate ISBN, we need to ensure our library database stays consistent.</p><p>This is where “consistency” comes into play. It ensures that a transaction takes the database from one consistent state to another, respecting rules and constraints.</p><p>Consistency guarantees that a database transaction transforms the database from one consistent state to another consistent state. It enforces constraints, ensuring that data remains within specified rules and boundaries.</p><pre>BEGIN;<br><br>-- Attempt to add a book with a duplicate ISBN<br>INSERT INTO library (isbn, title) VALUES (&#39;978-0451524935&#39;, &#39;1984&#39;);<br>INSERT INTO library (isbn, title) VALUES (&#39;978-0451524935&#39;, &#39;Brave New World&#39;);<br><br>COMMIT;</pre><p>In this case, the second INSERT operation violates a UNIQUE constraint, causing the entire transaction to fail. PostgreSQL ensures that no inconsistent data is stored.</p><h3>Isolation: Preventing Cross Talk</h3><p>Isolation ensures that multiple concurrent transactions do not interfere with each other. It guarantees that each transaction appears to be executed in isolation, as if it were the only transaction running on the system. Various isolation levels, such as <a href="https://www.sqlshack.com/dirty-reads-and-the-read-uncommitted-isolation-level/">Read Uncommitted</a>, Read Committed, <a href="https://www.postgresql.org/docs/current/transaction-iso.html">Repeatable Read</a>, and Serializable, control the degree of isolation.</p><p>Imagine a busy coffee shop with two baristas making lattes. Both are simultaneously preparing a latte for the same customer. You wouldn’t want one barista to interfere with the other’s work, right? Exactly!</p><p>Now, let’s isolate with code using the Serializable isolation level in PostgreSQL:</p><pre>-- Set the isolation level to Serializable<br>BEGIN ISOLATION LEVEL SERIALIZABLE;<br><br>-- Transaction 1: Deduct 10 items from stock<br>UPDATE products SET stock = stock - 10 WHERE product_id = 123;<br><br>-- Concurrent Transaction 2: Deduct 20 items from stock<br>UPDATE products SET stock = stock - 20 WHERE product_id = 123;<br><br>COMMIT;</pre><p>With “Serializable” isolation, PostgreSQL ensures these transactions run in a way that avoids conflicts, keeping our data safe and sound.</p><h3>Durability</h3><p>Durability guarantees that once a transaction is committed, its changes will persist, even in the face of system failures. It ensures that the data will not be lost or corrupted.</p><p>In PostgreSQL, durability is guaranteed by default. When you commit a transaction, the changes are stored permanently, and PostgreSQL takes care of ensuring data durability.</p><h3>Conclusion</h3><p>ACID properties play a vital role in maintaining data integrity and reliability. By understanding and implementing these properties in your database systems, you can ensure that your data remains consistent, isolated from concurrent transactions, and durable even in the event of system failures. PostgreSQL and other relational database systems provide robust support for ACID transactions, making them a reliable choice for mission-critical applications.</p><p><strong>Excerpts from my notes </strong>on <a href="https://www.udemy.com/course/database-engines-crash-course/">Fundamentals of Database Engineering</a> by <a href="https://medium.com/@hnasr">Hussein Nasser</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5abf9259cdc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieve More in Less Time — Insights from Deep Work]]></title>
            <link>https://theifedayo.medium.com/achieve-more-in-less-time-insights-from-deep-work-18b01453f5af?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b01453f5af</guid>
            <category><![CDATA[deep-work]]></category>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 08:25:03 GMT</pubDate>
            <atom:updated>2023-04-08T08:25:03.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>Achieve More in Less Time — Insights from Deep Work</h3><p>Everyone wants to succeed — whether they’re powering through their personal projects and commitments or ticking off professional to-do lists at a job. However, success doesn’t happen without some effort. It requires copious amounts of diligence, commitment, and even concentration.</p><p>And like with many activities in life, you’ll need a clear-cut strategy if you’re to achieve great success.</p><p>Deep work is one such strategy for getting things done. The concept simply refers to the capacity for undistracted concentration on a mentally taxing job. It’s pretty revolutionary and can turn even the average worker into a high-functioning expert.</p><h3>Why Should You Practice Deep Work?</h3><p>Let’s face it — work is hard, and we’d all rather spend most of our days unwinding to great music, food, and maybe social media. However, there’s no reason to make enemies out of your job and projects, no matter how stressful they might seem. But how exactly can deep work help you achieve more in less time?</p><p>Here are a few reasons you should consider practicing deep work:</p><ol><li>Improved productivity and quality of work.</li><li>Increased creativity and innovation.</li><li>Improved mental health and well-being.</li><li>Enhanced professional growth.</li></ol><p>In the next section of this article, I’ll explain just how deep work can influence your work culture in these four ways.</p><h3>1. Improved Productivity and Quality of Work</h3><p>Deep work allows you to focus all your attention and energy on a task. After all, you’re more likely to produce high-quality work when you’re fully immersed in a task. You’re also more likely to finish your tasks faster since you’re not being distracted by other things.</p><p>John is a close friend of mine and a writer who struggled with distractions while writing his final-year project chapters. He decided to try deep work by shutting off his phone, closing his social media apps, and focusing solely on his writing. To his surprise, he was able to write an entire chapter in just a few hours. The quality of his work also improved, and he felt more confident in his writing.</p><h3>2. Increased Creativity and Innovation</h3><p>Deep work can also boost your creativity and innovation. When you’re fully immersed in a task, you’re more likely to come up with new ideas and solutions. This is because you’re giving your mind the time and space it needs to think deeply and creatively.</p><p>For example, when struggling with solving a complex problem at work, I try to do deep work by going to a quiet place, turning off my phone, and focusing solely on the problem. After a few hours of deep work, I usually come up with a creative solution that impresses my colleagues.</p><h3>3. Improved Mental Health and Well-being</h3><p>Deep work can also have a positive impact on your mental health and well-being. When you’re fully immersed in a task, you’re more likely to experience a state of flow.</p><p>For instance, let’s say you’re a student who struggles with studying for long periods of time. By incorporating deep work into your study routine, you can improve your focus and concentration. You’ll also feel more satisfied with your studies, which can boost your mental well-being.</p><p>Flow is a mental state where you’re fully engaged in an activity and experience a sense of satisfaction and enjoyment.</p><h3>4. Enhanced Professional Growth</h3><p>Deep work can also lead to enhanced professional growth. When you’re fully immersed in a task, you’re more likely to learn and grow in your field. This is because you’re giving yourself the time and space to learn deeply and understand complex concepts.</p><p>For example, let’s say you’re a software developer who wants to learn a new programming language, by incorporating deep work into your learning routine, you can improve your understanding of the language. You’ll also be able to apply your new knowledge to your work, which can lead to career growth.</p><p>In conclusion, doing deep work is essential to achieving success in your personal and professional lives. It can improve your productivity and quality of work, boost your creativity and innovation, improve your mental health and well-being, and lead to enhanced professional growth. So don’t be afraid to turn off your phone, close your email, and focus solely on the task at hand. You might just be surprised by how much you can accomplish.</p><p><strong>Thanks</strong> to <a href="https://medium.com/@thetrueerudite">Ifeoluwa Adekoya</a> for reading drafts of this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b01453f5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Your First Tests For Node.js Apps]]></title>
            <link>https://theifedayo.medium.com/writing-your-first-tests-for-node-js-apps-8332ee1cc457?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8332ee1cc457</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 16:09:28 GMT</pubDate>
            <atom:updated>2023-02-24T16:09:28.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGk3fsWibgPz6QHhW2MUsw.png" /></figure><p>Software testing is a critical process in the software development cycle. It is the process of assessing the performance and features of a software application to discover and diagnose any flaws or bugs within it. This may entail running the software with different inputs to verify that the output meets predetermined criteria. The primary objective of software testing is to guarantee that the software is functioning as intended and satisfies the user’s needs.</p><p>It is impossible to exaggerate the importance of software testing. It contributes to ensuring the usability, functionality, and dependability of the software. Also, it aids in lowering the price of rectifying errors, which can become significantly more expensive when found later in the development cycle.</p><p>There are different types of software testing, including functional testing, performance testing, and security testing. Each type of testing serves a specific purpose and requires a unique set of tools and techniques.</p><p>To ensure the effectiveness of software testing, it is crucial to have a comprehensive testing plan that includes the identification of testing goals, the selection of appropriate testing tools, and the creation of test cases.</p><p>This article will examine the best techniques for writing tests in TypeScript and provide code examples to illustrate them.</p><h4><strong>Prerequisites</strong></h4><p>Popular programming language TypeScript enhances JavaScript with sophisticated features like optional static typing. By using TypeScript to create tests, you can assure the caliber of your code and identify mistakes as they arise early in the development cycle.</p><p>The prerequisites for following this guide are npm (Node Package Manager) and typescript.</p><p>Let’s check if we have npm installed on our computer</p><pre>npm -v<br># 8.3.1</pre><p>This command will return the version number of NPM if it is installed, or an error message if it is not. If you receive an error message, you will need to install NPM on your system.</p><p>To install NPM, you can download and install <a href="https://nodejs.org/en/">Node.js</a> from the official website. NPM is included with Node.js, so when you install Node.js, NPM will also be installed on your system.</p><p>To check the version of <a href="https://www.typescriptlang.org/download">TypeScript</a> installed on your system, you can use the following command in your terminal or command prompt:</p><pre>tsc -v<br># Version 4.7.4</pre><p>This will display the version number of TypeScript installed on your system. If TypeScript is not installed, you will need to install it using a package manager like npm.</p><p>To install TypeScript using npm, you can use the following command:</p><pre>npm install -g typescript</pre><p>This will install the latest version of TypeScript globally on your system.</p><h4><strong>Assumptions</strong></h4><p>In this tutorial, I assume you already have a node.js project you want to write tests for. We will be writing tests for a CMS (content management system) with TypeScript and Mocha, a popular testing framework for Node.js.</p><p>We have the user and post model, with endpoints for authentication and CRUD operations for the post model.</p><h4>Hands-on</h4><p>To get started, we need to install some dependencies into our project. We can use NPM to install these dependencies by running the command below in our terminal or command prompt:</p><pre>npm install --save-dev ts-node mocha chai supertest @types/mocha @types/chai @types/supertest</pre><p>This will install Mocha, Chai, Supertest, and the TypeScript types for Mocha, Chai, and Supertest.</p><p>In your src folder, you create a new folder called tests, and inside the tests folder, you create two files: user.test.ts and post.test.ts. user.test.ts will contain all tests for authentication and user endpoints and post.test.ts will contain all tests for the post endpoints.</p><p>Add the following code to user.test.ts</p><pre>import { expect } from &#39;chai&#39;;<br>import request from &#39;supertest&#39;;<br>import app from &#39;./../app&#39;;<br><br><br><br>describe(&#39;USER AUTH&#39;, () =&gt; {<br>    let testUserId: string;<br>    let authToken: string;<br><br>    it(&#39;should not create a new user with invalid data&#39;, async () =&gt; {<br>        const res = await request(app)<br>          .post(&#39;/auth/signup&#39;)<br>          .send({<br>            username: &#39;testuser&#39;,<br>            password: &#39;testpass&#39;,<br>          });<br>        expect(res.status).to.equal(400);<br>        expect(res.body.message).to.equal(&#39;Email is required&#39;);<br>    });<br><br><br>    it(&#39;should create a new user with valid data&#39;, async () =&gt; {<br>      const res = await request(app)<br>        .post(&#39;/auth/signup&#39;)<br>        .send({<br>          username: &#39;username&#39;,<br>          password: &#39;password&#39;,<br>          email: &#39;email@example.com&#39;,<br>        });<br>      expect(res.status).to.equal(200);<br>      expect(res.body.data.token).to.be.a(&#39;string&#39;);<br>      expect(res.body.data.user).to.be.an(&#39;object&#39;);<br>      expect(res.body.data.user.username).to.equal(&#39;username&#39;);<br>      expect(res.body.data.user.email).to.equal(&#39;email@example.com&#39;);<br>      expect(res.body.data.user.password).to.not.exist;<br>      testUserId = res.body.data.user.id;<br>    });<br><br><br>    it(&#39;should not login with invalid credentials&#39;, async () =&gt; {<br>        const res = await request(app)<br>          .post(&#39;/auth/login&#39;)<br>          .send({<br>            username: &#39;testuser&#39;,<br>            password: &#39;wrongpass&#39;,<br>          });<br>        expect(res.status).to.equal(401);<br>        expect(res.body.message).to.equal(&#39;Invalid username or password&#39;);<br>    });<br><br>    it(&#39;should login with valid credentials&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .post(&#39;/auth/login&#39;)<br>            .send({<br>            username: &#39;username&#39;,<br>            password: &#39;password&#39;,<br>            });<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.token).to.be.a(&#39;string&#39;);<br>        expect(res.body.data.user.id).to.equal(testUserId);<br>        expect(res.body.data.user.username).to.equal(&#39;username&#39;);<br>        expect(res.body.data.user.email).to.equal(&#39;email@example.com&#39;);<br>        expect(res.body.data.user.password).to.not.exist;<br>        authToken = res.body.data.token;<br>    });<br>  <br>    it(&#39;should get the current user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .get(`/users/${testUserId}`)<br>            .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.id).to.equal(testUserId);<br>        expect(res.body.data.username).to.equal(&#39;username&#39;);<br>        expect(res.body.data.email).to.equal(&#39;email@example.com&#39;);<br>        expect(res.body.data.password).to.not.exist;<br>    });<br><br>    it(&#39;should update the current user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .put(`/users/${testUserId}`)<br>            .set(&#39;Authorization&#39;, `Bearer ${authToken}`)<br>            .send({<br>            username: &#39;updatedusername&#39;,<br>            email: &#39;updatedemail@example.com&#39;,<br>            });<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.id).to.equal(testUserId);<br>        expect(res.body.data.username).to.equal(&#39;updatedusername&#39;);<br>        expect(res.body.data.email).to.equal(&#39;updatedemail@example.com&#39;);<br>        expect(res.body.data.password).to.not.exist;<br>    });<br><br>    it(&#39;should not update the current user with invalid data&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .put(`/users/${testUserId}`)<br>            .set(&#39;Authorization&#39;, `Bearer ${authToken}`)<br>            .send({<br>            email: &#39;invalidemail&#39;,<br>            });<br>        expect(res.status).to.equal(400);<br>        expect(res.body.message).to.equal(&#39;Invalid email&#39;);<br>    });<br><br>    it(&#39;should delete the current user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .delete(`/users/${testUserId}`)<br>            .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(res.status).to.equal(204);<br><br>        // Make sure the user was deleted<br>        const deletedRes = await request(app)<br>            .get(`/users/${testUserId}`)<br>            .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(deletedRes.status).to.equal(404);<br>        expect(deletedRes.body.message).to.equal(&#39;User not found&#39;);<br>    });<br>});</pre><p>These tests cover the authentication flow of creating a new user, logging in, and getting the current user’s information. Additionally, it tests the user module’s functionality by checking that the current user can be fetched, updated, and deleted.</p><p>It’s important to note that these tests only cover basic functionality and that there may be additional edge cases and error scenarios that should be tested depending on the specific requirements of your API.</p><p>In post.test.ts , we will write tests for the posts endpoints</p><pre>import { expect } from &#39;chai&#39;;<br>import request from &#39;supertest&#39;;<br>import app from &#39;./../app&#39;;<br><br><br><br>describe(&#39;POST&#39;, () =&gt; {<br>    let testUserId: string;<br>    let authToken: string;<br>    let testPostId: string;<br><br><br><br>    it(&#39;should create a new user with valid data&#39;, async () =&gt; {<br>        const res = await request(app)<br>        .post(&#39;/auth/signup&#39;)<br>        .send({<br>            username: &#39;username&#39;,<br>            password: &#39;password&#39;,<br>            email: &#39;email@example.com&#39;,<br>        });<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.token).to.be.a(&#39;string&#39;);<br>        expect(res.body.data.user).to.be.an(&#39;object&#39;);<br>        expect(res.body.data.user.username).to.equal(&#39;username&#39;);<br>        expect(res.body.data.user.email).to.equal(&#39;email@example.com&#39;);<br>        expect(res.body.data.user.password).to.not.exist;<br>        testUserId = res.body.data.user.id;<br>    });<br><br><br>    it(&#39;should login and return a token&#39;, async () =&gt; {<br>        const res = await request(app)<br>        .post(&#39;/auth/login&#39;)<br>        .send({<br>            username: &#39;username&#39;,<br>            password: &#39;password&#39;,<br>        });<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.token).to.be.a(&#39;string&#39;);<br>        expect(res.body.data.user.id).to.equal(testUserId);<br>        expect(res.body.data.user.username).to.equal(&#39;username&#39;);<br>        expect(res.body.data.user.email).to.equal(&#39;email@example.com&#39;);<br>        expect(res.body.data.user.password).to.not.exist;<br>        authToken = res.body.data.token;<br>    });<br><br>    it(&#39;should create a new post with authentication&#39;, async () =&gt; {<br>        const res = await request(app)<br>        .post(&#39;/posts&#39;)<br>        .send({<br>            title: &#39;New Post&#39;,<br>            content: &#39;This is content for new post.&#39;,<br>        })<br>        .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.title).to.equal(&#39;New Post&#39;);<br>        expect(res.body.data.content).to.equal(&#39;This is content for new post.&#39;);<br>        expect(res.body.data.author).to.equal(testUserId);<br>        testPostId = res.body.data.id;<br>    });<br><br>    it(&#39;should get a post by id&#39;, async () =&gt; {<br>        const res = await request(app).get(`/posts/${testPostId}`);<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.id).to.equal(testPostId);<br>        expect(res.body.data.title).to.equal(&#39;New Post&#39;);<br>        expect(res.body.data.content).to.equal(&#39;This is content for new post.&#39;);<br>        expect(res.body.data.author.id).to.equal(testUserId);<br>        expect(res.body.data.author.username).to.equal(&#39;username&#39;);<br>    });<br><br>    it(&#39;should update a post by id with authentication&#39;, async () =&gt; {<br>        const res = await request(app)<br>        .put(`/posts/${testPostId}`)<br>        .send({<br>            title: &#39;Updated Post&#39;,<br>            content: &#39;This is an updated post.&#39;,<br>        })<br>        .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(res.status).to.equal(200);<br>        expect(res.body.data.id).to.equal(testPostId);<br>        expect(res.body.data.title).to.equal(&#39;Updated Post&#39;);<br>        expect(res.body.data.content).to.equal(&#39;This is an updated post.&#39;);<br>        expect(res.body.data.author.id).to.equal(testUserId);<br>        expect(res.body.data.author.username).to.equal(&#39;username&#39;);<br>    });<br><br>    it(&#39;should delete a post by id with authentication&#39;, async () =&gt; {<br>        const res = await request(app)<br>        .delete(`/posts/${testPostId}`)<br>        .set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>        expect(res.status).to.equal(204);<br>    });<br>});</pre><p>We will create our final file and name it combine.test.ts , this will help us run our tests in the specific order that we want.</p><pre>// combine.test.ts<br>import &#39;./user.test&#39;;<br>import &#39;./post.test&#39;;</pre><p>In this file, We decided to run the user test first before testing other modules. The order of running tests modules-to-modules can be switched in any desired manner.</p><h4>Running Tests</h4><p>To run our tests, we will be adding a command script to our package.json file, we call it test</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;medium-tutorial-project&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;mocha --require ts-node/register &#39;./src/test/combine.test.ts&#39; --clearCache --timeout 60000 --exit&quot;<br>    ......<br>    ......<br>  },<br>  ......<br>  ......<br>}</pre><p>The code added defines a &quot;test&quot; script in the scripts section, it runs mocha tests using the ts-node/register compiler for TypeScript executing combine.test.ts. Other options such as --clearCache - will tell Mocha to clear the required cache before running the tests. This ensures that any changes made to the required modules are reflected in the tests, --timeout 60000 will set the timeout for the tests to 60 seconds (60000 milliseconds). If any test takes longer than this, it will fail and --exit tells Mocha to exit the test process once all tests have been completed.</p><p>To run the Mocha tests, you can use the following command in your terminal or command prompt:</p><pre>npm test</pre><p>This command will execute the test script defined in our package.json file and run our Mocha tests in the test folder and on combine.test.ts.</p><p>On your terminal or command prompt, you should have something similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSUvEMgfW_IEgKLGDkbZDw.png" /></figure><h4>Summary</h4><p>In this article, we’ve explored how to write tests for a TypeScript backend API using Mocha, Chai, and Supertest. We used a simple API for managing users and posts to demonstrate some best practices for testing a Node.js server.</p><p>By writing tests, we have ensured that our API behaves as expected and can catch errors early in the development process.</p><p>In conclusion, software testing is a critical process in software development that helps to ensure the quality and reliability of the software. It is an ongoing process that should be an integral part of the software development cycle.</p><p>Now go ahead and write some more tests for some of your other Node.js projects</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8332ee1cc457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building more reliable applications with Temporal]]></title>
            <link>https://theifedayo.medium.com/building-more-reliable-applications-with-temporal-7e7aa8868f40?source=rss-fe4ff6aa03c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7aa8868f40</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[temporal]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[reliability-engineering]]></category>
            <dc:creator><![CDATA[Ifedayo Adesiyan]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 13:22:11 GMT</pubDate>
            <atom:updated>2023-02-16T13:22:11.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf1TFqmklnwjaq-H3WhwTA.png" /></figure><p>The <a href="https://temporal.io/">Temporal</a> microservice orchestrator is a key component of the Temporal platform that provides coordination and management of microservices as they interact with one another to complete complex workflows. The orchestrator provides features such as task management, error handling, retries, and compensation to ensure that workflows are executed accurately and consistently, even in the face of failures or unexpected events.</p><p>Using Temporal in application development can help simplify the development of complex, time-sensitive workflows and improve the reliability and scalability of the applications. By using the Temporal orchestrator, developers can focus on the implementation of their business logic, and leave the coordination and management of the underlying microservices to the platform.</p><h3><strong>Illustration</strong></h3><p>Microservices architecture, for example, is used in company XYZ. The microservices approach to software development helps their teams deploy faster, but it comes with some issues, one of which is data consistency. How can data changes in microservice A be propagated to microservices B and C? send it through an event?</p><p>Yes, that works, but what if B updates itself and C had hiccups and just could not make the update?</p><p>Then that means we need to have a mechanism that allows us to handle such failures, make retries, and what else? How many situations like the one described above require us to write failure and retry logic?</p><p>Hence, the use of <a href="https://temporal.io/">Temporal</a> as a microservice orchestrator helps us solve the issues stated above.</p><h3>Prerequisites</h3><p>The prerequisite for this tutorial is having <a href="https://go.dev/doc/install">Go</a> and <a href="https://www.docker.com/products/docker-desktop/">Docker</a> installed and configured.</p><p>Verify that you’ve installed Go by opening a command prompt and typing the following command</p><pre>go version</pre><p>It should return something similar to this</p><pre>go version go1.19.3 darwin/amd64</pre><p>Also, verify docker is installed with</p><pre>docker --version<br>#Docker version 20.10.22, build 3a2c30b</pre><h3><strong>Choice</strong></h3><p>Temporal can be used inside and outside your project directory, as long as your application can access it. Your individual needs and the project’s infrastructure will determine your choice.<br>It may be simpler to maintain your project’s dependencies and setup if you decide to execute Temporal inside of your project directory because everything is contained there. However, running Temporal outside of your project directory might improve the degree of concern separation and make it simpler to manage numerous projects that share a single Temporal instance.</p><p>However, in this guide, we will run the temporal server inside our project directory.</p><h3><strong>Hello-workflow</strong></h3><p>We will be using the simple hello-workflow to orchestrate tasks within a distributed system. The starter and workers are the two main components that enable the distributed system to run, and in this guide, we will be implementing the starter and worker.</p><p>Here’s what our project directory will look like.</p><pre>├── dynamicconfig<br>│ ├── development-cass.yaml<br>│ └── development-sql.yaml<br>| └── docker.yaml<br>|<br>├── src<br>│ ├── helloworkflow <br>| |        └── workflow.go<br>│ ├── starter<br>| |        └── main.go<br>| └── worker<br>|          └── main.go<br>├── .env<br>├── docker-compose.yml<br></pre><p>You create a new Go project, say tutorial-guide and cd into it, then open the directory on your text editor. You create dynamicconfig folder in the root directory of your project and add the 3 yaml files. These files are needed to have the temporal-server up.</p><pre># development-cass.yaml<br>system.forceSearchAttributesCacheRefreshOnRead:<br>  - value: true # Dev setup only. Please don&#39;t turn this on in production.<br>    constraints: {}</pre><pre># development-sql.yaml<br>limit.maxIDLength:<br>  - value: 255<br>    constraints: {}<br>system.forceSearchAttributesCacheRefreshOnRead:<br>  - value: true # Dev setup only. Please don&#39;t turn this on in production.<br>    constraints: {}</pre><pre># docker.yaml<br>apiVersion: v1<br>clusters:<br>  - cluster:<br>      certificate-authority: path-to-your-ca.rt #e.g/System/Volumes/Data/Users/&lt;name&gt;/.minikube/ca.crt<br>      server: https://192.168.99.100:8443<br>    name: minikube<br>contexts:<br>  - context:<br>      cluster: minikube<br>      user: minikube<br>    name: minikube<br>current-context: minikube<br>kind: Config<br>preferences: {}<br>users:<br>  - name: minikube<br>    user:<br>      client-certificate: path-to-proxy-client-ca.key #e.g/System/Volumes/Data/Users/&lt;name&gt;/.minikube/proxy-client-ca.key<br>      client-key: path-to-proxy-client-ca.key #e.g/System/Volumes/Data/Users/&lt;name&gt;/.minikube/proxy-client-ca.key</pre><p>Use docker.yaml file to override the default dynamic config value (they are specified when creating the service config). More information about the docker.yaml file and how to use it [<a href="https://github.com/temporalio/docker-compose/tree/main/dynamicconfig">https://github.com/temporalio/docker-compose/tree/main/dynamicconfig</a>]</p><pre># docker-compose.yaml<br>version: &#39;3.5&#39;<br><br>services:<br>  elasticsearch:<br>    container_name: temporal-elasticsearch<br>    environment:<br>      - cluster.routing.allocation.disk.threshold_enabled=true<br>      - cluster.routing.allocation.disk.watermark.low=512mb<br>      - cluster.routing.allocation.disk.watermark.high=256mb<br>      - cluster.routing.allocation.disk.watermark.flood_stage=128mb<br>      - discovery.type=single-node<br>      - ES_JAVA_OPTS=-Xms256m -Xmx256m<br>      - xpack.security.enabled=false<br>    image: elasticsearch:${ELASTICSEARCH_VERSION}<br>    networks:<br>      - temporal-network<br>    expose:<br>      - 9200<br>    volumes:<br>      - /var/lib/elasticsearch/data<br>  postgresql:<br>    container_name: temporal-postgresql<br>    environment:<br>      POSTGRES_PASSWORD: temporal<br>      POSTGRES_USER: temporal<br>    image: postgres:${POSTGRESQL_VERSION}<br>    networks:<br>      - temporal-network<br>    expose:<br>      - 5432<br>    volumes:<br>      - /var/lib/postgresql/data<br>  temporal:<br>    container_name: temporal<br>    depends_on:<br>      - postgresql<br>      - elasticsearch<br>    environment:<br>      - DB=postgresql<br>      - DB_PORT=5432<br>      - POSTGRES_USER=temporal<br>      - POSTGRES_PWD=temporal<br>      - POSTGRES_SEEDS=postgresql<br>      - DYNAMIC_CONFIG_FILE_PATH=config/dynamicconfig/development-sql.yaml<br>      - ENABLE_ES=true<br>      - ES_SEEDS=elasticsearch<br>      - ES_VERSION=v7<br>    image: temporalio/auto-setup:${TEMPORAL_VERSION}<br>    networks:<br>      - temporal-network<br>    ports:<br>      - 7233:7233<br>    labels:<br>      kompose.volume.type: configMap<br>    volumes:<br>      - ./dynamicconfig:/etc/temporal/config/dynamicconfig<br>  temporal-admin-tools:<br>    container_name: temporal-admin-tools<br>    depends_on:<br>      - temporal<br>    environment:<br>      - TEMPORAL_CLI_ADDRESS=temporal:7233<br>    image: temporalio/admin-tools:${TEMPORAL_VERSION}<br>    networks:<br>      - temporal-network<br>    stdin_open: true<br>    tty: true<br>  temporal-ui:<br>    container_name: temporal-ui<br>    depends_on:<br>      - temporal<br>    environment:<br>      - TEMPORAL_ADDRESS=temporal:7233<br>      - TEMPORAL_CORS_ORIGINS=http://localhost:3000<br>    image: temporalio/ui:${TEMPORAL_UI_VERSION}<br>    networks:<br>      - temporal-network<br>    ports:<br>      - 8080:8080<br><br>networks:<br>  temporal-network:<br>    driver: bridge<br>    name: temporal-network</pre><p>Add the environment variables needed for the docker-compose.yaml file.</p><pre># .env<br>COMPOSE_PROJECT_NAME=temporal<br>CASSANDRA_VERSION=3.11.9<br>ELASTICSEARCH_VERSION=7.16.2<br>MYSQL_VERSION=8<br>POSTGRESQL_VERSION=13<br>TEMPORAL_VERSION=1.19.1<br>TEMPORAL_UI_VERSION=2.9.1</pre><p>The source code for the workflow that the Temporal Server runs is located in the workflow.go file. It is in charge of generating activities, monitoring their completion, and controlling the workflow. It specifies every action the workflow must do and is started by an event, such as a message from a queue or the addition of a new data item to the system.</p><pre>// workflow.go<br>package helloworkflow<br><br>import (<br> &quot;context&quot;<br> &quot;time&quot;<br><br> &quot;go.temporal.io/sdk/workflow&quot;<br>)<br><br>func Workflow(ctx workflow.Context, name string) (string, error) {<br> ao := workflow.ActivityOptions{<br>  ScheduleToStartTimeout: time.Minute,<br>  StartToCloseTimeout:    time.Minute,<br> }<br><br> ctx = workflow.WithActivityOptions(ctx, ao)<br><br> logger := workflow.GetLogger(ctx)<br><br> var result string<br> err := workflow.ExecuteActivity(ctx, Activity, name).Get(ctx, &amp;result)<br> if err != nil {<br>  logger.Error(&quot;Activity failed&quot;, &quot;Error&quot;, err)<br> }<br><br> return result, nil<br>}<br><br>func Activity(ctx context.Context, name string) (string, error) {<br> return &quot;Hello &quot; + name, nil<br>}</pre><p>The starter is responsible for coordinating the workflow executions within the system. It is responsible for scheduling the tasks to be executed and keeping the task statuses up to date. The starter also acts as a gateway for users to interact with the system via its API.</p><p>Now, we add these to our main.go file under the starter directory.</p><pre>// starter/main.go<br>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br><br> &quot;github.com/theifedayo/hello-workflow/src/helloworkflow&quot;<br> &quot;go.temporal.io/sdk/client&quot;<br>)<br><br>func main() {<br> c, err := client.NewClient(client.Options{<br>  <br> })<br> if err != nil {<br>  log.Fatalln(&quot;Unable to make client&quot;, err)<br> }<br><br> defer c.Close()<br><br> workflowOptions := client.StartWorkflowOptions{<br>  ID:        &quot;hello_world_workflowID&quot;,<br>  TaskQueue: &quot;hello-world&quot;,<br> }<br><br> we, err := c.ExecuteWorkflow(context.Background(), workflowOptions, helloworkflow.Workflow, &quot;ifedayo&quot;)<br> if err != nil {<br>  log.Fatalln(&quot;Unable to execute workflow&quot;, err)<br> }<br><br> var result string<br> // store the result of the run<br> err = we.Get(context.Background(), &amp;result)<br> if err != nil {<br>  log.Fatalln(&quot;Unable to get workflow result&quot;, err)<br> }<br> log.Println(&quot;workflow result:&quot;, result)<br>}</pre><p>Workers are responsible for executing the tasks. These workers are deployed across different nodes in the system, and their job is to receive the tasks from the starter and execute them. The workers are also responsible for sending the results back to the starter. The Workers can be scaled up or down depending on the workload</p><pre>// worker/main.go<br>package main<br><br>import (<br> &quot;log&quot;<br><br> &quot;github.com/theifedayo/hello-workflow/src/helloworkflow&quot;<br> &quot;go.temporal.io/sdk/client&quot;<br> &quot;go.temporal.io/sdk/worker&quot;<br>)<br><br>func main() {<br> c, err := client.NewClient(client.Options{})<br> if err != nil {<br>  log.Fatalln(&quot;Unable to make client&quot;, err)<br> }<br><br> defer c.Close()<br><br> w := worker.New(c, &quot;hello-world&quot;, worker.Options{})<br> w.RegisterWorkflow(helloworkflow.Workflow)<br> w.RegisterActivity(helloworkflow.Activity)<br><br> err = w.Run(worker.InterruptCh())<br> if err != nil {<br>  log.Fatalln(&quot;Unable to start workflow&quot;, err)<br> }<br>}</pre><h3><strong>Starting Everything Up</strong></h3><p>To start our workflow, we need our temporal server up. Go to your terminal and cd to your project directory and run</p><pre>docker-compose up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ry1C5HNQsqYTdFwSlpVmyQ.png" /></figure><p>This will start up all the services in our docker-compose.yaml.</p><p>Next up, we start our worker.</p><p>In general, you should start the workers before the starter, as the starter typically depends on the workers being available to perform their tasks. This means that the workers should be started and initialized before the starter begins to coordinate their activities.</p><pre>go run src/worker/main.go</pre><pre>2023/02/16 14:03:42 INFO  No logger configured for temporal client. Created default one.<br>2023/02/16 14:03:43 INFO  Started Worker Namespace default TaskQueue hello-world WorkerID 4465@Ifedayos-MacBook-Pro.local@</pre><p>And finally, we start the workflow</p><pre>go run src/starter/main.go</pre><pre>2023/02/16 14:05:52 INFO  No logger configured for temporal client. Created default one.<br>2023/02/16 14:05:52 workflow result: Hello ifedayo</pre><h3><strong>Viewing Workflows</strong></h3><p>Navigating to the browser on localhost:8080, we have a UI that gives more information about the workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iifUuIjG-U2WKnp7VsFVZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onZAenzTYg-HDeXDVgnAXg.png" /></figure><p>Temporal also provides a CLI tool for interacting with the Temporal server, tctl, which also performs various administrative tasks, such as starting and stopping workflows, querying workflow information, and managing workflow executions.</p><pre>tctl workflow list</pre><pre>WORKFLOW TYPE |      WORKFLOW ID       |                RUN ID                | TASK QUEUE  | START TIME | EXECUTION TIME | END TIME  <br>Workflow      | hello_world_workflowID | 0454098f-cdd9-4f64-af8b-ab77a6f86c35 | hello-world | 13:05:52   | 13:05:52       | 13:05:52  </pre><h3>Conclusion</h3><p>In this writing, we’ve learned how what temporal is, why use it, an illustration of using it in a company, choices of setting up a temporal server, how to start the server inside your go project directory, running workflow and worker, and finally viewing your workflows in a UI or CLI.</p><p>Cheers 🥂! You’re one step closer to building more reliable applications with Temporal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7aa8868f40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>