<?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 sorfeb on Medium]]></title>
        <description><![CDATA[Stories by sorfeb on Medium]]></description>
        <link>https://medium.com/@soros21febriano?source=rss-7bbc5606379e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AQs6_KC3bqQwzVMGiSJVQA.jpeg</url>
            <title>Stories by sorfeb on Medium</title>
            <link>https://medium.com/@soros21febriano?source=rss-7bbc5606379e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:04:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@soros21febriano/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[Ambatuscrum #10: Pushing the Limits: A Guide to Stress Testing and Modern Software Quality…]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-10-pushing-the-limits-a-guide-to-stress-testing-and-modern-software-quality-14e5c6bee148?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e5c6bee148</guid>
            <category><![CDATA[stress-testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[k6]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Thu, 15 May 2025 07:20:14 GMT</pubDate>
            <atom:updated>2025-05-19T17:14:55.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ambatuscrum #10: Pushing the Limits: A Guide to Stress Testing and Modern Software Quality Assurance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZJkEuyXbwPFjbbG0" /><figcaption>Photo by <a href="https://unsplash.com/@svkj?utm_source=medium&amp;utm_medium=referral">Solal Ohayon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the relentless digital race, delivering software that is not just functional but also robust, reliable, and secure is paramount. This is where Software Testing and Quality Assurance (QA) step into the limelight. Today, we’re diving deep into a critical aspect of QA: <strong>Stress Testing</strong>, with a special focus on how the modern tool <strong>k6</strong> empowers us to push our applications to their limits. We’ll also touch upon other essential QA practices like Behavior-Driven Development (BDD) and comprehensive security testing, illustrating how they collectively contribute to building resilient and high-quality software. The goal? To ensure our systems can handle the unexpected, that development aligns perfectly with user needs, and that our applications are fortresses against threats.</p><h3>Why We Can’t Skip QA: The Bedrock of Reliable Software</h3><p>Skipping or skimping on QA is like building a skyscraper on a shaky foundation — it’s a disaster waiting to happen. The costs of software defects are not just monetary, encompassing bug fixes, potential data loss, and system downtime. They also erode user trust, damage brand reputation, and can lead to significant business setbacks.</p><p>A proactive and comprehensive QA strategy is an investment that pays dividends by:</p><ul><li><strong>Enhancing user satisfaction and trust:</strong> Users expect seamless and reliable experiences.</li><li><strong>Reducing development and maintenance costs:</strong> Catching issues early is far cheaper than fixing them post-release.</li><li><strong>Strengthening brand reputation and business success:</strong> Quality software is a hallmark of a dependable brand.</li></ul><h3>Under Pressure: Mastering Stress Testing with k6</h3><p>At its core, <strong>Stress Testing</strong> is the practice of subjecting a system to loads far beyond its normal or peak operating conditions. The primary purpose isn’t just to see <em>if</em> it breaks, but <em>how</em> it breaks, <em>where</em> its breaking point lies, and how it behaves under extreme duress. This helps us ensure stability and identify critical failure points.</p><p><strong>The “Why”: Critical Benefits of Stress Testing</strong></p><ul><li><strong>Understanding System Capacity:</strong> It allows us to “menguji kapasitas kemampuan system melalui stress test” — to truly understand what our system can handle before performance degrades or failures occur.</li><li><strong>Ensuring Stability:</strong> Guarantees that the system remains stable and reliable even during unexpected traffic surges or high-demand periods.</li><li><strong>Identifying Bottlenecks:</strong> Pinpoints performance bottlenecks, whether in the code, database, network, or infrastructure.</li><li><strong>Informing Infrastructure Decisions:</strong> Provides data-driven insights for capacity planning and scaling infrastructure.</li></ul><h3><strong>k6: Your Modern Toolkit for Stress Testing</strong></h3><p>When it comes to modern stress and load testing, <strong>k6</strong> stands out. It’s an open-source, developer-centric tool designed for ease of use, performance, and extensibility. One of its key advantages is that tests are written in JavaScript, a language familiar to many developers, making it highly accessible.</p><p>Let’s look at how k6 concepts are applied, drawing from a typical load testing setup like the one in the singawas-be project&#39;s load-tests directory:</p><ul><li><strong>Introduction to k6:</strong> k6 allows you to write scripts that simulate virtual users (VUs) interacting with your API endpoints or web applications. Its performance-first approach means you can generate significant load from a single machine.</li><li><strong>Core Concepts in k6 for Stress Testing:</strong></li><li><strong>Virtual Users (VUs):</strong> These simulate concurrent users accessing your system. In your project’s load-tests/config/environment.js, you can define different VU levels:</li></ul><pre>  vus: {<br>    low: parseInt(__ENV.VUS_LOW) || 5,<br>    medium: parseInt(__ENV.VUS_MEDIUM) || 10,<br>    high: parseInt(__ENV.VUS_HIGH) || 20,<br>  },</pre><p>For a stress test, you’d typically aim for config.vus.highor even beyond.</p><ul><li><strong>Duration:</strong> This defines how long a test or specific stages within a test will run. Your environment.js also defines various durations:</li></ul><pre>  durations: {<br>    short: __ENV.DURATION_SHORT || &#39;30s&#39;,<br>    medium: __ENV.DURATION_MEDIUM || &#39;2m&#39;,<br>    long: __ENV.DURATION_LONG || &#39;5m&#39;,<br>  }</pre><ul><li><strong>Scenarios:</strong> k6 allows you to define complex test profiles using scenarios. In your load-tests/main.js, you have different scenarios like sustained_load, ramp_up, and crucially for our topic, stress_test:</li></ul><pre>    stress_test: {<br>      executor: &#39;ramping-vus&#39;,<br>      startVUs: 0,<br>      stages: [<br>        { duration: &#39;30s&#39;, target: config.vus.medium },<br>        { duration: &#39;1m&#39;, target: config.vus.high },<br>        { duration: &#39;30s&#39;, target: 0 },<br>      ],<br>      startTime: &#39;7m&#39;,  // Start after ramp_up<br>    }</pre><ul><li>This stress_test scenario (main.js line 43) is a perfect example of how to model a stress test.</li><li><strong>Executors:</strong> These control how VUs are scheduled and ramped. The ramping-vus executor, used in your stress_test scenario (main.js line 44), is ideal for stress testing as it allows you to gradually increase the load to a high number of VUs (e.g., config.vus.high), hold it, and then ramp down.</li><li><strong>Checks and Thresholds:</strong></li><li><strong>Checks</strong> are assertions to verify that your system responds correctly (e.g., HTTP status codes, response body content). For instance, in load-tests/scenarios/blacklist.js:</li></ul><pre>    const success = check(response, {<br>      &#39;blacklist check status is 200&#39;: (r) =&gt; r.status === 200,<br>      &#39;response time &lt; 500ms&#39;: (r) =&gt; r.timings.duration &lt; 500,<br>      &#39;response has correct structure&#39;: (r) =&gt; jsonData &amp;&amp; jsonData.hasOwnProperty(&#39;is_blacklisted&#39;),<br>    });</pre><p><strong>Thresholds</strong> define pass/fail criteria for your test based on metrics. Your main.js includes a threshold:</p><pre>  thresholds: {<br>    &#39;http_req_duration&#39;: [&#39;p(95)&lt;2000&#39;],</pre><p>For stress tests, you might observe these thresholds to see when they start failing.</p><ul><li><strong>Metrics:</strong> k6 collects various built-in metrics (like http_req_duration, http_req_failed). You can also define custom metrics. Your project uses custom metrics like ApiResponseTime, ApiRequests, and ErrorRate defined in load-tests/helpers/utils.js:</li></ul><pre>export const ApiResponseTime = new Trend(&#39;api_response_time&#39;);<br>export const ApiRequests = new Counter(&#39;api_requests&#39;);<br>export const ErrorRate = new Rate(&#39;error_rate&#39;);</pre><p>These are crucial for understanding how your API performs under stress. For example, ErrorRate.add(1); is called when checks fail or errors occur (e.g., in load-tests/scenarios/kelola_jadwal.js).</p><p><strong>Designing a Good Stress Test with k6 Stages:</strong> A well-designed stress test typically follows a pattern of gradually increasing load, maintaining it, and then decreasing it. This helps observe how the system behaves at various points and, importantly, if it recovers. The stages option in k6, often used with executors like ramping-vus, is perfect for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*VJKDj_6JFChj1lqx52oR5g.png" /><figcaption><em>A typical stress test profile showing ramp-up, steady state, and ramp-down phases; From: </em><a href="https://qainsights.com/how-to-design-workload-model-for-load-testing/">How to design Workload Model for Load Testing? — qainsights.com</a></figcaption></figure><p>Let’s break down these phases:</p><ol><li><strong>Ramp-up:</strong></li></ol><ul><li><strong>Purpose:</strong> Gradually increase the number of virtual users (VUs) or request rate. This helps to identify the point at which performance starts to degrade or errors begin to appear. It also allows the system to warm up (e.g., caches to populate).</li><li><strong>k6 Implementation:</strong> Define one or more stages with increasing target VU counts over specific durations. <em>Example stage:</em> { duration: &#39;2m&#39;, target: config.vus.medium } - Ramp up to a medium load over 2 minutes.</li></ul><p>2.<strong> Steady State (Sustained Load):</strong></p><ul><li><strong>Purpose:</strong> Maintain a high level of load (often beyond expected peak) for a sustained period. This is where you’re truly stressing the system to observe its stability, resource consumption (CPU, memory, I/O), and identify if it can handle the pressure long-term. This is the core of the stress test.</li><li><strong>k6 Implementation:</strong> A stage that holds the target VU count at the desired stress level for a significant duration. <em>Example stage:</em> { duration: &#39;5m&#39;, target: config.vus.high } - Maintain a high load for 5 minutes. For a true stress test, this target might be 150%, 200%, or even more of your anticipated peak load.</li></ul><p>3.<strong> Ramp-down:</strong></p><ul><li><strong>Purpose:</strong> Gradually decrease the load. This is crucial to observe if the system recovers gracefully. Does performance return to normal? Are resources released correctly?</li><li><strong>k6 Implementation:</strong> Define one or more stages with decreasing target VU counts. <em>Example stage:</em> { duration: &#39;1m&#39;, target: 0 } - Ramp down to 0 VUs over 1 minute.</li></ul><p>Your stress_test scenario in load-tests/main.js already implements this pattern:</p><pre>    stress_test: {<br>      executor: &#39;ramping-vus&#39;,<br>      startVUs: 0,<br>      stages: [<br>        { duration: &#39;30s&#39;, target: config.vus.medium }, // Ramp-up to medium<br>        { duration: &#39;1m&#39;, target: config.vus.high },   // Ramp-up to high (Stress/Steady State)<br>        { duration: &#39;30s&#39;, target: 0 },                 // Ramp-down<br>      ],<br>      startTime: &#39;7m&#39;,  // Start after ramp_up<br>    }</pre><ul><li><strong>Practical Example (Conceptual, drawing from your project):</strong> Imagine setting up a stress test for a critical API endpoint, like the one handled by blacklistScenarioin load-tests/scenarios/blacklist.js.</li></ul><ol><li><strong>Define the Scenario:</strong> Use the ramping-vus executor.</li><li><strong>Stages:</strong></li></ol><ul><li>Ramp up from 0 VUs to a medium load (e.g., config.vus.medium from environment.js) over a short period (e.g., 30s).</li><li>Then, aggressively ramp up to a high load (e.g., config.vus.high from environment.js) or even higher, simulating a massive surge, and hold this for a defined duration (e.g., 1m).</li><li>Finally, ramp down.</li></ul><p>3. <strong>Authentication:</strong> Ensure VUs are authenticated, perhaps using a shared token obtained in the setup function as seen in your main.js and passed to scenario functions like blacklistScenario(token). The actual token retrieval might use getAuthToken() from load-tests/helpers/auth.js and headers are prepared with getAuthHeaders(token) (load-tests/helpers/auth.js).</p><p>4.<strong> Checks &amp; Metrics:</strong> Continuously perform checks on responses and monitor ApiResponseTime and ErrorRate. The goal is to see how these metrics degrade as the load surpasses normal operational limits.</p><ul><li><strong>Running k6 tests:</strong> Executing k6 tests is straightforward. As noted in your load-tests/README.md, you&#39;d typically run:</li></ul><pre>k6 run load-tests/main.js</pre><ul><li>Or, if you need to pass environment variables like an authentication token:</li></ul><pre>k6 run -e TOKEN=&quot;{access_token}&quot; load-tests/main.js</pre><ul><li><strong>Analyzing Results:</strong> After a stress test, k6 provides a summary of metrics. For stress testing, you’re particularly interested in:</li><li>At what VU level or request rate does the ErrorRate start to climb significantly?</li><li>How does ApiResponseTime (especially p90, p95) degrade under extreme load?</li><li>Does the system recover after the stress period, or does it remain unstable? Your main.js also includes configuration for HTML and text summaries, which are invaluable for detailed analysis.</li></ul><h3><strong>A Glimpse into k6 Output: Sample Run of the Blacklist Scenario</strong></h3><p>To make the k6 output more tangible, let’s look at a sample run from our singawas-be project. I executed a specific script, run-blacklist-only.js, which focuses solely on the blacklistScenario. This script is configured for a short duration with a single virtual user, primarily to check its basic functionality and get a feel for the output.</p><pre>// ...existing code...<br>export const options = {<br>  vus: 1, // Number of virtual users<br>  duration: &#39;10s&#39;, // Duration of the test<br>};<br><br>export default function () {<br>  // Get the authentication token (either from env or by logging in)<br>  const token = getAuthToken();<br>  <br>  if (token) {<br>    // Execute only the blacklist scenario<br>    blacklistScenario(token);<br>  } else {<br>    console.error(&quot;Authentication failed, cannot run scenario.&quot;);<br>  }<br>}<br>// ...existing code...</pre><p>Here’s what the console output looks like after running k6 run load-tests/run-blacklist-only.js (assuming a token was provided via __ENV.TOKEN as indicated by &quot;Using provided authentication token&quot; messages):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKVdf4n-Dw6hAMw1IfKJLg.png" /><figcaption>Sample run of the k6 scenarios only for my Blacklist service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5HFmv3BWeB7efC5GJP_CA.png" /><figcaption>Sample report of the k6 scenarios only for my Blacklist service</figcaption></figure><p><strong>Deconstructing the Metrics:</strong></p><p>The summary output from k6 is packed with valuable information. Let’s break down some key metrics from the image above:</p><ul><li><strong>api_requests..................: 6 0.516452/s — </strong>This is one of our custom metrics defined in load-tests/helpers/utils.js. It shows that a total of 6 API requests were made during the test, at an average rate of approximately 0.52 requests per second.</li><li><strong>api_response_time...........: avg=81.65ms min=38.21ms med=45.88ms max=258.25ms p(90)=160.85ms p(95)=209.55ms — </strong>Another custom metric. This is a trend metric providing statistics about the response times of our API calls.</li><li>avg=81.65ms — The average response time was 81.65 milliseconds.</li><li>min=38.21ms— The fastest response took 38.21 milliseconds.</li><li>med=45.88ms— The median response time (50th percentile) was 45.88 milliseconds.</li><li>max=258.25ms— The slowest response took 258.25 milliseconds.</li><li>p(90)=160.85ms: 90% of the requests completed in 160.85 milliseconds or less.</li><li>p(95)=209.55ms: 95% of the requests completed in 209.55 milliseconds or less. This is often a key metric for Service Level Agreements (SLAs).</li><li><strong>checks........................: 100.00% ✓ 18 / 18 — </strong>This shows the success rate of our check() assertions defined within the blacklistScenario (e.g., &#39;blacklist check status is 200&#39;, &#39;response time &lt; 500ms&#39;). Here, 100% of the 18 checks passed, which is excellent.</li><li><strong>data_received...............: 2.3 kB 201 B/s — </strong>Total data received by k6 from the server (2.3 kilobytes) and the average rate.</li><li><strong>data_sent...................: 3.4 kB 294 B/s</strong>— Total data sent by k6 to the server (3.4 kilobytes) and the average rate.</li><li><strong>group_duration..............: avg=1.93s min=1.15s med=1.89s max=2.73s p(90)=2.64s p(95)=2.68s</strong>— Time spent within each execution of the group(‘Blacklist Checks’, function() { … }); block in blacklistScenario.</li><li><strong>http_req_blocked............: avg=420.56µs ...</strong>Time spent waiting for a free TCP connection slot from the k6 VU’s connection pool before initiating a request.</li><li><strong>http_req_connecting.........: avg=251.68µs ...</strong>Time spent establishing the TCP connection to the remote host. For HTTPS, this does not include TLS handshake time.</li><li><strong>http_req_duration...........: { expected_response:true }: avg=81.65ms ... — </strong>This is a built-in k6 metric representing the total time for the request, from just before sending the request to just after receiving the full response. The { expected_response:true } tag indicates these are requests where k6 expected a response (standard HTTP requests). Notice its average is the same as our custom api_response_time in this simple case.</li><li><strong>http_req_failed.............: 0.00% ✓ 0 / 6 — </strong>Percentage and count of HTTP requests that failed (e.g., network errors, non-2xx/3xx responses not caught by checks but considered failures by k6 default behavior or thresholds). Here, 0% failed.</li><li><strong>http_req_receiving..........: avg=736.86µs ... — </strong>Time spent receiving the response data from the server.</li><li><strong>http_req_sending............: avg=183.79µs ... — </strong>Time spent sending data to the remote host (e.g., request headers and body).</li><li><strong>http_req_tls_handshaking....: avg=0s ... — </strong>Time spent on the TLS handshake. It’s 0s here, likely because the test target is http://localhost:8000 (from config.baseUrl) which is not HTTPS. If it were HTTPS, this would show the time taken for SSL/TLS setup.</li><li><strong>http_req_waiting............: avg=80.65ms ... — </strong>Time spent waiting for the server to respond after the request was fully sent (Time To First Byte — TTFB). This is often a key indicator of server-side processing time.</li><li><strong>http_reqs.....................: 6 0.516452/s — </strong>Total number of HTTP requests made by k6. Matches our custom api_requests count.</li><li><strong>iteration_duration..........: avg=1.93s ... — </strong>The total time taken for one complete execution of the default function () in run-blacklist-only.js, which includes getting the token and running blacklistScenario(token).</li><li><strong>iterations..................: 6 0.516452/s</strong>— Total number of times the default function () completed.</li><li><strong>vus.....................: 1 min=1 max=1 — </strong>Number of active virtual users during the test. It was consistently 1, as configured in options.</li><li><strong>vus_max.....................: 1 min=1 max=1 — </strong>Maximum number of VUs allocated for the test.</li></ul><p><strong>Interpreting These Sample Results:</strong></p><p>For this specific, very light test on the blacklist scenario:</p><ul><li><strong>Performance is Good:</strong> Average and 95th percentile response times (around 81ms and 209ms respectively) are well within acceptable limits for many applications. The checks for &#39;response time &lt; 500ms&#39; passed comfortably.</li><li><strong>System is Stable (under this load):</strong> All checks passed, and there were no failed HTTP requests.</li><li><strong>Quick Server Processing:</strong> The http_req_waiting (TTFB) is the largest component of the http_req_duration, suggesting most of the time is spent on server-side processing rather than network latency or data transfer for these small requests/responses.</li></ul><p>This simple run gives us confidence that the basic blacklist check functionality is working correctly and performing well under minimal load. For a true stress test, we would significantly increase the vus and duration in our main test script (load-tests/main.js) and observe how these metrics change, looking for degradation points and potential errors as defined in our thresholds.</p><h3>Broadening the Arsenal: Other Essential QA Practices</h3><p>While stress testing is vital for resilience, a holistic QA strategy involves more:</p><ul><li><strong>Behavior-Driven Development (BDD): Aligning with Purpose</strong></li><li><strong>Concept:</strong> BDD fosters collaboration between business stakeholders, developers, and testers by defining application behavior in a natural, human-readable language (like Gherkin).</li><li><strong>Benefit:</strong> It ensures that development is directly tied to business requirements and user stories, “mampu menguji kesesuaian pengembangan fitur dengan requirement menggunakan BDD.”</li></ul><p><strong>Tools:</strong></p><ul><li><strong>Cucumber:</strong> A leading BDD tool that executes plain-text functional descriptions as automated tests.</li><li><strong>Behave:</strong> A BDD framework for Python projects.</li><li><strong>Serenity BDD:</strong> A framework that enriches your BDD test reports, making them more informative and useful as living documentation.</li><li><strong>Fortifying Your Defenses: Modern Security Testing</strong> Security cannot be an afterthought. Integrating security testing throughout the development lifecycle is crucial.</li><li><strong>Static Application Security Testing (SAST):</strong> Analyzes source code, bytecode, or binary code for security vulnerabilities without executing the application. Tools like <strong>GitLab SAST</strong> can be integrated into your CI/CD pipeline to scan code on every commit.</li><li><strong>Dynamic Application Security Testing (DAST):</strong> Tests the application in its running state by simulating external attacks. <strong>GitLab DAST</strong> can scan your live application or review environments.</li><li><strong>Dependency Scanning:</strong> Identifies known vulnerabilities in your project’s third-party libraries and dependencies. <strong>GitLab Dependency Scanning</strong> helps manage these risks.</li><li><strong>Penetration Testing:</strong> A more in-depth, often manual, security assessment where ethical hackers attempt to exploit vulnerabilities in your system, mimicking real-world attackers. This provides a realistic view of your security posture.</li><li><strong>Other State-of-the-Art Tools:</strong> The landscape also includes Interactive Application Security Testing (IAST), Runtime Application Self-Protection (RASP), and various specialized scanners.</li></ul><h3>Synergy in Action: Integrating QA for Maximum Impact</h3><p>These different testing types — Stress, BDD, Security — are not isolated silos. They are complementary and work best when integrated:</p><ul><li>BDD ensures you’re building the <em>right</em> thing.</li><li>Functional and Stress testing (with tools like k6) ensure you’re building the thing <em>right</em> and that it’s robust.</li><li>Security testing ensures you’re building it <em>securely</em>.</li></ul><p>Automation is key. Integrating these tests into your Continuous Integration/Continuous Deployment (CI/CD) pipelines (e.g., using GitLab CI/CD as suggested by the mention of GitLab SAST/DAST) provides continuous feedback, allowing teams to catch and fix issues early and often.</p><h3>Conclusion: Building Better, Stronger Software with k6 and Beyond</h3><p>A comprehensive Quality Assurance strategy, with a strong emphasis on practices like Stress Testing using powerful tools like k6, is non-negotiable for modern software development. By understanding your system’s limits with k6, ensuring features meet user needs with BDD, and fortifying your application with robust security testing, you build software that is not only functional but also reliable, resilient, and trustworthy.</p><p>Embrace these modern QA practices. Explore tools like k6, integrate them into your workflows, and push your applications to be the best they can be. Your users, and your bottom line, will thank you.</p><blockquote>References:</blockquote><blockquote>k6 Documentation: <a href="https://k6.io/docs/">https://k6.io/docs/</a></blockquote><blockquote>Cucumber: <a href="https://cucumber.io/docs/">https://cucumber.io/docs/</a></blockquote><blockquote>GitLab Application Security: <a href="https://docs.gitlab.com/ee/user/application_security/">https://docs.gitlab.com/ee/user/application_security/</a></blockquote><blockquote><a href="https://qainsights.com/how-to-design-workload-model-for-load-testing/">How to design Workload Model for Load Testing? — qainsights.com</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e5c6bee148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #9: Monitorama: Taming Your Django Dragons]]></title>
            <link>https://blog.devops.dev/ambatuscrum-9-monitorama-taming-your-django-dragons-9ea432f2d308?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ea432f2d308</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 07 May 2025 17:43:13 GMT</pubDate>
            <atom:updated>2025-05-15T12:45:29.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFIkab77fU-5Sur5" /><figcaption>Photo by <a href="https://unsplash.com/@jaqbovsky?utm_source=medium&amp;utm_medium=referral">Michał Jakubowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Modern web applications demand more than just functionality — they must be reliable, fast, and transparent when things go wrong. In this post, you’ll learn how to architect a monitoring stack that covers:</p><ol><li><strong>Built‑in platform monitoring</strong> (Firebase, GCP, AWS, DigitalOcean)</li><li><strong>Standard setups</strong> for error, log, user‑activity, and performance monitoring (Sentry, ELK/Cloud Logging, Google Analytics, New Relic)</li><li><strong>Custom instrumentation</strong> for your own business logic (e.g. tracking critical function calls)</li><li><strong>Advanced usage</strong>: dashboards, alerts, and continuous improvement</li></ol><p>We’ll illustrate with a real‑world example: instrumenting a Django REST Framework (DRF) service running in Docker, using Prometheus and Grafana.</p><h3>1. Why Monitoring Matters</h3><p>Imagine a customer filling out a form on your site — then suddenly nothing happens. Did the server crash? Was there a network spike? Without proper monitoring, you’re blind. With it, you can:</p><ul><li><strong>Detect</strong> incidents in real time</li><li><strong>Diagnose</strong> root causes by correlating errors, logs, and performance metrics</li><li><strong>Optimize</strong> resource usage and user experience</li><li><strong>Alert</strong> the team before SLAs are breached</li></ul><h3>2. Leverage Built‑In Platform Monitoring</h3><p>Most cloud and mobile platforms ship with free monitoring “for free”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f5a109b35304e936a0797f2af64d111/href">https://medium.com/media/1f5a109b35304e936a0797f2af64d111/href</a></iframe><blockquote><strong><em>Tip:</em></strong><em> Activate these out of the box. Even if you plan to deploy third‑party tools later, you’ll have a baseline.</em></blockquote><h3>3. Standard Monitoring Stack</h3><p>A healthy observability stack typically includes four pillars:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ee1d8ad5eb1d53586f1048646f71a8c/href">https://medium.com/media/4ee1d8ad5eb1d53586f1048646f71a8c/href</a></iframe><h3>3.1 Error Monitoring with Sentry</h3><ul><li><strong>Setup</strong>: Install the Sentry SDK in Django (sentry-sdk[django]), configure DSN.</li><li><strong>Django middleware</strong> to capture real client IP in Sentry</li></ul><pre># myapp/middleware.py<br>from ipware import get_client_ip<br>import sentry_sdk<br><br>class ClientIPMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        client_ip, _ = get_client_ip(request)<br>        real_port = request.META.get(&quot;HTTP_X_REAL_PORT&quot;)<br>        <br>        if client_ip:<br>            # attach “ip_address” field to every Sentry event<br>            sentry_sdk.set_user({<br>                &quot;ip_address&quot;: real_port and f&quot;{client_ip}:{real_port}&quot;<br>                              or client_ip<br>            })<br>        <br>        return self.get_response(request)</pre><ul><li><strong>Django settings</strong></li></ul><pre># settings.py<br>import sentry_sdk<br>from sentry_sdk.integrations.django import DjangoIntegration<br><br>sentry_sdk.init(<br>    dsn=os.environ[&quot;SENTRY_DSN&quot;],<br>    integrations=[DjangoIntegration()],<br>    traces_sample_rate=0.2,       # adjust for performance tracing<br>    send_default_pii=True,        # include user context from middleware<br>)<br>MIDDLEWARE = [<br>    # …<br>    &quot;myapp.middleware.ClientIPMiddleware&quot;,<br>    # …<br>]</pre><ul><li><strong>Outcome</strong>: Every unhandled exception (and breadcrumbs leading up to it) appears in Sentry with user context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNLfngq61R8rtdCSoarW3A.png" /><figcaption>Sentry Issues (Prioritized View)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/521e53c22be9d6221a043858c8ed9ead/href">https://medium.com/media/521e53c22be9d6221a043858c8ed9ead/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gCzzwr2XhuD7S6wuwUJXg.png" /><figcaption>Sentry Backend Insights</figcaption></figure><p>This view combines APM (transactions) and query‑level performance data collected by the Sentry Python SDK.</p><h4>A. Most Time‑Consuming Queries</h4><ul><li><strong>What</strong>: SQL statements ranked by total time spent executing.</li><li><strong>Why</strong>: Reveals hotspots in your ORM or raw SQL that slow responses (e.g. heavy INSERT INTO silk_request … or slow UPDATE statements).</li><li><strong>Action</strong>: Add indexes, batch writes, or reduce fields logged if these queries are not business‑critical.</li></ul><h4>B. Most Time‑Consuming Domains</h4><ul><li><strong>What</strong>: External HTTP calls (by domain) ranked by total latency.</li><li><strong>Why</strong>: Third‑party API calls (e.g. to *.ui.ac.id:8080) can dominate your request time.</li><li><strong>Action</strong>: Cache responses, add retries with backoff, or move calls into background jobs.</li></ul><h4>C. Transactions Per Minute</h4><ul><li><strong>What</strong>: Number of traced transactions (i.e. instrumented Django views/endpoints) per minute.</li><li><strong>Why</strong>: Correlate throughput with error spikes or latency changes.</li><li><strong>Action</strong>: If TPS jumps but p95 latency stays flat, your autoscaling is healthy; if latency also jumps, investigate resource constraints.</li></ul><h4>D. p50 / p75 Duration</h4><ul><li><strong>What</strong>: The 50th‑ and 75th‑percentile durations of your transactions over the selected time window.</li><li><strong>Why</strong>: p50 shows typical user experience; p75 begins to expose the “slower quartile.”</li><li><strong>Action</strong>: Set alert thresholds on p75 or p95 to catch regressions before they impact most users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPYoQzwIGCDU1O9_n05Ydg.png" /><figcaption>Discord Webhook notification from Sentry</figcaption></figure><h3>3.2 Log Monitoring</h3><ul><li><strong>Setup</strong>: Ship your Django logs (JSON‑formatted) to Elasticsearch or Grafana Loki.</li><li><strong>Outcome</strong>: You can query “which endpoints log ERROR most often?” and pivot on request parameters.</li></ul><h3>3.3 User Activity (Google Analytics)</h3><ul><li><strong>Setup</strong>: Add the GA4 snippet to your frontend (or server‑side track events via Measurement Protocol).</li><li><strong>Outcome</strong>: Understand user flows, drop‑off points, and conversion funnels.</li></ul><h3>3.4 Platform Performance (New Relic)</h3><ul><li><strong>Setup</strong>: Install the New Relic agent in your Python process, set your license key.</li><li><strong>Outcome</strong>: Get out‑of‑the‑box APM dashboards showing throughput, transaction traces, database query times.</li></ul><h3>4. Case Study: Prometheus &amp; Grafana on Dockerized DRF</h3><p>Here’s how I wired up Prometheus + Grafana to my Django REST Framework app in Docker. Within minutes I had real‑time metrics flowing.</p><h3>4.1 Docker‑Compose Overview</h3><pre>$ docker ps -a<br>CONTAINER ID   IMAGE                                STATUS       PORTS<br>f50d645d10eb   myapp-be-staging:latest             Up 37h       8001→8000<br>27a244b363cd   prom/prometheus                     Up 7h        9090→9090<br>b3bce01bde5a   grafana/grafana                     Up 6d        3002→3000<br>…</pre><h3>4.2 Prometheus Configuration (prometheus.yml)</h3><pre>global:<br>  scrape_interval: 15s<br>scrape_configs:<br>  - job_name: &#39;prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9090&#39;]<br>- job_name: &#39;singawas-be-production&#39;<br>    metrics_path: /metrics/<br>    static_configs:<br>      - targets: [&#39;myapp-be-production:8000&#39;]<br>  - job_name: &#39;singawas-be-dev&#39;<br>    metrics_path: /metrics/<br>    static_configs:<br>      - targets: [&#39;myapp-be-staging:8000&#39;]<br>  - job_name: &#39;singawas-fe&#39;<br>    static_configs:<br>      - targets: [&#39;myapp:3000&#39;]<br>remote_write:<br>  - url: https://your-remote-write-endpoint<br>    basic_auth:<br>      username: ***<br>      password: ***<br>    proxy_url: ***</pre><blockquote><strong><em>What this shows:</em></strong></blockquote><blockquote>Two back‑end jobs (production &amp; staging) scraping /metrics/ from DRF’s Prometheus exporter</blockquote><blockquote>Front‑end jobs to track overall request counts (if instrumented)</blockquote><blockquote>Remote write to a central metrics store</blockquote><h3>4.3 Grafana Dashboard Highlights</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TndsO9io1N2RvbgRBFGNHw.png" /><figcaption>Dashboard ID: 9528 by <a href="https://grafana.com/orgs/paskal">Dmitry Verhoturov</a></figcaption></figure><ul><li>Below are the panels from your “Simple Django” and “Django” dashboards, with the PromQL (or concept) behind each and why it matters.</li></ul><h4>1. Total Requests</h4><ul><li><strong>What</strong>: total HTTP requests per second (or minute) across all endpoints</li><li><strong>PromQL</strong>:</li></ul><pre>sum(rate(http_requests_total[1m]))</pre><ul><li><strong>Why</strong>: baseline throughput — spikes may indicate heavy load or abuse.</li></ul><h4>2. 2XX / 4XX / 5XX Responses</h4><ul><li><strong>What</strong>: break‑out of successful vs. client‑error vs. server‑error rates</li><li><strong>PromQL </strong>:</li></ul><pre>sum(rate(http_requests_total{status=~&quot;2..&quot;}[1m])) <br>sum(rate(http_requests_total{status=~&quot;4..&quot;}[1m])) <br>sum(rate(http_requests_total{status=~&quot;5..&quot;}[1m]))</pre><ul><li><strong>Why</strong>: rising 4XX might signal bad client calls; rising 5XX is a server‑failure alert.</li></ul><h4>3. Request Latency (p50, p95, p99)</h4><ul><li><strong>What</strong>: distribution of request durations</li><li><strong>PromQL</strong>:</li></ul><pre>histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) <br>histogram_quantile(0.95, …) <br>histogram_quantile(0.99, …)</pre><ul><li><strong>Why</strong>: p95/p99 show your “tail latency” — critical for SLAs and user experience.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0Il2jTzLVZir2EMoegbTg.png" /></figure><h4>4. CPU Usage</h4><ul><li><strong>What</strong>: CPU seconds consumed per second by your app containers</li><li><strong>PromQL</strong> (example):</li></ul><pre>rate(container_cpu_usage_seconds_total{container=&quot;myapp-be-staging&quot;}[1m])</pre><ul><li><strong>Why</strong>: sudden jumps can indicate inefficient code paths or traffic storms.</li></ul><h4>5. Virtual Memory</h4><ul><li><strong>What</strong>: memory footprint of your Django process</li><li><strong>PromQL</strong> (example):</li></ul><pre>container_memory_working_set_bytes{container=&quot;myapp-be-staging&quot;}</pre><ul><li><strong>Why</strong>: creeping memory use may herald a leak.</li></ul><h4>6. By Endpoint</h4><ul><li><strong>What</strong>: request count per route (e.g. /api/v1/orders/)</li><li><strong>PromQL</strong>:</li></ul><pre>sum(rate(http_requests_total[1m])) by (handler)</pre><ul><li><strong>Why</strong>: identifies your hottest endpoints; focus optimization where it counts.</li></ul><h4>7. Uptime (“up” metric)</h4><ul><li><strong>What</strong>: whether Prometheus can scrape each target (1 = up, 0 = down)</li><li><strong>PromQL</strong>:</li></ul><pre>up{job=&quot;singawas-be-production&quot;}</pre><ul><li><strong>Why</strong>: instant red/green health indicator.</li></ul><h4>8. Transactions Per Minute (Backend insights)</h4><ul><li><strong>What</strong>: total “transactions” (Sentry APM spans) per minute</li><li><strong>Why</strong>: correlate to request load and error spikes.</li></ul><h4>9. p50 / p75 Duration (Backend insights)</h4><ul><li><strong>What</strong>: median and 75th‑percentile transaction duration from Sentry APM</li><li><strong>Why</strong>: complements Prometheus histograms with end‑to‑end tracing data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/962f5e7809477ed2d657131f3b1e9050/href">https://medium.com/media/962f5e7809477ed2d657131f3b1e9050/href</a></iframe><h3>5. Advanced Usage: Alerts &amp; Custom Dashboards</h3><h4>5.1 Alerting with Prometheus</h4><pre>groups:<br>- name: app-alerts<br>  rules:<br>  - alert: HighErrorRate<br>    expr: increase(http_requests_total{status=~&quot;5..&quot;}[5m]) &gt; 5<br>    for: 2m<br>    labels:<br>      severity: critical<br>    annotations:<br>      summary: &quot;High 5xx error rate detected&quot;<br>      description: &quot;More than 5 server errors in the last 5 minutes.&quot;</pre><ul><li><strong>Route</strong> to Slack, email, or PagerDuty via Alertmanager</li><li><strong>Benefit</strong>: Your team wakes up before customers do.</li></ul><h4>5.2 Grafana Alerts</h4><ul><li>Define thresholds on latency panels (e.g. p95 &gt; 500 ms)</li><li>Trigger notifications to Microsoft Teams, OpsGenie, etc.</li></ul><h4>5.3 Custom Dashboards</h4><ul><li>Blend Sentry error counts with Prometheus metrics</li><li>Overlay user‑flow drop‑offs (GA) on performance graphs</li><li>Build “service health” views for on‑call engineers</li></ul><h3>6. Putting It All Together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa7df3b1fa6fcb4b896d26b24b61f01/href">https://medium.com/media/6aa7df3b1fa6fcb4b896d26b24b61f01/href</a></iframe><p>By closing the loop — from zero visibility to full‑stack observability — you ensure your application is resilient and your team is empowered to act.</p><h3>Next Steps</h3><ol><li><strong>Expand</strong> your custom metrics (database pool usage, cache hit rates)</li><li><strong>Automate</strong> on‑call runbooks via alert annotations</li><li><strong>Correlate</strong> logs, traces (Jaeger), and metrics for distributed tracing</li><li><strong>Share</strong> dashboards with stakeholders for data‑driven decision making</li></ol><p>With this foundation, you’ve transformed raw data into actionable insights — making performance, reliability, and user satisfaction a continuous, measurable journey.</p><p><em>Enjoyed this guide? If you try these steps in your own project, drop a comment or share your Grafana dashboards!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ea432f2d308" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/ambatuscrum-9-monitorama-taming-your-django-dragons-9ea432f2d308">Ambatuscrum #9: Monitorama: Taming Your Django Dragons</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[Ambatuscrum #8: Mastering Test Isolation with Mocks, Stubs, and Beyond!]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-8-mastering-test-isolation-with-mocks-stubs-and-beyond-880bf5e8b622?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/880bf5e8b622</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[stub]]></category>
            <category><![CDATA[mock]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Fri, 02 May 2025 19:03:26 GMT</pubDate>
            <atom:updated>2025-05-02T19:03:26.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OvrRB0eG31kYRzOC" /><figcaption>Photo by <a href="https://unsplash.com/@mufidpwt?utm_source=medium&amp;utm_medium=referral">Mufid Majnun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Testing is the backbone of reliable software development. It ensures that your code works as expected and remains maintainable as your application grows. In this blog, we’ll explore the concept of <strong>test isolation</strong> and how tools like mocks, stubs, and spies can help achieve it. We’ll also dive into real-world examples from a React-based project using <strong>Vitest</strong>, <strong>React Testing, </strong>and <strong>Library.</strong></p><h3>Testing Tools in Your Codebase</h3><p>This project uses <strong>Vitest</strong> as the primary testing framework, along with supporting libraries like <strong>React Testing Library</strong> and <strong>MockAdapter</strong>. These tools provide a robust environment for writing, running, and maintaining tests. Let’s dive into how these tools are used and how you can leverage them effectively.</p><h4>Vitest: The Core Testing Framework</h4><p>Vitest is a fast and modern testing framework designed for JavaScript and TypeScript projects. It integrates seamlessly with Vite, making it an excellent choice for your React-based project.</p><h4>Key Features of Vitest</h4><ul><li><strong>Fast Execution</strong>: Optimized for speed, especially in Vite projects.</li><li><strong>TypeScript Support</strong>: Built-in support for TypeScript.</li><li><strong>Mocking and Spying</strong>: Provides utilities like vi.mock and vi.spyOn.</li><li><strong>Coverage Reporting</strong>: Generates detailed test coverage reports.</li><li><strong>Snapshot Testing</strong>: Supports snapshot testing for React components.</li></ul><h4>How to Run Tests</h4><p>To run tests in your project, use the following commands:</p><ol><li><strong>Run All Tests</strong>:</li></ol><pre>npm run test</pre><p>This runs all test files matching the pattern defined in your vitest.config.js.</p><p><strong>2. Run Tests in Watch Mode</strong>:</p><pre>npm run test:ui</pre><p>This opens the Vitest UI, allowing you to run tests interactively and view results in real-time.</p><p><strong>3. Run Tests with Coverage</strong>:</p><pre>npm run coverage</pre><p>This generates a coverage report, showing which parts of your code are covered by tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ivlNpfW0uYATRH-.png" /><figcaption><a href="https://v1.vitest.dev/guide/coverage">https://v1.vitest.dev/guide/coverage</a></figcaption></figure><h3>Understanding Test Isolation</h3><p>Test isolation is a critical concept in software testing. It ensures that each test runs independently, without being affected by the state or behavior of other tests. This independence is vital for maintaining reliable and maintainable test suites. When tests are isolated, debugging becomes easier, and the risk of flaky tests is minimized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*CBCm8UrmPSdbaGiD.jpg" /><figcaption><a href="https://marabesi.com/software-engineering/mocks-dummies-spies-fakes-testing-your-code.html">Mocks, dummies, spies, fakes — testing your code</a></figcaption></figure><h3>Understanding Test Doubles: Mocks, Stubs, Spies, Fakes, and Dummies</h3><p>In software testing, <strong>test doubles</strong> are objects or functions that stand in for real components to isolate the unit under test. They help simulate various scenarios, control dependencies, and verify interactions. Let’s break down the key types of test doubles and their importance in achieving test isolation.</p><p>Key components of test doubles include:</p><ul><li><strong>Mocks</strong>: Simulate dependencies.</li><li><strong>Stubs</strong>: Replace methods with predefined behavior.</li><li><strong>Spies</strong>: Observe function calls and arguments.</li><li><strong>Fakes</strong>: lightweight implementations of complex systems</li></ul><h3>Mocks: Simulating Dependencies</h3><p>Mocks are used to simulate the behavior of real objects. They allow you to test how your code interacts with dependencies without relying on their actual implementations.</p><p><strong>Example: Mocking API Calls</strong></p><pre>const mockAxios = new MockAdapter(axios)<br>  mockAxios.onPost(&#39;/admin-auth/login/&#39;).reply(200, {<br>  access_token: &#39;test-access-token&#39;,<br>  refresh_token: &#39;test-refresh-token&#39;,<br>})</pre><p>This mock ensures that API calls return predefined responses, enabling you to test login functionality without hitting the actual server.</p><h4>Mocks in Action</h4><p>Mocks are extensively used in your codebase to simulate external dependencies.</p><p><strong>Example</strong>: Mocking API calls in authService.test.ts.</p><pre>vi.mock(&#39;axios&#39;, () =&gt; ({<br>  default: {<br>    post: vi.fn(),<br>    get: vi.fn(),<br>  },<br>}));<br><br>it(&#39;should fetch user profile successfully&#39;, async () =&gt; {<br>  const mockUserProfile = { name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; };<br>  vi.mocked(axios.get).mockResolvedValueOnce({ data: mockUserProfile });<br><br>  const result = await getUserProfile();<br><br>  expect(axios.get).toHaveBeenCalledWith(&#39;/auth/self/&#39;);<br>  expect(result).toEqual(mockUserProfile);<br>});</pre><p>This test ensures that the getUserProfile function behaves correctly when the API returns a successful response.</p><h3>Stubs: Controlling Behavior</h3><p>Stubs replace methods or functions with predefined behavior, allowing you to control how dependencies behave during tests.</p><p><strong>Key Features</strong>:</p><ul><li>Focus on controlling behavior.</li><li>Provide predefined outputs for testing.</li></ul><p><strong>Example: Stubbing </strong><strong>sessionStorage</strong></p><pre>const mockSessionStorage = {<br>  getItem: vi.fn(),<br>  setItem: vi.fn(),<br>  removeItem: vi.fn(),<br>  clear: vi.fn(),<br>}<br><br>Object.defineProperty(window, &#39;sessionStorage&#39;, { value: mockSessionStorage })</pre><p>This stub replaces the browser’s sessionStoragewith a mock implementation, enabling you to test token management without relying on the actual storage.</p><h4>Stubs in Action</h4><p>Stubs are used to control the behavior of specific methods.</p><p><strong>Example</strong>: Stubbing sessionStorage in storage.test.tsx.</p><pre>const mockSessionStorage = {<br>  getItem: vi.fn(() =&gt; &#39;mock-token&#39;),<br>  setItem: vi.fn(),<br>  removeItem: vi.fn(),<br>};<br>Object.defineProperty(window, &#39;sessionStorage&#39;, { value: mockSessionStorage });<br><br>it(&#39;sets access token correctly&#39;, () =&gt; {<br>  setToken(&#39;test-token&#39;);<br>  expect(mockSessionStorage.setItem).toHaveBeenCalledWith(&#39;access_token&#39;, &#39;test-token&#39;);<br>});</pre><p>This test verifies that the setToken function correctly stores the access token in sessionStorage.</p><h3>Spies: Observing Behavior</h3><p>Spies are used to observe and verify the behavior of real or mocked functions. They allow you to:</p><ul><li>Verify how many times a function was called.</li><li>Check the arguments passed to the function.</li></ul><p><strong>Key Features</strong>:</p><ul><li>Monitor real or mocked functions.</li><li>Verify side effects.</li></ul><p><strong>Example: Spying on </strong><strong>console.error</strong></p><pre>const consoleSpy = vi.spyOn(console, &#39;error&#39;).mockImplementation(() =&gt; {})<br>setToken(&#39;test-token&#39;)<br>expect(consoleSpy).toHaveBeenCalledWith(&#39;Error setting access token:&#39;, expect.any(Error))</pre><p>This spy verifies that errors are logged correctly when setting a token fails.</p><h4>Spies in Action</h4><p>Spies are used to observe function calls and arguments.</p><p><strong>Example</strong>: Spying on console.error in storage.test.tsx.</p><pre>const consoleSpy = vi.spyOn(console, &#39;error&#39;).mockImplementation(() =&gt; {});<br><br>it(&#39;handles exceptions when setting access token&#39;, () =&gt; {<br>  vi.mocked(mockSessionStorage.setItem).mockImplementationOnce(() =&gt; {<br>    throw new Error(&#39;Storage full&#39;);<br>  });<br><br>  setToken(&#39;test-token&#39;);<br><br>  expect(consoleSpy).toHaveBeenCalledWith(&#39;Error setting access token:&#39;, expect.any(Error));<br>});</pre><p>This test ensures that errors are logged when sessionStorage operations fail.</p><h4>Fakes</h4><p>Fakes are lightweight implementations of complex systems. They mimic the behavior of real systems but are simpler and faster.</p><p><strong>Key Features</strong>:</p><ul><li>Provide a simplified version of a real system.</li><li>Useful for simulating production-like behavior.</li></ul><p><strong>Example</strong>: An in-memory database or a fake API server.</p><h4>Dummies</h4><p>Dummies are placeholders for objects that are not actively used in the test. They are often used to satisfy function signatures.</p><p><strong>Key Features</strong>:</p><ul><li>Simplify test setup.</li><li>Do not affect the test outcome.</li></ul><p><strong>Example</strong>: Passing an empty object as a placeholder.</p><pre>const dummyUser = { id: null, name: &#39;&#39; };</pre><h4>Resetting State Between Tests</h4><p>To ensure test isolation, it’s essential to reset shared state and mocks between tests.</p><p><strong>Example: Clearing Mocks</strong></p><pre>beforeEach(() =&gt; {<br>  vi.clearAllMocks()<br>  mockSessionStorage.clear()<br>})</pre><p>This ensures that each test starts with a clean slate, preventing state leakage.</p><p><strong>Example: Restoring Mocks</strong><br>In jwt.test.tsx, mocks are restored after each test:</p><pre>afterEach(() =&gt; {<br>  vi.restoreAllMocks()<br>})</pre><p>This ensures that any modifications to mocked functions are reverted after each test.</p><h4>Advanced Mocking Techniques</h4><p>Mocking external libraries and React components can further isolate tests.</p><p><strong>Example: Mocking External Libraries</strong><br>In authService.test.ts, axios is mocked:</p><pre>vi.mock(&#39;axios&#39;, () =&gt; ({<br>  default: {<br>    post: vi.fn(),<br>    get: vi.fn(),<br>  },<br>}))</pre><p>This replaces axios methods with spies, allowing you to test how your code interacts with the library without making real network requests.</p><p><strong>Example: Mocking React Components</strong><br>In DetailUjian.test.tsx, the CardDetailUjian component is mocked:</p><pre>vi.mock(&#39;../../components/elements/Card/CardDetailUjian&#39;, () =&gt; ({<br>  default: () =&gt; &lt;div data-testid=&quot;card-detail-ujian&quot;&gt;Mocked Card&lt;/div&gt;,<br>}))</pre><p>This mock replaces the CardDetailUjian component with a simplified version, allowing you to focus on testing the parent component.</p><h4>Integration Scenarios</h4><p>Integration tests simulate real-world scenarios to ensure that multiple components work together as expected.</p><p><strong>Example: Simulating a Token Lifecycle</strong></p><p>In jwt.test.tsx, token-related utilities are tested:</p><pre>mockSessionStorage.setItem(&#39;access_token&#39;, validToken)<br>expect(isTokenValid()).toBe(true)<br>expect(getUserRole()).toBe(&#39;pengawas&#39;)</pre><p>This test verifies the behavior of token-related utilities throughout their lifecycle.</p><p><strong>Example: Testing Navigation and Routing</strong><br>In ProtectedRoute.test.tsx, navigation and routing are tested:</p><pre>render(<br>  &lt;MemoryRouter initialEntries={[&#39;/protected&#39;]}&gt;<br>    &lt;Routes&gt;<br>      &lt;Route path=&quot;/&quot; element={&lt;HomePage /&gt;} /&gt;<br>      &lt;Route element={&lt;ProtectedRoute allowedRoles={[&#39;admin&#39;]} /&gt;}&gt;<br>        &lt;Route path=&quot;/protected&quot; element={&lt;ProtectedContent /&gt;} /&gt;<br>      &lt;/Route&gt;<br>    &lt;/Routes&gt;<br>  &lt;/MemoryRouter&gt;<br>)</pre><p>This ensures that the ProtectedRoute component correctly restricts access based on user roles.</p><h4>Error Handling in Tests</h4><p>Testing error scenarios ensures that your application handles failures gracefully.</p><p><strong>Example: Mocking API Failures</strong></p><p>In administration.test.ts, API failures are mocked:</p><pre>mockAxios.onPost(&#39;/admin-auth/login/&#39;).reply(401, { error: &#39;Invalid credentials&#39; })<br>await expect(loginAdmin(&#39;testuser&#39;, &#39;wrongpassword&#39;)).rejects.toThrow(&#39;Invalid credentials&#39;)</pre><p>This test verifies that the application handles login failures correctly.</p><p><strong>Example: Handling Exceptions in </strong>sessionStorage<br>In storage.test.tsx, sessionStorage exceptions are handled:</p><pre>vi.mocked(mockSessionStorage.setItem).mockImplementationOnce(() =&gt; {<br>  throw new Error(&#39;Storage full&#39;)<br>})<br>setToken(&#39;test-token&#39;)<br>expect(consoleSpy).toHaveBeenCalledWith(<br>  &#39;Error setting access token:&#39;,<br>  expect.any(Error)<br>)</pre><p>This ensures that the application logs errors when sessionStorageoperations fail.</p><h3>Combining Test Doubles: A Comprehensive Test</h3><p>Let’s create a comprehensive test that combines mocks, stubs, and spies to test a login flow.</p><p><strong>Scenario</strong>: Testing the login functionality with error handling.</p><pre>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import { describe, it, expect, vi } from &#39;vitest&#39;;<br>import Login from &#39;../../components/Login&#39;;<br>import { loginAdmin } from &#39;../../api/services/administration&#39;;<br>import { toast } from &#39;react-toastify&#39;;<br><br>vi.mock(&#39;../../api/services/administration&#39;, () =&gt; ({<br>  loginAdmin: vi.fn(),<br>}));<br><br>vi.mock(&#39;react-toastify&#39;, () =&gt; ({<br>  toast: {<br>    success: vi.fn(),<br>    error: vi.fn(),<br>  },<br>}));<br><br>describe(&#39;Login Component&#39;, () =&gt; {<br>  it(&#39;handles successful login&#39;, async () =&gt; {<br>    // Mock successful login response<br>    vi.mocked(loginAdmin).mockResolvedValueOnce({ token: &#39;test-token&#39; });<br><br>    render(&lt;Login /&gt;);<br><br>    // Simulate user input<br>    fireEvent.change(screen.getByPlaceholderText(&#39;Username&#39;), { target: { value: &#39;testuser&#39; } });<br>    fireEvent.change(screen.getByPlaceholderText(&#39;Password&#39;), { target: { value: &#39;password&#39; } });<br><br>    // Simulate form submission<br>    fireEvent.click(screen.getByText(&#39;Login&#39;));<br><br>    // Wait for the API call<br>    await waitFor(() =&gt; {<br>      expect(loginAdmin).toHaveBeenCalledWith(&#39;testuser&#39;, &#39;password&#39;);<br>      expect(toast.success).toHaveBeenCalledWith(&#39;Login successful!&#39;);<br>    });<br>  });<br><br>  it(&#39;handles login failure&#39;, async () =&gt; {<br>    // Mock failed login response<br>    vi.mocked(loginAdmin).mockRejectedValueOnce(new Error(&#39;Invalid credentials&#39;));<br><br>    render(&lt;Login /&gt;);<br><br>    // Simulate user input<br>    fireEvent.change(screen.getByPlaceholderText(&#39;Username&#39;), { target: { value: &#39;testuser&#39; } });<br>    fireEvent.change(screen.getByPlaceholderText(&#39;Password&#39;), { target: { value: &#39;wrongpassword&#39; } });<br><br>    // Simulate form submission<br>    fireEvent.click(screen.getByText(&#39;Login&#39;));<br><br>    // Wait for the API call<br>    await waitFor(() =&gt; {<br>      expect(loginAdmin).toHaveBeenCalledWith(&#39;testuser&#39;, &#39;wrongpassword&#39;);<br>      expect(toast.error).toHaveBeenCalledWith(&#39;Invalid credentials&#39;);<br>    });<br>  });<br>});</pre><h3>Steps to Create a Comprehensive Test</h3><ol><li><strong>Mock External Dependencies</strong>: Use mocks to simulate API calls or external libraries.</li><li><strong>Stub Internal Methods</strong>: Replace specific methods with controlled behavior.</li><li><strong>Spy on Functions</strong>: Observe and verify function calls and arguments.</li><li><strong>Combine Test Doubles</strong>: Use mocks, stubs, and spies together to test complex scenarios.</li><li><strong>Reset State</strong>: Use beforeEach and afterEach hooks to reset mocks and stubs between tests.</li></ol><h3>Developing Tests with AI Assistance: Optimizing Your Workflow</h3><p>AI tools, like GitHub Copilot or ChatGPT, can significantly enhance your testing workflow by helping you write, refactor, and optimize test cases. By structuring your prompts effectively and leveraging AI’s capabilities, you can save time and improve the quality of your tests. This section focuses on how to use AI to develop tests, optimize code, and integrate test doubles like mocks, stubs, spies, fakes, and dummies.</p><h3>How AI Can Help in Writing Tests</h3><p>AI can assist in:</p><ol><li><strong>Generating Test Cases</strong>: Writing boilerplate test cases based on your code.</li><li><strong>Refactoring Tests</strong>: Improving the readability and maintainability of existing tests.</li><li><strong>Suggesting Test Doubles</strong>: Recommending when and how to use mocks, stubs, spies, fakes, or dummies.</li><li><strong>Improving Coverage</strong>: Identifying untested parts of your code and suggesting test cases.</li><li><strong>Debugging Tests</strong>: Analyzing failing tests and suggesting fixes.</li></ol><h3>How to Structure Prompts for AI</h3><p>To get the most out of AI, structure your prompts clearly and provide enough context. Here are some examples:</p><h4>1. Generate a Test Case</h4><p><strong>Prompt Structure</strong>:</p><ul><li>Describe the function or component you want to test.</li><li>Specify the behavior or scenario you want to cover.</li><li>Mention the testing framework and tools you are using.</li></ul><p><strong>Example Prompt</strong>:</p><blockquote>“Write a test case for a loginAdmin function that sends a POST request to /api/login and returns a token. Use Vitest and MockAdapter to mock the API call.&quot;</blockquote><p><strong>AI-Generated Output</strong>:</p><pre>import MockAdapter from &#39;axios-mock-adapter&#39;;<br>import axios from &#39;axios&#39;;<br>import { loginAdmin } from &#39;../../api/services/administration&#39;;<br><br>const mockAxios = new MockAdapter(axios);<br><br>it(&#39;should return a token on successful login&#39;, async () =&gt; {<br>  mockAxios.onPost(&#39;/api/login&#39;).reply(200, { token: &#39;test-token&#39; });<br><br>  const result = await loginAdmin(&#39;testuser&#39;, &#39;password&#39;);<br><br>  expect(result).toEqual({ token: &#39;test-token&#39; });<br>  expect(mockAxios.history.post[0].data).toContain(&#39;testuser&#39;);<br>});</pre><h4>2. Refactor an Existing Test</h4><p><strong>Prompt Structure</strong>:</p><ul><li>Paste the test code you want to refactor.</li><li>Specify what you want to improve (e.g., readability, maintainability, or performance).</li></ul><p><strong>Example Prompt</strong>:</p><blockquote><em>“Refactor this test to make it more readable and reusable. Use React Testing Library and Vitest.”</em></blockquote><p><strong>Input Code</strong>:</p><pre>it(&#39;renders the login form and handles submission&#39;, () =&gt; {<br>  render(&lt;Login /&gt;);<br>  fireEvent.change(screen.getByPlaceholderText(&#39;Username&#39;), { target: { value: &#39;testuser&#39; } });<br>  fireEvent.change(screen.getByPlaceholderText(&#39;Password&#39;), { target: { value: &#39;password&#39; } });<br>  fireEvent.click(screen.getByText(&#39;Login&#39;));<br>  expect(screen.getByText(&#39;Logging in...&#39;)).toBeInTheDocument();<br>});</pre><p><strong>AI-Generated Output</strong>:</p><pre>const fillLoginForm = (username, password) =&gt; {<br>  fireEvent.change(screen.getByPlaceholderText(&#39;Username&#39;), { target: { value: username } });<br>  fireEvent.change(screen.getByPlaceholderText(&#39;Password&#39;), { target: { value: password } });<br>};<br><br>it(&#39;renders the login form and handles submission&#39;, () =&gt; {<br>  render(&lt;Login /&gt;);<br>  fillLoginForm(&#39;testuser&#39;, &#39;password&#39;);<br>  fireEvent.click(screen.getByText(&#39;Login&#39;));<br>  expect(screen.getByText(&#39;Logging in...&#39;)).toBeInTheDocument();<br>});</pre><h4>3. Suggest Test Doubles</h4><p><strong>Prompt Structure</strong>:</p><ul><li>Describe the dependency or behavior you want to isolate.</li><li>Specify the type of test double you want to use (mock, stub, spy, etc.).</li></ul><p><strong>Example Prompt</strong>:</p><blockquote><em>“Suggest a test double for mocking an API call in a </em><em>fetchUserProfile function. Use Vitest and MockAdapter.&quot;</em></blockquote><p><strong>AI-Generated Output</strong>:</p><pre>import MockAdapter from &#39;axios-mock-adapter&#39;;<br>import axios from &#39;axios&#39;;<br>import { fetchUserProfile } from &#39;../../api/services/user&#39;;<br><br>const mockAxios = new MockAdapter(axios);<br><br>it(&#39;should fetch user profile successfully&#39;, async () =&gt; {<br>  const mockProfile = { name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; };<br>  mockAxios.onGet(&#39;/api/user/profile&#39;).reply(200, mockProfile);<br><br>  const result = await fetchUserProfile();<br><br>  expect(result).toEqual(mockProfile);<br>  expect(mockAxios.history.get[0].url).toBe(&#39;/api/user/profile&#39;);<br>});</pre><h4>4. Improve Coverage</h4><p><strong>Prompt Structure</strong>:</p><ul><li>Provide the function or component code.</li><li>Ask for test cases to cover edge cases or untested scenarios.</li></ul><p><strong>Example Prompt</strong>:</p><blockquote><em>“Suggest test cases for this </em><em>calculateDiscount function to improve coverage.&quot;</em></blockquote><p><strong>Input Code</strong>:</p><pre>function calculateDiscount(price, discount) {<br>  if (price &lt;= 0 || discount &lt; 0) {<br>    throw new Error(&#39;Invalid input&#39;);<br>  }<br>  return price - (price * discount) / 100;<br>}</pre><p><strong>AI-Generated Output</strong>:</p><pre>it(&#39;should calculate the correct discount&#39;, () =&gt; {<br>  expect(calculateDiscount(100, 10)).toBe(90);<br>});<br><br>it(&#39;should throw an error for negative price&#39;, () =&gt; {<br>  expect(() =&gt; calculateDiscount(-100, 10)).toThrow(&#39;Invalid input&#39;);<br>});<br><br>it(&#39;should throw an error for negative discount&#39;, () =&gt; {<br>  expect(() =&gt; calculateDiscount(100, -10)).toThrow(&#39;Invalid input&#39;);<br>});<br><br>it(&#39;should return the original price for 0% discount&#39;, () =&gt; {<br>  expect(calculateDiscount(100, 0)).toBe(100);<br>});</pre><h4>5. Debug a Failing Test</h4><p><strong>Prompt Structure</strong>:</p><ul><li>Paste the failing test and the error message.</li><li>Ask for suggestions to fix the issue.</li></ul><p><strong>Example Prompt</strong>:</p><blockquote><em>“This test is failing with a </em><em>TypeError: Cannot read property &#39;data&#39; of undefined. Suggest a fix.&quot;</em></blockquote><p><strong>Input Code</strong>:</p><pre>it(&#39;should fetch user profile&#39;, async () =&gt; {<br>  vi.mocked(axios.get).mockResolvedValueOnce(undefined);<br>  const result = await fetchUserProfile();<br>  expect(result).toEqual({ name: &#39;John Doe&#39; });<br>});</pre><p><strong>AI-Generated Output</strong>:</p><pre>// Fix: Ensure the mocked response includes a `data` property<br>vi.mocked(axios.get).mockResolvedValueOnce({ data: { name: &#39;John Doe&#39; } });</pre><h4>Conclusion</h4><p>By mastering test isolation with mocks, stubs, and spies, you can write reliable and maintainable tests. These techniques ensure that your tests are independent, predictable, and easy to debug. Start applying these practices in your projects today!</p><blockquote>References:</blockquote><blockquote><a href="https://marabesi.com/software-engineering/mocks-dummies-spies-fakes-testing-your-code.html">Mocks, dummies, spies, fakes — testing your code</a></blockquote><blockquote><a href="https://stackoverflow.com/questions/3459287/whats-the-difference-between-a-mock-stub">testing — What’s the difference between a mock &amp; stub? — Stack Overflow</a></blockquote><blockquote><a href="https://medium.com/@julius.prayoga/mock-stub-e7c0eaa801bf">A Guide to Mocking and Stubbing in Software Development | by Julius Raka | Medium</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880bf5e8b622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #7: Avoiding Analysis Paralysis in Vite + React]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-7-avoiding-analysis-paralysis-in-vite-react-137db73de3a2?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/137db73de3a2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[sonarqube]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 18:50:08 GMT</pubDate>
            <atom:updated>2025-04-09T18:50:08.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ACUMiWfRpAkwQk5U" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In software development, maintaining high-quality code is essential for scalability, maintainability, and performance. However, with the abundance of tools like <strong>SonarCloud</strong>, <strong>Code Climate</strong>, <strong>ESLint</strong>, and <strong>Prettier</strong>, teams can sometimes feel overwhelmed by the sheer volume of metrics and reports. This can lead to “analysis paralysis,” where actionable insights are lost in the noise.</p><p>In this blog, I’ll share how we implemented <strong>Quality Assurance (QA)</strong> practices in the <strong>SiNgawas</strong> project — a Vite + React frontend for an all-in-one exam proctoring system. By leveraging tools like <strong>SonarCloud</strong>, <strong>Vitest</strong>, <strong>ESLint</strong>, and <strong>Prettier</strong>, we ensured a structured, measurable, and impactful QA process.</p><h3>Outline</h3><h3>1. Explaining QA in Development</h3><ul><li>Identifying issues with static analysis tools</li><li>Fixing issues with actionable commits</li></ul><h3>2. Structured and Measurable QA Practices</h3><ul><li>Guarding CI/CD pipelines with SonarCloud</li><li>Enforcing 100% code coverage with Vitest</li></ul><h3>3. Using Additional Tools for Quality Analysis</h3><ul><li>Profiling with ESLint and Prettier</li><li>Measuring performance impact</li></ul><h3>1. Explaining QA in Development</h3><h4>Identifying Issues with Static Analysis Tools</h4><p>We used <strong>SonarCloud</strong> to identify bugs, vulnerabilities, and code smells in the project. For example, during an early scan, SonarCloud flagged several maintainability issues, such as unused variables and overly complex functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYflasxTpBxjotj-fQ5Beg.png" /><figcaption>My SonarQube Dashboard</figcaption></figure><h4>What SonarCloud Does</h4><p>SonarCloud is a cloud-based static analysis tool that scans your codebase for:</p><ol><li><strong>Security Vulnerabilities</strong>: Detects potential security risks, such as SQL injection, cross-site scripting (XSS), and hardcoded credentials.</li><li><strong>Code Smells</strong>: Highlights maintainability issues, such as overly complex functions, duplicated code, or unused variables.</li><li><strong>Bugs</strong>: Identifies logical errors that could lead to runtime crashes or unexpected behavior.</li><li><strong>Test Coverage</strong>: Measures how much of your code is covered by automated tests.</li></ol><h4>How SonarCloud Works</h4><p>SonarCloud uses a set of predefined <strong>rules</strong> for each programming language. These rules are categorized into:</p><ul><li><strong>Security Hotspots</strong>: Areas of code that require manual review to ensure they are secure.</li><li><strong>Maintainability</strong>: Code smells that make the code harder to read or modify.</li><li><strong>Reliability</strong>: Bugs that could cause the application to fail.</li></ul><p>For example, in our <strong>SiNgawas</strong> project, SonarCloud flagged the following issues:</p><ul><li><strong>Security</strong>: Hardcoded API keys in a configuration file.</li><li><strong>Code Smell</strong>: A function with too many parameters, making it difficult to maintain.</li><li><strong>Bug</strong>: A missing return statement in a conditional branch.</li></ul><p>Here’s an example of a flagged issue:</p><pre>export const API_KEY = &#39;hardcoded-key&#39; // Security issue flagged by SonarCloud</pre><p>Here’s an example of an issue flagged by SonarCloud:</p><pre>const EditableField: React.FC&lt;EditableFieldProps&gt; = ({<br>  label,<br>  value,<br>  isEditing,<br>  onEdit,<br>  onAccept,<br>  onCancel,<br>  onChange,<br>  error,<br>}) =&gt; {<br>  // Unused variable flagged by SonarCloud<br>  const unusedVariable = &#39;This is not used anywhere&#39;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      {isEditing ? (<br>        &lt;input value={value} onChange={(e) =&gt; onChange(e.target.value)} /&gt;<br>      ) : (<br>        &lt;span&gt;{value}&lt;/span&gt;<br>      )}<br>      {error &amp;&amp; &lt;span className=&quot;error&quot;&gt;{error}&lt;/span&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Fixing Issues with Actionable Commits</h4><p>To address the issue, we removed the unused variable and committed the fix:</p><pre>const EditableField: React.FC&lt;EditableFieldProps&gt; = ({<br>  label,<br>  value,<br>  isEditing,<br>  onEdit,<br>  onAccept,<br>  onCancel,<br>  onChange,<br>  error,<br>}) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      {isEditing ? (<br>        &lt;input value={value} onChange={(e) =&gt; onChange(e.target.value)} /&gt;<br>      ) : (<br>        &lt;span&gt;{value}&lt;/span&gt;<br>      )}<br>      {error &amp;&amp; &lt;span className=&quot;error&quot;&gt;{error}&lt;/span&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><p><strong>Commit Message</strong>:</p><p>fix: remove unused variable flagged by SonarCloud</p><p>This process of identifying and fixing issues ensures that the codebase remains clean and maintainable.</p><h3>2. Structured and Measurable QA Practices</h3><h4>Guarding CI/CD Pipelines with SonarCloud</h4><p>SonarCloud allows you to define <strong>quality gates</strong>, which are a set of conditions that must be met before code can be merged. For the <strong>SiNgawas</strong> project, we configured the following quality gates:</p><ul><li><strong>Minimum test coverage</strong>: 100%</li><li><strong>No critical vulnerabilities</strong></li><li><strong>Maximum code duplication</strong>: 5%</li></ul><p>These gates ensure that no code is merged unless it meets specific quality standards</p><p>Here’s the relevant CI/CD configuration:</p><pre>sonar-analysis:<br>  stage: sonar-analysis<br>  script:<br>    - sonar-scanner -Dsonar.host.url=&quot;${SONAR_HOST_URL}&quot; -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info<br>  rules:<br>    - if: $CI_PIPELINE_SOURCE == &#39;merge_request_event&#39;<br>    - if: $CI_COMMIT_BRANCH == &#39;main&#39;</pre><p>This setup ensures that every merge request is automatically analyzed, and developers are notified of any issues before merging.</p><h4>Code Smells</h4><p>Code smells are maintainability issues that don’t necessarily cause bugs but make the code harder to understand or modify. Examples include:</p><ul><li>Functions with too many parameters.</li><li>Long methods that perform multiple tasks.</li><li>Unused variables or imports.</li></ul><p>By addressing code smells, we improved the readability and maintainability of the codebase.</p><h4>Why Test Coverage Matters</h4><p>Test coverage measures how much of your code is executed during automated tests. High coverage ensures that critical paths are tested, reducing the likelihood of bugs in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69v2VtW9Q9K6A5X5oLNKeg.png" /><figcaption>My Vitest dashboard</figcaption></figure><h4>Enforcing 100% Code Coverage with Vitest</h4><p>We used <strong>Vitest</strong> to enforce 100% test coverage. The configuration ensures that all critical components, pages, and utilities are covered:</p><pre>export default defineConfig({<br>  test: {<br>    coverage: {<br>      provider: &#39;v8&#39;,<br>      enabled: true,<br>      reportsDirectory: &#39;./coverage&#39;,<br>      include: [<br>        &#39;**/src/components/**&#39;,<br>        &#39;**/src/pages/**&#39;,<br>        &#39;**/src/hooks/**&#39;,<br>        &#39;**/src/utils/**&#39;,<br>        &#39;**/src/api/**&#39;,<br>      ],<br>      exclude: [<br>        &#39;**/*.d.ts&#39;,<br>        &#39;**/types/**&#39;,<br>        &#39;**/*.config.*&#39;,<br>        &#39;**/dist/**&#39;,<br>      ],<br>      reporter: [&#39;text&#39;, &#39;json&#39;, &#39;html&#39;, &#39;lcov&#39;],<br>    },<br>  },<br>})</pre><p>Here’s an example of a test for the ErrorBoundary component:</p><pre>describe(&#39;ErrorBoundary&#39;, () =&gt; {<br>  it(&#39;renders fallback UI on error&#39;, () =&gt; {<br>    render(<br>      &lt;ErrorBoundary&gt;<br>        &lt;ErrorThrowingComponent /&gt;<br>      &lt;/ErrorBoundary&gt;<br>    )<br>    expect(screen.getByText(&#39;Something went wrong.&#39;)).toBeInTheDocument()<br>  })<br>})</pre><p>This ensures that all critical paths are tested, and no untested code is deployed.</p><h4>Why Use Vitest Instead of Jest?</h4><p>When choosing a testing framework for a modern JavaScript or TypeScript project, <strong>Jest</strong> has long been the go-to solution due to its rich feature set, extensive ecosystem, and widespread adoption. However, <strong>Vitest</strong>, a newer testing framework, has gained significant traction, especially in projects using <strong>Vite</strong> as the build tool.</p><ul><li><strong>Native Integration with Vite</strong>: Vitest is designed to work seamlessly with <strong>Vite</strong>, the modern build tool that emphasizes speed and simplicity. This native integration provides several advantages:</li><li><strong>Shared Configuration</strong>: Vitest uses the same configuration as Vite, meaning you don’t need to duplicate settings for module resolution, aliases, or plugins.</li><li><strong>Faster Setup</strong>: Since Vitest is built on top of Vite, it eliminates the need for additional setup to handle modern JavaScript features like ES modules, TypeScript, and JSX.</li><li><strong>Hot Module Replacement (HMR)</strong>: Vitest leverages Vite’s HMR for instant feedback during test development, making it faster and more developer-friendly.</li></ul><p>In contrast, Jest requires additional configuration (e.g., babel-jest or ts-jest) to handle modern JavaScript features, which can slow down the setup process.</p><h3>3. Using Additional Tools for Quality Analysis</h3><h4>Profiling with ESLint and Prettier</h4><p>ESLint is a static analysis tool that enforces coding standards and identifies potential issues. For example, it flagged unused imports and inconsistent formatting in our codebase.</p><p>We used <strong>ESLint</strong> and <strong>Prettier</strong> to enforce consistent coding standards and identify potential issues during development.</p><h4>Why Use Prettier and ESLint Together?</h4><p>When working on modern JavaScript or TypeScript projects, maintaining consistent code style and catching potential issues early are critical for improving code quality and developer productivity. <strong>Prettier</strong> and <strong>ESLint</strong> are two popular tools that serve complementary purposes in this regard. Below, I’ll explain what each tool does, their differences, and why using both together is a best practice.</p><h3>What is Prettier?</h3><p><strong>Prettier</strong> is an opinionated code formatter that enforces a consistent style across your codebase. It automatically reformats your code based on predefined rules, ensuring that all developers on the team follow the same style guide.</p><h4>Key Features of Prettier:</h4><ol><li><strong>Automatic Formatting</strong>: Prettier reformats code to adhere to its rules (e.g., indentation, line breaks, spacing) without requiring manual intervention.</li><li><strong>Language Support</strong>: It supports a wide range of languages, including JavaScript, TypeScript, HTML, CSS, JSON, and more.</li><li><strong>Opinionated Rules</strong>: Prettier has a fixed set of rules (e.g., single quotes, trailing commas) that cannot be customized extensively, which reduces debates over style preferences.</li><li><strong>Focus on Style</strong>: Prettier only handles code formatting and does not analyze or lint for potential bugs or best practices.</li></ol><h4>Example of Prettier in Action:</h4><p>Before Prettier:</p><pre>function example (arg) { console.log(arg) }</pre><p>After Prettier:</p><pre>function example(arg) {<br>  console.log(arg);<br>}</pre><h3>What is ESLint?</h3><p><strong>ESLint</strong> is a static code analysis tool that identifies and fixes problems in your JavaScript or TypeScript code. It enforces coding standards, detects potential bugs, and ensures best practices are followed.</p><h4>Key Features of ESLint:</h4><ol><li><strong>Linting Rules</strong>: ESLint provides a wide range of customizable rules to enforce coding standards (e.g., no unused variables, no console logs in production).</li><li><strong>Error Detection</strong>: It identifies potential bugs, anti-patterns, and code smells.</li><li><strong>Customizability</strong>: ESLint rules can be tailored to your project’s needs, and you can extend it with plugins for frameworks like React, Vue, or Node.js.</li><li><strong>Code Fixing</strong>: ESLint can automatically fix certain issues (e.g., unused imports, missing semicolons) using the --fix flag.</li></ol><h4>Example of ESLint in Action:</h4><p>Code with an issue:</p><pre>const unusedVariable = 42; // ESLint flags this as an unused variable<br>console.log(&quot;Hello World&quot;);</pre><p>ESLint Output:</p><pre>1:7  warning  &#39;unusedVariable&#39; is defined but never used  no-unused-vars</pre><h3>Why Use Both Prettier and ESLint?</h3><p>While Prettier and ESLint overlap in some areas (e.g., formatting rules), they serve different purposes and complement each other. Here’s why using both is beneficial:</p><h4>1. Prettier for Style Consistency</h4><p>Prettier ensures that all code in the project follows a consistent style, regardless of who writes it. This eliminates debates over formatting preferences (e.g., tabs vs. spaces) and allows developers to focus on writing functional code.</p><h4>2. ESLint for Code Quality</h4><p>ESLint enforces coding standards, detects potential bugs, and ensures best practices are followed. It goes beyond formatting to analyze the logic and structure of your code.</p><h4>3. Avoiding Conflicts</h4><p>By using both tools together, you can let Prettier handle formatting and ESLint handle code quality. To avoid conflicts, you can use the <strong>eslint-config-prettier</strong> package, which disables ESLint rules that conflict with Prettier.</p><h4>4. Improved Developer Productivity</h4><p>With Prettier handling formatting and ESLint catching errors, developers spend less time on code reviews and manual corrections, leading to faster development cycles.</p><h3>How to Use Prettier and ESLint Together</h3><p>Here’s how we configured Prettier and ESLint in the <strong>SiNgawas</strong> project:</p><p>Here’s the ESLint configuration:</p><pre>export default [<br>  {<br>    files: [&#39;**/*.{js,mjs,cjs,ts,tsx,jsx}&#39;],<br>    plugins: {<br>      prettier: pluginPrettier,<br>    },<br>    rules: {<br>      &#39;prettier/prettier&#39;: &#39;warn&#39;,<br>      &#39;react/react-in-jsx-scope&#39;: &#39;off&#39;, // Not needed in Vite<br>    },<br>  },<br>]</pre><p>And the Prettier configuration:</p><pre>{<br>  &quot;semi&quot;: false,<br>  &quot;singleQuote&quot;: true,<br>  &quot;trailingComma&quot;: &quot;es5&quot;,<br>  &quot;printWidth&quot;: 80,<br>  &quot;tabWidth&quot;: 2<br>}</pre><p>These tools helped us maintain a clean and readable codebase, reducing the likelihood of bugs caused by inconsistent formatting or overlooked issues.</p><h4>Measuring Performance Impact</h4><p>By enforcing consistent formatting and identifying unused code, ESLint and Prettier indirectly improved performance by reducing unnecessary code execution. For example, removing unused imports and variables reduced the bundle size, leading to faster load times.</p><h3>Conclusion</h3><p>By implementing structured and measurable QA practices, we ensured that the <strong>SiNgawas</strong> project maintained high-quality standards throughout development. Key takeaways include:</p><ul><li><strong>Static analysis tools</strong> like SonarCloud help identify and fix issues early.</li><li><strong>CI/CD integration</strong> ensures that quality gates are enforced automatically.</li><li><strong>Additional tools</strong> like ESLint and Prettier improve code readability and performance.</li></ul><p>These practices not only improved the maintainability of the codebase but also enhanced the overall developer experience.</p><p><em>References:</em></p><blockquote><a href="https://www.perforce.com/blog/qac/what-is-linting#:~:text=Linting%20is%20important%20to%20reduce,costs%20by%20finding%20errors%20earlier.">What Is Linting + When to Use Lint Tools | Perforce Software</a></blockquote><blockquote><a href="https://www.speakeasy.com/post/vitest-vs-jest">Vitest vs Jest</a></blockquote><blockquote><a href="https://www.reddit.com/r/node/comments/w95n80/why_use_prettier_if_eslint_can_format/">https://www.reddit.com/r/node/comments/w95n80/why_use_prettier_if_eslint_can_format/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=137db73de3a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #6: Cleaning Codes: Applying Best Practices in a Vite Project]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-6-cleaning-codes-applying-best-practices-in-a-vite-project-0abf1e897ff7?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0abf1e897ff7</guid>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 18:04:14 GMT</pubDate>
            <atom:updated>2025-04-09T18:02:47.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ryoooT0Hxyxy0uMv" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Developing a scalable and maintainable software system requires more than just writing code — it demands thoughtful architecture, adherence to design principles, and the use of industry best practices. In this blog, I’ll walk you through how I applied these concepts in <strong>SiNgawas</strong>, an all-in-one exam proctoring system. This project features a <strong>Django REST Framework (DRF)</strong> backend and a <strong>TypeScript Vite React</strong> frontend, with a focus on clean architecture, modular design, and maintainability.</p><h3>Laying the Foundation: Project Setup and Architecture</h3><p>The first step in building SiNgawas was to establish a solid foundation. I structured the project to ensure scalability and maintainability by organizing the codebase into clear, modular directories. Here’s an overview of the directory structure:</p><pre>src/<br>├── __tests__<br>├── api<br>├── assets<br>├── components/       # Reusable UI components<br>│   ├── auth/         # Auth-specific organisms<br>│   ├── common/       # Miscellaneous<br>│   ├── elements/     # Basic UI elements (e.g., Button, InputField)<br>│   ├── modules/      # Feature-specific components (e.g., EditableField, UserRoles)<br>│   ├── layouts/      # Layout components (e.g., MainLayout)<br>│   ├── containers/   # Components managing state and logic (e.g., ProfileContainer)<br>├── context/          # React Context for global state (e.g., AuthContext)<br>├── hooks/            # Custom hooks (e.g., useProfile)<br>├── pages/            # Page-level components (e.g., Profile, LoginAdmin)<br>├── routes/           # Route definitions (e.g., ProtectedRoute)<br>├── utils/            # Utility functions (e.g., validators, JWT helpers)<br>├── config/           # Environment-specific configurations (e.g., env.ts)</pre><p><strong>Why?</strong><br>Avoids the “mega-components” problem while preventing over-fragmentation. Balances <strong>clean architecture</strong> with <strong>developer productivity</strong>.</p><p>This directory structure takes inspiration from:</p><ol><li><a href="https://atomicdesign.bradfrost.com/"><strong>Atomic Design</strong></a> (Brad Frost) → Component hierarchy.</li><li><strong>Conventional Routing</strong> (Next.js, Remix) → Feature colocation.</li><li><strong>Domain-Driven Design</strong> → features/ mirrors business logic.</li><li><strong>Progressive Disclosure</strong> — Simple to start (components/ + pages/), scales with features/.</li></ol><p>This structure adheres to <strong>Separation of Concerns (SoC)</strong>, ensuring that each module has a single responsibility. For example, reusable UI components like Button are placed in elements/, while feature-specific components like EditableField are in modules/.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*z_EDh5pMMLt4hsZc.jpg" /><figcaption><a href="https://smashingtips.com/programming/implementing-solid-principles-react-frontend-development/">https://smashingtips.com/programming/implementing-solid-principles-react-frontend-development/</a></figcaption></figure><h3>Designing for Scalability: Applying SOLID Principles</h3><p>To ensure the system could scale and adapt to future requirements, I followed the <strong>SOLID principles</strong>:</p><h4>1. Single Responsibility Principle (SRP)</h4><p>Each component or module in SiNgawas is designed to handle a single responsibility. For example: EditableField</p><p>The component is responsible for rendering an editable input field with validation and error handling.</p><pre>interface EditableFieldProps {<br>  label: string<br>  value: string<br>  isEditing: boolean<br>  onEdit: () =&gt; void<br>  onAccept: () =&gt; void<br>  onCancel: () =&gt; void<br>  onChange: (value: string) =&gt; void<br>  error?: string<br>}<br><br>const EditableField: React.FC&lt;EditableFieldProps&gt; = ({<br>  label,<br>  value,<br>  isEditing,<br>  onEdit,<br>  onAccept,<br>  onCancel,<br>  onChange,<br>  error,<br>}) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      {isEditing ? (<br>        &lt;input value={value} onChange={(e) =&gt; onChange(e.target.value)} /&gt;<br>      ) : (<br>        &lt;span&gt;{value}&lt;/span&gt;<br>      )}<br>      {error &amp;&amp; &lt;span className=&quot;error&quot;&gt;{error}&lt;/span&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>This modular design makes the component reusable across different pages. Without SRP, you might create a “mega-component” that handles UI, state, and API logic all in one place. While this might seem faster initially, it results in <strong>spaghetti code</strong> that’s hard to debug and maintain.</p><h4>2. Open/Closed Principle (OCP)</h4><p>OCP ensures that components are <strong>open for extension but closed for modification</strong>. This allows you to add new functionality without altering existing code, reducing the risk of introducing bugs.</p><p>Components and utilities are designed to be <strong>open for extension but closed for modification</strong>. For example, the ProtectedRoute component allows role-based access control without modifying its core logic.</p><pre>const ProtectedRoute: React.FC&lt;{ allowedRoles?: string[] }&gt; = ({ allowedRoles }) =&gt; {<br>  const { isAuthenticated, user } = useAuth()<br><br>  if (!isAuthenticated) {<br>    return &lt;Navigate to=&quot;/&quot; /&gt;<br>  }<br><br>  if (allowedRoles &amp;&amp; !allowedRoles.includes(user.role)) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; /&gt;<br>  }<br><br>  return &lt;Outlet /&gt;<br>}</pre><ul><li>If you modify existing code to add new functionality, you risk breaking existing features. For example:</li><li>If ProtectedRoute didn’t use props and instead hardcoded roles, adding a new role would require modifying the component directly, potentially introducing bugs.</li><li>This approach leads to <strong>rigid code</strong> that’s difficult to adapt to new requirements.</li></ul><h4>3. Liskov Substitution Principle (LSP)</h4><p>The ProtectedRoute component ensures that any route requiring authentication or role-based access control can be substituted without breaking the application. It uses the useAuth hook to determine the user’s authentication state and role.</p><pre>import { Navigate, Outlet } from &#39;react-router-dom&#39;<br>import { useAuth } from &#39;../context/AuthContext&#39;<br><br>const ProtectedRoute: React.FC&lt;{ allowedRoles?: string[] }&gt; = ({ allowedRoles }) =&gt; {<br>  const { isAuthenticated, user } = useAuth()<br><br>  if (!isAuthenticated) {<br>    return &lt;Navigate to=&quot;/&quot; /&gt;<br>  }<br><br>  if (allowedRoles &amp;&amp; !allowedRoles.includes(user.role || &#39;&#39;)) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; /&gt;<br>  }<br><br>  return &lt;Outlet /&gt;<br>}<br><br>export default ProtectedRoute<br></pre><p>This component adheres to LSP because it can be extended or reused for different role-based access scenarios without modifying its core logic. For example, you can use it for admin-only routes or general authenticated routes.</p><h4>4. Interface Segregation Principle (ISP)</h4><p>Example ProfileContainer Component with Segregated Interfaces:</p><p>In the ProfileContainer component, I applied the <strong>Interface Segregation Principle</strong> by defining specific interfaces for different parts of the component’s functionality. This ensures that the component only depends on the properties it actually needs, avoiding bloated or unnecessary dependencies.</p><pre>interface ProfileData {<br>  email: string<br>  whatsappNumber: string<br>}<br><br>interface EditableFieldProps {<br>  label: string<br>  value: string<br>  isEditing: boolean<br>  onEdit: () =&gt; void<br>  onAccept: () =&gt; void<br>  onCancel: () =&gt; void<br>  onChange: (value: string) =&gt; void<br>  error?: string<br>}<br><br>const ProfileContainer: React.FC = () =&gt; {<br>  const [tempData, setTempData] = useState&lt;ProfileData&gt;({<br>    email: &#39;user@example.com&#39;,<br>    whatsappNumber: &#39;1234567890&#39;,<br>  })<br>  const [isEditing, setIsEditing] = useState({<br>    email: false,<br>    whatsappNumber: false,<br>  })<br>  const [errors, setErrors] = useState&lt;Partial&lt;ProfileData&gt;&gt;({})<br><br>  const handleEdit = (field: keyof ProfileData) =&gt; {<br>    setIsEditing((prev) =&gt; ({ ...prev, [field]: true }))<br>  }<br><br>  const handleAccept = (field: keyof ProfileData) =&gt; {<br>    setIsEditing((prev) =&gt; ({ ...prev, [field]: false }))<br>    // Add validation logic here<br>  }<br><br>  const handleCancel = (field: keyof ProfileData) =&gt; {<br>    setIsEditing((prev) =&gt; ({ ...prev, [field]: false }))<br>  }<br><br>  const handleChange = (field: keyof ProfileData, value: string) =&gt; {<br>    setTempData((prev) =&gt; ({ ...prev, [field]: value }))<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;EditableField<br>        label=&quot;Email&quot;<br>        value={tempData.email}<br>        isEditing={isEditing.email}<br>        onEdit={() =&gt; handleEdit(&#39;email&#39;)}<br>        onAccept={() =&gt; handleAccept(&#39;email&#39;)}<br>        onCancel={() =&gt; handleCancel(&#39;email&#39;)}<br>        onChange={(value) =&gt; handleChange(&#39;email&#39;, value)}<br>        error={errors.email}<br>      /&gt;<br>      &lt;EditableField<br>        label=&quot;Whatsapp&quot;<br>        value={tempData.whatsappNumber}<br>        isEditing={isEditing.whatsappNumber}<br>        onEdit={() =&gt; handleEdit(&#39;whatsappNumber&#39;)}<br>        onAccept={() =&gt; handleAccept(&#39;whatsappNumber&#39;)}<br>        onCancel={() =&gt; handleCancel(&#39;whatsappNumber&#39;)}<br>        onChange={(value) =&gt; handleChange(&#39;whatsappNumber&#39;, value)}<br>        error={errors.whatsappNumber}<br>      /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>How This Demonstrates ISP</h4><ol><li><strong>Specific Interfaces:</strong></li></ol><ul><li>The EditableFieldProps interface is tailored specifically for the EditableField component, ensuring it only depends on the properties it needs (e.g., label, value, isEditing, etc.).</li><li>The ProfileData interface is used for managing the profile&#39;s data structure, keeping it separate from the UI logic.</li></ul><p><strong>2. Avoiding Bloated Interfaces:</strong></p><ul><li>Instead of creating a single, large interface that includes properties for both EditableField and ProfileContainer, the interfaces are segregated based on their specific responsibilities.</li></ul><p><strong>3. Reusability:</strong></p><ul><li>The EditableField component can be reused in other parts of the application without requiring changes to its interface or logic.</li></ul><p><strong>4. Maintainability:</strong></p><ul><li>If a new field (e.g., phoneNumber) is added to the profile, only the ProfileData and related handlers need to be updated. The EditableField interface remains unaffected.</li></ul><h4>5. Dependency Inversion Principle (DIP)</h4><p>High-level modules depend on abstractions rather than concrete implementations. For example, the authService abstracts authentication 7hy7logic, allowing components like AuthCallback to remain decoupled.</p><pre>export const login = async (username: string, password: string) =&gt; {<br>  const response = await axios.post(&#39;/auth/login&#39;, { username, password })<br>  sessionStorage.setItem(&#39;access_token&#39;, response.data.access_token)<br>}</pre><p>This abstraction makes it easier to swap out the implementation (e.g., replacing axios with another HTTP client) without affecting dependent components.</p><p>If high-level modules depend on concrete implementations, changes to those implementations can break the entire application. For example:</p><p>If AuthCallback directly used axios for API calls, switching to a different HTTP client would require modifying the component. This results in <strong>tight coupling</strong> and makes the code harder to test and refactor.</p><h3>Several More Best Practices in React and TypeScript</h3><h4>1. Context API for Global State Management</h4><p>I used the <strong>Context API</strong> to manage global state, such as authentication. The AuthContext provides a centralized way to handle user authentication across the app.</p><pre>const AuthContext = createContext&lt;AuthContextType | undefined&gt;(undefined)<br><br>export const AuthProvider: React.FC = ({ children }) =&gt; {<br>  const [isAuthenticated, setIsAuthenticated] = useState(false)<br><br>  const login = (token: string) =&gt; {<br>    sessionStorage.setItem(&#39;access_token&#39;, token)<br>    setIsAuthenticated(true)<br>  }<br><br>  return (<br>    &lt;AuthContext.Provider value={{ isAuthenticated, login }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  )<br>}</pre><h4>2. Error Handling with Error Boundaries</h4><p>To improve resilience, I implemented an ErrorBoundary component that catches runtime errors and displays a fallback UI.</p><pre>class ErrorBoundary extends React.Component {<br>  state = { hasError: false }<br><br>  static getDerivedStateFromError() {<br>    return { hasError: true }<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      return &lt;div&gt;Something went wrong.&lt;/div&gt;<br>    }<br>    return this.props.children<br>  }<br>}</pre><h4>3. Environment-Specific Configurations</h4><p>I configured the project to support multiple environments (development, staging, production) using a centralized env.ts file.</p><pre>const config = {<br>  API_BASE_URL: process.env.REACT_APP_API_BASE_URL || &#39;http://localhost:8000&#39;,<br>}<br><br>export default config</pre><h3>Choosing the Right Architecture</h3><p>Below is a comparison of several best practice approaches that can be applied to a project like <strong>SiNgawas</strong>:</p><h3><strong>Aspects:</strong></h3><p><strong>State Management</strong></p><ul><li><strong>Approach 1: </strong>Using <strong>Context API</strong> for global state like authentication.</li><li><strong>Approach 2: </strong>Using libraries like <strong>Redux</strong> for more complex state management.</li></ul><p><strong>Reusable Components</strong></p><ul><li><strong>Approach 1: </strong>Creating small components like EditableField with a single responsibility.</li><li><strong>Approach 2: </strong>Creating large components with multiple responsibilities (anti-pattern).</li></ul><p><strong>Routing</strong></p><ul><li><strong>Approach 1: </strong>Using ProtectedRoute for role-based access control.</li><li><strong>Approach 2: </strong>Adding authentication logic directly in each page component (inefficient).</li></ul><p><strong>Error Handling</strong></p><ul><li><strong>Approach 1: </strong>Using ErrorBoundary to handle runtime errors.</li><li><strong>Approach 2: </strong>Handling errors manually in each component (redundant).</li></ul><p><strong>Environment Config</strong></p><ul><li><strong>Approach 1: </strong>Using an env.ts file for environment-based configurations.</li><li><strong>Approach 2: </strong>Hardcoding API URLs or other configurations directly in the code.</li></ul><p>The <strong>first approach is more modular, scalable, and maintainable</strong> compared to the second approach.</p><p>When designing SiNgawas, I prioritized <strong>modularity</strong>, <strong>reusability</strong>, and <strong>scalability</strong>. Here are some key takeaways:</p><ol><li><strong>Modular Design:</strong> Breaking the application into reusable components and hooks reduces duplication and improves maintainability.</li><li><strong>Role-Based Access Control:</strong> Using ProtectedRoute ensures that only authorized users can access certain pages.</li><li><strong>Error Resilience:</strong> Implementing ErrorBoundary improves the user experience by gracefully handling unexpected errors.</li></ol><h3>Conclusion</h3><p>By adhering to <strong>SOLID principles</strong>, leveraging <strong>React best practices</strong>, and setting up a robust CI/CD pipeline, I was able to build a scalable and maintainable system in SiNgawas. This approach not only improved code quality but also ensured that the application could adapt to future requirements.</p><p>If you’re building a similar system, I encourage you to think critically about your architecture, choose the right design patterns, and follow industry standards to create software that stands the test of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0abf1e897ff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #4: Central Authentication Service of SSO UI — Because Logging In Shouldn’t Be a Puzzle]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-4-central-authentication-service-of-sso-ui-because-logging-in-shouldnt-be-a-puzzle-95b606a45d9b?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b606a45d9b</guid>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 04:38:55 GMT</pubDate>
            <atom:updated>2025-05-05T17:43:40.366Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@soros21febriano/ambatuscrum-5-tdd-the-developers-daily-dose-of-dread-9c759ada0d97?source=your_stories_page--------------------------------------------">Ambatuscrum #4: </a>Central Implementing SSO UI’s Authentication Service— Because Logging In Shouldn’t Be a Puzzle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i87lDYrVNV8iodsM" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today, we’re diving into the <strong>Central Authentication Service (CAS)</strong> of <strong>SSO UI</strong> — because why remember 50 passwords when you can just remember one and hope it doesn’t get pwned?</p><p>In our project, <strong>SiNgawas</strong> (an all-in-one exam proctor registration system), we implemented <strong>Single Sign-On (SSO)</strong> using our university’s <strong>CAS</strong> to make life easier for users (and harder for attackers).</p><p>But wait — <strong>security isn’t just about convenience</strong>; it’s about making sure your auth flow doesn’t accidentally become a VIP entrance for hackers. So, let’s break it down!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AQh4TQxR5qFM98-6.jpg" /><figcaption>CAS Illustration by: <a href="https://blog.tfm.ro/searching-for-central-authentication-service/">https://blog.tfm.ro/searching-for-central-authentication-service/</a></figcaption></figure><h3>How Our CAS Flow Works</h3><p>Here’s the <strong>CAS dance</strong> we implemented:</p><pre>const API_BASE_URL = config.API_BASE_URL<br><br>export const handleSSOLogin = () =&gt; {<br>  const currentPath = window.location.pathname<br>  sessionStorage.setItem(&#39;auth_redirect&#39;, currentPath)<br><br>  const serviceUrl = `${config.FRONTEND_BASE_URL}/auth/callback`<br>  window.location.href = `${config.SSO_BASE_URL}/login?service=${serviceUrl}`<br>}</pre><ol><li><strong>Frontend (Vite + React)</strong>:</li></ol><ul><li>User clicks “Login with SSO UI.”</li><li>Redirects to CAS login page (where they enter their credentials).</li><li>Upon success, CAS sends back a <strong>ticket</strong> (like a VIP pass, but for auth).</li></ul><pre>export const validateTicket = async (ticket: string): Promise&lt;AuthResult&gt; =&gt; {<br>  try {<br>    const response = await axios.get(`${API_BASE_URL}/auth/login/`, {<br>      params: { ticket },<br>    })<br><br>    if (<br>      response.status === 200 &amp;&amp;<br>      response.data &amp;&amp;<br>      response.data.access_token<br>    ) {<br>      sessionStorage.setItem(&#39;access_token&#39;, response.data.access_token)<br>      if (response.data.refresh_token) {<br>        sessionStorage.setItem(&#39;refresh_token&#39;, response.data.refresh_token)<br>      }<br>      window.dispatchEvent(new Event(&#39;authChange&#39;))<br><br>      return {<br>        success: true,<br>        tokens: {<br>          access_token: response.data.access_token,<br>          refresh_token: response.data.refresh_token,<br>        },<br>      }<br>    }</pre><p><strong>2. Backend (Django REST Framework)</strong>:</p><pre>def get(self, request):<br>        config = SSOJWTConfig()<br>        ticket = request.GET.get(&quot;ticket&quot;)<br>        if not ticket:<br>            return Response({&quot;error&quot;: &quot;Missing ticket&quot;}, status=400)<br>        try:<br>            service_response = validate_ticket(config, ticket)<br>        except ValidateTicketError:<br>            return Response({&quot;error&quot;: &quot;User authentication failed&quot;}, status=401)<br>        auth_success = service_response.get(&quot;authentication_success&quot;)<br>        if not auth_success:<br>            return Response({&quot;error&quot;: &quot;Invalid ticket response&quot;}, status=401)<br>        username = auth_success.get(&quot;user&quot;)<br><br>        if not username:<br>            return Response({&quot;error&quot;: &quot;Invalid user data&quot;}, status=401)<br>        <br>        user_attributes = auth_success.get(&quot;attributes&quot;, {})<br>        npm = user_attributes.get(&quot;npm&quot;)<br>       ...<br><br>        access_token = create_token(config, &quot;access_token&quot;, service_response)<br>        refresh_token = create_token(config, &quot;refresh_token&quot;, service_response)<br><br>        user = SSOAuthenticationBackend().authenticate(request, token=access_token)<br>        if user:<br>            login(request, user)<br>            request.session[&quot;sso_token&quot;] = access_token<br>            request.session.modified = True<br>            return Response({<br>                &quot;message&quot;: &quot;Login successful&quot;,<br>                &quot;access_token&quot;: access_token,<br>                &quot;refresh_token&quot;: refresh_token<br>            })<br>        return Response({&quot;error&quot;: &quot;User authentication failed&quot;}, status=401)</pre><ul><li>Frontend sends the ticket to the backend.</li><li>Backend asks CAS: <em>“Hey, is this ticket legit?”</em></li><li>If CAS says <strong>“Yes”</strong>, backend issues a <strong>JWT (access + refresh token)</strong>.</li><li>Frontend stores tokens in <strong>sessionStorage</strong> (more on security implications later).</li></ul><p><strong>3. User is now authenticated!</strong> 🎉</p><ul><li>Until he token expires… then it’s refresh token time.</li></ul><h3>Understanding CAS Through a Cinema Ticket Analogy</h3><p>To better visualize how CAS works, imagine <strong>booking a movie ticket online</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vmpZajAys3PDr__z" /><figcaption>Photo by <a href="https://unsplash.com/@pipe_fx?utm_source=medium&amp;utm_medium=referral">Felipe Bustillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Getting the Ticket (Authentication)</h3><ul><li>You visit a <strong>movie booking website</strong> (like the <strong>CAS login page</strong>) and purchase a ticket.</li><li>The website issues you a <strong>QR code ticket</strong> (similar to a <strong>CAS service ticket</strong>).</li></ul><h3>2. Entering the Cinema (Service Validation)</h3><ul><li>At the cinema, you show your <strong>QR code</strong> to the attendant.</li><li>The attendant <strong>scans it</strong> to verify its validity (just like the backend validating the CAS ticket with the SSO server).</li></ul><h3>3. Getting Your Seat (JWT Issuance)</h3><ul><li>If the ticket is valid, you’re granted entry and given a <strong>seat number</strong> (analogous to the backend issuing a <strong>JWT</strong>).</li><li>This seat number is <strong>temporary</strong> — once the movie ends (JWT expires), you need a new one (refresh token).</li></ul><h3>4. Security Checks (Preventing Fraud)</h3><ul><li><strong>Fake Tickets?</strong> The attendant checks with the booking system (like backend checks with CAS).</li><li><strong>Stolen Tickets?</strong> A used QR code can’t be reused (CAS tickets are single use).</li><li><strong>Expired Tickets?</strong> Late arrivals are denied entry (like expired JWTs).</li></ul><h4>Why This Matters for Security</h4><ul><li><strong>No Direct Entry:</strong> Just as you can’t enter a cinema without a valid ticket, users can’t access services without CAS validation.</li><li><strong>One-Time Use:</strong> CAS tickets, like QR codes, prevent replay attacks.</li><li><strong>Delegated Trust:</strong> The cinema trusts the booking system (just as your backend trusts CAS).</li></ul><h3>Security Considerations</h3><h4>1. Secure Programming?</h4><p>Since <strong>secure programming</strong> was a requirement, we had to:</p><ul><li><strong>Validate the ticket server-side</strong> (never trust the frontend with auth logic).</li><li><strong>Use HTTPS everywhere</strong> (because plaintext auth is like sending passwords on a postcard).</li><li><strong>Set short-lived JWT tokens</strong> (so if they leak, the damage is limited).</li></ul><h4>2. OWASP Stuff We Applied (Because Security Checklists Are Cool)</h4><ul><li><strong>OWASP Top 10</strong> is our Bible. Here’s what we tackled:</li></ul><p><strong>A2: Broken Authentication</strong> → Weak authentication mechanisms allow attackers to compromise credentials or exploit session management flaws.</p><p><strong>Our Mitigations:</strong></p><ul><li><strong>CAS-Based SSO:</strong> Centralized, university-verified authentication reduces password fatigue and phishing risks.</li><li><strong>JWT Best Practices: <br>- </strong>Short-lived access tokens (15–30 mins), <br>- Refresh tokens with strict expiration and one-time use, <br>- Server-side signature validation (no client-side tampering).</li><li><strong>No Password Storage:</strong> Since we rely on SSO, we avoid handling raw passwords entirely.</li></ul><p><strong>A3: Sensitive Data Exposure</strong> → Tokens stored in <strong>sessionStorage </strong>(not localStorage) to avoid XSS persistence.</p><p><strong>Our Mitigations:</strong></p><ul><li><strong>HTTPS Everywhere:</strong> All CAS, frontend-backend, and API traffic enforce TLS.</li><li><strong>Secure Token Storage:<br>- </strong>JWTs stored in sessionStorage (cleared on tab close) instead of localStorage.<br>- Future improvement: Migrate to HttpOnly cookies (requires CSRF protection).<br>- <strong>No Sensitive Data in JWTs:</strong> Tokens contain only minimal claims (e.g., user ID, expiry).</li></ul><p><strong>A5: Broken Access Control</strong> → Users can access unauthorized functions/data.<br><strong>Our Mitigations:</strong></p><ul><li><strong>Backend Validation:</strong> Every API call verifies the JWT’s signature and expiry.</li><li><strong>Role-Based Access Control (RBAC):</strong></li><li>JWTs include user roles (e.g., dosen, mahasiswa, admin).</li><li>Backend checks roles before permitting actions (e.g., only admins can create exams).</li></ul><h3>Possible Security Holes (Because No System Is Perfect)</h3><ol><li><strong>sessionStorage vs. XSS</strong></li></ol><ul><li>Storing tokens in sessionStorage is better than localStorage (clears on tab close).</li><li>But… if an XSS attack happens, <strong>tokens can still be stolen</strong>.</li><li><strong>Mitigation?</strong> Use httpOnly cookies (but then CSRF protection is needed).</li></ul><p><strong>2. CAS Ticket Replay Attacks</strong></p><ul><li>What if someone intercepts the ticket and reuses it?</li><li><strong>Solution:</strong> CAS tickets are <strong>single-use</strong> (but we still validate them ASAP).</li></ul><p><strong>3. JWT Token Leakage</strong></p><ul><li>If someone steals the JWT, they can impersonate the user.</li><li><strong>Defense:</strong> Short expiry + refresh tokens + monitoring weird logins.</li></ul><h3>Red, Purple and Blue</h3><p>Now that we’ve identified potential holes (XSS, replay, token leakage), let’s put our CAS‑SSO flow through a full adversarial drill:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JjsBXuvXqeDgYzgI.jpg" /><figcaption><a href="https://www.riskcrew.com/red-team-testing-vs-blue-team-testing-whats-the-difference/">https://www.riskcrew.com/red-team-testing-vs-blue-team-testing-whats-the-difference/</a></figcaption></figure><h3>Red‑Team Testing (Offensive)</h3><p>These simulate a real attacker. Align each with OWASP’s Web Security Testing Guide (WSTG) and SSO best practices.</p><ul><li><strong>Replay‑Attack on CAS Ticket: </strong>Capture a legitimate CAS service ticket (e.g. via proxy) and attempt to reuse it against /auth/login/.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2EUHeDTLg6N9AaYAFoYNQ.png" /><figcaption>Capturing legitimate ticket form the URL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWK3t_AVPbN09iI-uq5uWg.png" /><figcaption>Reusing ticket on another tab immediately failed</figcaption></figure><blockquote><em>Verdict: passed ✅</em></blockquote><h4>2. Session Management &amp; Token Handling</h4><ul><li><strong>Session Fixation: </strong>Before login, set a crafted sessionStorage token. After login, verify that a new session identifier is issued rather than continuing the old one. <a href="https://owasp.org/www-project-web-security-testing-guide/assets/archive/OWASP_Testing_Guide_v4.pdf?utm_source=chatgpt.com">OWASP</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnxaMkFGYziYhaB8AqDeOg.png" /><figcaption>Manipulate access token in sessionStorage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*h8QVQwmIRv-v6U4qQ1AXnw.png" /><figcaption>Web logs us out because of invalid authentication</figcaption></figure><blockquote>Verdict: passed ✅</blockquote><h3>Blue‑Team Controls &amp; Monitoring (Defensive)</h3><p>While red‑team finds holes, blue‑team work ensures you detect and respond in real‑time.</p><h3>1. Logging &amp; SIEM</h3><ul><li><strong>Audit Ticket Validation: </strong>Log every ticket‑validation request with timestamp, source IP, ticket ID, and outcome.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*CoCi45eXIIht_doQoN158g.png" /><figcaption>Logging invalid tickets in terminal</figcaption></figure><ul><li><strong>JWT Anomaly Detection: </strong>Monitor JWT issuance patterns. Alert if a single user requests refresh tokens at an unusual frequency.</li></ul><h3>2. Intrusion Detection / WAF Rules</h3><ul><li><strong>Signature‑Based Rules: </strong>Block known bad payloads (XSS, SQLi) at the WAF before they reach your UI or API.</li><li><strong>Rate‑Limit Enforcement: </strong>Enforce per‑IP rate limits on login and ticket‑validation endpoints. Log and throttle aggressive clients.</li></ul><h3>3. Endpoint Monitoring</h3><ul><li><strong>Failed vs. Successful Logins: </strong>Correlate spikes in failed CAS logins vs. successful ones. Unusual patterns may indicate brute‑force attempts.</li><li><strong>Session Hijack Indicators: </strong>Detect simultaneous sessions from geographically distant IPs for the same user.</li></ul><h3>4. Incident Response Playbooks</h3><ul><li><strong>Ticket‑Replay Playbook: </strong>On detection of replayed ticket, automatically revoke all associated JWTs and force re‑authentication.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWK3t_AVPbN09iI-uq5uWg.png" /><figcaption>Reusing ticket on another tab immediately failed</figcaption></figure><ul><li><strong>Compromised‑Token Response: </strong>Blacklist stolen tokens, notify users, and rotate signing keys if needed. (On-progress)</li></ul><h3>Purple‑Team Collaboration</h3><p>Finally, combine insights from both sides:</p><ul><li><strong>Joint Exercises</strong>: Run red‑team attacks while blue‑team monitors and responds in real‑time.</li><li><strong>Metrics Review</strong>: Track MTTR (mean time to respond), detection rate, and residual risk.</li><li><strong>Continuous Improvement</strong>: Feed findings back into your CI pipeline (e.g. automate OWASP ZAP scans, ticket‑replay scripts).</li></ul><h3>Conclusion: Auth Should Be Secure, But Also… Not Annoying</h3><p>Implementing <strong>CAS + JWT</strong> was fun (and a bit nerve-wracking). We followed <strong>OWASP guidelines</strong>, avoided common pitfalls, and even set up <strong>SonarQube Security Scans </strong>to catch sneaky vulnerabilities.</p><p><strong>Key Takeaways:</strong><br>✔ <strong>Never trust the frontend with auth logic.</strong><br>✔ <strong>OWASP Top 10 is your security cheat sheet.</strong><br>✔ <strong>Security isn’t a one-time thing — it’s SDLC-wide.</strong></p><p><strong>Stay secure, folks!</strong> 🔒</p><h3>References</h3><blockquote><a href="https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/">OWASP Secure Coding Practices-Quick Reference Guide | OWASP Foundation</a></blockquote><blockquote><a href="https://owasp.org/www-project-top-ten/">OWASP Top Ten | OWASP Foundation</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b606a45d9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #5: TDD: The Developer’s Daily Dose of Dread!]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-5-tdd-the-developers-daily-dose-of-dread-9c759ada0d97?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c759ada0d97</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 07:29:25 GMT</pubDate>
            <atom:updated>2025-04-28T16:55:20.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*VgmBVbSLRkWCjvNl.jpg" /><figcaption><a href="https://makeameme.org/meme/testdriven-development-its">Test-Driven Development It’s Like Digging a well, one step at a time — Big Chungus Meme Generator</a></figcaption></figure><p><a href="https://www.quora.com/Is-TDD-a-waste-of-time">(1) Is TDD a waste of time? — Quora</a></p><p>From the thread above, a Quora user, probably a software engineer annoyed by the amount of word TDD needs, questioned whether deliberately writing a stupendous number of tests before really making something is worth it or not.</p><p>Most of the answers there answered: fixing and bugs in production actually makes up most and is a very wasteful usage of time. TDD minimizes or prevents developers to pay for the time wasted to fix bugs in the future.</p><blockquote>“No. It does have an increased time cost initially, but it can have large time savings in the long run.<br>Imagine you have 2 options for paying rent: $1 a day, then $60 is due at the end of the month, or $2 a day and $10 is due at the end of the month. If you just look at your per-day cost, the second option seems like a waste of money, but it only costs you $70 a month, while the first is $90 a month.<br>Its the same with test-driven development. You take more time now to write tests and ensure correctness, and you have far fewer bugs later. Since fixing bugs is the biggest time sink in development, reducing that time pays off. It may not be obvious how much time you save; the test you write now may catch a bug, and you fix it easily now, but if it had slipped through it could have taken weeks to debug later when you don’t know what is causing your problem. So, even when using it, the time savings may not be noticeable.”</blockquote><p>This analogy perfectly encapsulates the value of TDD: an upfront investment that saves time and effort in the long run.</p><p><strong>The Core of TDD: Focusing on Behavior, But from a Different Angle</strong><br>At its core, TDD (Test-Driven Development) focuses on behavior, but it is specifically concerned with testing small units of code to ensure they perform as expected. A test in TDD checks the result of a particular behavior within a function or method and confirms it aligns with predefined expectations.</p><p>While TDD helps verify correctness at a low level, it doesn’t directly address <em>how</em> the system’s behavior meets the business or user expectations. This is where <strong>Behavior-Driven Development (BDD)</strong> differs. BDD takes TDD’s principles but shifts the focus to the system as a whole, emphasizing user stories and expected behaviors in natural language scenarios. BDD tests are written in a way that both technical and non-technical stakeholders can understand, ensuring that the system behaves as expected in real-world use cases.</p><p>A test can be broken down into four steps:</p><ol><li><strong>Arrange</strong>: Prepare the environment for the test. This includes setting up objects, initializing services, or preparing database records.</li><li><strong>Act</strong>: Perform the singular action that triggers the behavior under test.</li><li><strong>Assert</strong>: Evaluate the resulting state to ensure it matches expectations.</li><li><strong>Cleanup</strong>: Restore the environment to its original state to avoid influencing other tests.</li></ol><p>For example, in the Blacklist app, I applied TDD to validate the creation of blacklist entries. Here’s how the process looked:</p><pre>import pytest<br>from django.utils import timezone<br>from apps.blacklist.models import Blacklist<br><br>class TestBlacklistCreationAndBasicFunctionality:<br>    @pytest.mark.django_db<br>    def test_create_blacklist_entry(self):<br>        &quot;&quot;&quot;Test if a blacklist entry can be created with correct fields.&quot;&quot;&quot;<br>        # Arrange<br>        start_date = timezone.now().date()<br>        end_date = start_date + timezone.timedelta(days=7)<br><br>        # Act<br>        blacklist_entry = Blacklist.objects.create(<br>            npm=&quot;2206081534&quot;,<br>            startDate=start_date,<br>            endDate=end_date,<br>            keterangan=&quot;Violation of rules&quot;<br>        )<br><br>        # Assert<br>        assert blacklist_entry.npm == &quot;2206081534&quot;<br>        assert blacklist_entry.startDate == start_date<br>        assert blacklist_entry.endDate == end_date<br>        assert blacklist_entry.keterangan == &quot;Violation of rules&quot;</pre><p>This test ensures that a blacklist entry is created correctly with all required fields.</p><h3>How to Write “Good” Tests — Positive, Negative, Edge + the <strong>FIRST</strong> Principle</h3><ol><li><strong>Cover three angles for every behaviour</strong></li></ol><ul><li><strong>Positive</strong>: the happy path works (expected inputs produce expected outputs).</li><li><strong>Negative</strong>: invalid inputs or error conditions are handled gracefully.</li><li><strong>Edge</strong>: boundary values, empty states, and “just over the line” cases reveal off-by-one or overflow bugs.</li></ul><p><strong>2. Apply the <em>FIRST</em> mnemonic to each test</strong></p><p><strong>F — Fast — </strong>Executes in milliseconds. No database/network unless absolutely required; use in-memory fakes.</p><pre>class TestBlacklistBusinessLogicAndProperties:<br>    def test_is_blacklist_expired(self):<br>        &quot;&quot;&quot;Test if the is_expired property works correctly.&quot;&quot;&quot;<br>        # Arrange<br>        today = timezone.now().date()<br>        yesterday = today - timezone.timedelta(days=1)<br>        <br>        # Using in-memory objects instead of database<br>        blacklist = Blacklist(<br>            npm=&quot;2206081534&quot;,<br>            startDate=yesterday,<br>            endDate=yesterday,<br>            keterangan=&quot;Expired blacklist&quot;<br>        )<br>        <br>        # Act &amp; Assert<br>        assert blacklist.is_expired is True</pre><p><strong>I — Independent — </strong>Order doesn’t matter. Set up all data you need inside the test; avoid shared state.</p><pre>class TestIsRuanganAvailable(TestCase):<br>    def test_room_available(self):<br>        # Arrange - Setup everything needed within the test<br>        mock_room = MagicMock()<br>        mock_room.is_available.return_value = True<br><br>        # Act<br>        result = is_ruangan_available(mock_room)<br><br>        # Assert<br>        self.assertTrue(result)</pre><p><strong>R — Repeatable — </strong>Same result on every run, anywhere. Freeze time, mock randomness, control external services.</p><pre>class TambahUjianTest(TestCase):<br>    def setUp(self):<br>        self.client = Client()<br>        self.request_body = {<br>            &quot;id_mata_kuliah&quot;: &quot;CSCM603117&quot;,<br>            &quot;tanggal_ujian&quot;: &quot;2025-04-01&quot;,  # Fixed date, not dependent on current date<br>            &quot;nama_ujian&quot;: &quot;Analisis Numerik Siang&quot;,<br>            &quot;syarat_angkatan&quot;: 2022,<br>            &quot;waktu_mulai&quot;: &quot;09:00&quot;,<br>            &quot;waktu_selesai&quot;: &quot;10:40&quot;,<br>            &quot;ruangans&quot;: [<br>                {<br>                    &quot;ruangan&quot;: &quot;b8bde06f-85a1-4b3e-ae41-2ae87f02838e&quot;,<br>                    &quot;jumlah_mahasiswa&quot;: 30<br>                }<br>            ]<br>        }</pre><p><strong>S — Self-Validating — </strong>One clear pass/fail assertion. Don’t print to console; rely on assertions only.</p><pre>def test_blacklist_check_endpoint(client, blacklisted_user):<br>    &quot;&quot;&quot;Test the blacklist check endpoint returns correct status.&quot;&quot;&quot;<br>    # Act<br>    response = client.get(f&#39;/blacklist/check/{blacklisted_user.npm}&#39;)<br>    <br>    # Assert - Clear pass/fail criteria<br>    assert response.status_code == 200<br>    assert response.json() == {<br>        &#39;is_blacklisted&#39;: True,<br>        &#39;blacklist_info&#39;: {<br>            &#39;npm&#39;: blacklisted_user.npm,<br>            &#39;start_date&#39;: blacklisted_user.startDate.isoformat(),<br>            &#39;end_date&#39;: blacklisted_user.endDate.isoformat(),<br>            &#39;keterangan&#39;: blacklisted_user.keterangan<br>        }<br>    }</pre><p><strong>T — Timely — </strong>Written <em>before</em> production code (Red-Green-Refactor). Protects design and prevents regression from day one.</p><pre># From the GitLab history, we can see tests were written first:<br># [RED] feat(Blacklist): Create Blacklist Model<br># [RED] Add tests for Blacklist model creation and field validation<br># [GREEN] feat(Blacklist): Passed test for Blacklist&#39;s business logic views</pre><p><strong>3. Name tests like executable documentation</strong></p><p>One of the most powerful aspects of TDD is that well-written tests serve as living documentation for your codebase. By giving your tests descriptive names, you create a form of executable documentation that clearly communicates what each component of your system should do.</p><p><strong>4. Keep the AAA pattern obvious</strong></p><p>The Arrange-Act-Assert (AAA) pattern is a cornerstone of good test design. It clearly separates the setup of the test scenario, the action being tested, and the verification of the results.</p><p><strong>5. Refactor mercilessly</strong></p><p>TDD isn’t just about writing tests first; it’s also about continuous improvement of both your test code and production code. After getting tests to pass, refactoring is a critical step that’s often overlooked.</p><p>For example, after implementing several blacklist-related features, I noticed duplication in the test setup code. This led to a refactoring:</p><pre>class BlacklistTestBase:<br>    &quot;&quot;&quot;Base class providing common setup for blacklist tests.&quot;&quot;&quot;<br>    <br>    @pytest.fixture<br>    def sample_blacklist(self):<br>        &quot;&quot;&quot;Create a standard blacklist entry for testing.&quot;&quot;&quot;<br>        today = timezone.now().date()<br>        start_date = today - timezone.timedelta(days=1)<br>        end_date = today + timezone.timedelta(days=6)<br>        <br>        return Blacklist.objects.create(<br>            npm=&quot;2206081534&quot;,<br>            startDate=start_date,<br>            endDate=end_date,<br>            keterangan=&quot;Test blacklist&quot;<br>        )<br><br>class TestBlacklistAPI(BlacklistTestBase):<br>    def test_api_returns_active_blacklist(self, client, sample_blacklist):<br>        &quot;&quot;&quot;API should return details for active blacklist entries.&quot;&quot;&quot;<br>        # Act<br>        response = client.get(f&#39;/blacklist/check/{sample_blacklist.npm}&#39;)<br>        <br>        # Assert<br>        assert response.status_code == 200<br>        assert response.json()[&#39;is_blacklisted&#39;] is True</pre><p>This refactoring eliminated duplicate setup code across multiple test classes, making the tests more maintainable and focused on the specific behaviors being tested.</p><p>Refactoring isn’t just about cleaning up code — it’s about improving design and removing technical debt. The safety net provided by comprehensive tests makes refactoring much less risky.</p><h3>Scaling TDD Across Features</h3><p>As I applied TDD to more features, I began to see its benefits in terms of code quality and maintainability. For instance, when implementing the is_user_blacklisted functionality, I wrote tests for success cases, failure cases, and edge cases. Here’s an example:</p><pre>class TestBlacklistBusinessLogicAndProperties:<br>    @pytest.mark.django_db<br>    def test_is_user_blacklisted_function(self):<br>        &quot;&quot;&quot;Test a helper function to check if a user is currently blacklisted.&quot;&quot;&quot;<br>        # Arrange<br>        npm = &quot;2206081534&quot;<br>        today = timezone.now().date()<br>        yesterday = today - timezone.timedelta(days=1)<br>        tomorrow = today + timezone.timedelta(days=1)<br><br>        Blacklist.objects.create(<br>            npm=npm,<br>            startDate=yesterday,<br>            endDate=tomorrow,<br>            keterangan=&quot;Current blacklist&quot;<br>        )<br><br>        # Act<br>        is_blacklisted = Blacklist.is_user_blacklisted(npm)<br><br>        # Assert<br>        assert is_blacklisted is True</pre><p>This test ensures that the is_user_blacklisted method correctly identifies whether a user is currently blacklisted.</p><p>In the simplest terms, a test is meant to look at the result of a particular behavior, and make sure that result aligns with what you would expect. Behavior is not something that can be empirically measured, which is why writing tests can be challenging.</p><p>“Behavior” is the way in which some system <strong>acts in response</strong> to a particular situation and/or stimuli. But exactly <em>how</em> or <em>why</em> something is done is not quite as important as <em>what</em> was done.</p><h3>The Red-Green-Refactor Commit Methodology</h3><p>The <strong>Red-Green-Refactor</strong> cycle is a cornerstone of TDD. When combined with Git, it provides a structured and traceable development process. Here’s how it works:</p><h4>1. Red Phase: Write a Failing Test</h4><pre>git add .<br>git commit -m &quot;[RED] feat(Blacklist): Add failing test for blacklist creation&quot;</pre><p>Write a test for the desired functionality. Since the functionality doesn’t exist yet, the test will fail.</p><h4>2. Green Phase: Make the Test Pass</h4><pre>git add .<br>git commit -m &quot;[GREEN] feat(Blacklist): Implement blacklist creation functionality&quot;</pre><p>Write just enough code to make the failing test pass</p><h4>3. Refactor Phase: Improve the Code</h4><pre>git add .<br>git commit -m &quot;[REFACTOR] refactor(Blacklist): Simplify blacklist creation logic&quot;</pre><p>Refactor the code for readability, maintainability, or performance without changing its behaviors.</p><p>This methodology ensures that each step of development is deliberate and traceable. The GitLab commit history (see below) demonstrates how I applied this process in the Blacklist app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5P6eN966Ptpl_KQH_9zQw.png" /></figure><p>As seen in the GitLab commit history, I followed a disciplined TDD approach by committing changes incrementally. Each commit represents a step in the TDD cycle: writing tests (RED), implementing functionality to pass the tests (GREEN), and refactoring the code for maintainability.</p><p>The <strong>Red-Green-Refactor</strong> cycle is a core practice in Test-Driven Development (TDD). It ensures that code is developed iteratively, with a focus on correctness, simplicity, and maintainability. When combined with Git, this methodology becomes even more powerful, as it allows developers to track progress, document changes, and maintain a clean history of the development process.</p><h3>Integrating TDD with CI/CD and Code Quality Tools</h3><p>To ensure the effectiveness of TDD, I integrated it into a robust CI/CD pipeline using GitLab. The pipeline automates testing, code quality checks, and deployments. Here’s an excerpt from the .gitlab-ci.ymlfile:</p><pre>test-django:<br>  image: $IMAGE_PYTHON<br>  stage: test<br>  script:<br>    - pytest --cov=. --cov-report=xml<br>  artifacts:<br>    paths:<br>      - coverage.xml<br><br>sonarqube:<br>  image:<br>    name: sonarsource/sonar-scanner-cli:11<br>  stage: sonar<br>  script:<br>    - sonar-scanner -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SONAR_TOKEN -Dsonar.python.coverage.reportPaths=coverage.xml</pre><p>In this pipeline:</p><ul><li><strong>Pytest</strong> is used to run the tests and generate a coverage report.</li><li><strong>SonarQube</strong> is used to analyze the codebase and enforce a quality gate, ensuring that the code coverage remains above a certain threshold.</li></ul><p>As part of the pipeline, I used <strong>pytest</strong> to run tests and generate a coverage report. The following image shows the test session output, where 427 tests were executed across various modules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*0safV1zaFLYwbMbaELMi3A.png" /></figure><p>The coverage report was then generated as an HTML file, providing detailed insights into the test coverage for each file. For example, the views.py file had 17% coverage, highlighting areas that required additional testing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*lMAhVnacttynZVGc-Xs27g.png" /></figure><p>To ensure the effectiveness of TDD, I integrated it with a CI/CD pipeline and SonarQube for code quality analysis. As shown in the SonarQube dashboard, the project consistently passed the quality gate with 100% test coverage and no critical issues. This level of coverage was achieved by writing comprehensive tests for all features, including edge cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCL7IWhgPmp517rg4lVbvQ.png" /><figcaption>SonarQube Quality Gate</figcaption></figure><p>The pipeline configuration ensured that every commit was analyzed for code quality and coverage. Any commit failing the quality gate was flagged, preventing it from being merged into the main branch.</p><h3>The Benefits of TDD</h3><p>Through disciplined application of TDD, I observed several benefits:</p><ol><li><strong>Improved Code Quality</strong>: Writing tests first forces you to think critically about the design and functionality of your code.</li><li><strong>Fewer Bugs</strong>: Comprehensive test coverage ensures that most issues are caught before they reach production.</li><li><strong>Easier Refactoring</strong>: High test coverage provides confidence when making changes to the codebase.</li><li><strong>Faster Debugging</strong>: When a test fails, it pinpoints the exact location of the issue.</li></ol><h3>Final Thoughts</h3><p>TDD is not a waste of time. It’s an investment in the future of your codebase. By catching bugs early and ensuring high-quality code, TDD saves time and effort in the long run.</p><p>If you’re new to TDD, start small. Pick a simple feature, write tests first, and experience the difference it makes. Over time, you’ll find that TDD not only improves your code but also enhances your skills as a developer.</p><blockquote>References:</blockquote><blockquote><a href="https://docs.pytest.org/en/stable/explanation/anatomy.html#test-anatomy">Anatomy of a test — pytest documentation</a></blockquote><blockquote><a href="https://katalon.com/resources-center/blog/tdd-vs-bdd">TDD vs BDD: Full Comparison</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c759ada0d97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #3: Marie Kondo Your Code: Refactoring That Sparks Joy (and Fewer Bugs)]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-3-marie-kondo-your-code-refactoring-that-sparks-joy-and-fewer-bugs-3721eb3f0943?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3721eb3f0943</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[refactor]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 17:26:14 GMT</pubDate>
            <atom:updated>2025-05-27T17:17:58.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fqCojDK1IhsvujAQ" /><figcaption>Photo by <a href="https://unsplash.com/@tumbao1949?utm_source=medium&amp;utm_medium=referral">James Wainscoat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Refactoring is often seen as a chore, something to be done only when necessary. But what if we approach it differently? Inspired by Marie Kondo, the philosophy of keeping only what sparks joy can apply to code as well. Clean, maintainable, and efficient code sparks joy — not just for developers but for everyone who interacts with the system.</p><p>In the world of enterprise software development, well-structured code is the foundation for maintainable, scalable applications. Martin Fowler’s seminal work on refactoring and design patterns provides a comprehensive guide to transforming code from merely functional to truly exceptional. In this article, I’ll share insights on applying these principles to enterprise applications, with a focus on Python/Django projects, and demonstrate how thoughtful refactoring can enhance both code quality and system performance.</p><h3>Why “Refactor” ≠ “Rewrite”</h3><p>Pattern-guided refactors give you:</p><ul><li><strong>Predictability</strong> — each micro-step keeps tests green, mirroring Fowler’s discipline. <a href="https://martinfowler.com/articles/2024-refactoring-code-samples.html?utm_source=chatgpt.com">martinfowler.com</a></li><li><strong>Explainable trade-offs</strong> — every pattern (Service Layer, Repository, CQRS) solves a coherence problem but adds indirection; knowing the forces lets you justify the choice in technical reviews. <a href="https://github.com/cloudblue/django-cqrs?utm_source=chatgpt.com">GitHub</a><a href="https://douwevandermeij.medium.com/the-repository-pattern-via-cqrs-with-python-django-elasticsearch-cb38437721d3?utm_source=chatgpt.com">Medium</a></li><li><strong>Enterprise scalability</strong> — layering DTOs, Outbox, or Saga lets your Django monolith grow into a federated or event-driven architecture without a painful lift-and-shift. <a href="https://taiphuong.medium.com/internal-communication-services-with-saga-pattern-event-sourcing-using-rabbitmq-django-celery-c037b2bdf116?utm_source=chatgpt.com">Medium</a>.</li></ul><h3>Core Patterns Already Baked Into Django</h3><p>Django quietly packs a handful of classic design patterns right into its framework DNA. Knowing where each one lives — and what benefit it delivers — lets you lean on Django’s native strengths instead of reinventing wheels during a refactor. The table that follows is your quick reference: pattern name, where you’ll encounter it in a Django project, and the specific payoff you get for free.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2809aed8533e0abae1c4d2854c816130/href">https://medium.com/media/2809aed8533e0abae1c4d2854c816130/href</a></iframe><h3>Advanced, Django-Flavoured Patterns That “Spark Joy”</h3><h4>Fat Models, Thin Views (a.k.a. “Service-Layer Light”)</h4><p><a href="https://spookylukey.github.io/django-views-the-right-way/thin-views.html">Luke Plant’s “Thin Views”</a> manifesto shows how pushing validation &amp; domain rules into models/services eliminates duplicated checks in HTTP glue.<br> <strong>My Blacklist refactor</strong> embodies this: uniqueness constraints, clean(), and is_active live in the model; the view shrinks to I/O orchestration.</p><p><strong>Trade-off:</strong> simple for CRUD, but complex workflows may outgrow model DDS (Domain Deep Service) logic; promote rules to a dedicated services/ module when methods turn into mini-controllers.</p><h3>Case Study A: Fat Models, Thin Views — The Blacklist Feature</h3><p>One key feature of SiNgawas is the ability to determine whether a user is blacklisted from proctoring exams. The business logic ensures that:</p><ul><li>A user (identified by NPM) can be blacklisted for a specific date range.</li><li>There should be no overlapping blacklist periods for the same user.</li><li>The system should efficiently determine if a user is currently blacklisted.</li></ul><p>Below is the original implementation of the Blacklist model:</p><pre># authentication/models.py <br><br>from django.db import models<br>import uuid<br><br>class Blacklist(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    npm = models.CharField(max_length=10)<br>    startDate = models.DateField()<br>    endDate = models.DateField()<br>    keterangan = models.TextField()<br><br>    def __str__(self):<br>        return f&quot;Blacklist-{self.npm} ({self.startDate} - {self.endDate}), {self.keterangan}&quot;</pre><p>During that time, I thought: “I guess this is it, models.py are just definitions of the corresponding table into my <em>Supabase PostgreSQL Database</em>.” But thank heavens, my partner, <em>Anthropic’s Claude 3.7 (Preview) </em>told me about the “<em>Fat Models, Thin Views” </em>philosophy, which is about putting the business logic within the models.py code, ensuring consistency and validity in defining rows of the table.</p><p>So, with my genius partner, we adhered to that philosophy, improving my code readability, maintainability, and (i hope) performance. It mainly <em>“cleans” </em>itself on every data insert and adds a property to check if the student’s blacklist period is active or not:</p><pre>class Blacklist(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    npm = models.CharField(max_length=10)<br>    startDate = models.DateField()<br>    endDate = models.DateField()<br>    keterangan = models.TextField()<br><br>    class Meta:<br>        constraints = [<br>            models.UniqueConstraint(<br>                fields=[&#39;npm&#39;],<br>                condition=models.Q(endDate__gte=timezone.now().date()),<br>                name=&#39;unique_active_blacklist&#39;<br>            )<br>        ]<br>        indexes = [<br>            models.Index(fields=[&#39;npm&#39;, &#39;startDate&#39;, &#39;endDate&#39;], name=&#39;blacklist_search_idx&#39;),<br>        ]<br><br>    def clean(self):<br>        if self.endDate &lt; self.startDate:<br>            raise ValidationError(&quot;End date cannot be before start date&quot;)<br><br>        overlapping = Blacklist.objects.filter(<br>            npm=self.npm,<br>            startDate__lte=self.endDate,<br>            endDate__gte=self.startDate<br>        )<br><br>        if self.pk:<br>            overlapping = overlapping.exclude(pk=self.pk)<br><br>        if overlapping.exists():<br>            raise ValidationError(&quot;This student already has a blacklist record for an overlapping period.&quot;)<br><br>    @property<br>    def is_active(self):<br>        today = timezone.now().date()<br>        return self.startDate &lt;= today &lt;= self.endDate</pre><p>Then, updating views.py is also a must, but just a miniscule code to support the workings of the Blacklist validation:</p><pre>from django.shortcuts import render<br>from django.utils import timezone<br>from rest_framework.decorators import api_view, permission_classes<br>from rest_framework.permissions import IsAuthenticated<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>from .models import Blacklist<br><br>def get_user_npm(request):<br>    &quot;&quot;&quot;<br>    Temporary function to get user NPM until SSO is integrated.<br>    <br>    TODO: In production, this will be replaced with code that extracts<br>    the NPM from the SSO authentication payload.<br>    &quot;&quot;&quot;<br>    return request.GET.get(&#39;npm&#39;, None)<br><br>def format_blacklist_response(npm, blacklist=None):<br>    &quot;&quot;&quot;Helper function to format consistent blacklist API responses.&quot;&quot;&quot;<br>    is_blacklisted = blacklist is not None<br>    blacklist_info = None<br>    <br>    if is_blacklisted:<br>        blacklist_info = {<br>            &quot;start_date&quot;: blacklist.startDate,<br>            &quot;end_date&quot;: blacklist.endDate,<br>            &quot;reason&quot;: blacklist.keterangan,<br>            &quot;days_remaining&quot;: blacklist.days_remaining<br>        }<br>    <br>    return {<br>        &quot;npm&quot;: npm,<br>        &quot;is_blacklisted&quot;: is_blacklisted,<br>        &quot;blacklist_info&quot;: blacklist_info<br>    }<br><br># @permission_classes([IsAuthenticated])<br>@api_view([&#39;GET&#39;])<br>def check_blacklist_status(request):<br>    &quot;&quot;&quot;Check if a user is blacklisted.&quot;&quot;&quot;<br>    <br>    if request.user.is_authenticated:<br>        # TODO: Future implementation: npm = request.user.npm<br>        pass<br>    <br>    # Fall back to query parameter<br>    npm = get_user_npm(request)<br>    <br>    if not npm:<br>        return Response(<br>            {&quot;error&quot;: &quot;No NPM provided or user not authenticated&quot;}, <br>            status=status.HTTP_400_BAD_REQUEST<br>        )<br>        <br>    blacklist = Blacklist.get_active_blacklist(npm)<br>    response_data = format_blacklist_response(npm, blacklist)<br>    <br>    return Response(response_data)</pre><p>Well yes that is still a pretty long code, but it is still mainly just comments and TODOs for future integration with the login SSO.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597bab7da71840d76e3e7547251c1832/href">https://medium.com/media/597bab7da71840d76e3e7547251c1832/href</a></iframe><p>Result: LOC in views.py ↓ 30 %, cyclomatic complexity ↓ 40 %; tests are model-level, thus 4× faster.</p><h3>Case Study B — PengawasExportService: From Utility Class to Service Layer</h3><h4>Before — “God Object” Utility + Heavy View</h4><pre># apps/kelola_jadwal/views.py   (everything jammed together)<br><br>from django.http import HttpResponse<br>from openpyxl import Workbook<br>from apps.kelola_jadwal.models import RoleRuangan<br>import datetime<br><br>def export_pengawas(request):<br>    wb = Workbook()                       # loads full workbook in memory<br>    ws = wb.active<br>    ws.title = &quot;Data Pengawas&quot;<br><br>    # Header row<br>    headers = [&quot;Tanggal&quot;, &quot;Sesi&quot;, &quot;Jam&quot;, &quot;Mata Kuliah&quot;,<br>               &quot;Ruangan&quot;, &quot;Peserta&quot;, &quot;Nama&quot;, &quot;Tipe&quot;, &quot;Email&quot;, &quot;WhatsApp&quot;]<br>    ws.append(headers)<br><br>    # Business logic + queries + formatting **all mixed in one loop**<br>    for rr in RoleRuangan.objects.select_related(<br>            &#39;role_ujian__user&#39;,<br>            &#39;role_ujian__ujian__id_mata_kuliah&#39;,<br>            &#39;role_ujian__ujian__sesi&#39;,<br>            &#39;ujian_ruangan__ruangan&#39;):<br>        <br>        ujian      = rr.role_ujian.ujian<br>        sesi       = ujian.sesi<br>        user       = rr.role_ujian.user<br>        ruangan    = rr.ujian_ruangan.ruangan<br>        mk         = ujian.id_mata_kuliah<br><br>        ws.append([<br>            sesi.tanggal.strftime(&quot;%A, %d %B %Y&quot;),<br>            sesi.get_sesi_waktu_display(),<br>            f&quot;{ujian.waktu_mulai:%H.%M} - {ujian.waktu_selesai:%H.%M}&quot;,<br>            mk.nama_mata_kuliah,<br>            f&quot;{ruangan.nama_ruangan} ({ruangan.get_lokasi_display()})&quot;,<br>            rr.ujian_ruangan.jumlah_mahasiswa,<br>            user.nama,<br>            rr.role_ujian.get_role_display(),<br>            user.email,<br>            getattr(user, &quot;phone_number&quot;, &quot;&quot;),<br>        ])<br><br>    # narrow columns; no autosize; huge memory if rows &gt;&gt; 10 k<br>    response = HttpResponse(<br>        content_type=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;<br>    )<br>    fname = datetime.datetime.now().strftime(&quot;pengawas_%Y%m%d_%H%M%S.xlsx&quot;)<br>    response[&quot;Content-Disposition&quot;] = f&#39;attachment; filename=&quot;{fname}&quot;&#39;<br>    wb.save(response)                 # saves after full workbook in RAM<br>    return response</pre><p><em>Smells</em> → one giant function, duplicated header strings, mixing I/O, queries, business rules, and a “read/write” workbook that can eat gigabytes of RAM on large datasets. <a href="https://serverfault.com/questions/1109013/why-does-writing-to-a-workbook-of-a-few-mb-with-pythons-openpyxl-module-eat-gig?utm_source=chatgpt.com">Server Fault</a></p><h4>After — Repository + DTO + Streamed Service Layer</h4><ol><li>repositories.py</li></ol><pre># apps/kelola_jadwal/repositories.py<br>from apps.kelola_jadwal.models import RoleRuangan<br><br>class RoleRuanganRepo:<br>    &quot;&quot;&quot;Repository = explicit gateway to persistence (Cosmic Python).&quot;&quot;&quot;<br>    @staticmethod<br>    def all_with_related():<br>        return (RoleRuangan.objects<br>                .select_related(<br>                    &quot;role_ujian__user&quot;,<br>                    &quot;role_ujian__ujian__id_mata_kuliah&quot;,<br>                    &quot;role_ujian__ujian__sesi&quot;,<br>                    &quot;ujian_ruangan__ruangan&quot;))</pre><p>2. dtos.py</p><pre># apps/kelola_jadwal/dtos.py<br>from dataclasses import dataclass<br>from datetime import date<br><br>@dataclass(frozen=True)<br>class ProctorRow:<br>    tanggal:       str<br>    sesi:          str<br>    jam:           str<br>    mata_kuliah:   str<br>    ruangan:       str<br>    peserta:       int<br>    nama:          str<br>    tipe:          str<br>    email:         str<br>    whatsapp:      str</pre><p>3. services/export_proctor.py</p><pre># apps/kelola_jadwal/services/export_proctor.py<br>from typing import Iterable<br>from openpyxl import Workbook<br>from openpyxl.utils import get_column_letter<br>from openpyxl.styles import Font<br>from openpyxl.worksheet.write_only import WriteOnlyWorksheet<br>from io import BytesIO<br><br>from .dtos import ProctorRow<br>from ..repositories import RoleRuanganRepo<br><br>class ProctorExportService:<br>    HEADERS = [<br>        &quot;Tanggal Ujian&quot;, &quot;Sesi&quot;, &quot;Jam&quot;, &quot;Mata Kuliah&quot;, &quot;Ruangan&quot;,<br>        &quot;Peserta&quot;, &quot;Nama&quot;, &quot;Tipe Pengawas&quot;, &quot;Email&quot;, &quot;WhatsApp&quot;<br>    ]<br><br>    def _to_dto(self, rr) -&gt; ProctorRow:<br>        ujian   = rr.role_ujian.ujian<br>        sesi    = ujian.sesi<br>        user    = rr.role_ujian.user<br>        ruangan = rr.ujian_ruangan.ruangan<br>        mk      = ujian.id_mata_kuliah<br><br>        jam = &quot;&quot;<br>        if ujian.waktu_mulai and ujian.waktu_selesai:<br>            jam = f&quot;{ujian.waktu_mulai:%H.%M} - {ujian.waktu_selesai:%H.%M}&quot;<br><br>        return ProctorRow(<br>            tanggal      = sesi.tanggal.strftime(&quot;%A, %d %B %Y&quot;),<br>            sesi         = sesi.get_sesi_waktu_display(),<br>            jam          = jam,<br>            mata_kuliah  = mk.nama_mata_kuliah,<br>            ruangan      = f&quot;{ruangan.nama_ruangan} ({ruangan.get_lokasi_display()})&quot;,<br>            peserta      = rr.ujian_ruangan.jumlah_mahasiswa,<br>            nama         = user.nama,<br>            tipe         = rr.role_ujian.get_role_display(),<br>            email        = user.email,<br>            whatsapp     = getattr(user, &quot;phone_number&quot;, &quot;&quot;),<br>        )<br><br>    # --- public API -----------------------------------------------------<br><br>    def generate_xlsx_bytes(self) -&gt; bytes:<br>        wb: Workbook              = Workbook(write_only=True)  # low-mem mode :contentReference[oaicite:1]{index=1}<br>        ws: WriteOnlyWorksheet    = wb.create_sheet(&quot;Data Pengawas&quot;)<br><br>        # header row (bold)<br>        ws.append([Font(bold=True).copy(value=h) for h in self.HEADERS])<br><br>        # stream rows<br>        for rr in RoleRuanganRepo.all_with_related().iterator():<br>            dto = self._to_dto(rr)<br>            ws.append(dto.__dict__.values())<br><br>        buffer = BytesIO()<br>        wb.save(buffer)           # single save; write-only can only save once<br>        buffer.seek(0)<br>        return buffer.getvalue()</pre><p>4. Slim View</p><pre># apps/kelola_jadwal/api/export.py<br>from rest_framework.views import APIView<br>from rest_framework.permissions import IsAdminUser<br>from django.http import HttpResponse<br>import datetime<br><br>from apps.kelola_jadwal.services.export_proctor import ProctorExportService<br><br>class ExportPengawasXLSXView(APIView):<br>    permission_classes = [IsAdminUser]<br><br>    def get(self, request):<br>        xlsx = ProctorExportService().generate_xlsx_bytes()<br>        timestamp = datetime.datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)<br>        response  = HttpResponse(<br>            xlsx,<br>            content_type=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;,<br>        )<br>        response[&quot;Content-Disposition&quot;] = (<br>            f&#39;attachment; filename=&quot;data_pengawas_{timestamp}.xlsx&quot;&#39;<br>        )<br>        return response</pre><h3>Key Improvements &amp; References</h3><ul><li><strong>Memory-safe streaming</strong> with Workbook(write_only=True) keeps RAM &lt; 10 MB even for 1 M rows.</li><li><strong>Repository + DTO</strong> isolates ORM from export logic.</li><li><strong>Service Layer</strong> centralizes business rules, aligning with community advice for large Django projects.</li><li>Column-width auto-resize deliberately dropped — write-only mode cannot inspect cells afterwards.</li><li>View shrinks to five lines; no DB access, no file-format code.</li></ul><p>Copy, run tests, and watch your CI time — and memory footprint — shrink!</p><p>Refactoring isn’t finished once the code compiles — the real payoff shows up when every subsequent stage of the Software Development Life Cycle gets easier, faster, and safer.</p><p>By moving business rules into models (or a dedicated service layer) and slimming views down to pure HTTP plumbing, we create a separation of concerns that acts like a well-tuned conveyor belt: each SDLC phase receives just the pieces it needs, in the cleanest possible shape.</p><p>Below, let’s walk through that conveyor belt, phase by phase, to see exactly <strong>where the joy appears</strong> — and why this one architectural choice keeps paying dividends long after the refactor PR is merged.</p><h3>1. Requirements Analysis Phase</h3><p><strong>Benefit:</strong> Clear Separation of Concerns (SoC)</p><ul><li>Business logic is encapsulated in models and services, while views focus only on handling HTTP requests.</li><li>This makes it easier to <strong>translate functional requirements</strong> into technical implementation without spreading logic across files.</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Easier Requirement Mapping</strong> → Developers can identify where a requirement should be implemented (Model vs. View).<br>- <strong>Consistency in Feature Design</strong> → Encourages systematic handling of business logic across different modules.</p><h3>2. System Design Phase</h3><p><strong>Benefit:</strong> Scalability and Maintainability</p><ul><li>By keeping models responsible for business logic, <strong>adding new features</strong> or modifying rules is localized.</li><li>Easier to enforce <strong>design patterns</strong> (e.g., Repository, Service Layer).</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Encourages Modular Design</strong> → Reduces interdependencies, making system design more scalable.<br>- <strong>Easier Refactoring</strong> → When business rules evolve, changes happen in models/services, not scattered across views.</p><h3>3. Implementation Phase</h3><p><strong>Benefit:</strong> Code Reusability and Readability</p><ul><li>Views remain <strong>lightweight</strong>, handling only request validation and response formatting.</li><li>The same business logic can be reused in <strong>different views, APIs, or CLI commands</strong> without duplication.</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Reduces Code Duplication</strong> → A single source of truth for business rules.<br>- <strong>Improves Readability</strong> → Developers can quickly understand the role of each component.</p><h3>4. Testing Phase</h3><p><strong>Benefit:</strong> Easier Unit Testing &amp; Mocking</p><ul><li>Since business logic is decoupled from views, <strong>unit tests</strong> can be written at the model/service level <strong>without requiring an HTTP request</strong>.</li><li>View tests focus only on <strong>request handling</strong>, ensuring <strong>separation of responsibilities</strong>.</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Faster and More Focused Tests</strong> → Business logic is tested in isolation.<br>- <strong>Easier Mocking</strong> → Unit tests don’t need to rely on database queries.</p><h3>5. Deployment Phase</h3><p><strong>Benefit:</strong> Better Performance &amp; Load Distribution</p><ul><li>Processing-intensive operations are handled at the model level, reducing the view’s workload.</li><li>Improves API response times by <strong>minimizing unnecessary logic in views</strong>.</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Optimized API Performance</strong> → Views act as thin request handlers, improving response times.<br>- <strong>Better Load Management</strong> → Heavy computations are <strong>offloaded</strong> from HTTP request processing.</p><h3>6. Maintenance &amp; Future Enhancements</h3><p><strong>Benefit:</strong> Easier Debugging and Feature Expansion</p><ul><li>When debugging issues, developers <strong>only check models and services</strong> for logic errors.</li><li>New business rules can be implemented in models <strong>without affecting views</strong>.</li></ul><p><strong>Impact on SDLC:</strong><br>- <strong>Faster Bug Fixing</strong> → Clear separation of logic reduces debugging complexity.<br>- <strong>Smoother Feature Addition</strong> → Business logic modifications don’t require touching views.</p><h3>7. Security &amp; Compliance</h3><p><strong>Benefit:</strong> Centralized Business Logic Validation</p><ul><li>All validation and business rules are enforced at the model/service level, <strong>reducing security risks</strong> from bypassing view-based checks.</li><li>Ensures compliance with <strong>data integrity rules</strong> and business constraints.</li></ul><p><em>Sources:</em></p><ul><li><a href="https://spookylukey.github.io/django-views-the-right-way/thin-views.html">https://spookylukey.github.io/django-views-the-right-way/thin-views.html</a></li><li><a href="https://www.geeksforgeeks.org/refactoring-introduction-and-its-techniques/">Refactoring — Introduction and Its Techniques — GeeksforGeeks</a></li><li><a href="https://docs.djangoproject.com/en/5.2/topics/http/middleware/">Middleware | Django documentation | Django</a></li><li><a href="https://adamj.eu/tech/2016/11/30/optimizing-construction-of-django-querysets/?utm_source=chatgpt.com">Optimizing the construction of Django QuerySets — Adam Johnson</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3721eb3f0943" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #2: SiNgawas Team AssembleMy Family My Team! ]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-2-singawas-team-assemble-my-family-my-team-b58304d7d33a?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58304d7d33a</guid>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[teamwork]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 17:08:56 GMT</pubDate>
            <atom:updated>2025-04-28T18:17:18.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qsMsbrz-dFUL1PFc" /><figcaption>Photo by <a href="https://unsplash.com/@miinyuii?utm_source=medium&amp;utm_medium=referral">Duy Pham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Make Friends, Establish Relations &amp; Help People</h3><p>Building meaningful relationships is the cornerstone of any successful team. In SiNgawas, we don’t just work together; we support, uplift, and empower each other. Our journey isn’t just about completing a project but about fostering deep connections that extend beyond work.</p><h3>My Experience During Scrum</h3><p>From the very first meeting, I felt an overwhelming sense of excitement about this Scrum project. Working alongside Akmal, Belati, Hanau, Rafli, Raissa, Sasa, and myself has been nothing short of amazing. Akmal, as our Product Owner, took the initiative, setting the tone for an organized and collaborative workflow. His leadership allowed everyone to naturally chip in, making our teamwork efficient and seamless.</p><p>One of my key contributions was in setting up technologies, providing insights into the best architecture choices, and refining the user flow. I also made sure we asked the right questions to our client, ensuring our product was well-aligned with the intended vision. Every Discord call was a blend of professionalism and fun, where appropriate jokes were shared, mutual respect was maintained, and offensive language was never a part of our conversations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*vkWoTs8SAdeRlfSiRXf87w.png" /><figcaption>Family Picture</figcaption></figure><p>Despite everyone having tight schedules, we always delivered on our commitments. The combination of support, humor, and shared responsibility made the experience both enjoyable and productive. SiNgawas isn’t just a team — it’s a family that grows, learns, and succeeds together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ut1-mL2NqLUUohmN" /><figcaption>Us plotting to make the best app</figcaption></figure><h3>Building Strong Relationships in the Team</h3><p>Creating strong, meaningful relationships within a team is crucial for its success. It’s not just about working together on tasks; it’s about knowing each other’s strengths, vulnerabilities, and how we can complement one another. In <strong>SiNgawas</strong>, I believe we’ve truly embraced this principle. From my first day, I made it a point to be open and available for anyone needing help, whether it was through casual chats or during our daily standups. This helped establish trust, which is the foundation of any good team.</p><p><strong>What I Did:</strong> I actively participated in our <strong>Discord conversations</strong>, making sure to be supportive and encouraging. I also took the initiative to <strong>create guides for frontend developers</strong> who were new to the project, helping them navigate the development process smoothly. Onboarding backend developers was another task I tackled, ensuring they felt comfortable with the tools and technologies we were using. The aim was always to create an inclusive, welcoming environment where everyone felt they could ask questions and contribute without hesitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGmsUarkil-IBRQpDZT4XA.png" /></figure><p><strong>What I Did:</strong> I actively participated in our <strong>Discord conversations</strong>, making sure to be supportive and encouraging. I also took the initiative to <strong>create guides for frontend developers</strong> who were new to the project, helping them navigate the development process smoothly. Onboarding backend developers was another task I tackled, ensuring they felt comfortable with the tools and technologies we were using. The aim was always to create an inclusive, welcoming environment where everyone felt they could ask questions and contribute without hesitation.</p><h3>Understanding People and Bringing Joy</h3><p>A remarkable team is not only efficient but also one that understands and cares about its members. Even in difficult moments, we need to maintain a sense of joy and keep pushing forward. This doesn’t mean avoiding hard conversations, but rather approaching challenges with a positive mindset. Whether we were troubleshooting a tough bug or facing a looming deadline, we always found ways to keep our spirits high, making jokes when appropriate, and offering words of encouragement.</p><p><strong>What I Did:</strong> During our <strong>Scrum meetings</strong>, I made sure to actively listen to everyone, acknowledging their contributions and offering support where needed. Even though our schedules were tight, we made it a priority to check in on each other, creating a supportive and friendly environment. It was important to not just focus on the work, but also on our <strong>well-being as a team</strong>, ensuring no one was feeling overwhelmed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*RsDWoaPJPxoz3-QgYp7GUA.png" /><figcaption>Us Checking up on <a href="https://medium.com/u/3990c4960a41">Farrell Muhammad Hanau</a></figcaption></figure><h3>Motivating the Team and Building Dynamics</h3><p>One of the most rewarding parts of being part of this team was the opportunity to <strong>motivate and build dynamics</strong>. We always worked to build each other up, not just through praise but also by giving constructive feedback in a way that helped everyone improve. Our <strong>team slogan</strong> — “SiNgawas Team Assemble!” — became a rallying cry, reminding us of our commitment to supporting one another. Every time we faced a challenge, we’d reflect on this slogan and use it as motivation to push through.</p><p><strong>What I Did:</strong> In terms of capacity building, I helped ensure our <strong>team’s growth</strong> was not just about skill enhancement but also about improving our collaboration. Regular team evaluations were something I suggested, which gave everyone an opportunity to share feedback and highlight areas for improvement. This process allowed us to identify strengths and weaknesses within the team and make necessary adjustments.</p><p>Additionally, integrating our workflow with tools like <strong>webhooks for GitLab</strong> alerts and notifications has been incredibly helpful for keeping everyone informed. Every time a new pull request or merge request is made, our team gets notifications through channels like <strong>Discord</strong>, ensuring we stay on top of ongoing development and issues.</p><h3>Servant Leadership in Action</h3><p>The leadership style in SiNgawas is rooted in <strong>servant leadership</strong>, where we prioritize the needs of the team over individual ambitions. It’s about making sure everyone has the support and resources they need to succeed. This was particularly important when we were making decisions about the project’s direction, as everyone’s opinion was valued, and collaboration was always emphasized over hierarchy.</p><p><strong>What I Did:</strong> I made sure to actively listen during discussions and provided resources, be it in the form of guides or clarification on tech stack choices, to ensure that everyone had what they needed to succeed. <strong>Leading by example</strong> was key, and I always made an effort to show humility and empathy, ensuring that every team member knew their input mattered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*2pWXRZo-regZRUtmWa-QJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*7vlxWl_l9Dvde2UtxFRgUA.png" /></figure><p>In terms of <strong>issue tracking and problem resolution</strong>, we actively used <strong>GitLab Issues</strong> to track bugs and tasks. Every issue became an opportunity for us to brainstorm and troubleshoot together. Whether it was a minor bug or a significant challenge, we worked collaboratively to resolve it.</p><h3>Innovation and Continuous Improvement</h3><p>As part of our Scrum process, we constantly aimed for <strong>innovation and breakthroughs</strong>. These innovations didn’t just have to be technical but could also relate to <strong>team engagement</strong> and improving our workflow. I helped foster an environment where every sprint felt like a fresh opportunity to improve, and we actively discussed what could be done better in the future.</p><p><strong>What I Did:</strong> In each sprint, I made sure we were experimenting with new tools and approaches, testing them to see how they could benefit our product and the team. Whether it was trying out new libraries or tweaking our <strong>team workflows</strong>, I made it a point to ensure we weren’t just sticking to what worked, but constantly evolving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xI1wdd074-2pKxzG3fLapw.png" /></figure><p><strong>What I Did:</strong> In each sprint, I made sure we were experimenting with new tools and approaches, testing them to see how they could benefit our product and the team. Whether it was trying out new libraries or tweaking our <strong>team workflows</strong>, I made it a point to ensure we weren’t just sticking to what worked, but constantly evolving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi2hvXdEY8TqdLg2HGyRkQ.png" /></figure><p>For example, with <strong>GitLab and webhook alerts</strong>, we innovated by automating the notification process for merge requests and issue updates. This allowed us to catch potential conflicts early, making our workflow more seamless and efficient.</p><h3>Conclusion</h3><p>Overall, being a part of <strong>SiNgawas</strong> has been an incredibly fulfilling experience. We’ve succeeded not only in building a great product but also in creating a space where relationships flourish, joy is maintained, and productivity thrives. As we continue forward, I look forward to what we’ll achieve, knowing that our foundation of strong relationships, servant leadership, and constant innovation will carry us through.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58304d7d33a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambatuscrum #1: Why a Well-Managed Git Repo Runs Smoother Than Any Government Office]]></title>
            <link>https://medium.com/@soros21febriano/ambatuscrum-1-why-a-well-managed-git-repo-runs-smoother-than-any-government-office-278e7851076c?source=rss-7bbc5606379e------2</link>
            <guid isPermaLink="false">https://medium.com/p/278e7851076c</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[merge-request]]></category>
            <category><![CDATA[let-me-merge]]></category>
            <dc:creator><![CDATA[sorfeb]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 16:57:50 GMT</pubDate>
            <atom:updated>2025-05-03T16:43:04.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2I_Y-9lgKSR0SKhA" /><figcaption>Photo by <a href="https://unsplash.com/@brookecagle?utm_source=medium&amp;utm_medium=referral">Brooke Cagle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Preface:</strong><br>If you’ve ever worked with <strong>Git</strong>, you know the <strong>pain and beauty</strong> of managing a repository. Every commit, every merge request, every conflict resolution — it’s all part of a structured, transparent, and (mostly) efficient process.</p><p>Now, imagine if our governments operated like a scrum team of college students that really need an A on the Software Project. Policies would have pull requests before breaking society, documentation would be clearer than a new intern’s first README, and bad decisions wouldn’t get merged into main without review. But alas, instead of scrum boards, we have bureaucracy, and instead of clean commit histories, we have laws full of spaghetti logic.</p><p>Let me walk you through my experiences, where Git merge requests, scrum boards, and commit messages have streamlined my projects better than any government process ever could…</p><h3>Chapter 1: Order vs. Chaos — The Git Repo That Keeps Us Sane</h3><p>If you’ve ever tried to <strong>build a project in a team of seven developers</strong>, you know that <strong>without structure, things fall apart fast</strong>. Files get overwritten, someone pushes an untested feature to main, and before you know it, you&#39;re debugging production issues while questioning your life choices.</p><p>That’s why in <strong>SiNgawas</strong>, we set up a <strong>clear GitLab workflow</strong> to avoid complete anarchy:</p><ul><li><strong>Branch Naming Conventions for Clarity:</strong></li><li>dev-{name} → For individual development branches.</li><li>pbi-{id_number}-{backlog_name} → For feature-based development, aligned with our <strong>Notion Scrum Board</strong>.</li><li>development → staging → main → To control the flow of changes.</li></ul><p>This structure allows us to <strong>trace every change</strong>, <strong>avoid unnecessary merge conflicts</strong>, and ensure that no one accidentally pushes broken code directly into production.</p><h4>Why It Works:</h4><ol><li>Every developer knows <strong>where their code belongs</strong>.</li><li><strong>Backlogs are mapped to branches</strong>, so there’s no mystery about what a feature branch is for.</li><li><strong>Merging into main isn’t a free-for-all</strong>, preventing “accidental feature releases” (a.k.a. chaos).</li></ol><p>The result? We don’t wake up to <strong>mysterious code changes</strong> that “someone” pushed without telling anyone. And that alone is a <strong>win for our sanity</strong>.</p><h3>Chapter 2: Discord — The Ultimate Communication Hub</h3><p>Let’s talk about <strong>team communication</strong>. Imagine trying to coordinate complex software development using <strong>a chat app where messages get buried under stickers, unrelated conversations, and late replies</strong> (<em>cough</em> Line <em>cough</em>).</p><p>At first, we tried <strong>asynchronous communication via messaging</strong>, but the <strong>delays</strong> were unbearable. Messages would sit unread for hours, and by the time a reply came, the topic had already shifted 10 times.</p><p><strong>Enter: Discord.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nMHCNEXVg8sq0KRk9c_Kw.png" /><figcaption>Our beloved Discord</figcaption></figure><p>We <strong>moved to daily Discord meetings</strong> for:</p><ul><li><strong>Real-time, low-latency communication</strong> → No more waiting forever for a response.</li><li><strong>Screen-sharing for debugging together</strong> → Way faster than sending screenshots back and forth.</li><li><strong>Simulating real-world team interactions</strong> → Builds <strong>team chemistry</strong> and makes debugging feel less isolating.</li></ul><p>Now, instead of spending <strong>30 minutes scrolling up</strong> to find that one buried message, we just <strong>talk, discuss, and solve problems immediately</strong>. It also made working on SiNgawas <strong>feel less like an academic group project and more like an actual dev team</strong>.</p><blockquote>Automating Notifications with GitLab Webhooks</blockquote><p>Manual status checks are a thing of the past. By feeding GitLab events straight into Discord, your team stays in sync without context‑switching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WFMVMgK406YvcG0eEDk2g.png" /><figcaption>Our webhook bot names “Hanau”</figcaption></figure><h4>Here’s how we do it:</h4><ol><li><strong>Create a Discord Webhook</strong></li></ol><ul><li>In your notification channel (e.g. #singawas-be-notif), go to Server Settings → Integrations → Webhooks → “Create Webhook.”</li><li>Copy the webhook URL.</li></ul><p><strong>2. Configure GitLab Project Hook</strong></p><ul><li>In your GitLab repo, navigate to Settings → Webhooks.</li><li>Paste the Discord webhook URL.</li><li>Select triggers: Push events, Merge request events, Issue events, Pipeline events.</li><li>Enable SSL verification for security.</li></ul><p><strong>3. Customize the Payload</strong></p><ul><li>Optionally filter branches or event types so only development → staging → main merges show up.</li><li>Use GitLab’s “Custom context message” to highlight MR titles, authors, and links.</li></ul><p><strong>4. Validate in Discord</strong></p><ul><li>Push a test commit or open a merge request.</li><li>You’ll see a message like “🔀 farrell.muhammad22 merged !87 Merge dev-hanau into development” appear instantly.</li></ul><p><strong>5. Maintain and Iterate</strong></p><ul><li>Periodically review which events are noisy and disable unnecessary triggers (e.g. tag pushes).</li><li>Add actionable buttons in Discord (via message embeds) to approve MRs or jump to pipelines.</li></ul><h4>Developer Onboarding Guides in Discord</h4><p>When bringing new frontend and backend developers into your project, a dedicated onboarding space in Discord can make all the difference. In our #fe-guide channel (see Chapter 1), we laid out environment setup, run scripts, and common tasks. Let’s formalize that into a reusable process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99KcqNU-GEGDBR2JwnnWog.png" /><figcaption>#fe-guide</figcaption></figure><ol><li><strong>Create an Onboarding Channel</strong></li></ol><ul><li>Set up a #start-here or #onboarding channel.</li><li>Pin a welcome message that links to your FE and BE developer guides.</li><li>Use Discord’s Community Onboarding questions to automatically assign roles (e.g. “Frontend,” “Backend”) based on their answers.</li></ul><p><strong>2. Publish Structured Guides</strong></p><ul><li><strong>Frontend Guide</strong>: Include sections like Environment Setup, Component Library Usage, Styling Conventions, and Testing Commands.</li><li><strong>Backend Guide</strong>: Cover API schema, database migrations, local server launch, and monitoring endpoints.</li><li>Attach code snippets, sample .env files, and link to your GitLab repo’s README.</li></ul><p><strong>3. Automate Role Assignment</strong></p><ul><li>Use a bot (e.g. Dots or custom Discord bot) to ask new members “Which area are you working on?” and grant “FE Dev” or “BE Dev” roles.</li><li>This ensures they see only the relevant channels and guides.</li></ul><p><strong>4. Host Live Q&amp;A Sessions</strong></p><ul><li>Schedule a weekly “office hours” voice channel where juniors can ask seniors about setup issues.</li><li>Record these sessions and drop the clips into the onboarding channel.</li></ul><blockquote>By centralizing all onboarding materials in Discord, you reduce confusion, accelerate ramp‑up time, and foster a sense of belonging from day one.</blockquote><h3>Chapter 3: Communication — The Dev Team’s Secret Weapon</h3><p>Merge requests (MRs) are <strong>where good intentions meet cold, hard reality</strong>. It’s easy to think your code is perfect — until someone else <strong>reviews it and finds everything wrong with it</strong>.</p><p>In our team:</p><ul><li><strong>If you merge into a PBI branch</strong>, your fellow <strong>backlog contributors must QA</strong> it first.</li><li><strong>If you merge into dev, staging, or main,</strong> the <strong>entire team must review it</strong>.</li></ul><p>And most importantly:<br>🛑 <strong>No “yes-men” allowed.</strong></p><ul><li>A <strong>real code review means critical feedback</strong>, not just <a href="https://github.com/jquery/2015-developer-summit/issues/24">&quot;LGTM&quot; (Looks Good to Me).</a> Slangs from the Urban Dictionary or our local hometowns are allowed as long as it is not giving malicious intent or adding confusion.</li><li>If something <strong>is unclear</strong>, it gets flagged and fixed <em>before</em> merging.</li></ul><p>This approach ensures that <strong>bad code doesn’t make it upstream</strong>, because fixing issues in development is much easier than debugging them in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPof_BTOyBxc4h6ks9kQpQ.png" /></figure><p>As you can see, our team is walking the talk. Everyone gives constructive criticism, supporting each other, giving meaningful feedbacks, and pointing out aspects to improve. If we keep doing this for each Merge Requests, I am sure that our repo will comply with industry standards!</p><h3>Chapter 4: Merge Requests — Filtering Out Bad Code Like a Good Legal System Should</h3><p>Everyone’s been guilty of writing <strong>bad commit messages</strong> at some point. Maybe you’ve committed something like:<br>❌ &quot;1&quot;<br>❌ &quot;.&quot;<br>❌ &quot;done&quot;</p><p>While funny in the moment, these messages are <strong>useless</strong> when you need to debug something six months later.</p><p>That’s why our team adopted <strong>a structured commit format</strong>, inspired by:</p><ul><li><a href="https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716">Josh Buchea’s Git Commit Guide</a></li><li>A <strong>senior’s software repo standards</strong>: <a href="https://gitlab.cs.ui.ac.id/maams-ppl/maams-be">MAAMS Backend</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evL3nTjH4kxE1GIevi-nOA.png" /><figcaption>My commits for the front repo</figcaption></figure><p>Our format:<br>🔹 <strong>[RED]: feat(Authentication): add SSO UI authentication feature</strong><br>🔹 <strong>[YELLOW]: fix(UI): correct button padding in login form</strong><br>🔹 <strong>[GREEN]: refactor(Database): optimize query for user search</strong></p><p>Each commit <strong>clearly tells</strong>:<br>✅ <strong>What changed</strong> (e.g., a feature, fix, refactor).<br>✅ <strong>Where it happened</strong> (e.g., Authentication, UI, Database).<br>✅ <strong>Why it matters</strong> (e.g., SSO integration, UI improvement).</p><p><strong>Lesson learned?</strong> Commit messages are <strong>not just for you today — they’re for your future self (and teammates) who will one day debug your code</strong>.</p><h3>Chapter 5: Commit Messages — Because Clarity is a Love Letter to Your Future Self</h3><p>At first, enforcing <strong>branch naming conventions, structured merge requests, and semantic commit messages</strong> felt like <strong>extra work</strong>. Some team members questioned, <strong>“Why all this discipline?”</strong></p><p>But here’s why it pays off:</p><ul><li><strong>We already work like a real dev team.</strong></li><li><strong>Recruiters look for candidates who understand Git workflows</strong> — this is a major advantage in job hunting.</li><li><strong>Our teamwork efficiency has skyrocketed</strong> — even complex backlogs feel manageable.</li></ul><p>And the best part? <strong>This experience will stick with us beyond this project.</strong></p><p>By the time this course ends, <strong>we’re not just students who built an app</strong> — we’re a <strong>team of engineers with real-world experience</strong>. That’s a <strong>career advantage that will get us noticed</strong>.</p><h3>Chapter 6: Jira — The Town Hall</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJ4HI8o9edGcedT7RAbw_A.png" /><figcaption>Our beloved Jira — an agile project management tool</figcaption></figure><p>Ah, the legendary Town Hall. No, not the one where the mayor talks about how well the town’s chickens are laying eggs. We’re talking about the virtual “town hall” that is Jira — a place where developers gather to stare at tickets, keep their brains in check, and occasionally lose track of the number of times they’ve hit “refresh” hoping to see some progress. Welcome to the Scrum board, where magic and chaos coexist in a beautiful mess.</p><h4>From Notion to Jira: The Great Migration</h4><p>If you’ve ever tried to run a Scrum board in Notion, you know that it’s a bit like trying to make a sandwich with just one piece of bread — technically possible but not quite fulfilling. Notion gave us the flexibility to add… everything. Features? Sure. Categories? Why not. Tables inside tables? Absolutely. But, as you might guess, this overabundance of customization led us down a rabbit hole of confusion. What to add, how to structure it — who knew Scrum boards could be so complicated? Eventually, we realized that Notion wasn’t specialized for Scrum. It was like using a Swiss army knife for a job that only required a spoon. So, we made the move to Jira in Sprint 2, and oh boy, was it a game-changer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7_QlOKFEdLVSkzLYYIGhg.png" /><figcaption>Our forgotten Notion relic</figcaption></figure><p>Jira, for all its quirks and frustrations, has one thing going for it: <strong>structure</strong>. It’s like moving from a messy garage to a well-organized storage unit where things (mostly) stay in their place. With Jira, we were finally able to focus on the core of our workflow instead of wrestling with what feature should be added next.</p><h4>The Scrum Board — Where Tasks Live and Die</h4><p>Now, as you can see from the screenshots, our Scrum board looks like a well-oiled machine… sort of. With Sprint 2 underway, our issues are clearly defined and categorized. We’ve got tasks moving in and out of the <strong>To Do</strong>, <strong>In Progress</strong>, and <strong>Done</strong> columns. It’s almost as if we’ve moved from the “chaotic artist” phase to the “methodical engineer” phase of the development cycle. There’s even a healthy sprinkling of pink and purple to keep things stylish. But really, it’s not about the colors (okay, maybe a little), it’s about ensuring we’ve got a handle on all the moving parts.</p><p>What I love most about Jira is how it turns ambiguity into clarity. Remember those times in Notion when you’d look at a task and wonder, “What exactly is this person supposed to do?” Now, it’s crystal clear. Each issue is tied to a specific assignee, has clear acceptance criteria, and best of all — <strong>due dates</strong>. Yes, that magical thing called a deadline that everyone loves to hate, but secretly helps get things done.</p><h4>Sprint 2: In Progress, But Not Always Smooth Sailing</h4><p>Sprint 2 has been a wild ride. We kicked it off with some housekeeping, fixing issues from Sprint 1, and, well, just getting ourselves situated. The beauty of Scrum (and Jira’s Scrum board) is how it allows you to see everything you’re working on at a glance. You know which tasks are in progress, who’s assigned to them, and — most importantly — what needs to be done next. You’ll see tasks like <strong>“Import Schedule”</strong> and <strong>“Edit Course Data”</strong> buzzing around in the <strong>In Progress</strong> section. These are the tasks that make us feel like we’re actually moving the needle.</p><p>But let’s not sugarcoat it — Jira is also where the struggle happens. Just ask anyone staring at their issue for the umpteenth time, wondering how to proceed. It’s not all rainbows and perfectly aligned sprints. In fact, the constant “refreshing” of the board and the occasional shuffle of priority remind me of a cat constantly knocking things off the table… unpredictable but necessary for growth.</p><h4>Key Jira Benefits: Like Finding the Perfect Coffee Cup</h4><p>So, why stick with Jira? Simple. It helps keep us on track, even when we’re one coffee away from disaster. The <strong>Backlog</strong> view is a godsend — it shows us exactly where we stand. Do we have too many items in <strong>To Do</strong>? Maybe we need to reassess. Is someone overwhelmed? Maybe it’s time to pull in some reinforcements. It gives us that bird’s eye view that we didn’t quite have in Notion, but we’re definitely feeling now.</p><p>And, of course, there are the cool little gems that make developers smile — like the <strong>“Assign to me”</strong> button. No more awkward meetings where everyone points at each other saying, “You do it!” Instead, you can just claim ownership of your task with a click. There’s also the <strong>Issue Tracking</strong> feature, where you can follow tasks in real-time and see how things are progressing. You can even comment directly on issues. No more endless email chains — Jira keeps everything in one place. It’s like a well-mapped` treasure hunt for your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LW-b5gMEpe-A_4UA3uVaZA.png" /></figure><p>When it comes to agile project management, two names often rise to the top: Notion and Jira. Both platforms offer boards, tasks, and collaboration features — but their philosophies, strengths, and ideal use cases differ significantly. Here’s a side‑by‑side comparison synthesized from Everhour, Sabili, and Tettra:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e2efd413965111fe23e74161367e0d3/href">https://medium.com/media/3e2efd413965111fe23e74161367e0d3/href</a></iframe><p>Jira transforms your student Scrum experiment into a professional‑grade process — empowering you with the planning, controls, and insights that keep complex software projects on track.</p><blockquote>Reference(s):</blockquote><blockquote><a href="https://everhour.com/blog/notion-vs-jira/#:~:text=Notion%20vs%20Jira%20%E2%80%93%20two%20powerful,project%20tracking%20and%20software%20development.">Notion vs Jira: Which Tool Dominates Project Management? [2025]</a></blockquote><blockquote><a href="https://sabili.id/notion-vs-jira-pilih-mana/">https://sabili.id/notion-vs-jira-pilih-mana/</a></blockquote><blockquote><a href="https://tettra.com/article/notion-vs-jira/">https://tettra.com/article/notion-vs-jira/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=278e7851076c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>