<?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 Aushaaf Fadhilah Azzah on Medium]]></title>
        <description><![CDATA[Stories by Aushaaf Fadhilah Azzah on Medium]]></description>
        <link>https://medium.com/@fadhilahazzah04?source=rss-7182a105ab92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bOUIICHanz8kE69B</url>
            <title>Stories by Aushaaf Fadhilah Azzah on Medium</title>
            <link>https://medium.com/@fadhilahazzah04?source=rss-7182a105ab92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:37:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fadhilahazzah04/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[Best Practice Programming and SOLID Principles]]></title>
            <link>https://medium.com/@fadhilahazzah04/best-practice-programming-and-solid-principles-91aa1a6224bc?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/91aa1a6224bc</guid>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 15:33:42 GMT</pubDate>
            <atom:updated>2024-04-23T15:33:42.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cZs2yGcs3HNI8H47.jpg" /></figure><p>Best practice programming encompasses a set of guidelines, principles, and techniques that developers follow to write high-quality, maintainable, and efficient code. One of the cornerstone concepts in best practice programming is the SOLID principles, which are a set of five design principles aimed at improving the architecture and design of object-oriented software. In this article, we’ll delve into the details of best practice programming, focusing specifically on the SOLID principles, and provide detailed examples to illustrate each principle.</p><h3>Understanding Best Practice Programming</h3><p>Best practice programming is all about adopting proven techniques and principles that lead to better code quality, easier maintenance, and enhanced scalability. Some key aspects of best practice programming include:</p><ol><li><strong>Modularity</strong>: Breaking down code into modular components to promote reusability and maintainability.</li><li><strong>Clean Code</strong>: Writing code that is easy to read, understand, and modify.</li><li><strong>Efficiency</strong>: Optimizing code for performance and resource utilization.</li><li><strong>Testing</strong>: Emphasizing the importance of testing to ensure code correctness and reliability.</li><li><strong>Documentation</strong>: Documenting code to facilitate understanding and collaboration among developers.</li></ol><h3>Object-Oriented Programming</h3><p>Object-Oriented Programming (OOP) is a programming paradigm that designs software based on objects resembling real-world entities. Each object has its attributes and methods defined within its class.</p><p>In OOP, there are four principles concerning how objects interact with each other:</p><ol><li><strong>Encapsulation</strong>: Objects hide their internal workings, exposing only necessary attributes and methods to the outside world.</li><li><strong>Inheritance</strong>: Classes can be derived from existing classes, inheriting their attributes and methods and allowing for customization through overriding or addition.</li><li><strong>Polymorphism</strong>: Methods can behave differently based on the specific subclass, allowing for flexibility and dynamic behavior.</li><li><strong>Abstraction</strong>: Focuses on the general characteristics of an object, ignoring implementation details for a clearer understanding.</li></ol><h3>SOLID Principles</h3><p>The SOLID principles are a set of guidelines that help software developers create maintainable, scalable, and robust <strong>object-oriented</strong> code. These principles, introduced by Robert C. Martin (Uncle Bob), are widely regarded as fundamental concepts in object-oriented design. In this section, we’ll delve into each SOLID principle, explain its importance, and provide examples to illustrate how they can be applied in real-world scenarios.</p><h3>1. Single Responsibility Principle (SRP)</h3><blockquote><strong>A class should have only one reason to change</strong>, or in other words, <strong>it should have only one responsibility</strong>.</blockquote><p>The Single Responsibility Principle states that a class should have only one reason to change, meaning it should have a single responsibility or focus. This principle promotes code that is more modular, easier to understand, and less prone to bugs.</p><h4>Example</h4><p>Consider a UserService class that handles user management operations such as registration, authentication, and profile management.</p><pre>public class UserService {<br>    public void registerUser(User user) {<br>        // Logic for user registration<br>    }<br><br>    public boolean authenticateUser(String username, String password) {<br>        // Logic for user authentication<br>        return true;<br>    }<br><br>    public UserProfile getUserProfile(User user) {<br>        // Logic to retrieve user profile<br>        return userProfile;<br>    }<br>}</pre><p>Following SRP, we can separate these responsibilities into distinct classes:</p><pre>public class UserRegistrationService {<br>    public void registerUser(User user) {<br>        // Logic for user registration<br>    }<br>}<br>public class UserAuthenticationService {<br>    public boolean authenticateUser(String username, String password) {<br>        // Logic for user authentication<br>        return true;<br>    }<br>}<br>public class UserProfileService {<br>    public UserProfile getUserProfile(User user) {<br>        // Logic to retrieve user profile<br>        return userProfile;<br>    }<br>}</pre><h3>2. Open/Closed Principle (OCP)</h3><blockquote><strong>Software entities (classes, modules, functions, and so on) should be open for extension but closed for modification.</strong></blockquote><p>The Open/Closed Principle advocates for classes to be open for extension but closed for modification. This means that classes should be designed in a way that new functionality can be added through extension without altering existing code.</p><h4>Example</h4><p>Suppose we have a Shape class with different subclasses for geometric shapes.</p><pre>public abstract class Shape {<br>    public abstract double area();<br>}<br><br>public class Rectangle extends Shape {<br>    private double length;<br>    private double width;<br><br>    public Rectangle(double length, double width) {<br>        this.length = length;<br>        this.width = width;<br>    }<br><br>    @Override<br>    public double area() {<br>        return length * width;<br>    }<br>}</pre><p>We have applied OCP by allowing new shapes to be added without modifying the Shape class:</p><pre>public class Circle extends Shape {<br>    private double radius;<br><br>    public Circle(double radius) {<br>        this.radius = radius;<br>    }<br><br>    @Override<br>    public double area() {<br>        return Math.PI * radius * radius;<br>    }<br>}</pre><h3>3. Liskov Substitution Principle (LSP)</h3><blockquote><strong>Any instance of a derived class should be substitutable for an instance of its base class without affecting the correctness of the program.</strong></blockquote><p>The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program. This principle ensures consistency and compatibility in object-oriented designs.</p><h4>Example</h4><p>Consider a Bird superclass with Duck and Ostrich subclasses. Both subclasses should be substitutable for Bird without causing unexpected behavior:</p><pre>class Rectangle {<br>    protected int width;<br>    protected int height;<br><br>    public void setWidth(int width) {<br>        this.width = width;<br>    }<br><br>    public void setHeight(int height) {<br>        this.height = height;<br>    }<br><br>    public int calculateArea() {<br>        return width * height;<br>    }<br>}<br><br>class Square extends Rectangle {<br>    @Override<br>    public void setWidth(int width) {<br>        this.width = width;<br>        this.height = width;<br>    }<br><br>    @Override<br>    public void setHeight(int height) {<br>        this.width = height;<br>        this.height = height;<br>    }<br>}<br><br>public class LiskovSubstitutionDemo {<br>    public static void main(String[] args) {<br>        Rectangle rectangle = new Square();<br>        rectangle.setWidth(5);<br>        rectangle.setHeight(10);<br>        int area = rectangle.calculateArea();<br>        System.out.println(&quot;Area: &quot; + area); // 100<br>    }<br>}</pre><p>In the LiskovSubstitutionDemo class, we create a Rectangle object but assign it a Square instance. We then set the width and height using the setWidth and setHeight methods, expecting it to behave like a rectangle. However, since Square overrides these methods to maintain equal width and height, the computed area is incorrect, violating the expected behavior of a rectangle.</p><p>To adhere to the Liskov Substitution Principle, we need to revise our design. One way to do this is to remove the inheritance relationship between Square and Rectangle and instead create separate classes that represent a square and a rectangle without relying on inheritance.</p><pre>class Rectangle {<br>    protected int width;<br>    protected int height;<br><br>    public Rectangle(int width, int height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public int calculateArea() {<br>        return width * height;<br>    }<br>}<br><br>class Square {<br>    private int side;<br><br>    public Square(int side) {<br>        this.side = side;<br>    }<br><br>    public int calculateArea() {<br>        return side * side;<br>    }<br>}<br><br>public class LiskovSubstitutionDemo {<br>    public static void main(String[] args) {<br>        Rectangle rectangle = new Rectangle(5, 10);<br>        Square square = new Square(5);<br><br>        int rectangleArea = rectangle.calculateArea();<br>        int squareArea = square.calculateArea();<br><br>        System.out.println(&quot;Rectangle Area: &quot; + rectangleArea); // 50<br>        System.out.println(&quot;Square Area: &quot; + squareArea); // 25<br>    }<br>}</pre><h3>4. Interface Segregation Principle (ISP)</h3><blockquote><strong>Interfaces should be segregated based on the functionality they provide, rather than having a monolithic interface.</strong></blockquote><p>This principle avoids forcing clients to implement interfaces with methods they don’t need.</p><h4>Example</h4><p>Consider an Animal interface that includes methods for both flying and swimming. However, not all animals can both fly and swim. This design forces classes like Bird and Fish to implement methods that are not applicable to them, violating the Interface Segregation Principle.</p><pre>public interface Animal {<br>    void fly();<br>    void swim();<br>}<br><br>public class Bird implements Animal {<br>    @Override<br>    public void fly() {<br>        // Implementation for flying birds<br>    }<br><br>    @Override<br>    public void swim() {<br>        // Not applicable for birds<br>    }<br>}<br><br>public class Fish implements Animal {<br>    @Override<br>    public void fly() {<br>        // Not applicable for fish<br>    }<br><br>    @Override<br>    public void swim() {<br>        // Implementation for swimming fish<br>    }<br>}</pre><p>We can segregate Animal interface into Flyable and Swimmable based on their characteristics. Now, classes such as Bird only need to implement the Flyable interface, and classes like Fish only need to implement the Swimmable interface. This design ensures that classes implement only the methods they need, avoiding unnecessary dependencies and promoting a cleaner interface structure.</p><pre>public interface Flyable {<br>    void fly();<br>}<br><br>public interface Swimmable {<br>    void swim();<br>}<br><br>public class Bird implements Flyable {<br>    @Override<br>    public void fly() {<br>        // Implementation for flying birds<br>    }<br>}<br><br>public class Fish implements Swimmable {<br>    @Override<br>    public void swim() {<br>        // Implementation for swimming fish<br>    }<br>}</pre><h3>5. Dependency Inversion Principle (DIP)</h3><blockquote><strong>High-level modules should not depend on low-level modules, but both should depend on abstractions.</strong></blockquote><blockquote><strong>Abstractions should not depend on details. Details should depend on abstractions.</strong></blockquote><p>The Dependency Inversion Principle emphasizes dependency inversion, where high-level modules should not depend on low-level modules. Instead, both should depend on abstractions, promoting loose coupling and easier maintenance.</p><h4>Example</h4><p>Consider a PaymentService class which directly depends on the PayPalGateway concrete implementation. This tight coupling makes it challenging to switch to a different payment gateway implementation without modifying the PaymentService class, violating the Dependency Inversion Principle.</p><pre>public class PaymentService {<br>    private PayPalGateway payPalGateway;<br><br>    public PaymentService() {<br>        this.payPalGateway = new PayPalGateway();<br>    }<br><br>    public void makePayment(double amount) {<br>        // Business logic for making payments<br>        payPalGateway.processPayment(amount);<br>    }<br>}</pre><p>After applying the Dependency Inversion Principle, the PaymentService class depends on the PaymentGateway interface instead of a concrete implementation. This abstraction allows us to inject different payment gateway implementations (such as PayPalGateway, StripeGateway, etc.) into PaymentService without changing its code. This decoupling promotes flexibility, maintainability, and easier integration of new payment gateway implementations into the system.</p><pre>public interface PaymentGateway {<br>    void processPayment(double amount);<br>}<br><br>public class PayPalGateway implements PaymentGateway {<br>    @Override<br>    public void processPayment(double amount) {<br>        // Implementation for processing payment via PayPal<br>    }<br>}<br><br>public class PaymentService {<br>    private PaymentGateway gateway;<br><br>    public PaymentService(PaymentGateway gateway) {<br>        this.gateway = gateway;<br>    }<br><br>    public void makePayment(double amount) {<br>        // Business logic for making payments<br>        gateway.processPayment(amount);<br>    }<br>}</pre><h3>Conclusion</h3><p>By understanding and applying the SOLID principles along with other best practice programming concepts, developers can write code that is more maintainable, scalable, and robust. These principles promote clean design, modular architecture, and efficient code reuse, leading to higher productivity and better software quality. Incorporating these principles into your programming practices can significantly enhance the overall development process and the quality of your software products.</p><h4>References</h4><p>[1] <a href="https://www.freecodecamp.org/news/solid-principles-for-better-software-design/">What is SOLID? Principles for Better Software Design (freecodecamp.org)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91aa1a6224bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Becoming a People Person: My Journey into People Management, Team Dynamics, and Servant Leadership]]></title>
            <link>https://medium.com/@fadhilahazzah04/becoming-a-people-person-my-journey-into-people-management-team-dynamics-and-servant-leadership-6fb2a8647f0b?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb2a8647f0b</guid>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 13:41:43 GMT</pubDate>
            <atom:updated>2024-04-23T13:41:43.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*0kO13-LVoMMhyvgF.jpg" /><figcaption>Taken from OMORI</figcaption></figure><p>In the realm of effective team dynamics and successful project management, being a people person is not just a desirable trait, but a crucial skill set. It encompasses the art of people management, the finesse of building strong team dynamics, and the heart of servant leadership. Let’s delve into each aspect to understand how they contribute to creating a harmonious, productive, and thriving team environment.</p><h3>People Management: Nurturing Relationships for Success</h3><p>People management goes beyond delegating tasks and overseeing workflows. It’s about fostering camaraderie, warmth, and genuine friendships within the team. Encouraging a balance between work progress and shared laughter can significantly enhance team cohesion. In my experience, creating a friendly atmosphere where team members can joke, laugh, and code together not only strengthens bonds but also improves communication flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Ryv2HHPVnDSBD_wBPWnSYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mo0pERutYtT9JrpR1LvJ-w.png" /></figure><p>Understanding the importance of people management is key to avoiding common pitfalls such as burnout, communication breakdowns, unresolved conflicts, and lack of support systems. A well-managed team not only achieves its goals effectively but also thrives in a supportive and uplifting environment.</p><h3>Team Dynamics: Building Bridges and Creating Synergy</h3><p>Effective team dynamics are the cornerstone of a successful project. It involves making friends, establishing relations, and helping people grow within the team. By understanding each team member’s strengths, weaknesses, and motivations, a leader can optimize collaboration and create a synergy that drives productivity and innovation.</p><p>Navigating through challenges with a positive attitude, bringing joy and happiness even in difficult moments, and remaining productive amidst obstacles are hallmarks of strong team dynamics. By fostering a culture of mutual respect, open communication, and continuous learning, teams can achieve remarkable results while enjoying the journey together.</p><p>I try to achieve this by giving compliments and appreciating every bit of efforts given by my friends. It seems small, but giving compliments may have a bigger impact than you think, because it tends to have a ripple effect that extends far beyond the immediate moment. When we express genuine appreciation for someone’s work or contribution, it not only boosts their confidence and morale but also inspires them to excel further. This positive reinforcement encourages a cycle of continual improvement and excellence within the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*1deA0AEt8mEmiHtlLKw9oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RaqoK8ZG0SbuVh-TL2225w.png" /></figure><h3>Servant Leadership: Leading with Empathy and Integrity</h3><p>At the heart of every great team is a servant leader — a leader who leads with empathy, humility, and a genuine desire to serve others. A servant leader not only focuses on goals and achievements but also prioritizes the well-being and growth of the team members.</p><p>By actively listening, providing support, and appreciating even the smallest contributions, a servant leader creates a nurturing environment where team members feel valued and motivated. Leading by example, offering help when needed, and showing gratitude in meaningful ways are core principles of servant leadership.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*ZP8h2WfNOmYFhI60hdH72g.png" /></figure><p>In my opinion, expressing gratitude, like saying “thank you” or “thanks” is vital for aspiring servant leaders. It goes beyond mere politeness, showing genuine appreciation for others’ efforts. By fostering a culture of gratitude, leaders create a positive environment where team members feel valued and motivated. This culture strengthens relationships, empowers individuals, and inspires excellence. Leading by example in expressing gratitude sets a positive tone, encouraging teamwork and mutual respect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*AcA1lCEWx2M5pSE9if9Gtw.png" /></figure><h3>Conclusion</h3><p>In the journey of becoming a people person and mastering the realms of people management, team dynamics, and servant leadership, one thing becomes clear: success is not just about achieving goals but also about fostering meaningful relationships, creating synergy, and nurturing a positive team culture. By embracing the art of people management, building strong team dynamics, and leading with empathy and gratitude, we pave the way for a harmonious and productive team environment where everyone thrives. Let’s remember that behind every successful project is a team united by camaraderie, understanding, and a shared vision of excellence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb2a8647f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django App Monitoring with Prometheus and Grafana]]></title>
            <link>https://blog.devops.dev/monitoring-your-django-app-with-prometheus-and-grafana-5859b8815e84?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/5859b8815e84</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 08:44:17 GMT</pubDate>
            <atom:updated>2024-05-02T18:43:37.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ZVp629KEQchT1ifm.png" /></figure><p>Monitoring is crucial for ensuring the stability, performance, and availability of your Django applications. In this article, we’ll explore how to set up monitoring using Prometheus and Grafana, two powerful tools that provide deep insights into the behavior of your application. We will also use Docker Compose for more efficient deployment, but you may choose to install both of the tools manually.</p><h3>Why Monitoring Matters</h3><p>Before diving into the technical details, let’s understand why monitoring is essential. Monitoring helps you:</p><ol><li>Detect Issues Early: Identify potential problems before they escalate into critical issues.</li><li>Optimize Performance: Analyze performance metrics to fine-tune your application for optimal efficiency.</li><li>Ensure Reliability: Monitor uptime, response times, and error rates to ensure a reliable user experience.</li><li>Capacity Planning: Understand resource usage trends to plan for scaling and resource allocation.</li></ol><h3>Prometheus</h3><p>Prometheus is an open-source monitoring and alerting toolkit designed for reliability and scalability. It is specifically built for monitoring cloud-native applications and microservices architectures. Here are key aspects of Prometheus:</p><ol><li>Metrics Collection: Prometheus collects metrics from targets by scraping HTTP endpoints exposed by the targets. These endpoints provide data in a format that Prometheus understands, typically in a simple text-based format.</li><li>Data Model: Prometheus has a powerful data model based on time series data. It stores metrics as time series, where each series consists of a metric name and a set of key-value pairs called labels. This data model allows for flexible querying and analysis of metrics.</li><li>PromQL: Prometheus Query Language (PromQL) is used to query and manipulate metrics data. It provides operators for aggregation, filtering, and mathematical operations, enabling advanced analysis of time series data.</li><li>Alerting: Prometheus includes a robust alerting system. Users can define alert rules based on PromQL expressions to trigger alerts when certain conditions are met. Alerts can be sent via various notification channels such as email, Slack, or custom integrations.</li><li>Service Discovery: Prometheus supports service discovery mechanisms to dynamically discover and monitor targets in a cloud-native environment. It can discover targets using DNS, Kubernetes, EC2, and other service discovery methods.</li></ol><h3>Grafana</h3><p>Grafana is a leading open-source platform for monitoring and observability. It provides rich visualization, analytics, and alerting capabilities, making it a popular choice for creating dashboards and analyzing metrics data. Here are key aspects of Grafana:</p><ol><li>Data Source Integration: Grafana can integrate with various data sources, including Prometheus, to visualize metrics data. It supports a wide range of data sources such as databases, time series databases, cloud monitoring services, and more.</li><li>Dashboard Creation: Grafana allows users to create interactive and customizable dashboards using a drag-and-drop interface. Dashboards can include various types of visualizations such as graphs, tables, heatmaps, and gauges.</li><li>Community Driven: Grafana’s development is heavily influenced by its community. Users contribute plugins, dashboards, and improvements, fostering innovation and ensuring that Grafana evolves to meet the dynamic needs of modern monitoring and observability practices.</li><li>Alerting and Notifications: Grafana provides robust alerting capabilities. Users can define alert rules based on metrics data and receive notifications via email, Slack, PagerDuty, or other channels when alerts are triggered.</li><li>Templating and Variables: Grafana supports templating and variables, allowing users to create dynamic dashboards that can adapt to different environments or configurations. Variables can be used to filter data, switch between data sources, or customize dashboard views.</li><li>Data Exploration: Grafana includes powerful data exploration features that enable users to drill down into metrics data, zoom in on specific time ranges, apply filters, and perform ad-hoc analysis directly within the dashboard interface.</li></ol><h3>Setting Up Prometheus &amp; Grafana</h3><h4>Setting Up django-prometheus</h4><p>There is a python library called django-prometheus which helps in exporting Django monitoring metrics for Prometheus. To install it simply run this command:</p><pre>pip install django-prometheus</pre><p>Next, we need to set some things up in our settings.py, add these lines <strong>after</strong> your INSTALLED_APPS and MIDDLEWARE variable are declared:</p><pre>INSTALLED_APPS = [<br>   ...<br>   &quot;django_prometheus&quot;,<br>]<br><br>MIDDLEWARE = (<br>    [&quot;django_prometheus.middleware.PrometheusBeforeMiddleware&quot;]<br>    + MIDDLEWARE<br>    + [&quot;django_prometheus.middleware.PrometheusAfterMiddleware&quot;]<br>)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*VmKtz3c-sSDOYSUBxLlogw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*aYUpJG7xsi8qtVUvy_1xiw.png" /></figure><p>Great! Now let’s make the metrics exported by django-prometheus accessible by adding these in urls.py:</p><pre>urlpatterns = [<br>    ...<br>    path(&quot;prometheus/&quot;, include(&quot;django_prometheus.urls&quot;)),<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*p0N1MpFhhQirPZjt1K7HFg.png" /></figure><p>Nice work, we should be able to access our metrics by going to /prometheus/metrics endpoint!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*4-imKCBoljKRiky8CjyoeA.png" /><figcaption>Prometheus Metrics</figcaption></figure><h4>Setting Up Prometheus &amp; Grafana with Docker Compose</h4><p>Below is the docker compose file used to setup both Prometheus &amp; Grafana. Save it to a file called docker-compose.monitoring.yml.</p><pre>---<br>version: &#39;3.8&#39;<br><br>networks:<br>  monitoring:<br>    driver: bridge<br><br>volumes:<br>  prometheus_data: {}<br>  grafana-data: {}<br><br>services:<br>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    restart: unless-stopped<br>    volumes:<br>      - ./prometheus.yml:/etc/prometheus/prometheus.yml<br>      - prometheus_data:/prometheus<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;<br>      - &#39;--storage.tsdb.path=/prometheus&#39;<br>      - &#39;--web.console.libraries=/etc/prometheus/console_libraries&#39;<br>      - &#39;--web.console.templates=/etc/prometheus/consoles&#39;<br>      - &#39;--web.enable-lifecycle&#39;<br>    ports:<br>      - 9090:9090<br>    networks:<br>      - monitoring<br><br>  grafana:<br>    image: grafana/grafana-oss:latest<br>    container_name: grafana<br>    ports:<br>      - &#39;3000:3000&#39;<br>    volumes:<br>      - grafana-data:/var/lib/grafana<br>    restart: unless-stopped<br>    networks:<br>      - monitoring</pre><p>Don’t forget to add your Prometheus config file, save it to a file called prometheus.yml. Here is my config for our application.</p><pre>global:<br>  scrape_interval: 15s<br>scrape_configs:<br>  - job_name: &#39;django_app&#39;<br>    metrics_path: &#39;/prometheus/metrics&#39;<br>    static_configs:<br>      - targets: [&#39;host.docker.internal:8080&#39;]</pre><p>Basically, above configuration is targeting localhost:8080/prometheus/metrics of the host machine from our Prometheus docker container every 15 seconds.</p><p>Now, run below command in your CLI to run the docker compose file and build the images:</p><pre>docker-compose -f docker-compose.monitoring.yml up --build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irSE_xG3BHKvU7enRmTJkQ.png" /></figure><p>We can now access our Grafana &amp; Prometheus by going to localhost:3000 and localhost:9090 respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qenIeRidpluYa0f2zHuKJA.png" /><figcaption>Prometheus Targets (http://localhost:9090/targets)</figcaption></figure><p>When accessing Grafana endpoint for the first time, you will be greeted with a login page, input admin as the username and password, and you are in! Furthermore, you will be prompted to change your password and you should definitely do that. Below is the look of Grafana Dashboard after you have successfully logged in as admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeM3vlon_OyaipiA3-jkOw.png" /><figcaption>Grafana Admin Dashboard (http://localhost:3000)</figcaption></figure><h3>Adding a Grafana Dashboard</h3><p>In this section, we will explore how to add a dashboard to monitor our application’s metrics. Remember when I said Grafana is community driven? That means we can add dashboards made by the community! I found a beautiful dashboard which works well with django-prometheus made by andreynovikov (<a href="https://grafana.com/grafana/dashboards/17658-django/">https://grafana.com/grafana/dashboards/17658-django/</a>). Let us now explore how to add that dashboard in our Grafana!</p><h4>Adding Our Data Source</h4><p>Remember that our data source is from Prometheus. Let’s add it!</p><ul><li>Go to <strong>Data sources</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JD_wDH5DVRYSnNZKt_0goQ.png" /></figure><ul><li>Click <strong>Add data source</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_sB-44GnB9w9qSwSEBwQw.png" /></figure><ul><li>Choose <strong>Prometheus</strong>, and now our first data source is created.😁</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XL0bO12A5axe9I00blZeMw.png" /></figure><ul><li>Scroll down into <strong>Connection</strong>, and fill Prometheus server URL with <a href="http://prometheus:9090."><strong>http://prometheus:9090</strong></a>, which is our Prometheus docker container’s domain when accessed by our Grafana docker container.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgmrfuVzahO0W0i5Axqcgg.png" /></figure><ul><li>Scroll to the bottom and click <strong>Save &amp; Test</strong>, if there are green checkmarks (which hopefully you have) then you are good to go!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZSmD-FbMXpHWz9O3Ddkf9w.png" /></figure><h4>Adding The Dashboard</h4><p>Now, we will add that dashboard made by andreynovikov into our Grafana. Let’s dive right in!</p><ul><li>Go to <strong>Dashboards</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOGDQgk7DkDJbm3ZSQVcUQ.png" /></figure><ul><li>Click <strong>Create Dashboard</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfXBQnEnHvXMrU_ORb0sew.png" /></figure><ul><li>Click <strong>Import dashboard, </strong>and<strong> </strong>fill the “Find and import dashboards” input field with the URL of your desired dashboard, then click <strong>Load</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j47uCMxgQAw7kPyHb7GtMQ.png" /></figure><ul><li>Choose our just created <strong>prometheus</strong> data source as the data source, and then click <strong>Import.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_csp6RxZDbGq6I7McSrRjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*i2gO0yVP5JNOfsTKxhA6tA.png" /></figure><ul><li>And, voila! We will be greeted with our imported dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aqx_doceENNpI8Z2mO0CTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yz-uCs80KY093n-pArvTLw.png" /></figure><p>And there you have it! You’ll now have a comprehensive dashboard showcasing metrics relevant to monitoring your Django app. In our imported dashboard, we are able to see how many requests/seconds, the number of DB query errors, number of requests by processing time, request latency, response statuses, and many more! Those information are useful when you are doing performance testing / stress testing with Apache JMeter. Please see my article about JMeter if you haven’t heard about it: (<a href="https://medium.com/@fadhilahazzah04/enhancing-software-quality-through-comprehensive-testing-stress-tests-and-penetration-tests-356a8d59e54b">https://medium.com/@fadhilahazzah04/enhancing-software-quality-through-comprehensive-testing-stress-tests-and-penetration-tests-356a8d59e54b</a>).</p><p>If you think that the provided information is not enough, you may add more components by clicking <strong>Add </strong>button in the bar below the navigation bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*uVl5ehFHMED8IHoVqOe2Ug.png" /></figure><p>Alternatively, you could search for another dashboard more tailored to your needs. You can explore more dashboards made by the community just by visiting <a href="https://grafana.com/grafana/dashboards/">https://grafana.com/grafana/dashboards/</a>.</p><h3>Conclusion</h3><p>Monitoring your Django app with Prometheus and Grafana using Docker Compose provides a robust solution for gaining insights into your application’s performance and reliability. By leveraging these powerful tools and the Docker Compose environment, you can streamline the setup process and focus on optimizing your application.</p><p>Continuous monitoring allows you to detect issues early, optimize performance, ensure reliability, and plan for scaling as your application grows. With Prometheus for metrics collection, Grafana for visualization and analysis, and Docker Compose for efficient deployment, you have a powerful monitoring stack at your disposal.</p><p>In conclusion, monitoring is not just about reacting to problems but also about proactively managing and improving your application’s performance. With the tools and techniques discussed in this article, you can take your monitoring capabilities to the next level and ensure a seamless user experience for your application.</p><h4>References</h4><p>[1] <a href="https://dev.to/chafroudtarek/part-1-how-to-set-up-grafana-and-prometheus-using-docker-i47">PART 1: How to Set Up Grafana and Prometheus Using Docker — DEV Community</a></p><p>[2] <a href="https://prometheus.io/">Prometheus — Monitoring system &amp; time series database</a></p><p>[3] <a href="https://grafana.com/">Grafana: The open observability platform | Grafana Labs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5859b8815e84" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/monitoring-your-django-app-with-prometheus-and-grafana-5859b8815e84">Django App Monitoring with Prometheus and Grafana</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Software Quality Through Comprehensive Testing: Stress Tests and Penetration Tests]]></title>
            <link>https://medium.com/@fadhilahazzah04/enhancing-software-quality-through-comprehensive-testing-stress-tests-and-penetration-tests-356a8d59e54b?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/356a8d59e54b</guid>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 05:24:03 GMT</pubDate>
            <atom:updated>2024-04-05T05:39:28.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*VqP5e6oLuU0kLmaT.jpg" /></figure><p>In today’s rapidly evolving digital landscape, ensuring the quality and security of software applications is paramount. Software testing and quality assurance (QA) play a crucial role in this process, with specialized testing techniques like stress testing, and penetration testing gaining prominence. This article delves into these testing methodologies, highlighting the significance of each and exploring tools such as JMeter for performance/stress testing, OWASP ZAP for automated penetration testing or vulnerability scanning, and a practical example of JWT penetration testing attempt.</p><h3>Understanding Stress Testing</h3><p>Stress testing is a vital component of software testing that evaluates the system’s stability and performance under extreme conditions. It involves pushing the software beyond its normal operational capacity to identify potential bottlenecks, performance limitations, and points of failure. By subjecting the system to heavy loads, stress testing helps assess its resilience and scalability, ensuring it can handle peak usage scenarios without compromising performance.</p><h3>Leveraging JMeter for Stress Testing</h3><p>Apache JMeter is a widely used open-source tool for load testing and performance measurement. It enables testers to simulate a large number of users, transactions, and requests to gauge how the system responds under varying loads. JMeter’s intuitive interface, robust testing capabilities, and support for diverse protocols make it an ideal choice for conducting comprehensive stress tests. Testers can analyze response times, throughput, error rates, and resource utilization to fine-tune the system for optimal performance.</p><p>In this article, I will guide you through my journey of stress-testing my created feature, which is authentication endpoint! Let’s dive in.</p><h4>Installing Apache JMeter (Windows)</h4><ol><li>Go to <a href="https://jmeter.apache.org/download_jmeter.cgi">Apache JMeter — Download</a> and download the <strong>zip</strong> file in the <strong>Binaries</strong> section.</li><li>Extract the zip file.</li><li>Go to bin/ directory, and open <strong>jmeter.bat, </strong>a batch file to launch the GUI, and JMeter GUI will be launched!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky-KgPsRdbWbFpa6V8-ZLg.png" /></figure><h4>Setting Up Your Test Plan</h4><p>Here are the general steps you can follow to get your test plan up and running:</p><ol><li>In JMeter, a test plan is a container for your tests. Right-click on the Test Plan node in the left-hand tree view and select “Add &gt; Threads (Users) &gt; Thread Group” to create a new thread group.</li><li>Configure the thread group by setting the number of threads (simulated users), ramp-up period (time to start all threads), and loop count (number of times to execute the test).</li><li>Add components such as samplers (HTTP requests, FTP requests, etc.), config elements (HTTP Header Manager, etc.) to simulate user actions.</li><li>Add listeners (View Results Tree, Summary Reports, etc.) to the thread group for visualizing and analyzing the testing result.</li><li>Run the tests!</li></ol><p>Here’s a practical example to demonstrate above steps:</p><ol><li><strong>Creating a Thread Group</strong></li></ol><p>Right Click your Test Plan and click <strong>Add &gt; Threads (Users) &gt; Thread Group</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*k-GRzC3TL3P7rVlorty-ig.png" /></figure><p>And, voila your thread group have been created!</p><p><strong>2. Configure the Thread Group</strong></p><p>Our virtual machine has the lowest specification at the moment because of budget reasons, so let’s try not to be too hard on them 😭. Let’s set the number of threads (users) into 20, and ramp-up to 5 seconds, so approximately there will be 4 users attempting to login in a second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfUx1OxUIdWKSHn0U_na6Q.png" /></figure><p><strong>3. Adding Required Components</strong></p><p>My authentication endpoint only accepts <strong>application/json</strong> as the Content-Type, so let’s add a Config HTTP Header Manager to simulate that! Right click your Thread Group and hover to <strong>Add &gt; Config Element &gt; HTTP Header Manager.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*nSHIPtPQYnU5SA6XRGahMA.png" /></figure><p>Now, click “Add” and add your headers, in my case it’s <strong>Content-Type: application/json</strong>. Hence, my HTTP Header Manager will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JouGNkPuzguKB6CxIzDDIA.png" /></figure><p>Great, now let’s create our HTTP request sampler to simulate the authentication request by clicking <strong>Add &gt; Sampler &gt; HTTP Request.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*q-FA7sDIHFkOic6CHq_5sA.png" /></figure><p>Then provide the configuration according to the behavior request you want, here is the configuration of the request that I will test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTRXbeSoj8nqKcN-YTbSmQ.png" /></figure><p>Nice, we have created the basic components required to do HTTP request for authentication. Let’s move to the next step.</p><p><strong>4. Adding Listeners</strong></p><p>I will only use two listeners, which is “View Results Tree” and “Summary Report”. To do that, click both <strong>Add &gt; Listener &gt; View Results Tree</strong> and <strong>Add &gt; Listener &gt; Summary Report</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iymWZejqNmcheajocgG36A.png" /></figure><p>Phew, and we have done the setup required for the testing. Now it’s time to run those tests!</p><p><strong>5. Run the Tests</strong></p><p>Simple! Just click that green play button to run the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*9Eyb4ScbmZirSeJTUai4Rw.png" /></figure><p>From the “Summary Report” below, it can be seen that all of our 20 requests are done successfully because the <strong>Error%</strong> is <strong>0,00%</strong>! You can also infer useful information like the average, min, and max time required for the test to be done (in milliseconds), also the throughput in which the server’s capability to serve how many threads per seconds. In our case, the server is only able to serve <strong>1,6 threads / second</strong> which is pretty small, but it’s a given because of our VM specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oto3JgSbmOobgXLp9YJoKA.png" /></figure><p>Now, just adjust those Number of threads (users) and Ramp-up time to do the stress test. For example, we can try to see how many <strong>Error%</strong> will be if there are 40 users in 5 seconds of ramp-up time. Don’t forget to clear the listeners by right clicking the listener then click Clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*CeVmWhhG4VsJ0leNt25Bkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*3cQ9clX-eijyphLKx6_Vsw.png" /></figure><p>And here are the results! It seems our server can still handle that amount of request, and that’s pretty good given our VM specification is still at the lowest yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzoMFO6g3zOO8eI4Nl0qWA.png" /></figure><h3>Uncovering Vulnerabilities with Penetration Testing</h3><p>Penetration testing, or pen testing, is a proactive security assessment technique that simulates real-world cyberattacks to identify vulnerabilities and weaknesses in software systems. It goes beyond traditional testing approaches by actively attempting to exploit vulnerabilities, assess security controls, and validate the effectiveness of security measures. Penetration testing helps organizations identify and remediate potential security risks before they can be exploited by malicious actors, safeguarding sensitive data and ensuring regulatory compliance.</p><h3>Harnessing OWASP ZAP for Penetration Testing</h3><p>The Open Web Application Security Project (OWASP) Zed Attack Proxy (ZAP) is a powerful tool for web application security testing, including penetration testing. ZAP’s comprehensive suite of features enables testers to perform automated scans, intercept and manipulate traffic, identify security vulnerabilities such as SQL injection, cross-site scripting (XSS), broken authentication, and other vulnerabilities / risks whilst generating detailed reports for remediation. By leveraging OWASP ZAP, organizations can fortify their applications against cyber threats and enhance overall security posture.</p><h4>Installing and Launching OWASP ZAP</h4><p>Go to <a href="https://www.zaproxy.org/download/">ZAP — Download (zaproxy.org)</a> and choose the option according to your Operating System. After the installation, launch OWASP ZAP and you will be greeted with this section. We will explore the automated scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qavdCyX3OLJbWMeLz1K44g.png" /></figure><h4>Automated Scan</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4V-ScXnU6tAYfZAXKqBv3w.png" /></figure><p>Let’s provide our frontend URL to test for potential vulnerability and click <strong>Attack</strong>. Wait for it, and OWASP ZAP will create a summary regarding the alerts, or even found attack vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*tnZWGcodzcNHglPavWXtIg.png" /></figure><p>It seems that our frontend application is subject to 4 medium alerts, 3 low alerts, and 6 informational alerts. OWASP ZAP also explains what those alerts are, why those alerts are harmful, and how to fix those like below example on the CORS Misconfiguration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHHQJ0wWS1yk7LLlHXryPw.png" /></figure><p>Those alerts may be negligible on its own, but if it was chained with other attack(s) it may result in data breaches, or even worse a whole server takeover.</p><h3>Practical Example of Penetration Testing Attempt on JWT Authentication</h3><p>We use DRF’s simple JWT library for authentication. But I don’t fully trust that library, so I will try to conduct a little penetration test trying JWT alg none header attack.</p><h4>Basics of JWT</h4><p>Basically, JWT consists of three parts, the header, payload, and signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fyb1Tj34cFyi9pE7.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*Nsw6BgF5maeVUtKA.png" /></figure><p>Notice that there are “alg” in the header, that is the algorithm used to sign our JWT, in the example it is HS256 (HMAC with SHA-256).</p><h4>What Is Alg None Header Attack?</h4><p>In a badly developed library, it’s possible to modify the signing algorithm (“alg”) to <strong>“None”</strong> so there will be no verification whatsoever on the signature, which is very bad! Because malicious adversaries can simply change the value in the payload part to gain unauthorized access. For example adding <strong>“is_superuser”: True</strong> to gain superuser access.</p><h4>Constructing Malicious JWT</h4><p>We will use <a href="https://github.com/ticarpi/jwt_tool">https://github.com/ticarpi/jwt_tool</a>, a tool for tweaking JWTs. Let’s get a sample JWT from our website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sglV08WQiO7LA8OnpPiZg.png" /></figure><p>Copy that access token, and put it into the jwt_tool.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xmeixq8Vs568Xwsh8-w2wQ.png" /></figure><p>Now, let’s change the alg into “None”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*lOnDUDxa3nY4jjIucJtHvg.png" /></figure><p>Let’s continue to modify the payload values, we will try to extend the timestamp so our newly created token will not expire just yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*OS3YPyydftbGUhNMLl_Q1Q.png" /></figure><p>Great, let’s continue and we got out malicious JWT token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9o7I_k8PUX-SbIszyi8xnw.png" /></figure><h4>Seeing our Malicious JWT in Action</h4><p>Let’s see if that malicious JWT is working by editing the value of access-token in our local storage into that newly created malicious JWT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*avQ_VuY9A1hjmhuLv7INhA.png" /></figure><p>Now we will try to access our profile, which obviously require valid JWT to check if our malicious JWT works or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7hF6tj8r0_xdngVljSulQ.png" /></figure><p>Phew, as we can see it’s not working as our endpoint returned “Given token not valid for any token type”. So, we are safe from this attack!</p><h3>Conclusion</h3><p>In the fast-paced world of software development, the quest for quality and security is unending. Stress testing with tools like JMeter provides invaluable insights into how our systems behave under pressure, helping us fortify them for peak performance. On the other hand, penetration testing, facilitated by tools like OWASP ZAP, acts as a shield against potential cyber threats, ensuring that our applications remain resilient in the face of malicious attacks.</p><p>By combining stress testing to assess performance limits and penetration testing to identify vulnerabilities, software teams can build robust, reliable, and secure applications. These testing methodologies, when integrated into the development lifecycle, contribute significantly to enhancing software quality, fostering user trust, and safeguarding sensitive data.</p><p>As we navigate the ever-evolving digital landscape, embracing comprehensive testing practices is not just a choice but a necessity. It’s the cornerstone of building software that not only meets user expectations but also withstands the challenges of the modern cyber landscape.</p><h4>References</h4><p>[1] <a href="https://hariatylumbantobing.medium.com/analisis-hasil-performance-test-pada-jmeter-1d7a432906d7">Analisis Hasil Performance Test pada JMeter | by Hariaty Lumbantobing | Medium</a></p><p>[2] <a href="https://www.hackerone.com/knowledge-center/owasp-zap-6-key-capabilities-and-quick-tutorial">OWASP ZAP: 6 Key Capabilities and a Quick Tutorial | HackerOne</a></p><p>[3] <a href="https://jwt.io/introduction/">JSON Web Token Introduction — jwt.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356a8d59e54b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Software Quality with Static Analysis: A Guide to SonarQube]]></title>
            <link>https://medium.com/@fadhilahazzah04/enhancing-software-quality-with-static-analysis-a-guide-to-sonarqube-af02bc74ebf7?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/af02bc74ebf7</guid>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 16:29:03 GMT</pubDate>
            <atom:updated>2024-03-24T17:40:20.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CWMF40u3gYJIVKjV.png" /></figure><p>In today’s fast-paced software development environment, ensuring the quality and reliability of code is crucial for delivering successful projects. One of the key practices in Software Quality Assurance (SQA) is static analysis, which involves examining code without executing it. Among the many tools available for static analysis, SonarQube stands out as a comprehensive platform that supports standard best practices for code quality. In this article, we’ll delve into the importance of static analysis, the benefits of using SonarQube, and how it can enhance your software development process.</p><h3>Understanding Static Analysis</h3><p>Static analysis is a process that analyzes code without actually running it. It examines the code for syntactic, semantic, and structural issues, identifying potential bugs, vulnerabilities, and code smells. This analysis is performed during the development phase, allowing developers to catch and fix issues early in the cycle, reducing the likelihood of defects reaching production.</p><h3>Importance of Software Quality Assurance</h3><p>Software Quality Assurance (SQA) is a set of processes and activities aimed at ensuring that software meets quality standards and requirements. It encompasses various practices, including testing, code reviews, and static analysis. SQA helps in improving the reliability, maintainability, and performance of software systems, ultimately leading to customer satisfaction and trust.</p><h3>Benefits of Static Analysis with SonarQube</h3><p>SonarQube is a popular static analysis platform that offers a wide range of features to support code quality improvement. Some key benefits of using SonarQube include:</p><p><strong>1. Code Quality Metrics</strong></p><p>SonarQube provides comprehensive metrics and reports on code quality, including code coverage, duplication, complexity, and maintainability. These metrics help teams identify areas for improvement and track progress over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELz5pRLEnCi44ifrY1Kngw.png" /></figure><p><strong>2. Automated Code Review</strong></p><p>SonarQube automates code review processes, flagging issues such as coding standards violations, potential bugs, security vulnerabilities, and performance bottlenecks. This helps in maintaining code consistency and adherence to best practices.</p><p>In the example below, SonarQube is able to detect a potential null pointer bug, which could make our application crash if not handled ASAP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E2N7gmNGrJ8Sa0h9.png" /></figure><p>SonarQube also have security hotspot to assess potential vulnerabilities in our codebase according to industry standards such as SANS, CWE, and OWASP. It also provides actionable recommendations to help developers address issues and improve code quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ffL1ALcGPH1AtRmf.png" /></figure><p><strong>3. Integration with CI/CD Pipelines</strong></p><p>SonarQube seamlessly integrates with Continuous Integration/Continuous Deployment (CI/CD) pipelines, allowing for automated code analysis as part of the build and deployment process. This ensures that code quality checks are performed consistently and efficiently. Below is our team’s .gitlab-ci.yml to automatically tests and update tests coverage info to SonarQube.</p><pre>UnitTest:<br>  image: python:3.10-slim<br>  stage: test<br>  before_script:<br>    - export DB_NAME=$DB_NAME<br>    - export DB_USER=$DB_USER<br>    - export DB_PASSWORD=$DB_PASSWORD<br>    - export DB_HOST=$DB_HOST<br>    - export DB_PORT=$DB_PORT<br>    - export SECRET_KEY=$SECRET_KEY<br>    - pip install -r requirements.txt<br>    - python manage.py makemigrations<br>    - python manage.py migrate<br>    - pip install coverage-badge<br>  script:<br>    - coverage run manage.py test -v 2<br>    - coverage report <br>    - coverage xml <br>    - coverage-badge -o coverage.svg<br>  coverage: &#39;/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/&#39;<br>  artifacts:<br>    paths:<br>      - coverage.xml<br>      - coverage.svg<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: coverage.xml<br>  only:<br>    - development<br>    - /(?i)PBI-.*/<br><br>SonarScanner:<br>  image: sonarsource/sonar-scanner-cli:latest<br>  stage: sonarqube<br>  dependencies:<br>    - UnitTest<br>  script:<br>    - sonar-scanner <br>      -Dsonar.projectKey=$PROJECT_KEY<br>      -Dsonar.host.url=https://sonarqube.cs.ui.ac.id <br>      -Dsonar.login=$SONAR_TOKEN<br>  only:<br>    - development<br>    - /(?i)PBI-.*/</pre><p><strong>4. Customizable Rules and Quality Gates</strong></p><p>SonarQube allows teams to define custom rules and quality gates based on their specific requirements and coding standards. This flexibility enables teams to tailor code analysis to their project needs. Below is our team’s sonar-project.properties to configure SonarQube for our needs:</p><pre>## Server<br>sonar.host.url=https://sonarqube.cs.ui.ac.id<br>sonar.login=${SONAR_TOKEN}<br><br>## Project configuration<br>sonar.projectKey=${PROJECT_KEY}<br><br>## Path to sources<br>sonar.sources=.<br>sonar.exclusions=\<br>  **/migrations/*,\<br>  manage.py,\<br>  **/apps.py,\<br>  **/__init__.py,\<br>  **/admin.py,\<br>  **/base_model.py,\<br>  **/settings.py,\<br>  **/tests/*,\<br>  **/tests.py,\<br>  **/*sgi.py,\<br>  main.py<br># sonar.inclusions=<br><br>## Path to tests<br>sonar.tests=.<br># sonar.test.exclusions=<br>sonar.test.inclusions=**/tests/*, **/tests.py<br><br>## Source encoding<br>sonar.sourceEncoding=UTF-8<br><br>## Quality gate config<br>sonar.qualitygate.wait=true<br><br>## Coverage paths<br>sonar.python.coverage.reportPaths=coverage.xml</pre><h3>Features of SonarQube</h3><p>SonarQube offers a range of powerful features that contribute to enhancing software quality through static analysis. Let’s dive deeper into each of these features to understand their overview, issues they address, security hotspots, measures, code, and activity.</p><h4><strong>Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELz5pRLEnCi44ifrY1Kngw.png" /></figure><p>SonarQube provides a comprehensive overview of code quality metrics and issues, helping teams gain insights into the overall health of their codebase. It offers a centralized dashboard where developers and stakeholders can visualize key metrics, trends, and areas for improvement.</p><h4><strong>Issues</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8TIdny7_lSsCvUUMKzZMQ.png" /></figure><p>SonarQube identifies and categorizes issues in code based on severity levels such as blocker, critical, major, minor, and info. These issues include coding standards violations, potential bugs, performance bottlenecks, and code smells. Each issue is accompanied by detailed information, including the affected code snippet, recommended actions, and severity impact.</p><h4>Security Hotspots</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0keau4bMDN1VKwJEtcZ8A.png" /></figure><p>As explained in the previous section, security hotspots in SonarQube highlight potential vulnerabilities in the codebase that could lead to security breaches. These hotspots are assessed based on industry standards such as SANS Top 25, CWE, and OWASP Top 10, ensuring that teams address critical security concerns early in the development process. SonarQube provides actionable recommendations to mitigate security risks and improve code security.</p><h4>Measures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbqtLRKylyFe5ukj2iGZfQ.png" /></figure><p>SonarQube measures code quality using a variety of metrics, including code coverage, duplication, complexity, maintainability, and reliability. These measures help teams assess the quality of their codebase and prioritize areas for refactoring and improvement. SonarQube provides detailed reports and charts for each metric, enabling teams to track progress and set quality goals.</p><h4>Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faHTiFT3qxvjavGwJBq2eA.png" /></figure><p>SonarQube allows developers to drill down into specific code segments to analyze issues, review code smells, and understand complex dependencies. The code view in SonarQube provides syntax-highlighted code snippets, issue markers, and inline comments, facilitating code review and collaboration among team members.</p><h4>Activity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JA-7UdSPvu-ExmgkWckAig.png" /></figure><p>SonarQube tracks code changes and activity over time, providing historical data on code quality improvements, regressions, and trends. Teams can monitor the impact of code changes, identify patterns in issue resolution, and measure the effectiveness of quality initiatives. SonarQube’s activity tracking helps in maintaining code quality standards consistently across development cycles.</p><h3>Practical Example of SonarQube Issues</h3><h4>The Issue</h4><p>Let’s assume you have implemented below code and got this issue from SonarQube:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UEHCTGUIwQlBu9IAj4TFTA.png" /></figure><p>SonarQube detects this as an SQL injection vulnerability. This vulnerability arises when user inputs are directly concatenated into SQL queries without proper escape, allowing attackers to inject malicious SQL commands.</p><h4>The Fix</h4><p>To fix the SQL injection vulnerability, we can use parameterized queries. Here’s an example:</p><pre>cur.execute(&quot;SELECT * FROM TABLE WHERE USERNAME=?;&quot;, (o.fieldA,))</pre><p>With this parameterized query, the value of o.fieldA is treated as a parameter rather than being directly concatenated into the SQL query. This approach prevents SQL injection attacks by ensuring that user inputs are escaped and treated as data rather than executable code. Rejoice, because for now your application is safe from that vulnerable line of code!</p><h3>Conclusion</h3><p>Static analysis with SonarQube plays a crucial role in enhancing software quality by identifying and addressing code issues early in the development lifecycle. By leveraging SonarQube’s features and best practices, teams can improve code quality, reduce technical debt, and deliver more reliable and maintainable software solutions. Incorporate static analysis into your software development process with SonarQube to achieve higher levels of quality and efficiency.</p><h4>References</h4><p>[1] <a href="https://docs.sonarsource.com/sonarqube/">https://docs.sonarsource.com/sonarqube/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af02bc74ebf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development (TDD): An Investment or A Chore?]]></title>
            <link>https://medium.com/@fadhilahazzah04/test-driven-development-tdd-an-investment-or-a-chore-d314df7fd2c5?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/d314df7fd2c5</guid>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 14:11:21 GMT</pubDate>
            <atom:updated>2024-03-05T14:49:02.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*rM1uOXY97N-39LcM" /><figcaption>Taken from <a href="https://medium.com/basic-people/rev-test-driven-disaster-330cb75e780f">Medium</a></figcaption></figure><p>Test-Driven Development (TDD) is a software development methodology that has gained popularity in recent years. Some argue that TDD is an investment in the long-term success of a project, ensuring code quality, maintainability, and reducing bugs. However, some view it as a time-consuming chore that slows down the development process. In this article, we’ll explore the benefits and challenges of adopting Test-Driven Development.</p><blockquote><strong>DISCLAIMER</strong>: This marks my first attempt at TDD and considering the modest size of my project at the moment, my experience with TDD is practically little to non-existent. Nevertheless, let’s dive into it.</blockquote><h3>Understanding TDD</h3><p>Test-Driven Development (TDD) was developed by Kent Beck in the late 1990’s as part of Extreme Programming. TDD follows a simple cycle known as the <strong>Red — Green — Refactor</strong> cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*XbBSUaMTHjbWHs0i.png" /><figcaption>TDD Workflow | Taken from <a href="https://www.spiceworks.com/tech/devops/articles/what-is-tdd/">What is TDD (Test Driven Development)? (spiceworks.com)</a></figcaption></figure><p>The process begins with writing a failing test (Red), followed by writing the minimum code necessary to make the test pass (Green), and finally refactoring the code to improve its structure without changing its behavior (Refactor).</p><h3>My Experience with DDT — A Failed TDD</h3><p>Okay, so imagine that you want to implement a JWT-based login API using Django Rest Framework. After surfing through the internet, you found a library called <a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">Simple JWT</a> which helps you do that very easily. You are so excited but remembered a single disturbing thing, that you must do it with TDD. What should you do? Should you learn the intricacies of the library and then writing the test?</p><p>You pondered and thought that it’s too much work. But a moment later you had a brilliant idea, “What if I develop the code first and write tests later but commit the tests first?!”. Shamelessly, that’s what I did 🤣, and notice that’s not TDD, but a DDT (Development-Driven Test) instead 😱.</p><p>Now please take a look at this test I made with DDT:</p><pre>from django.test import TestCase<br>from django.contrib.auth import get_user_model<br>from rest_framework.test import APIClient<br><br>TOKEN_URI = &#39;/token/&#39;<br>REFRESH_URI = &#39;/token/refresh/&#39;<br>VERIFY_URI = &#39;/token/verify/&#39;<br><br><br>class AuthenticationTestCase(TestCase):<br>    def setUp(self):<br>        self.client = APIClient()<br>        self.username = &#39;test@example.com&#39;<br>        self.password = &#39;p455w0rd!&#39;<br>        self.user = get_user_model().objects.create_user(<br>            username=self.username,<br>            password=self.password,<br>            is_active=True<br>        )<br><br>    def obtain_tokens(self, username=None, password=None):<br>        response = self.client.post(<br>            TOKEN_URI,<br>            {&#39;username&#39;: username or self.username,<br>             &#39;password&#39;: password or self.password},<br>            format=&#39;json&#39;<br>        )<br>        response_data = response.data<br>        self.assertEqual(response.status_code, 200)<br>        self.assertIn(&#39;access&#39;, response_data)<br>        self.assertIn(&#39;refresh&#39;, response_data)<br>        return response_data[&#39;access&#39;], response_data[&#39;refresh&#39;]<br><br>    def test_obtain_token_success(self):<br>        access_token, refresh_token = self.obtain_tokens()<br><br>        self.assertTrue(access_token)<br>        self.assertTrue(refresh_token)<br><br>    def test_obtain_token_fail_when_user_is_inactive(self):<br>        self.user.is_active = False<br>        self.user.save()<br><br>        response = self.client.post(<br>            TOKEN_URI,<br>            {&#39;username&#39;: self.username, &#39;password&#39;: self.password},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 401)<br><br>    def test_obtain_token_fail_with_invalid_credentials(self):<br>        response = self.client.post(<br>            TOKEN_URI,<br>            {&#39;username&#39;: self.username, &#39;password&#39;: &#39;invalid_password&#39;},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 401)<br><br>    def test_refresh_token_success(self):<br>        access_token, refresh_token = self.obtain_tokens()<br><br>        response = self.client.post(<br>            REFRESH_URI,<br>            {&#39;refresh&#39;: refresh_token},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 200)<br>        self.assertIn(&#39;access&#39;, response.data)<br>        self.assertNotEqual(access_token, response.data[&#39;access&#39;])<br><br>    def test_refresh_token_fail_with_invalid_refresh_token(self):<br>        response = self.client.post(<br>            REFRESH_URI,<br>            {&#39;refresh&#39;: &#39;invalid_refresh_token&#39;},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 401)<br><br>    def test_verify_token_success(self):<br>        access_token, _ = self.obtain_tokens()<br><br>        response = self.client.post(<br>            VERIFY_URI,<br>            {&#39;token&#39;: access_token},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 200)<br><br>    def test_verify_token_fail_with_invalid_access_token(self):<br>        response = self.client.post(<br>            VERIFY_URI,<br>            {&#39;token&#39;: &#39;invalid_access_token&#39;},<br>            format=&#39;json&#39;<br>        )<br>        self.assertEqual(response.status_code, 401)</pre><p>Yeah, it very much looks like a DDT code. Now when I think back about that test, I should not even do that test at all. Because when I checked the docs again, I saw that Simple JWT had 100% code coverage, so why bother testing it??? 🗿🗿🗿</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*wzBbFFjyvLAmIW9I2wcIhw.png" /><figcaption>Simple JWT with 100% Code Coverage</figcaption></figure><p>Now, I learnt that we shouldn’t test a behavior of underlying library, because most of the time it’s a waste of time.</p><h3>My Revised Attempt at TDD</h3><p>Let’s assume that I’m still working on the same JWT login API feature using Simple JWT. Here’s what I’m planning to implement:</p><ul><li>token/: Obtaining brand new JWT Access Token &amp; Refresh Token.</li><li>token/refresh/: Obtaining new JWT Access Token through Refresh Token.</li><li>token/verify/: Verifying validity of JWT Tokens</li><li>protected/: Getting dummy items that were accessible by all <strong>authenticated</strong> users.</li></ul><h4>1. [RED] — Writing a Failing Test</h4><p>I learnt my lesson and won’t bother creating tests for Simple JWT library’s authentication, because it already had 100% coverage. So, I skipped the Red — Green — Refactor phase for authentication and straight up implemented it:</p><pre># urls.py<br>from django.urls import path<br>from api.views import GetDummyItemAPI, ProtectedGetDummyItemAPI<br>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>    TokenVerifyView,<br>)<br><br>urlpatterns = [<br>    path(&#39;&#39;, GetDummyItemAPI.as_view(), name=&#39;get-dummy-item&#39;),<br>    path(&#39;token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),<br>    path(&#39;token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>    path(&#39;token/verify/&#39;, TokenVerifyView.as_view(), name=&#39;token_verify&#39;),<br>]</pre><p>Okay, now let’s create authorization test cases to get those protected dummy items! But, because I don’t know the intricacies of the library, I’m printing the response into the standard output (STDOUT), so I know the intricacies of the library and make a test out of it later. First, create a dummy view for the endpoint protected/:</p><pre># views.py<br>from rest_framework.request import Request<br>from rest_framework.response import Response<br>from rest_framework.views import APIView<br>from rest_framework.permissions import AllowAny, IsAuthenticated<br><br>from administration.models.dummy_item import DummyItem<br>from .serializers import DummyItemSerializer<br><br>class GetDummyItemAPI(APIView):<br>    permission_classes = (AllowAny,)<br><br>    def get(self, request: Request) -&gt; Response:<br>        dummy_items = DummyItem.objects.all()<br>        serializer = DummyItemSerializer(dummy_items, many=True)<br>        return Response(serializer.data)<br><br>class ProtectedGetDummyItemAPI(GetDummyItemAPI):<br>    pass</pre><pre># urls.py<br>from django.urls import path<br>from api.views import GetDummyItemAPI, ProtectedGetDummyItemAPI<br>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>    TokenVerifyView,<br>)<br><br>urlpatterns = [<br>    path(&#39;&#39;, GetDummyItemAPI.as_view(), name=&#39;get-dummy-item&#39;),<br>    path(&#39;protected/&#39;, ProtectedGetDummyItemAPI.as_view(),<br>         name=&#39;protected-get-dummy-item&#39;),<br>    path(&#39;token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),<br>    path(&#39;token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>    path(&#39;token/verify/&#39;, TokenVerifyView.as_view(), name=&#39;token_verify&#39;),<br>]</pre><p>Now, let’s write a function that obtains JWT, obtain_tokens() which also prints the response detail into STDOUT and a test that uses it:</p><pre>from django.test import TestCase<br>from django.contrib.auth import get_user_model<br>from rest_framework.test import APIClient<br><br>PROTECTED_URI = &#39;/protected/&#39;<br><br><br>class AuthorizationTestCase(TestCase):<br>    def setUp(self):<br>        self.client = APIClient()<br>        self.username = &#39;test@example.com&#39;<br>        self.password = &#39;p455w0rd!&#39;<br>        self.user = get_user_model().objects.create_user(<br>            username=self.username,<br>            password=self.password,<br>            is_active=True<br>        )<br><br>    def obtain_tokens(self, username=None, password=None):<br>        response = self.client.post(<br>            &#39;/token/&#39;,<br>            {&#39;username&#39;: username or self.username,<br>             &#39;password&#39;: password or self.password},<br>            format=&#39;json&#39;<br>        )<br>        print(response, response.data, response.status_code)<br><br>    def test_get_protected_dummy_item_success(self):<br>        response = self.obtain_tokens(self.username, self.password)<br>        self.assertEqual(response.status_code, 200)</pre><p>Okay, now let’s run it and see:</p><pre>❯ py manage.py test api<br>Found 1 test(s).<br>System check identified no issues (0 silenced).<br>&lt;Response status_code=200, &quot;application/json&quot;&gt; {&#39;refresh&#39;: &#39;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwOTEzODAxMywiaWF0IjoxNzA5MDUxNjEzLCJqdGkiOiJlODcwMjNlNTkzMmE0M2I0YjAyZTAwZjFlMjA4ZTM1YiIsInVzZXJfaWQiOjE2OH0.Nit9ihYwiC_0qy-W5NWvKuHV4Hu89RxeQewoJIpnxmU&#39;, &#39;access&#39;: &#39;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA5MDUxOTEzLCJpYXQiOjE3MDkwNTE2MTMsImp0aSI6IjlkMjFjZjY1MWU1ZjRiODQ5ZDg4YTc0OWNlNmM0NmY4IiwidXNlcl9pZCI6MTY4fQ.eFYVlhGgYj6GmAUuQo_N1x9RBTKLNVgzVliiCohMKE4&#39;} 200<br>.<br>----------------------------------------------------------------------<br>Ran 1 test in 0.401s<br><br>OK</pre><p>Aha, now I know that token/ returned a JSON response with “refresh” and “access” keys. Now, we can complete our authorization tests:</p><pre>from django.test import TestCase<br>from django.contrib.auth import get_user_model<br>from rest_framework.test import APIClient<br><br>PROTECTED_URI = &#39;/protected/&#39;<br>TOKEN_URI = &#39;/token/&#39;<br>TOKEN_REFRESH_URI = &#39;/token/refresh/&#39;<br><br><br>class AuthorizationTestCase(TestCase):<br>    def setUp(self):<br>        self.client = APIClient()<br>        self.username = &#39;test@example.com&#39;<br>        self.password = &#39;p455w0rd!&#39;<br>        self.user = get_user_model().objects.create_user(<br>            username=self.username,<br>            password=self.password,<br>            is_active=True<br>        )<br><br>    def obtain_tokens(self, username, password):<br>        response = self.client.post(<br>            TOKEN_URI,<br>            {&#39;username&#39;: username,<br>             &#39;password&#39;: password},<br>            format=&#39;json&#39;<br>        )<br>        return response<br><br>    def test_get_protected_dummy_item_success(self):<br>        response = self.obtain_tokens(self.username, self.password)<br>        self.assertEqual(response.status_code, 200)<br>        self.client.credentials(<br>            HTTP_AUTHORIZATION=&#39;Bearer &#39; + response.data[&#39;access&#39;])<br>        response = self.client.get(PROTECTED_URI)<br>        self.assertEqual(response.status_code, 200)<br><br>    def test_get_protected_dummy_item_fail_without_token(self):<br>        response = self.client.get(PROTECTED_URI)<br>        self.assertEqual(response.status_code, 401)<br><br>    def test_get_protected_dummy_item_fail_with_invalid_token(self):<br>        self.client.credentials(HTTP_AUTHORIZATION=&#39;Bearer invalid_token&#39;)<br>        response = self.client.get(PROTECTED_URI)<br>        self.assertEqual(response.status_code, 401)</pre><pre>❯ py manage.py test api<br>Found 3 test(s).<br>System check identified no issues (0 silenced).<br>.F&lt;Response status_code=200, &quot;application/json&quot;&gt; {&#39;refresh&#39;: &#39;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwOTEzOTE2MiwiaWF0IjoxNzA5MDUyNzYyLCJqdGkiOiIxYjE1MTc3YTNiYTc0ODI4YjE4OWQ2OTk0Y2M1MjQxZiIsInVzZXJfaWQiOjE3Mn0.nHEJlFG5w5s0BwgfDfWD6FDrM8SBZwLtyrHoLeIrFN4&#39;, &#39;access&#39;: &#39;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA5MDUzMDYyLCJpYXQiOjE3MDkwNTI3NjIsImp0aSI6IjJlMzNhODViODcyMzRiNDZiZDAwOTY2YzE3MGJlMWFlIiwidXNlcl9pZCI6MTcyfQ.aC-BZ99pR2KEnI53OPmg7HOZ8gW1HTjF3MomGk0hpZc&#39;} 200<br>.<br>======================================================================<br>FAIL: test_get_protected_dummy_item_fail_without_token (api.tests.test_authorization.AuthorizationTestCase)<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;C:\Coolyeah\Sem6\PPL\cirrhocheck\cirrhocheck-api\api\tests\test_authorization.py&quot;, line 41, in test_get_protected_dummy_item_fail_without_token<br>    self.assertEqual(response.status_code, 401)<br>AssertionError: 200 != 401<br><br>----------------------------------------------------------------------<br>Ran 3 tests in 0.749s<br><br>FAILED (failures=1)</pre><p>Great, as expected it failed. Let us <strong>commit</strong> these changes and make minimal changes to the code so the tests are GREEN.</p><h4><strong>2. [GREEN] — Writing Minimum Code Necessary for GREEN TESTS</strong></h4><p>Okay, now let us implement our ProtectedGetDummyItemAPI:</p><pre># views.py<br>from rest_framework.request import Request<br>from rest_framework.response import Response<br>from rest_framework.views import APIView<br>from rest_framework.permissions import AllowAny, IsAuthenticated<br><br>from administration.models.dummy_item import DummyItem<br>from .serializers import DummyItemSerializer<br><br><br>class GetDummyItemAPI(APIView):<br>    permission_classes = (AllowAny,)<br><br>    def get(self, request: Request) -&gt; Response:<br>        dummy_items = DummyItem.objects.all()<br>        serializer = DummyItemSerializer(dummy_items, many=True)<br>        return Response(serializer.data)<br><br><br>class ProtectedGetDummyItemAPI(APIView):<br>    permission_classes = (IsAuthenticated,)<br><br>    def get(self, request: Request) -&gt; Response:<br>        dummy_items = DummyItem.objects.all()<br>        serializer = DummyItemSerializer(dummy_items, many=True)<br>        return Response(serializer.data) </pre><p>Run the tests again:</p><pre>❯ py manage.py test api<br>Found 3 test(s).<br>System check identified no issues (0 silenced).<br>...<br>----------------------------------------------------------------------<br>Ran 3 tests in 0.771s<br><br>OK</pre><p>And now it’s GREEEN, great! Let’s <strong>commit</strong> these and move to the next steps.</p><h4>3. [REFACTOR] Refactoring The Code</h4><p>Well, I’m not sure if this is a good practice or not, but we can do a little inheritance in our protected class, so let us do it:</p><pre>from rest_framework.request import Request<br>from rest_framework.response import Response<br>from rest_framework.views import APIView<br>from rest_framework.permissions import AllowAny, IsAuthenticated<br><br>from administration.models.dummy_item import DummyItem<br>from .serializers import DummyItemSerializer<br><br><br>class GetDummyItemAPI(APIView):<br>    permission_classes = (AllowAny,)<br><br>    def get(self, request: Request) -&gt; Response:<br>        dummy_items = DummyItem.objects.all()<br>        serializer = DummyItemSerializer(dummy_items, many=True)<br>        return Response(serializer.data)<br><br><br>class ProtectedGetDummyItemAPI(GetDummyItemAPI):<br>    permission_classes = (IsAuthenticated,)</pre><p>Run the tests:</p><pre>❯ py manage.py test api<br>Found 3 test(s).<br>System check identified no issues (0 silenced).<br>...<br>----------------------------------------------------------------------<br>Ran 3 tests in 0.779s<br><br>OK</pre><p>And it’s still green, we successfully refactored without changing the expected behavior!</p><p>Look, we got 100% code coverage and that means there aren’t any untested line of codes in our codebase, now that’s reassuring!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*0GQv3ou1o5C1VJnky0LvbA.png" /><figcaption>100% Code Coverage</figcaption></figure><h3>Conclusion</h3><p>Nice, we have done a cycle of TDD! What do you think? I do think the whole TDD process is like a chore — exhausting, slows me down, and haven’t been intuitive to me yet. But I truly see the benefits to it, here are some of my takes:</p><ol><li><strong>It reduces bugs and time spent debugging</strong>, because of those great tests. But please do keep in mind that TDD <strong>wouldn’t be able to completely exterminate it</strong> because our tests could be the one with bugs, and there possibly are still edge cases not covered by our cases.</li><li><strong>It makes changes and refactoring so much easier and less frightening</strong>, because we wrote tests in advance that we hopefully can rely on.</li><li><strong>It helps develop logic in our codes,</strong> because by doing TDD I’m forced to think about the logic first before I start jumping right to the coding part.</li><li><strong>Your tests can serve as a guide to people reading your codes</strong>, because our tests showed the expected behaviors of our code. So tests can be a great entry point for people to read at first.</li><li>And all of the points above results in <strong>less technical debts</strong>.</li></ol><p>So, I do believe TDD is an <strong>investment</strong> to the future of our codes, but at the same time it’s a <strong>chore</strong>.</p><h4>References:</h4><ol><li><a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">Simple JWT — Simple JWT 5.2.2.post30+gfaf92e8 documentation (django-rest-framework-simplejwt.readthedocs.io)</a></li><li><a href="https://northcoders.com/company/blog/the-benefits-of-test-driven-development-tdd">The Benefits of Test-Driven Development (TDD) | Northcoders</a></li><li><a href="https://www.stride.build/blog/what-to-test-and-what-not-to-test">Test-Driven Development: What to Test (and What Not to Test) | Stride</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d314df7fd2c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab CI/CD & Docker: Easy Automated Deployment]]></title>
            <link>https://medium.com/@fadhilahazzah04/gitlab-ci-cd-docker-easy-automated-deployment-b0cb4f516e22?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0cb4f516e22</guid>
            <category><![CDATA[gitlab-ci-docker]]></category>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 12:05:51 GMT</pubDate>
            <atom:updated>2024-02-27T17:48:06.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*E8wWNGu4ckatk2hA.png" /><figcaption>Taken from <a href="https://poor-developer.blogspot.com/2020/08/gitlab-cicd-on-docker.html">Gitlab CI/CD on Docker (poor-developer.blogspot.com)</a></figcaption></figure><p>In today’s fast-paced development environment, automation is a key factor in ensuring efficient and reliable software deployment. GitLab CI/CD, combined with Docker, provides a powerful solution for automating the deployment process, enabling developers to streamline workflows and deliver applications with ease. This article explores the integration of GitLab CI/CD and Docker to achieve automatic deployment and enhance the overall development lifecycle.</p><h3>Understanding Docker and Containerization</h3><p>Docker has revolutionized the way applications are deployed by introducing containerization. I might be oversimplifying here, but you may think of containers as lightweight Virtual Machines. Containers encapsulate an application and its dependencies, providing a consistent environment across different stages of development, testing, and production. Docker images enable developers to package applications, making them easily portable and scalable. But, the most notable thing of all, it solved the infamous <em>“It works on my machine”</em> problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*JwKTsg0MngWGb6v5.jpg" /><figcaption>Taken from <a href="https://www.reddit.com/r/ProgrammerHumor/comments/c1s54z/but_it_works_on_my_machine/">r/ProgrammerHumor</a></figcaption></figure><p>One thing to note though, in this article, we won’t be utilizing Docker for the deployment of our application. Instead, we will be using it for setting up a GitLab Runner, the executor for our GitLab CI/CD.</p><h4>Installing Docker CE</h4><p>Follow the official <a href="https://docs.docker.com/engine/install/">docs</a> and choose the installation steps based on your OS Distro!</p><h3>Understanding GitLab CI/CD</h3><p>GitLab CI/CD is a continuous integration and continuous deployment (CI/CD) tool integrated into the GitLab platform to execute CI/CD pipelines. It allows developers to define workflows as code, automating various stages of the development pipeline. With GitLab CI/CD, you can automate tasks such as building, testing, and deploying applications, ensuring consistent and reliable results.</p><blockquote>CI/CD Pipeline consists of stages, and CI/CD stage consists of jobs.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*cNJ6M-cqwTrp7PHC.png" /><figcaption>CI/CD Pipeline</figcaption></figure><h4>Setting Up Custom GitLab Runner</h4><p>You can set up custom GitLab runner if the shared runner isn’t enough to your needs. In our case, the shared runner can’t SSH into our GCP Compute Engine so we had to create a custom GitLab runner, and here’s how:</p><ol><li>Follow this <a href="https://docs.gitlab.com/runner/install/">guide</a> to install gitlab-runner CLI. In our case, we will be <a href="https://docs.gitlab.com/runner/install/docker.html">installing it as a docker service</a>.</li><li>Go to your GitLab repository. On the left sidebar, select <strong>Search or go to</strong> and find your project.</li><li>Select <strong>Settings &gt; CI/CD</strong>.</li><li>Select <strong>New project runner</strong>.</li><li>Select your operating system.</li><li>In the <strong>Tags</strong> section, select the <strong>Run untagged</strong> checkbox. <a href="https://docs.gitlab.com/ee/ci/runners/configure_runners.html#control-jobs-that-a-runner-can-run">Tags</a> specify which jobs the runner can run and are optional.</li><li>Select <strong>Create runner</strong>.</li><li>Follow the on-screen instructions to register the runner from the command line. When prompted:</li></ol><ul><li>For executor, because your runner will run on the Docker container, enter docker. The <a href="https://docs.gitlab.com/runner/executors/">executor</a> is the environment where the runner executes the job.</li><li>For GitLab instance URL, use the URL for your GitLab instance. For example, if your project is hosted on gitlab.example.com/yourname/yourproject, then your GitLab instance URL is https://gitlab.example.com. If your project is hosted on GitLab.com, the URL is <a href="https://gitlab.com./">https://gitlab.com</a></li></ul><p>9. Start your runner by running gitlab-runner run inside the container:</p><pre>$ docker exec -it gitlab-runner gitlab-runner run<br>Runtime platform                                    arch=amd64 os=linux pid=156 revision=c72a09b6 version=16.8.0<br>Starting multi-runner from /etc/gitlab-runner/config.toml...  builds=0 max_builds=0<br>Running in system-mode.                            <br>                                                   <br>Configuration loaded                                builds=0 max_builds=1<br>listen_address not defined, metrics &amp; debug endpoints disabled  builds=0 max_builds=1<br>[session_server].listen_address not defined, session endpoints disabled  builds=0 max_builds=1<br>Initializing executor providers                     builds=0 max_builds=1</pre><p>10. Verify your runner by running gitlab-runner list inside the container:</p><pre>$ docker exec -it gitlab-runner gitlab-runner list<br>Runtime platform                                    arch=amd64 os=linux pid=170 revision=c72a09b6 version=16.8.0<br>Listing configured runners                          ConfigFile=/etc/gitlab-runner/config.toml<br>cirrhocheck-runner-gcp                              Executor=docker Token=&lt;REDACTED&gt; URL=https://gitlab.cs.ui.ac.id/</pre><h4>Can we use Docker to Execute GitLab CI/CD Jobs?</h4><p>Yes, you very much can! But only if you are using docker as your runner’s executor. We can specify a Docker image to execute each job, like this:</p><pre>SonarScanner:<br>  image: sonarsource/sonar-scanner-cli:latest<br>  stage: sonarqube<br>  dependencies:<br>    - UnitTest<br>  script:<br>    - sonar-scanner <br>      -Dsonar.projectKey=$PROJECT_KEY<br>      -Dsonar.host.url=https://sonarqube.cs.ui.ac.id <br>      -Dsonar.login=$SONAR_TOKEN<br>  only:<br>    - development<br>    - /(?i)PBI-.*/</pre><blockquote>Observe that there is an image keyword inside the SonarScanner job, it denotes the image that will execute that CI/CD job.</blockquote><p>This way of doing things will save our time and effort to setup the required tools or OS just for the CI/CD scripts to be executed.</p><h3>Onto the GitLab CI/CD</h3><p>Okay, knowing those 2 tools briefly, we will be using them to achieve automatic deployment on our Django Rest Application!</p><p>Here’s our GitLab CI/CD (.gitlab.ci.yml) file:</p><pre>variables:<br>  DEVELOPMENT_GCP_USERNAME: $DEVELOPMENT_GCP_USERNAME<br>  DEVELOPMENT_GCP_STATIC_IP: $DEVELOPMENT_GCP_STATIC_IP<br>  PRODUCTION_GCP_USERNAME: $PRODUCTION_GCP_USERNAME<br>  PRODUCTION_GCP_STATIC_IP: $PRODUCTION_GCP_STATIC_IP<br><br>  DB_NAME: $DB_NAME<br>  DB_USER: $DB_USER<br>  DB_PASSWORD: $DB_PASSWORD<br>  DB_HOST: $DB_HOST<br>  DB_PORT: $DP_PORT<br>  SECRET_KEY: $SECRET_KEY<br><br>stages:<br>  - deploy<br>  - test<br>  - sonarqube<br><br>deploy:<br>  stage: deploy<br>  image: python:3.8<br>  before_script:<br>    - |<br>      if [ &quot;$CI_COMMIT_BRANCH&quot; == &quot;main&quot; ]; then<br>        export GCP_USERNAME=$PRODUCTION_GCP_USERNAME<br>        export GCP_STATIC_IP=$PRODUCTION_GCP_STATIC_IP<br>      elif [ &quot;$CI_COMMIT_BRANCH&quot; == &quot;staging&quot; ]; then<br>        export GCP_USERNAME=$DEVELOPMENT_GCP_USERNAME<br>        export GCP_STATIC_IP=$DEVELOPMENT_GCP_STATIC_IP<br>      fi<br>    - chmod 400 $SSH_KEY<br>  script:<br>    - ssh -o StrictHostKeyChecking=no -i $SSH_KEY $GCP_USERNAME@$GCP_STATIC_IP &quot;<br>      cd /home/rifqi_farel/cirrhocheck-api &amp;&amp; git switch $CI_COMMIT_BRANCH &amp;&amp; git pull origin $CI_COMMIT_BRANCH &amp;&amp; <br>      python3 -m pip install --upgrade pip &amp;&amp; python3 -m venv venv &amp;&amp; source venv/bin/activate &amp;&amp; <br>      pip install -r requirements.txt &amp;&amp; python3 manage.py migrate &amp;&amp; sudo systemctl restart gunicorn&quot;<br>  only:<br>    - staging<br>    - main<br><br>UnitTest:<br>  image: python:3.8<br>  stage: test<br>  before_script:<br>    - export DB_NAME=$DB_NAME<br>    - export DB_USER=$DB_USER<br>    - export DB_PASSWORD=$DB_PASSWORD<br>    - export DB_HOST=$DB_HOST<br>    - export DB_PORT=$DB_PORT<br>    - export SECRET_KEY=$SECRET_KEY<br>    - pip install -r requirements.txt<br>    - python manage.py makemigrations<br>    - python manage.py migrate<br>    - pip install coverage-badge<br>  script:<br>    - coverage run manage.py test -v 2<br>    - coverage report <br>    - coverage xml <br>    - coverage-badge -o coverage.svg<br>  coverage: &#39;/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/&#39;<br>  artifacts:<br>    paths:<br>      - coverage.xml<br>      - coverage.svg<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: coverage.xml<br>  only:<br>    - development<br>    - /(?i)PBI-.*/<br><br>SonarScanner:<br>  image: sonarsource/sonar-scanner-cli:latest<br>  stage: sonarqube<br>  dependencies:<br>    - UnitTest<br>  script:<br>    - sonar-scanner <br>      -Dsonar.projectKey=$PROJECT_KEY<br>      -Dsonar.host.url=https://sonarqube.cs.ui.ac.id <br>      -Dsonar.login=$SONAR_TOKEN<br>  only:<br>    - development<br>    - /(?i)PBI-.*/</pre><p>It may seem daunting at first, but let’s break it down together! Let’s take a look at what components are there and what it does:</p><p><strong>Variables</strong></p><pre>variables:<br>  DEVELOPMENT_GCP_USERNAME: $DEVELOPMENT_GCP_USERNAME<br>  DEVELOPMENT_GCP_STATIC_IP: $DEVELOPMENT_GCP_STATIC_IP<br>  PRODUCTION_GCP_USERNAME: $PRODUCTION_GCP_USERNAME<br>  PRODUCTION_GCP_STATIC_IP: $PRODUCTION_GCP_STATIC_IP<br><br>  DB_NAME: $DB_NAME<br>  DB_USER: $DB_USER<br>  DB_PASSWORD: $DB_PASSWORD<br>  DB_HOST: $DB_HOST<br>  DB_PORT: $DP_PORT<br>  SECRET_KEY: $SECRET_KEY</pre><p>Those are the environment variables, in which we usually store our confidential information. We can set the value of those variables inside the CI/CD pipeline with the help of <a href="https://docs.gitlab.com/ee/ci/variables/">GitLab Variables</a>.</p><p><strong>Stages</strong></p><pre>stages:<br>  - deploy<br>  - test<br>  - sonarqube</pre><p>There are only 3 stages: deploy, test, and sonarqube. Each stage only has 1 job too, so it&#39;s not too complex.</p><p><strong>Jobs</strong></p><p>There are only 3 jobs in total: deploy, UnitTest, SonarScanner. Let’s break a job down by understanding what the keywords are inside of the most complete job, which is UnitTest:</p><pre>UnitTest:<br>  image: python:3.8<br>  stage: test<br>  before_script:<br>    - export DB_NAME=$DB_NAME<br>    - export DB_USER=$DB_USER<br>    - export DB_PASSWORD=$DB_PASSWORD<br>    - export DB_HOST=$DB_HOST<br>    - export DB_PORT=$DB_PORT<br>    - export SECRET_KEY=$SECRET_KEY<br>    - pip install -r requirements.txt<br>    - python manage.py makemigrations<br>    - python manage.py migrate<br>    - pip install coverage-badge<br>  script:<br>    - coverage run manage.py test -v 2<br>    - coverage report <br>    - coverage xml <br>    - coverage-badge -o coverage.svg<br>  coverage: &#39;/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/&#39;<br>  artifacts:<br>    paths:<br>      - coverage.xml<br>      - coverage.svg<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: coverage.xml<br>  only:<br>    - development<br>    - /(?i)PBI-.*/</pre><blockquote><strong>image: </strong>Specifying the Docker image used to execute the job.</blockquote><blockquote><strong>stage: </strong>Specifying in which stage this job is in.</blockquote><blockquote><strong>before_script: </strong>Override a set of commands that are executed before the job.</blockquote><blockquote><strong>script: </strong>Shell script that is executed by a runner.</blockquote><blockquote><strong>coverage:</strong> Code coverage settings for a given job.</blockquote><blockquote><strong>artifacts: </strong>List of files and directories to attach to a job on success.</blockquote><blockquote><strong>only</strong>: Branches where this job will be executed.</blockquote><blockquote>If you want to learn more checkout the official <a href="https://docs.gitlab.com/ee/ci/yaml/">docs</a>!</blockquote><p>Okay, now that we understand how to create a basic job, let’s just explain what each job inside our CI/CD pipeline does:</p><ul><li><strong>deploy</strong>: As the name suggests, it will deploy our application into GCP Compute Engine according to the branch (production for main branch, staging for staging branch) inside the python:3.8 Docker image. This job will <strong>only</strong> be executed at main or staging branch.</li><li><strong>UnitTest</strong>: This job will run the unit tests, and generate a coverage report inside the python:3.8 Docker image. This job will <strong>only</strong> be executed at development or PBI branch.</li><li><strong>SonarScanner</strong> : This job will perform code analysis using sonar-scanner-cli Docker image and submit the results to the SonarQube server. This job will <strong>only</strong> be executed at development or PBI branch.</li></ul><h3>Conclusion</h3><p>We explored how Gitlab CI/CD can be integrated with Docker for easy automated deployment. Docker is used for setting up GitLab Runner, so we can execute whatever scripts we want without worrying about incompatibility and dependency errors.</p><h4>References:</h4><ol><li><a href="https://docs.gitlab.com/ee/ci/">Get started with GitLab CI/CD | GitLab</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0cb4f516e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git: Version Control System for Collaborative Tasks — An Introduction]]></title>
            <link>https://medium.com/@fadhilahazzah04/git-version-control-system-for-collaborative-tasks-an-introduction-27382b4d5e54?source=rss-7182a105ab92------2</link>
            <guid isPermaLink="false">https://medium.com/p/27382b4d5e54</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Aushaaf Fadhilah Azzah]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 18:22:49 GMT</pubDate>
            <atom:updated>2024-05-21T01:24:06.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Guide to Git and Linear for Collaborative Tasks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*36uxBzCXmIKpCiGW" /><figcaption>Taken from <a href="https://linear.app/docs/github">Linear Docs</a></figcaption></figure><p>In the world of software development and collaborative projects, effective version control is essential. Git, a distributed version control system, has emerged as a powerful tool that revolutionizes the way developers manage and collaborate on projects. Linear, a sleek and clean project management tool has also emerged as an amazing tool for project managers to further tracks the project’s progress. In this article, we will delve into Git &amp; Linear, their significance, and how they facilitate collaborative tasks among teams.</p><h3>Understanding Version Control Systems</h3><p>Version control systems (VCS) are tools that help manage changes to source code over time. They track modifications, facilitate collaboration, and provide a historical record of code evolution. VCS allows multiple developers to work on a project simultaneously, ensuring seamless integration of their changes.</p><h3>What is Git?</h3><p>Git, developed by Linus Torvalds in 2005, is a <strong>distributed</strong> version control system (DVCS) that has gained widespread adoption in the software development community. Because of its distributed nature, Git does not rely on a single, central repository. Instead, each developer has a complete copy of the repository, including its entire history.</p><p>This distributed nature offers several advantages, such as the ability to work offline, increased resilience, and better collaboration. Developers can create branches to work on specific features or bug fixes independently, and these branches can later be merged back into the main codebase.</p><blockquote>Why not use other collaborative platforms such as Google Drive with Google Docs? Both facilitated collaboration and history tracking, right?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*pmfU-nj02VHcc0O1" /><figcaption>Taken from <a href="https://www.reddit.com/r/ProgrammerHumor/comments/axjcwp/the_best_way_of_saving_your_code/">r/ProgrammerHumor</a></figcaption></figure><p>Well, recall that Git is a DVCS, so each developer has a complete copy of the repository. That alone is a huge benefit, because developer can make offline changes, thus increasing development flexibility. Another benefit is the juicy features that Git provides which will surely ease developers to manage their projects. Let’s take a look at some of those juicy features in Git later in this article.</p><h3>Some Git Terminologies</h3><p>In this section, we will explore some of the key concepts and terminologies used in Git.</p><h4>1. Repository</h4><p>A Git repository, or repo, is a collection of files and folders along with their complete history. Repositories can be local or hosted on a remote server like GitHub, GitLab, or Bitbucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhXFQJ1y8MIgG6B3IQS3oQ.png" /><figcaption>A GitLab repository</figcaption></figure><h4>2. Commit</h4><p>A commit represents a <strong>snapshot</strong> of the project at a specific point in time. Developers create commits to save changes and document what has been done. Each commit has an identifier in the form of <em>SHA1-hash.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9q3509K4E6ikDooQtCHrg.png" /><figcaption>A commit with its hash in GitLab</figcaption></figure><h4>3. Branch</h4><p>Branching allows developers to diverge from the main codebase and work on new features or bug fixes independently without worrying about conflicts. Once the changes are stable, the branch can be merged back into the main codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*Wlula9wyfqHRWFUl.png" /><figcaption>Illustration taken from <a href="https://www.harness.io/blog/git-branching">Git Branching in Harness | Harness</a></figcaption></figure><h4>4. Merge</h4><p>Merging combines changes from different branches into a single branch and snapshotting them with a commit. Below are illustrations on how a feature branch and a main branch will be merged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*NZswBibm1Bb8ZUFi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*b-X-Hjfx-D-gilyn" /><figcaption>Taken from <a href="https://www.atlassian.com/git/tutorials/using-branches/git-merge">Git Merge | Atlassian Git Tutorial</a></figcaption></figure><p>See how a <em>”new merge commit” </em>successfully merged the changes in feature branch and main branch.</p><h4>5. Merge Request (or Pull Request)</h4><p>In Git-based collaboration platforms like GitLab, a pull request or merge request is a proposal to merge changes from one branch into another. It facilitates code review and discussion with threads and approval before merging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKdJ7ijWiHjwjmUPdKHHiw.png" /><figcaption>A merge request in GitLab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2illF9FLM7yjAw_THuBBiw.png" /><figcaption>A thread in GitLab’s merge request</figcaption></figure><h3>Git Basics</h3><p>In this section, we will explore basics of Git, and how you can use it to collaborate on a project with others!</p><h4>Installation</h4><blockquote>Before using Git, we must install it first.</blockquote><blockquote>— Captain Obvious</blockquote><p>Here are the steps to install git:</p><ol><li>See <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Git — Installing Git (git-scm.com)</a> to install Git.</li><li>Check your installation with git --version and you should see similar output like below if you succeed.</li></ol><pre>❯ git --version<br>git version 2.43.0</pre><h4>Git Basic Workflow and Commands</h4><p>Finally, to the demonstrations! We will be utilizing some of the commands in Git to create a repository in your favorite remote repositories such as GitHub, GitLab, or Bitbucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QA7NQJHZjqYZOC56.png" /><figcaption>Taken from <a href="https://openclassrooms.com/en/courses/7476131-manage-your-code-project-with-git-and-github/7681891-work-in-your-local-git-repository">Work in Your Local Git Repository — Manage Your Code Project With Git and GitHub — OpenClassrooms</a></figcaption></figure><p><strong>1. Initializing a Repository</strong></p><p>There are 2 ways to do this. The first one is using git init to <em>evolve</em> your non-git working directory into a local git repository. This command will add .git/ folder in the respective directory indicating that it’s now a git repository.</p><pre>❯ git init <br>Initialized empty Git repository in &lt;PATH&gt;/.git/</pre><p>The second way is using git clone to clone an existing remote repository.</p><pre># With HTTPS<br>❯ git clone https://example.com/gitproject.git<br><br># With SSH<br>❯ git clone user@server:project.git</pre><p><strong>2. Adding a Remote URL</strong></p><p>When collaborating on a project, you often need to link your local repository to a remote repository, such as on GitHub, GitLab, or Bitbucket. The git remote command is used for this purpose. This command will usually enough to take care of your authentication problem, so don’t forget to do this command.</p><pre># Add a remote named &#39;origin&#39; with the repository URL<br>❯ git remote add origin https://example.com/yourusername/yourproject.git<br><br># Add a remote named &#39;origin&#39; with SSH<br>❯ git remote add origin https://example.com/gitproject.git<br><br># Setting a new Remote URL<br>❯ git remote set-url https://example.com/gitproject.git</pre><p><strong>3. Checking the Status</strong></p><p>To see the status of your repository and the changes you’ve made, use the git status command.</p><pre>❯ git status<br>On branch main<br>Your branch is up to date with &#39;origin/main&#39;.<br>Changes not staged for commit:<br>  (use &quot;git add &lt;file&gt;...&quot; to update what will be committed)<br>  (use &quot;git restore &lt;file&gt;...&quot; to discard changes in working directory)<br>        modified:   file.txt<br>no changes added to commit (use &quot;git add&quot; and/or &quot;git commit -a&quot;)</pre><p><strong>4. Adding your changes to Local Repository</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*kH-dOSWJ7yKgarrX.png" /><figcaption>Taken from <a href="https://heapsteep.com/how-to-add-a-project-to-git-github-gitlab/">How to add a project to Git/GitHub/GitLab — (heapsteep.com)</a></figcaption></figure><p>We will be utilizing git add and git commit to add our changes into local repository. After modifying some files, we add them into staging area with git add command.</p><pre># Adding changes of specific files<br>❯ git add [file-name-1] [file-name-2] ...<br><br># Adding changes in current directory<br>❯ git add .<br><br># Adding changes in entire project / repository<br>❯ git add --all</pre><p>After that, we will take a snapshot by committing your changes in local repository using git commit command. There are some <a href="https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716">semantics</a> that you can follow, but you can basically write a message denoting what is modified by this commit.</p><pre># Example commit following semantic commit message<br>git commit -m &quot;feat: JwT login API&quot;<br><br># Example commit message<br>git commit -m &quot;Implement JwT Login API&quot;</pre><p><strong>5. Pulling Changes from Remote Repository</strong></p><p>To incorporate changes made by others in the remote repository into your local repository, you can use the git pull command.</p><pre># Pull changes from the &#39;main&#39; branch of the &#39;origin&#39; remote<br>❯ git pull origin main</pre><p><strong>6. Pushing Changes to Remote Repository</strong></p><p>After making local commits, you can finally share those changes with others by pushing them to the remote repository!</p><pre># Push changes to the &#39;main&#39; branch of the &#39;origin&#39; remote<br>❯ git push origin main</pre><p>Okay, at this point you should be able to see your changes in the remote repository of your choice, Great! But we’re not done yet…</p><p><strong>7. Creating and Switching Branches</strong></p><p>Remember about branches we talked before? We can create and switch to a branch by utilizing git branch and git checkout command.</p><pre># Create a new branch<br>❯ git branch new-feature<br><br># Switch to the new branch<br>❯ git checkout new-feature<br><br># Or both at one command; Create and switch to a new branch<br>❯ git checkout -b new-feature<br></pre><p>We will talk more about branches in the next section!</p><p><strong>8. Merging Branches</strong></p><p>Once your changes are stable, you can merge them back into the main branch using the git merge command or by utilizing <strong>Merge Requests / Pull Requests </strong>discussed before.</p><pre># Switch to the main branch<br>❯ git checkout main<br><br># Merge changes from the feature branch<br>❯ git merge new-feature</pre><h4>Advanced Git Commands</h4><p>Let’s also take a sneak-peek at some advanced commands which is cherry-pick, revert, stash, log, reset, and reflog.</p><p><strong>1. Cherry-pick</strong></p><p>Cherry-picking allows developers to select specific commits from one branch and apply them to another, useful for incorporating critical changes or bug fixes into different branches without merging entire branches.</p><pre>❯ git cherry-pick &lt;commit-hash&gt;</pre><p>This command is useful to apply changes in a specific commit. For example, when we are committing in the wrong branch, we can simply cherry-pick that commit. Let’s see an example, we accidentally committed into feat/admin-get-all-users when we actually want to commit in our branch, which is feat/admin-add-user2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sobgCkePwO7lZYzr77Nj_g.png" /></figure><p>We can cherry-pick that! Let us create our branch and cherry-pick that accidental commit into our newly created branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*JeN4b9nlm7S-noljxIkm9w.png" /></figure><p>Nice, that commit is now applied to our feat/admin-add-user-2 branch.</p><p><strong>2. Revert</strong></p><p>The revert command in Git undoes a specific commit, creating a new commit that effectively reverses the changes introduced by the reverted commit. This is valuable for rolling back changes while preserving the commit history.</p><pre>❯ git revert &lt;commit-hash&gt;</pre><p>For example, let’s say we have a typo that will break the codebase and it’s committed. Notice the typo that’s highlighted by git diff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*MlN6ylDrnX2DaEtEpOFerQ.png" /></figure><p>When we push it, we will realize that there are typo because the pipeline will fail. And when that happens, we can revert that problematic commit so our pipeline will succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*g1z_q228MMm_jpX6_Mf4HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMLWPnUHChq5khDxC-kuww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*zQ7qlIxFt6Fy3g5ZQ_0DOQ.png" /></figure><p><strong>3. Stash</strong></p><p>This allows developers to temporarily store changes that are not ready to be committed, making it convenient to switch contexts or work on different tasks without committing incomplete code. When you run git stash, Git takes all the modifications to tracked files and saves them on a &quot;stash stack.&quot; This action reverts your working directory to the state of the last commit, providing a clean slate to work on other tasks. You can stash changes multiple times, creating a stack of stashes, each with a unique identifier.</p><p>To retrieve your stashed changes, you can use git stash apply, which applies the most recent stash without removing it from the stack. Alternatively, git stash pop can be used to apply and remove the most recent stash in one step. This flexibility allows developers to manage work-in-progress effectively, avoiding the need to commit unfinished work while maintaining a clean and organized repository history.</p><pre>❯ git stash<br><br># To see the &quot;stash stack&quot;<br>❯ git stash list<br><br># To apply the stashed changes back and pop it from the &quot;stash stack&quot;<br>❯ git stash pop<br><br># To only apply the stashed changes back without popping it<br>❯ git stash apply</pre><p>This command is useful if you want to change branch, but your work is still not completed and it’s best to not commit it first. Instead of commit-ing, we can stash it first, then when we are back to our working branch, we pop the stash to restore our work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*02NcY9h6MDeexTjXa1kklg.png" /><figcaption>Can’t change branch because there is incomplete work</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7X3jxJQuHtClESRu9rScA.png" /><figcaption>Can change branch because we stashed it</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*7v9O_YEnTPSgDCgYJbiMnA.png" /><figcaption>Back to our working branch and stash pop to continue our work</figcaption></figure><p><strong>4. Log</strong></p><p>The git log command is used to display the commit history of a repository. When you run git log, Git presents a chronological list of commits, starting from the most recent commit and going back in time. By default, the log includes information such as the commit hash, author, date, and commit message for each commit. This command is invaluable for understanding the development timeline, tracking changes, and reviewing the commit history of a project.</p><pre>❯ git log<br><br># To show the logs as a graph and each commit in one line<br>❯ git log --graph --oneline</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*ORr7mP_Z5bcGmqsGZC2HEw.png" /><figcaption>Default git log</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xJFV-OHKunhTs2oTuyGXQ.png" /><figcaption>With graph and oneline option</figcaption></figure><p><strong>5. Reset</strong></p><p>Reset allows you to move the HEAD and/or current branch to a specified commit or reset the state of the working directory.</p><ul><li>Example with --soft:</li></ul><p>This command resets the HEAD to the previous commit, essentially undoing the previous commit while keeping your changes staged.</p><pre>❯ git reset --soft HEAD~1</pre><ul><li>Example with --hard:</li></ul><p>This command resets the HEAD to the commit before the previous commit, and discards all changes in the working directory and staging area.</p><pre>❯ git reset --hard HEAD~2</pre><p>For example we want to undo our changes just like in the revert but don’t want to clobber up the commit history by reverting because it’s just a silly mistake. We will do git reset into our [REFACTOR] commit which has hash value of <strong>743767a</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*lbdde-mOjxoTUTz7FISDDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zPVmVreR29zWXRl73zckg.png" /></figure><p>Nice, now the committed typo is gone with clean commit history. If you are still confused about revert vs reset, here is a nice illustration that highlights the difference between reset and revert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*Tnmdn5F0H01zwzEK.png" /></figure><p><strong>6. Reflog</strong></p><p>This command provides a detailed log of reference changes within a Git repository. Unlike git log, which primarily focuses on commit history based on branches and tags, git reflog tracks all recent actions that affect the repository&#39;s HEAD and branch pointers. This includes commits, merges, checkouts, resets, and other operations that modify the repository&#39;s state. The git reflog output includes chronological entries with commit hashes and descriptions of recent actions, making it particularly useful for troubleshooting, recovering lost commits or changes, and understanding the sequence of operations that have occurred in the repository. For example, executing git reflog will show a log of reference changes, providing insights into the recent history of the repository&#39;s branches and HEAD movements.</p><p>For example, I have created a destructive commit with hash <strong>cf25d0a</strong>. Then, I did git reset --hard HEAD~1 to undo the commit. As seen in the screenshot below, git reflog detect those changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbFWKvlmfWMrbSVdyxjFPA.png" /></figure><h4>Bonus Tip: Delete Commits in Remote Repository Without a Trace</h4><p>We essentially did the git reset technique, but we will use git push -f to force-push into remote repository. The general steps are:</p><ol><li>git log to see our reset point’s commit hash.</li><li>git reset &lt;commit-hash&gt; (or git reset HEAD~1 to undo the last commit)</li><li>git add and git commit</li><li>git push -f</li></ol><p>If there is no problem, then you should have deleted some commits done in the remote repository from HEAD until your chosen reset point. You may think that this action is irrecoverable, but git reflog and doing git reset again can actually restore those “lost/deleted” commits.</p><h4>Git Config</h4><p>We can make some configuration in our git commands, to see what our config looks like right now, we can use git config --list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ZAfplqP2lzn32-zB_oF_gw.png" /></figure><p>Our identity (username &amp; email) is also stored there. Let us see some important configuration:</p><ul><li><strong>Auto CRLF: </strong>If we use a Linux VM for our server but we develop in Windows machine, it’s important to set this to false so that our newline won’t use carriage which cannot be read by Linux. We can do it with git config --global core.autocrlf false:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*TjTrhmCcs12gv3vDYA0DRQ.png" /></figure><ul><li><strong>Pull Rebase: </strong>When you run git pull, you can choose the strategy for integrating changes from the remote branch into your local branch. The two main strategies are merge and rebase. Merge combines the changes from the remote branch with your local branch, creating a new merge commit. This keeps the history of both branches intact, showing that a merge occurred. Rebase, on the other hand, rewrites the history of your local branch as if your local changes were made on top of the changes from the remote branch. It moves your local commits to the tip of the remote branch, resulting in a linear history without merge commits. By default, git pull uses the merge strategy. If you prefer to use rebase instead, you can run this command:</li></ul><pre>git config pull.rebase true</pre><h3><strong>Git Flow: A Branching Strategy</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZmeUX5Gr9ZhlyrpS" /><figcaption>Git Flow Illustration — Taken from <a href="https://wiki.ppl.cs.ui.ac.id/doc/git-flow-v1-rU6JgGXLN0">Git Flow V1 — Wiki PPL (ui.ac.id)</a></figcaption></figure><p>In Git, a branching strategy like Git Flow is a structured approach to managing branches, providing a clear path for development, testing, and release. Let’s explore the key branches in Git Flow!</p><p><strong>1. Master Branch</strong></p><p>The Master Branch is the main branch that stores <strong>production-ready</strong> source code intended for deployment into the production environment. The code in this branch is agreed upon, tested, and free from integration conflicts among developers, making it ready for user deployment.</p><p><strong>2. Staging Branch</strong></p><p>This branch is the repository that stores <strong>integrated</strong> code from each PBI (or feature) being worked on. In this branch, manual testing is usually conducted to ensure that the implemented features meet requirements and are free from bugs. If the codes in this branch are deemed production-ready, merging from this branch to the master branch will take place.</p><p><strong>3. PBI (Product Backlog Item) Branches</strong></p><p>PBI Branches are branches dedicated to implementing a <strong>specific</strong> Product Backlog Item chosen during a sprint. Multiple branches for Product Backlog Items will be created, each named according to the respective Product Backlog Item being developed.</p><p><strong>4. Hotfix Branch</strong></p><p>The Hotfix Branch is a branch derived from the master branch, created when there is a <strong>bug or error</strong> in the <strong>production</strong> code . The Hotfix Branch serves as a space to fix bugs (bug fixing) occurring in the master branch. After fixing the bug and ready for delivery, the hotfix branch is merged back into the master branch.</p><p><strong>5. Coldfix Branch</strong></p><p>The Coldfix Branch is created to perform a <strong>rollback</strong> (revert all changes from all product backlog item branches). This can happen if, during a sprint review, the product owner rejects one or all of the product backlog items that have been implemented for release.</p><h3>Linear</h3><h4>Scrum Board</h4><p>In the realm of collaborative software development, efficient task management is a cornerstone for success. Scrum Boards, inspired by the Agile methodology, provide a visual and organized way to manage tasks throughout their lifecycle. The Linear Scrum Board, in particular, simplifies this process by categorizing issues/tasks through statuses like “To Do”, “In Progress”, “In Review”, and “Done.”</p><p><strong>1. To Do:</strong></p><ul><li>Tasks that need to be addressed.</li><li>New features or bug fixes that are in the queue.</li></ul><p><strong>2. In Progress:</strong></p><ul><li>Tasks that are currently being worked on.</li><li>Developers can move tasks from “To Do” to “In Progress” as they start working on them.</li></ul><p><strong>3. In Review:</strong></p><ul><li>Tasks that are done and to be reviewed.</li><li>Developers can move tasks from “In Progress” to “In Review” after they finished working on them to be reviewed by others.</li></ul><p><strong>4. Done:</strong></p><ul><li>Completed tasks.</li><li>Once a task is finished, it moves to the “Done” column.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGcL4LOlazpuxL50_OHB0g.png" /><figcaption>Issues in Scrum Board</figcaption></figure><p>Issues also have properties other than status, such as:</p><ul><li><strong>Priority:</strong> Priority level of the issue (Urgent / High / Medium / Low).</li><li><strong>Assignee:</strong> Who is working on that issue.</li><li><strong>Story Points:</strong> An estimation unit that holds how long the issue will be fixed.</li><li><strong>Label:</strong> Labels of an issue.</li><li><strong>Project:</strong> Which project is this issue addressed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*1SwCESsyQsoUiO9NpMz7Qg.png" /><figcaption>Properties of an issue</figcaption></figure><h4>Projects</h4><p>We can see all of our projects and set the status of each project. There is also a start date and target date. Notice that “Sprint 2” project doesn’t fulfill the target date, hence the red mark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttRfqjd2qf_8hFvFC5cNeA.png" /><figcaption>Projects in Linear</figcaption></figure><p>Let’s take a look at “Sprint 3” project. There is a sidebar button in the top-right of the screen that shows the project’s details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvXukeo_Wy7u6ybp7ux1XA.png" /><figcaption>Project Details</figcaption></figure><p>We also can see <strong>Progress Chart</strong>, a chart that shows how many projects have been started and completed across the timeframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*oeyn6CezJS3EPPWrm7TYZw.png" /><figcaption>Project’s Progress Chart</figcaption></figure><h4><strong>Insights</strong></h4><p>Linear also provides Insights, in which we basically can visualize our issue data and get insights from it. Sadly, that feature is for Plus members only, but luckily Linear provides free 30-day trial for us to try out, yay!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*SmMpISe1MgfgCUEJD-n4-Q.png" /></figure><p>For example, in the image below we can see how was the story points distributed, and the progress of each assignee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*THaKQMoWbrn_TSZrJY4jMw.png" /></figure><p>There is also burn-up chart, or cumulative flow diagrams, that show how streams of work have changed over time. Let’s take a look at an example taken from <a href="https://linear.app/changelog/2023-06-15-burn-up-charts">official Linear docs</a>. In below snapshot, we are looking at issues with the label <em>Bug</em> across all engineering teams. You can see the overall bug growth by looking at the top-level issue count. So, as a project manager we may conclude that we need to improve our bug fixing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Fr1TsF342LRubulEDPbTVA.png" /><figcaption>Burn-Up Chart — Taken from <a href="https://linear.app/changelog/2023-06-15-burn-up-charts">https://linear.app/changelog/2023-06-15-burn-up-charts</a></figcaption></figure><h3>Conclusion</h3><p>In conclusion, Git and Linear are powerful tools that revolutionize version control and project management in collaborative software development. Git’s distributed nature and rich feature set enable seamless collaboration, branching for independent work, and efficient code management. Linear’s sleek interface, Scrum board, and insights offer a structured approach to task management and project progress tracking. Together, Git and Linear provide developers and project managers with the tools they need for effective collaboration and successful project delivery.</p><h4>References:</h4><ol><li><a href="https://git-scm.com/book/en/v2">Git — Book (git-scm.com)</a></li><li><a href="https://wiki.ppl.cs.ui.ac.id/doc/git-flow-v1-rU6JgGXLN0">Git Flow V1 — Wiki PPL (ui.ac.id)</a></li><li><a href="https://linear.app/docs">Linear Docs</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27382b4d5e54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>