<?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 Kenbalya on Medium]]></title>
        <description><![CDATA[Stories by Kenbalya on Medium]]></description>
        <link>https://medium.com/@kenbalya27?source=rss-29e0e45b570c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*swF6f9zvRVjYh3xX</url>
            <title>Stories by Kenbalya on Medium</title>
            <link>https://medium.com/@kenbalya27?source=rss-29e0e45b570c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:57:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kenbalya27/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[Beyond Unit Testing: Advanced Mocking, Stubbing, and AI-Assisted Quality Assurance in Django]]></title>
            <link>https://medium.com/@kenbalya27/beyond-unit-testing-advanced-mocking-stubbing-and-ai-assisted-quality-assurance-in-django-b636f30e067a?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b636f30e067a</guid>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Tue, 13 May 2025 06:57:57 GMT</pubDate>
            <atom:updated>2025-05-15T15:14:05.422Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern backend systems, especially those involving multiple services, external APIs, or caching layers, testing is not just about validation — it’s a cornerstone of long-term software quality. When building a disease surveillance system, such as our Django API to fetch all case locations, relying on traditional testing methods falls short.</p><p>To ensure reliable, fast, and isolated tests, developers must use mocking and stubbing to isolate external dependencies like databases, services, and authentication layers. In this article, we walk through a real Django API testing scenario where AI-assisted tools like ChatGPT were used to generate test scaffolds, followed by critical analysis and refinement to reach production-grade test quality.</p><p>Mocking and stubbing are two fundamental concepts in unit testing that help isolate the unit of code under test by replacing its dependencies with controlled versions. Stubbing refers to creating fake methods or objects that return pre-defined outputs when called, regardless of any real implementation. This is useful when your code depends on external systems (like APIs or databases) and you want to simulate their behavior without invoking the actual service. For example, if a function fetches data from a remote server, you can stub the network call to return a fixed response, making your test faster and more reliable.</p><p>Mocking, on the other hand, goes a step further by not only simulating behavior like stubs but also allowing you to verify interactions such as whether a method was called, how many times it was called, and with what arguments. Mocks are ideal when you want to ensure the code under test interacts correctly with its dependencies. For instance, if your function is supposed to send an email, you can mock the email service and later assert that the send_email() method was called exactly once with the expected recipient and message. While stubs are primarily about controlling return values, mocks focus on behavior verification, making them powerful tools for Test-Driven Development (TDD).</p><h3>Case Study: AllCaseLocationsView APIView</h3><p>Here’s the view we’re testing. It relies on injected services, performs database queries, and conditionally returns different HTTP responses:</p><pre>class AllCaseLocationsView(APIView):<br>    authentication_classes = [APIKeyAuthentication]<br>    permission_classes = []<br>    serializer_class = CaseLocationSerializer<br><br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        cache_service = CacheService()<br>        repository = CaseRepository()<br>        self.service = CaseService(repository, cache_service)<br>        self.filter_service = CaseFilterService()<br><br>    def get(self, request):<br>        try:<br>            cases = self.service.get_all_case_locations()<br>            serialized_data = self.serializer_class(cases, many=True).data<br>            if not serialized_data:<br>                return Response({&quot;error&quot;: &quot;No case locations found&quot;}, status=status.HTTP_404_NOT_FOUND)<br>            return Response(serialized_data, status=status.HTTP_200_OK)<br>        except Exception as e:<br>            print(e)<br>            return Response({&quot;error&quot;: INTERNAL_SERVER_ERR_MSG}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</pre><p>This view encapsulates several challenges for testing:</p><ul><li>Interacts with service and repository layers</li><li>Relies on authentication</li><li>Serializes model instances</li><li>Needs to handle multiple failure conditions</li></ul><h3>Step 1: Use AI Generated Test</h3><p>Using AI Assistant like ChatGPT, the initial test case based on my experience would only look like (not 100% the same):</p><pre>from rest_framework import status<br>from rest_framework.test import APITestCase<br>from unittest.mock import patch<br>from django.urls import reverse<br><br>class CaseAPITest(APITestCase):<br><br>    @patch(&#39;path.to.your.CaseService.get_all_case_locations&#39;)<br>    @patch(&#39;path.to.your.CaseLocationSerializer&#39;)<br>    def test_get_case_locations(self, mock_serializer, mock_get_all_case_locations):<br>        # Mock the return value of the service&#39;s method<br>        mock_get_all_case_locations.return_value = [{&#39;location&#39;: &#39;Location 1&#39;}, {&#39;location&#39;: &#39;Location 2&#39;}]<br>        <br>        # Mock the serializer to return the same data without actually serializing<br>        mock_serializer.return_value = [{&#39;location&#39;: &#39;Location 1&#39;}, {&#39;location&#39;: &#39;Location 2&#39;}]<br><br>        url = reverse(&#39;all-case-locations&#39;)  # Adjust the URL as per your routing<br>        response = self.client.get(url)<br><br>        self.assertEqual(response.status_code, status.HTTP_200_OK)<br>        self.assertEqual(response.data, [{&#39;location&#39;: &#39;Location 1&#39;}, {&#39;location&#39;: &#39;Location 2&#39;}])<br><br>    @patch(&#39;path.to.your.CaseService.get_all_case_locations&#39;)<br>    @patch(&#39;path.to.your.CaseLocationSerializer&#39;)<br>    def test_get_case_locations_empty(self, mock_serializer, mock_get_all_case_locations):<br>        # Simulate no case locations found<br>        mock_get_all_case_locations.return_value = []<br><br>        # Mock the serializer to return empty data<br>        mock_serializer.return_value = []<br><br>        url = reverse(&#39;all-case-locations&#39;)<br>        response = self.client.get(url)<br><br>        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)<br>        self.assertEqual(response.data, {&quot;error&quot;: &quot;No case locations found&quot;})<br><br>    @patch(&#39;path.to.your.CaseService.get_all_case_locations&#39;)<br>    def test_get_case_locations_server_error(self, mock_get_all_case_locations):<br>        # Simulate an exception being raised in the service<br>        mock_get_all_case_locations.side_effect = Exception(&quot;Some error occurred&quot;)<br><br>        url = reverse(&#39;all-case-locations&#39;)<br>        response = self.client.get(url)<br><br>        self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)<br>        self.assertEqual(response.data, {&quot;error&quot;: &quot;Internal server error&quot;})  # Assuming INTERNAL_SERVER_ERR_MSG is this</pre><p>While helpful, this approach has limitations:</p><ul><li>Incorrect import path for patching (should be pt_backend.services.CaseService.get_all_case_locations)</li><li>No test coverage for authentication (e.g., missing API key)</li><li>No test for edge cases such as empty data or exceptions</li><li>Most likely doesn’t cover 100% of the tested methods</li><li>Wrong URLs</li></ul><h3>Step 2: Correct and Complete The Test Suite</h3><ol><li>Always define setups, you know your system best so take effort in making it, it will be helpful for future works:</li></ol><pre>def setUp(self):<br>        self.client = APIClient()<br>        # Set up API key authentication<br>        os.environ[&#39;SECRET_API_KEY&#39;] = &#39;test-api-key&#39;<br>        self.client.credentials(HTTP_X_API_KEY=&#39;test-api-key&#39;)<br><br>        self.disease1 = Disease.objects.create(name=&quot;Flu&quot;, level_of_alertness=2)<br>        self.disease2 = Disease.objects.create(name=&quot;COVID-19&quot;, level_of_alertness=5)<br>        self.location1 = Location.objects.create(latitude=-6.2088, longitude=106.8456, city=&quot;Jakarta&quot;, province=&quot;DKI Jakarta&quot;)<br>        self.location2 = Location.objects.create(latitude=-6.9175, longitude=107.6191, city=&quot;Bandung&quot;, province=&quot;Jawa Barat&quot;)<br>        self.case1 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Male&quot;, age=30, city=&quot;Jakarta&quot;, status=&quot;confirmed&quot;, disease=self.disease1, location=self.location1<br>        )<br>        self.case2 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Female&quot;, age=25, city=&quot;Bandung&quot;, status=&quot;recovered&quot;, disease=self.disease2, location=self.location2<br>        )<br><br>        self.cache_service = CacheService()</pre><p>2. Define a teardown (optional), for me is necessary because I’m using a dummy API-KEY here which needed to be erased after being used:</p><pre>def tearDown(self):<br>        # Clean up environment variable<br>        os.environ.pop(&#39;SECRET_API_KEY&#39;, None)</pre><p>3. Correct the positive/happy scenario:</p><pre>def test_get_all_case_locations(self):<br>        &quot;&quot;&quot;Test getting all case locations successfully&quot;&quot;&quot;<br>        mock_locations = [<br>            {&quot;id&quot;: str(self.case1.id), &quot;location__longitude&quot;: &#39;106.845600&#39;, &quot;location__latitude&quot;: &#39;-6.208800&#39;, &quot;city&quot;: &quot;Jakarta&quot;, &quot;location__province&quot;: &quot;DKI Jakarta&quot;},<br>            {&quot;id&quot;: str(self.case2.id), &quot;location__longitude&quot;: &#39;107.619100&#39;, &quot;location__latitude&quot;: &#39;-6.917500&#39;, &quot;city&quot;: &quot;Bandung&quot;, &quot;location__province&quot;: &quot;Jawa Barat&quot;}<br>        ]<br>        <br>        with patch(&#39;pt_backend.services.CaseService.get_all_case_locations&#39;) as mock_get_locations:<br>            mock_get_locations.return_value = mock_locations<br>            url = reverse(&#39;all-case-locations&#39;)<br>            response = self.client.get(url)<br>            response_data = [dict(x) for x in response.data]<br>            self.assertEqual(response.status_code, status.HTTP_200_OK)<br>            self.assertEqual(response_data, mock_locations)<br>            mock_get_locations.assert_called_once()</pre><p>4. Correct the negative scenario:</p><pre>def test_get_all_case_locations_empty(self):<br>        &quot;&quot;&quot;Test getting all case locations when no data exists&quot;&quot;&quot;<br>        with patch(&#39;pt_backend.services.CaseService.get_all_case_locations&#39;) as mock_get_locations:<br>            mock_get_locations.return_value = []<br>            url = reverse(&#39;all-case-locations&#39;)<br>            response = self.client.get(url)<br>            <br>            self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)<br>            self.assertEqual(response.data, {&quot;error&quot;: &quot;No case locations found&quot;})<br>            mock_get_locations.assert_called_once()</pre><p>5. Correct or expand the exception handling test, add missing exception scenarios:</p><pre>   def test_get_all_case_locations_exception(self):<br>     &quot;&quot;&quot;Test handling exception when getting case locations&quot;&quot;&quot;<br>      with patch(&#39;pt_backend.services.CaseService.get_all_case_locations&#39;) as mock_get_locations:<br>           mock_get_locations.side_effect = Exception(&quot;Database error&quot;)<br>           url = reverse(&#39;all-case-locations&#39;)<br>           response = self.client.get(url)<br>            <br>           self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)<br>           self.assertIn(&#39;error&#39;, response.data)<br><br>@patch(&#39;pt_backend.services.CaseService.get_all_case_locations&#39;)<br>    def test_all_case_locations_get_exception(self, mock_get_locations):<br>        mock_get_locations.side_effect = Exception(&quot;Test exception&quot;)      <br>        url = reverse(&#39;all-case-locations&#39;)<br>        response = self.client.get(url)     <br>        self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)<br>        self.assertEqual(response.data, {&quot;error&quot;: &quot;An unexpected error occurred. Please try again later.&quot;})</pre><p>6. Test other scenarios to ensure 100% code coverage:</p><pre>def test_get_all_case_locations_missing_api_key(self):<br>        self.client.credentials()<br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)<br>        self.assertEqual(response.json(), {&quot;detail&quot;: &quot;Invalid API Key&quot;})<br><br>def test_get_all_case_locations_invalid_api_key(self):<br>        self.client.credentials(HTTP_X_API_KEY=&quot;wrong-api-key&quot;)<br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)<br>        self.assertEqual(response.json(), {&quot;detail&quot;: &quot;Invalid API Key&quot;})</pre><h3>Several Other Mocking Techniques Implemented</h3><p>Below are several advanced mocking techniques that was implemented on my project</p><h4>Mocking Database Query</h4><p>Database mocking simulates database interactions by replacing actual queries with predefined responses or exceptions, allowing tests to run without needing a real database connection.</p><pre>@patch(&#39;pt_backend.models.News.objects.values_list&#39;, side_effect=ObjectDoesNotExist)<br>def test_get_all_news_name_exception(self, mock_get_all_news):<br>    result = self.repository.get_all_news_name()<br>    self.assertEqual(result, {&quot;error&quot;: &quot;Error retrieving news&quot;})</pre><p>The test above mocks the database behavior when the queried object does not exist</p><pre>with patch(&#39;pt_backend.models.Case.objects.select_related&#39;, side_effect=Exception(&quot;Test error&quot;)):<br>    result = self.repository.get_case_detail_by_id(self.case1.id)<br>    self.assertIsNone(result)</pre><p>This mock simulates a database failure by overriding select_related with an exception, allowing you to test how your code handles database errors without needing an actual database connection.</p><h4>Dependency Mock</h4><p>Dependency mocking involves replacing a class or service that a component depends on with a mock version to isolate and test the component’s behavior independently of its external dependencies.</p><pre>@patch(&#39;authentication.views.AuthService&#39;)<br>    def test_successful_login(self, mock_auth_service):<br>        &quot;&quot;&quot;Test successful login request - happy path&quot;&quot;&quot;<br>        # Configure mock<br>        mock_auth_service_instance = mock_auth_service.return_value<br>        mock_auth_service_instance.login.return_value = {&#39;access_token&#39;: &#39;dummy-token&#39;}<br>        <br>        # Make request<br>        data = {<br>            &#39;email&#39;: &#39;test@example.com&#39;,<br>            &#39;password&#39;: &#39;Password123!&#39; # NOSONAR – test data, not a real secret<br>        }<br>        response = self.client.post(self.url, data, format=&#39;json&#39;)<br>        <br>        # Verify<br>        self.assertEqual(response.status_code, status.HTTP_200_OK)<br>        self.assertIn(&#39;access_token&#39;, response.data)<br>        self.assertIn(&#39;detail&#39;, response.data)<br>        self.assertEqual(response.data[&#39;detail&#39;], &#39;Login successful&#39;)<br>        mock_auth_service_instance.login.assert_called_once_with(<br>            email=&#39;test@example.com&#39;, <br>            password=&#39;Password123!&#39; # NOSONAR – test data, not a real secret<br>        )</pre><p>AuthService class (a dependency of the view) is replaced with a mock object to isolate and test the view logic independently of the real authentication implementation.</p><h4>Method Mocking</h4><p>Method mocking replaces a specific method of an object or class with a mock implementation to control its behavior during testing and verify how it was called.</p><pre>def test_initiate_password_reset_email_service_runtime_error(self):<br>        &quot;&quot;&quot;Test handling when email service throws RuntimeError&quot;&quot;&quot;<br>        # Setup mock to raise RuntimeError<br>        self.email_service.send_email.side_effect = RuntimeError(&quot;Email service failed&quot;)<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify all dependencies were called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_called_once_with(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        self.email_service.send_email.assert_called_once()<br>        <br>        # Verify false is returned<br>        self.assertFalse(result)</pre><p>send_email method of the email_service dependency is configured to raise a RuntimeError, allowing the test to verify that the main service handles the exception and returns False appropriately.</p><h4>Module Mocking</h4><p>Module mocking replaces an entire imported module or specific exports with mock implementations, allowing you to isolate the code under test from its real dependencies.</p><pre>jest.mock(&quot;@amcharts/amcharts5&quot;, () =&gt; ({<br>  Root: {<br>    new: jest.fn().mockImplementation((div: HTMLDivElement) =&gt; {<br>      return {<br>        setThemes: jest.fn(),<br>        dispose: jest.fn(),<br>        container: {<br>          children: {<br>            push: jest.fn().mockImplementation((child) =&gt; child),<br>          },<br>        },<br>        verticalLayout: {},<br>      };<br>    }),<br>  },<br>  Legend: {<br>    new: jest.fn().mockImplementation((root, options) =&gt; {<br>      return {<br>        data: {<br>          setAll: jest.fn(),<br>        },<br>        labels: {<br>          template: {<br>            setAll: jest.fn(),<br>          },<br>        },<br>        valueLabels: {<br>          template: {<br>            setAll: jest.fn(),<br>          },<br>        },<br>      };<br>    }),<br>  },<br>  percent: jest.fn().mockImplementation((value: number) =&gt; `${value}%`),<br>  color: jest.fn().mockImplementation((color: number) =&gt; color),<br>}));</pre><p>jest.mock was used to replace the <a href="http://twitter.com/amcharts/amcharts5">@amcharts/amcharts5</a> module with custom mock implementations of its classes and functions, enabling unit tests to run without loading the actual charting library.</p><h4>API Mocking</h4><p>API mocking simulates the behavior of real API calls by returning predefined responses, enabling tests to run quickly and reliably without relying on actual backend services.</p><pre>jest.mock(&#39;../../services/api&#39;);<br><br>describe(&#39;useLocations&#39;, () =&gt; {<br>  beforeEach(() =&gt; {<br>    jest.clearAllMocks();<br>  });<br><br>  // Positive case: Successful data fetch<br>  it(&#39;should fetch and set locations data successfully&#39;, async () =&gt; {<br>    const mockLocations: MapLocation[] = [<br>      { id: &#39;1&#39;, city: &#39;Location 1&#39;, location__latitude: 1.0, location__longitude: 1.0 },<br>      { id: &#39;2&#39;, city: &#39;Location 2&#39;, location__latitude: 2.0, location__longitude: 2.0 }<br>    ];<br><br>    (mapApi.getLocations as jest.Mock).mockResolvedValueOnce(mockLocations);<br><br>    const { result } = renderHook(() =&gt; useLocations());<br><br>    // Initial state<br>    expect(result.current.isLoading).toBe(true);<br>    expect(result.current.data).toEqual([]);<br>    expect(result.current.error).toBe(null);<br><br>    await waitFor(() =&gt; {<br>      expect(result.current.isLoading).toBe(false);<br>    });<br><br>    // Final state<br>    expect(result.current.data).toEqual(mockLocations);<br>    expect(result.current.error).toBe(null);<br>    expect(mapApi.getLocations).toHaveBeenCalledTimes(1);<br>  });</pre><p>using jest.mock to replace the API, specifically mocking mapApi.getLocations to return predefined location data. Allowing the useLocations hook to be tested without making real API calls.</p><h3>Coverage, Stubbing, and Test Isolation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*T7rWh8fD4fWlXQ2DAWJ3Zg.png" /></figure><p>By critiquing the AI output, we turned basic unit tests into production-ready, fully isolated test cases that handle both success and failure.</p><h3>Advanced Concepts Demonstrated</h3><ol><li><strong>Dependency Isolation:</strong> We mock not just method return values, but also the side effects and raised exceptions.</li><li><strong>Service-Oriented Testing:</strong> Test logic lives in CaseService, but we patch it in views because that’s where it&#39;s called.</li><li><strong>Authentication Pathways:</strong> Ensuring proper API key behavior through environment and client headers.</li><li><strong>Decorator Handling:</strong> Even if AI overlooks decorators like @measure_time, you can patch them using @patch(&#39;module.decorator&#39;, lambda f: f).</li></ol><h3>Real-World Impacts</h3><p>Without proper mocking:</p><ul><li>Tests would hit the actual database, slowing feedback loops.</li><li>API failures (e.g., timeouts) would cause flaky test results.</li><li>Decorators would interfere with test execution and coverage tracking.</li></ul><p>By using mocks, stubs, and environment isolation:<br> — Our tests are deterministic,<br> — Fast (no DB or external API), and<br> — Maintainable as the system evolves.</p><h3>Conclusion</h3><p>Mocking and stubbing are not merely tools — they are strategies for achieving long-term software excellence. While AI assistance can kickstart testing efforts, critical review and augmentation by the developer is what makes those tests valuable in real projects.</p><blockquote><strong><em>“Use AI to write tests. Use your brain to make them bulletproof.”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b636f30e067a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Further Testing: Stress and Penetration Testing]]></title>
            <link>https://medium.com/@kenbalya27/further-testing-stress-and-penetration-testing-5573acf23284?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5573acf23284</guid>
            <category><![CDATA[quality-assurance]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Thu, 08 May 2025 05:32:27 GMT</pubDate>
            <atom:updated>2025-05-13T06:02:31.805Z</atom:updated>
            <content:encoded><![CDATA[<p>Stress and penetration testing are critical components in preparing a production-ready application because they ensure the system’s reliability, scalability, and security under real-world conditions. Stress testing simulates extreme usage scenarios like high traffic spikes or limited system resources to identify performance bottlenecks and determine how the app behaves under maximum load. This process helps developers pinpoint weaknesses such as memory leaks, slow response times, or system crashes, which could otherwise lead to downtime or poor user experience in production. By addressing these issues early, organizations can build confidence that the app can handle real operational demands without failing.</p><p>Penetration testing, on the other hand, is essential for identifying and fixing security vulnerabilities before malicious actors can exploit them. It simulates attacks that mimic real-world hacking techniques to uncover flaws in authentication, input validation, access controls, and other critical areas. This proactive approach ensures that sensitive user data, business logic, and infrastructure remain protected. Without penetration testing, even well-designed apps can become easy targets for breaches, leading to data loss, financial damage, and a loss of customer trust. In short, stress and penetration testing are not just precautionary they are fundamental to building robust, secure, and trustworthy applications.</p><p>Lets do some stress and penetration testing to gain some insights about performance bottlenecks and our app’s security.</p><h3>Stress Testing With k6: Login Feature Performance</h3><p>k6 is an open-source load testing tool designed for testing the performance of APIs, microservices, and websites by simulating large numbers of virtual users. It helps identify performance bottlenecks and system limitations by generating traffic and measuring metrics like response time, error rates, and throughput under varying load conditions.</p><ol><li>Step 1: Install k6, you can directly install it on their site</li><li>Step 2: Configure your test script, here is mine for login test:</li></ol><pre>import http from &#39;k6/http&#39;;<br>import { check, sleep } from &#39;k6&#39;;<br><br>export let options = {<br>  vus: 20,<br>  duration: &#39;20s&#39;,<br>};<br><br>const users = [<br>  { email: &#39;realuser@test.com&#39;, password: &#39;#Realpass123&#39; }, // True user<br>  { email: &#39;wronguser@test.com&#39;, password: &#39;wrongpass&#39; }, // <br>  { email: &#39;admin@notfound.com&#39;, password: &#39;whatever&#39; }, // <br>  { email: &#39;k6user@test.com&#39;, password: &#39;wrongpass&#39; }, // <br>];<br><br>export default function () {<br>  const user = users[Math.floor(Math.random() * users.length)];<br><br>  const url = &#39;your/app/url&#39;;<br>  const payload = JSON.stringify(user);<br><br>  const params = {<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;X-API-KEY&#39;: &#39;your-api-key&#39;,// if exist<br>    },<br>  };<br><br>  let res = http.post(url, payload, params);<br><br>  check(res, {<br>    &#39;status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;login response time &lt; 500ms&#39;: (r) =&gt; r.timings.duration &lt; 500,<br>  });<br><br>  // Optional log<br>  console.log(`Email: ${user.email} | Status: ${res.status}`);<br><br>  sleep(1);<br>}</pre><p>This k6 script performs a stress test on a login endpoint by simulating 20 virtual users over 20 seconds, each randomly attempting to log in using a mix of valid and invalid credentials. It sends HTTP POST requests with JSON payloads and checks whether the response status is 200 and if the response time is under 500ms, helping evaluate the system’s behavior under repeated login attempts. Notice that we simulate 1 true user and 3 false one.</p><p>3. run: k6 run test.js and see the results</p><p>Here are the first few lines of my console and the summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nFhIZq2EEWDiXJ-ZNcYRQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOhIzDoBK_UtulH6fKNwOw.png" /></figure><p>The k6 stress test results show that the application’s login endpoint is severely throttled under load, with 99.6% of requests failing and returning HTTP 429 (Too Many Requests), indicating the presence of aggressive rate limiting. Only one request returned HTTP 200, highlighting that even valid users were blocked after a short spike. Although 91% of requests had a response time under 500ms, the test failed its core success checks due to these rejections.</p><p>Actionable insights: the rate-limiting mechanism needs to be adjusted to tolerate higher volumes for valid traffic without compromising security. Consider implementing adaptive rate limiting, IP/user-based quotas, or graceful degradation strategies. Additionally, the login service may benefit from scaling resources horizontally or offloading auth traffic through caching or load balancers. So first, lest adjust the limit rate in django</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_THROTTLE_CLASSES&#39;: [<br>        &#39;rest_framework.throttling.UserRateThrottle&#39;,<br>        &#39;rest_framework.throttling.AnonRateThrottle&#39;,<br>    ],<br>    &#39;DEFAULT_THROTTLE_RATES&#39;: {<br>        &#39;user&#39;: &#39;1000/min&#39;,      # temporary high limit for testing<br>        &#39;anon&#39;: &#39;500/min&#39;,       # likewise for unauthenticated<br>        &#39;password_reset&#39;: &#39;50/day&#39;,<br>    },<br>}</pre><p>It may not always work since the performance will still be dependent on the server architecture we have. If the specifications don’t meet the required, then we need to use some advanced tools and techniques, the best combo is:</p><ul><li>Rate limiting (Django throttling, NGINX, API Gateway) [done as shown above]</li><li>Queue offloading (RabbitMQ/Celery) for async jobs</li><li>Caching (Redis) to reduce DB load</li><li>Autoscaling if in a cloud environment</li><li>Load Balancing</li></ul><h3>Penetration Testing</h3><p>One of the most common hacking techniques that is widely used is SQL Injection. SQL Injection is a serious security vulnerability where an attacker inserts or “injects” malicious SQL code into a query through input fields, URLs, or headers to manipulate the database. If an application does not properly validate or sanitize user input, attackers can gain unauthorized access to sensitive data like passwords, financial records, or personal information. In severe cases, SQL injection can allow attackers to bypass authentication, modify or delete records, or even take full control of the database server. This makes it particularly dangerous for applications that manage critical or confidential data, such as banking systems, healthcare platforms, or admin portals.</p><p>To ensure our application’s safety, we need to test our backend whether it can prevent SQL Injection payloads or not. Lets try to retrieve user data from one of our backend API service which is case filtering with POST method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QG2Okyit8obdPpvKIxWB4A.png" /></figure><p>The payload { “location”: “UNION SELECT * FROM USERS — “} attempts a SQL injection by using UNION SELECT to append the results of a query that selects all records from the USERS table. The — is a comment sequence in SQL that ignores the rest of the original query, allowing the injected query to run independently and potentially expose sensitive user data.</p><p>However, notice that we didn’t get any user data. Instead, we got an unfiltered location data. This means our app is still safe right due to the SQL Injection not performing as expected? NO! Big No!</p><p>The { “location”: “UNION SELECT * FROM USERS — “} means we have to filter cases where the city is equal to “UNION SELECT * FROM USERS — “ or location__province is equal to “UNION SELECT * FROM USERS — “. However, we don’t have any of those right? Which means something is definitely wrong! It’s most likely due to some bugs that happened in the lower level logic of our filtering service, however since I don’t have access to that part of the code, I’ll just create an additional “shield” for our application without modifying any existing codes.</p><p>We can define a module which performed as an interceptor for SQL Injection payloads and integrate it with our views as follow:</p><pre>import re<br>import unicodedata<br>from rest_framework.exceptions import ValidationError<br><br>class SQLInjectionDetector:<br>    &quot;&quot;&quot;<br>    Stronger SQL Injection Detector with input normalization.<br>    &quot;&quot;&quot;<br><br>    SUSPICIOUS_PATTERNS = [<br>        r&quot;(?i)(select\s.+\sfrom)&quot;,             # SELECT ... FROM<br>        r&quot;(?i)(union\s+select)&quot;,                # UNION SELECT<br>        r&quot;(?i)(insert\s+into)&quot;,                 # INSERT INTO<br>        r&quot;(?i)(update\s+\w+\s+set)&quot;,             # UPDATE table SET<br>        r&quot;(?i)(delete\s+from)&quot;,                 # DELETE FROM<br>        r&quot;(?i)(drop\s+table|drop\s+database)&quot;,   # DROP TABLE or DATABASE<br>        r&quot;(?i)(create\s+table|create\s+database)&quot;, # CREATE TABLE or DATABASE<br>        r&quot;(?i)(exec\s+\()&quot;,                     # EXEC(<br>        r&quot;(?i)(--|#)&quot;,                          # Comment injections<br>        r&quot;(?i)(;)&quot;,                             # Multiple queries<br>    ]<br><br>    @classmethod<br>    def normalize(cls, value: str) -&gt; str:<br>        # Convert special unicode to ascii<br>        value = unicodedata.normalize(&#39;NFKD&#39;, value).encode(&#39;ascii&#39;, &#39;ignore&#39;).decode(&#39;ascii&#39;)<br>        # Remove extra spaces and lower the string<br>        value = re.sub(r&#39;\s+&#39;, &#39; &#39;, value)<br>        return value.lower()<br><br>    @classmethod<br>    def _is_suspicious(cls, value: str) -&gt; bool:<br>        if not isinstance(value, str):<br>            return False<br>        <br>        normalized_value = cls.normalize(value)<br><br>        for pattern in cls.SUSPICIOUS_PATTERNS:<br>            if re.search(pattern, normalized_value):<br>                return True<br>        return False<br><br>    @classmethod<br>    def check(cls, request):<br>        &quot;&quot;&quot;<br>        Check request.query_params (GET) and request.data (POST/PUT) for SQL injection attempts.<br>        &quot;&quot;&quot;<br>        cls._check_dict_for_injection(request.query_params)<br><br>        if hasattr(request, &quot;data&quot;):<br>            cls._check_data_for_injection(request.data)<br><br>    @classmethod<br>    def _check_dict_for_injection(cls, data_dict):<br>        for key, value in data_dict.items():<br>            cls._validate_input(key, value)<br><br>    @classmethod<br>    def _check_data_for_injection(cls, data):<br>        for key, value in data.items():<br>            if isinstance(value, str):<br>                cls._validate_input(key, value)<br>            elif isinstance(value, list):<br>                for item in value:<br>                    if isinstance(item, str):<br>                        cls._validate_input(key, item, is_list=True)<br><br>    @classmethod<br>    def _validate_input(cls, key, value, is_list=False):<br>        if cls._is_suspicious(value):<br>            source = &quot;list for&quot; if is_list else &quot;&quot;<br>            raise ValidationError(f&quot;Input {source} &#39;{key}&#39; contains suspicious SQL injection pattern.&quot;)</pre><p>After applying it to views, lets checkout the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*mT06ESjnnoR7o8Ii.png" /></figure><p>The module works well in intercepting SQL Injection payloads! However, it only acts as the frontline defender of our application. The issue with the bug in the lower level will be communicated to our product owner so the bug could be resolved as well by following OWASP Top 10.</p><h3>Further Penetration Testing: Done SQL Injections, Is it Safe?</h3><p>Since I have tested SQL Injections in all API endpoints and none of them managed to bypass the security measures, it doesn’t mean that our application is free from vulnerabilities. From a cybersecurity point of view, no matter how strong an application’s security appears to be, there will always be the possibility of weaknesses. This is rooted in the fact that every security system is built by humans, and human work is never without limitations. Unless it were secured by God Himself, we must always assume that some form of vulnerability could exist within the system. Therefore, our responsibility is not to aim for a flawless system — which is unrealistic — but to continuously minimize risks and reduce the surface area of potential attacks.</p><p>To support this mindset, I used one of the most powerful tools available for security testing: <strong>Burp Suite</strong>. This tool allows us to intercept, analyze, and manipulate the traffic between the client and server, offering deep insights into what is happening behind the scenes in a web application. While automated scanners are helpful, manual inspection using Burp Suite often reveals subtle security flaws that automated tools might overlook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gttLrkodvM8mn-hXvjBcA.png" /><figcaption>Api-Key exposed!</figcaption></figure><p>During testing, one such issue I discovered was the exposure of an <strong>API key in the request headers</strong>. As I analyzed the outgoing HTTP requests captured by Burp Suite, I noticed that every authenticated API call included an API key sent in plaintext. This means that if an attacker were to intercept this traffic — for instance, over an unsecured public Wi-Fi network or from a compromised device — they could easily extract this key and use it to access protected endpoints. Even though HTTPS encrypts traffic in transit, relying solely on encryption is not enough if the application exposes sensitive information in places where it shouldn’t.</p><p>This discovery highlights a broader concern in security: the mismanagement of secrets on the client side. API keys should be treated as highly sensitive credentials. They should be stored securely on the backend and never be exposed in the frontend code or transmitted in headers unless absolutely necessary and with proper protection in place. Using static keys that never expire makes the situation even riskier. Instead, applications should implement short-lived tokens — such as JWTs with expiration — and limit their scope and usage. Additionally, practices like IP whitelisting, rate limiting, and regular key rotation can significantly reduce the risk of key leakage.</p><p>In conclusion, Burp Suite proved to be more than just a tool for injection testing — it served as a critical lens through which we could identify insecure practices that might otherwise go unnoticed. This reinforces an essential truth in cybersecurity: perfect security doesn’t exist, but by being proactive and detail-oriented, we can continually move closer to a system that is resilient and well-defended.</p><h3>Conclusion</h3><p>Stress and penetration testing are essential pillars of quality assurance, especially for production-grade applications that handle critical operations and sensitive data. In our case, these tests uncovered key performance bottlenecks and security vulnerabilities that, if left undetected, could have severely compromised both system stability and data protection. Stress testing revealed how the system behaves under high user loads, exposing limitations in scalability and response time, while penetration testing highlighted potential entry points for malicious actors to exploit. Without these evaluations, deploying the application would have been a high-stakes gamble, potentially leading to downtime, data breaches, or reputational damage. These tests are not just precautionary , they are non-negotiable measures to ensure that our application performs reliably and securely under real-world conditions, ultimately building user trust and long-term success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5573acf23284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LogRocket: A Maverick for Frontend Monitoring]]></title>
            <link>https://medium.com/@kenbalya27/logrocket-a-maverick-for-frontend-monitoring-e80468ee4b5c?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e80468ee4b5c</guid>
            <category><![CDATA[platform-monitoring]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Wed, 07 May 2025 16:56:32 GMT</pubDate>
            <atom:updated>2025-05-20T17:25:27.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Monitoring is essential to ensure an application’s performance, availability, and security by providing real-time visibility into system behavior and user interactions. It helps detect and diagnose issues early — such as errors, bottlenecks, or unauthorized access — before they impact users. Additionally, monitoring enables data-driven decisions for optimizing system performance and scaling effectively.</p><p>There are a lot of ways to perform platform monitoring, the easiest one is through the built-in server logs in our deployment server, because they provide raw, low-level diagnostics directly from the server or app runtime. They’re useful for debugging but lack aggregation, visualization, and often require manual inspection.</p><p>We can take it to another level by using general monitoring tools like grafana , in which most developers used this type of monitoring tools to monitor their apps. They offer <strong>aggregated, real-time dashboards</strong> by visualizing data from various sources (like Prometheus, Loki, Elasticsearch). They are ideal for system-wide observability (CPU, memory, API latency, etc.) but may need configuration to track user-level or frontend-specific events.</p><h3><strong>LogRocket: Specialized Frontend Monitoring for User Experience and Behavioral Insights</strong></h3><p>Sometimes, to ensure our application’s quality, we need to break down monitoring into sub-levels so each component has its own focus, with tools customized to its unique requirements. One of these is frontend monitoring, where tools like LogRocket are used to gain deep insight into user experience by capturing session replays, UI interactions, JavaScript errors, and network requests from the user’s perspective. Unlike general monitoring tools, LogRocket is tailored to answer questions like “What exactly did the user do before this bug occurred?” or “How does performance vary across different devices or browsers?” — enabling frontend teams to debug efficiently, optimize user flows, and improve overall usability based on real, contextual data. Lets break it down:</p><ol><li><strong>A bridge between technical metrics and the user’s behavior:</strong></li></ol><ul><li>Provides Session Replays</li><li>Tracks slow requests</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNAY5TDVPlF_QDGjJA6kDw.png" /><figcaption>Error Tracking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kp7MmCx_6zolJmhdef1izw.png" /><figcaption>Session Replay</figcaption></figure><p>2. Custom Monitoring</p><p>We can make a custom monitoring scenario which is supported by visualization tools like charts. We can create charts to monitor performance, user experience, sessions, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQBZsuwK6OiPuT9V8h9sbw.png" /><figcaption>Most Active User Monitoring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voH2Eir2Qsng2ZrIt4LIIg.png" /><figcaption>Average CPU Loads</figcaption></figure><p>3. Provided Dashboards with built-in templates</p><p>Beside charts, LogRocket also provides dashboard for a more comprehensive monitoring per custom usage. Here are our project’s examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC-LVD-VKcjG94cqCNwZdw.png" /><figcaption>Performance Monitoring</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mntWv84pLx-5I96EdvVBlw.png" /><figcaption>User Experience Monitoring</figcaption></figure><p>Notice that only from a small fragment of LogRocket that I showed earlier, a developer can gain a lot of insights based on their monitoring focus. Here, our focus is to monitor user experience to make sure that they are satisfied in using our application. With the insights we got, we can easily plan fixes to be made in order to further satisfy the user’s experience.</p><p>Based on what I found earlier, a lot of actions can be taken. For example, notice the issues that was found, we can optimize the functions that caused frustrating requests. In the other hand, we have to make sure that our app wasn’t down in the afternoon-evening, since user’s access was found mostly during this time period.</p><h3><strong>The Game Changer</strong></h3><p>LogRocket is a game changer compared to traditional monitoring tools because it shifts the focus from system-level metrics to user-centric insights, enabling developers to see exactly how users interact with their applications through session replays, DOM state tracking, and detailed user behavior logs. While traditional tools like server logs or infrastructure dashboards provide valuable backend performance and error data, they often miss the nuances of what users actually experience. LogRocket bridges this gap by combining error tracking with real-time visual context making it dramatically easier to reproduce bugs, understand usability issues, and prioritize fixes based on real impact, ultimately accelerating the debugging process and improving user satisfaction.</p><h3><strong>How to Configure it? EASY!</strong></h3><p>I’ll demonstrate how I integrated my Next JS app with LogRocket. This way, you can also have this game changing monitoring tools setup for your own application! Before that, you have to login and create a project in LogRocket’s site and bring the project id.</p><ol><li>Install Necessary Packages:</li></ol><pre>npm install logrocket<br># or<br>yarn add logrocket</pre><p>2. Initialize in utils/logrocket.ts:</p><pre>import LogRocket from &quot;logrocket&quot;;<br><br>export function initLogRocket() {<br>  if (typeof window !== &quot;undefined&quot;) {<br>    LogRocket.init(&quot;your-app-id&quot;); // Replace with your LogRocket app ID<br>  }<br>}</pre><p>3. Create LogRocket client-initializer in app/logrocket-client.ts:</p><pre>&#39;use client&#39;;<br><br>import { useEffect } from &#39;react&#39;;<br>import { initLogRocket } from &#39;../utils/logrocket&#39;;<br><br>export default function LogRocketInitializer() {<br>  useEffect(() =&gt; {<br>    initLogRocket();<br>  }, []);<br><br>  return null; // This component doesn&#39;t render anything<br>}</pre><p>4. Import the component to app/layout.tsx:</p><pre>import LogRocketInitializer from &quot;./logrocket-client&quot;; // Add this<br>import type { Metadata, Viewport } from &quot;next&quot;;<br>import &quot;../styles/globals.css&quot;;<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={`${inter.className} min-h-screen`}&gt;<br>        &lt;LogRocketInitializer /&gt;<br>        &lt;main className=&quot;min-h-screen pt-20&quot;&gt;<br>          {children}<br>        &lt;/main&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Run your Next JS app in localhost or push it into production, either way the link between LogRocket and your application had been made.</p><h3>Additional Useful Feature: Alerting</h3><p>One of the most useful role of a monitoring platform is to inform the developer or operator as soon as possible if an issue occurs in order to fix the issue as soon as possible, hence our application will be issueless for a longer period which implies user’s satisfaction.</p><h4>High CPU Load Monitoring</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Ykiw_1oPlKQ8uXFTd1Fo4w.png" /></figure><p>When the issue was resolved, it will inform us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*94d0JnLh6OmNoKSqS0JXmA.png" /></figure><h3>Daily Issues Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwipS1lZhJDNoIOSK2PuNw.png" /></figure><p>Every 24 hours, LogRocket will notify it’s users regarding issues that was found within the day. High severity issues as seen above will be explicitly stated on the alert.</p><p>Other alerting trigger can also be customized, for example when a medium-high severity issue occurred or when the deployment crashed.</p><h3><strong>Conclusion</strong></h3><p>Monitoring isn’t just about checking if your servers are running — it’s about understanding how real people use your app. Traditional tools like Prometheus or Grafana are great for backend health, but they miss what users actually see and do. LogRocket changes that by giving you everything in one place: user behavior, errors, and performance, all tied to real sessions. You can watch replays, get alerts, and fix problems before users even complain. It’s easy to set up, simple to use, and even the free plan gives you powerful insights that many paid tools don’t. With LogRocket, monitoring becomes less about guesswork — and more about clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e80468ee4b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 2nd Most Annoying Part of Software Development: Applying Design Pattern, a late game changer.]]></title>
            <link>https://medium.com/@kenbalya27/the-2nd-most-annoying-part-of-software-development-applying-design-pattern-a-late-game-changer-fc4fada7c3a5?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4fada7c3a5</guid>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 03:55:09 GMT</pubDate>
            <atom:updated>2025-05-28T04:30:50.493Z</atom:updated>
            <content:encoded><![CDATA[<p>A design pattern is a reusable solution to a common problem in software design, serving as a best practice template for structuring code. It helps improve code maintainability, scalability, and readability by providing proven approaches to recurring design challenges.</p><p>In my case, design pattern is necessary since code refactoring will be a common sequence within the development process. Furthermore, our client will most likely do some further developments for our application, in which we need to ensure maintainability by applying these stuff. Lets dive in to my journey in applying design pattern for my project</p><h3>Task Overview</h3><p>We need to visualize cases locations in a map on our frontend app, therefore we need an API service that serves to return the data desired for the frontend to consume.</p><p>Based on the scenario, we need to apply a design pattern that is suitable for data extraction process, meaning the design pattern should cover database query and business process. Therefore, we are going to use the following design patterns:</p><ul><li>Repository Pattern: a design pattern that separates the data access logic from the business logic by providing a centralized interface for data operations. It helps manage interactions with the data source (like a database) in a clean, testable, and decoupled way.</li><li>Service Pattern: a design pattern that encapsulates business logic into separate service classes, keeping it isolated from controllers and data access layers. This promotes code reusability, separation of concerns, and easier testing and maintenance.</li></ul><p>In other words, repository pattern will be used as a place where interactions with the database holds place, and service pattern is a place where we group lower level logics like repositories based on their business usage. Using this 2 patterns ensures that business processes are handled accordingly based on it’s purposes. The effect will later be seen when handling more feature requests primarily similar ones, refactoring, and of course while testing.</p><h3>Implementation</h3><p>a. Repository Pattern: We need to create a repository of classes where each classes holds single responsibility, lets create one for querying locations data from the database:</p><pre>class CaseRepository(CaseRepositoryInterface):<br>  def get_all_locations(self):<br>        return Case.get_all_locations()</pre><p>The class above is responsible to make interactions for data related to Cases, meaning Case becomes the main entity for this class. If another Case data query is needed in the future, we can just add another method to the CaseRepository class.</p><p>b. Service Pattern: We need to create services by grouping them based on their business need. For our case, our business is to retrieve something regarding Cases, so we can make a class named CaseService to handle services related to Case Retreival:</p><pre>class CaseService(CaseRetrievalInterface):<br><br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br>    <br>    def get_all_case_locations(self):<br>         locations = self.repository.get_all_locations()<br>        return locations if locations else []</pre><p>First of all, determine whether we need any kind of dependency from a lower level process (i.e. Repositories and others). If so, then inject it as a dependency to the class. After that, just define a method to handle the service layer logic of our process.</p><p>Now what can we further do for the service? Notice that the retrieval process is a get all, therefore we can always do some caching rather than querying the database over and over again. So we can have another service focused on caching, we name it CacheService:</p><pre>class CacheService(CacheInterface):<br>    def get(self, key):<br>        return cache.get(key)<br><br>    def set(self, key, value, timeout):<br>        cache.set(key, value, timeout)<br><br>    def delete(self, key):<br>        cache.delete(key)</pre><p>Next, we refactor CaseService to implement caching:</p><pre>class CaseService(CaseRetrievalInterface):<br>    CAHCE_KEY_ALL_CASES_LOCATIONS = &quot;all_cases_locations&quot;<br>    CACHE_TIMEOUT = 300 <br><br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br>        self.cache_service = cache_service<br>    <br>    def get_all_case_locations(self):<br>        locations = self.cache_service.get(self.CAHCE_KEY_ALL_CASES_LOCATIONS)<br>        if locations is None:<br>            locations = self.repository.get_all_locations()<br>            self.cache_service.set(self.CAHCE_KEY_ALL_CASES_LOCATIONS, locations, timeout=self.CACHE_TIMEOUT)<br>        return locations if locations else []</pre><h3>Why would this help?</h3><p>Lets assume we need another API service, now the frontend needs to consume an API which returns all cases with several attributes. The pattern of implementing it is the same as before:</p><p>a. Repository Pattern: Since the data is also centered in Cases, we can include this one to CaseRepository:</p><pre>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_cases(self):<br>        return Case.objects.all().values(<br>            &quot;id&quot;,<br>            &quot;location__province&quot;,<br>            &quot;location__city&quot;,<br>            &quot;news__portal&quot;,<br>            &quot;severity&quot;,<br>            &quot;news__date_published&quot;<br>        )<br>    def get_all_locations(self):<br>        return Case.get_all_locations()</pre><p>b. Service Pattern: Since it is a part of Case Retrieval process, we include it into the CaseService class:</p><pre>class CaseService(CaseRetrievalInterface):<br>    CACHE_KEY_ALL_CASES = &quot;all_cases&quot;<br>    CAHCE_KEY_ALL_CASES_LOCATIONS = &quot;all_cases_locations&quot;<br>    CACHE_TIMEOUT = 300 <br><br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br>        self.cache_service = cache_service<br><br>    def get_all_cases(self):<br>        cases = self.cache_service.get(self.CACHE_KEY_ALL_CASES)<br>        if cases is None:<br>            cases = self.repository.get_all_cases()<br>            self.cache_service.set(self.CACHE_KEY_ALL_CASES, cases, timeout=self.CACHE_TIMEOUT)<br>        return cases if cases else []<br>    <br>    def get_all_case_locations(self):<br>        locations = self.cache_service.get(self.CAHCE_KEY_ALL_CASES_LOCATIONS)<br>        if locations is None:<br>            locations = self.repository.get_all_locations()<br>            self.cache_service.set(self.CAHCE_KEY_ALL_CASES_LOCATIONS, locations, timeout=self.CACHE_TIMEOUT)<br>        return locations if locations else []</pre><p>Now we already have a new feature within a blink of an eye!</p><h3><strong>Creational Design Pattern</strong></h3><p>This time, I was assigned to implement user registration task. However, it was more challenging since our client demanded a registration service that gives flexibility if additional roles are present. At the moment, we only 1 role is present on our application, if one day they needed to add additional roles, we need to ensure that they can easily reproduce our code without altering core logics. This is when creational pattern came to my rescue.</p><p>A <strong>creational pattern</strong> is a design pattern that helps you create objects in a flexible and reusable way, instead of directly using new everywhere. It hides the complex steps of object creation and lets you change how objects are created without changing the main code. The creational pattern I will use here is F<strong>actory Method Pattern</strong> enhanced with <strong>Registry Pattern</strong>.</p><p>The <strong>Factory Method pattern</strong> is a creational design pattern that defines an interface for creating objects but lets subclasses decide which class to instantiate, promoting loose coupling and flexibility. The <strong>Registry pattern</strong> complements this by maintaining a central directory of available classes or instances (factories, in this case), allowing us to look them up dynamically by a key like a string or name. Together, they make it easy to extend functionality (like adding new user roles) without changing the core logic as needed in my task. So lets execute it!</p><h3><strong>Implement Data Transfer Object (DTO)</strong></h3><p>A <strong>DTO (Data Transfer Object)</strong> is a simple object used to group and transfer related data between different parts of a system, especially across layers like from a service to a controller. It helps keep code clean by separating raw model data from the formatted output, making the application easier to maintain and test.</p><p>dto.py:</p><pre>from dataclasses import dataclass<br>from typing import List<br>from pt_backend.models import User, Role, Permission<br><br><br>@dataclass(frozen=True)<br>class RegisteredUserDTO:<br>    user: User<br>    role: Role<br>    permissions: List[Permission]<br><br>    def __str__(self) -&gt; str:<br>        return f&quot;{self.user} ({self.role.name})&quot;</pre><p>The <strong>RegisteredUserDTO</strong> class is used to <strong>encapsulate and transport data</strong> that results from the registration process, without exposing the internal details of the database models or business logic.</p><h3><strong>Define a Base Factory Interface</strong></h3><p>base.py:</p><pre>from __future__ import annotations<br>from abc import ABC<br>from typing import Iterable, List<br><br>from django.db import transaction<br>from django.contrib.auth.hashers import make_password<br><br>from pt_backend.models import (<br>    User,<br>    Role,<br>    Permission,<br>    UserRole,<br>    RolePermission,<br>)<br>from .dto import RegisteredUserDTO<br><br><br>class AbstractRegistrationFactory(ABC):<br>    base_role_name: str<br>    initial_permission_names: Iterable[str] = ()<br><br>    # ---------- public API --------------------------------------------------<br>    @transaction.atomic<br>    def register(self, *, name: str, email: str, raw_password: str, **extra) -&gt; RegisteredUserDTO:<br>        role = self._get_or_create_role()<br>        perms = self._get_or_create_permissions()<br><br>        user = User.objects.create(<br>            name=name,<br>            email=email,<br>            password=make_password(raw_password),<br>            role=role.name,      <br>            **extra,<br>        )<br>        UserRole.objects.create(user=user, role=role)<br>        for perm in perms:<br>            RolePermission.objects.get_or_create(role=role, permission=perm)<br><br>        return RegisteredUserDTO(user, role, perms)<br><br>    # ---------- helpers -----------------------------------------------------<br>    def _get_or_create_role(self) -&gt; Role:<br>        return Role.objects.get_or_create(name=self.base_role_name.upper())[0]<br><br>    def _get_or_create_permissions(self) -&gt; List[Permission]:<br>        out: List[Permission] = []<br>        for name in self.initial_permission_names:<br>            perm, _ = Permission.objects.get_or_create(<br>                name=name,<br>                defaults={&quot;description&quot;: name.replace(&quot;_&quot;, &quot; &quot;).capitalize()},<br>            )<br>            out.append(perm)<br>        return out</pre><p><strong>AbstractRegistrationFactory</strong> defines a reusable template for creating users with a specific role and permissions using a consistent registration flow. It centralizes the common logic, so role-specific factories only need to define what&#39;s unique—making the code easier to extend and maintain.</p><h3><strong>Implement Registry Pattern</strong></h3><p>registry.py:</p><pre>from typing import Dict<br>from .base import AbstractRegistrationFactory<br><br>_FACTORIES: Dict[str, AbstractRegistrationFactory] = {}<br><br><br>def register_factory(cls: type[AbstractRegistrationFactory]) -&gt; type:<br>    &quot;&quot;&quot;Decorator – run on import time.&quot;&quot;&quot;<br>    _FACTORIES[cls.base_role_name.upper()] = cls()<br>    return cls<br><br><br>def get_factory(role_name: str) -&gt; AbstractRegistrationFactory:<br>    try:<br>        return _FACTORIES[role_name.upper()]<br>    except KeyError as exc:<br>        raise ValueError(f&quot;Unknown role {role_name!r}. Available: {list(_FACTORIES)}&quot;) from exc</pre><p>The registry.py file manages the <strong>registration and retrieval</strong> of all user registration factories by role name using the <strong>Registry pattern</strong>. It ensures that each factory is registered once via the <strong>@register_factory</strong> decorator and provides the <strong>get_factory</strong> function to dynamically fetch the correct factory based on a given role.</p><h3><strong>Create a Role-Specific Factory</strong></h3><p>Now, since we only need 1 role named Tenaga Ahli, lets create a factory specific for than role.</p><p>tenaga_ahli.py:</p><pre>from ..base import AbstractRegistrationFactory<br>from ..registry import register_factory<br><br><br>@register_factory<br>class TenagaAhliFactory(AbstractRegistrationFactory):<br>    base_role_name = &quot;TENAGA_AHLI&quot;<br>    initial_permission_names = (&quot;submit_report&quot;, &quot;view_dashboard&quot;)</pre><h3>Auto-Import All Factory Files</h3><p>__init__.py:</p><pre>from importlib import import_module<br>from pathlib import Path<br><br>from .registry import get_factory  <br><br>_factories_dir = Path(__file__).with_suffix(&quot;&quot;).parent / &quot;factories&quot;<br>for p in _factories_dir.glob(&quot;*.py&quot;):<br>    import_module(f&quot;{__package__}.factories.{p.stem}&quot;)<br><br>__all__ = [&quot;get_factory&quot;]</pre><h3>Use the Factory in the Service</h3><p>Implement service pattern for this specific use case similar to the one mentioned before.</p><p>service.py:</p><pre>from __future__ import annotations<br>from django.contrib.auth.password_validation import validate_password<br>from django.core.exceptions import ValidationError<br>from django.db import transaction<br>from ..registration import get_factory<br>from .dto import RegisteredUserDTO<br>from pt_backend.models import User  <br><br><br>class RegistrationError(Exception):<br>    &quot;&quot;&quot;Raised when the registration flow cannot complete.&quot;&quot;&quot;<br><br><br>class RegistrationService:<br><br>    @classmethod<br>    @transaction.atomic<br>    def register_user(<br>        cls,<br>        *,<br>        role_name: str,<br>        name: str,<br>        email: str,<br>        password: str,<br>        **extra_user_fields,<br>    ) -&gt; RegisteredUserDTO:<br>        try:<br>            cls._ensure_email_unused(email)<br>            validate_password(password)<br><br>            factory = get_factory(role_name)<br>            dto = factory.register(<br>                name=name,<br>                email=email,<br>                raw_password=password,<br>                **extra_user_fields,<br>            )<br><br>            cls._send_welcome_email(dto)<br><br>            return dto<br><br>        except (ValidationError, Exception) as exc:<br>            raise RegistrationError(str(exc)) from exc<br><br>    @staticmethod<br>    def _ensure_email_unused(email: str) -&gt; None:<br>        if User.objects.filter(email__iexact=email).exists():<br>            raise ValidationError(&quot;A user with this e-mail already exists.&quot;)<br>        <br>    @staticmethod<br>    def _send_welcome_email(dto: RegisteredUserDTO) -&gt; None:<br>        &quot;&quot;&quot;For further development process&quot;&quot;&quot;<br>        pass</pre><h3>What’s Next?</h3><p>Now that we’ve implemented the Factory Method combined with the Registry pattern, we can expect our registration system to be <strong>highly extensible, maintainable, and cleanly organized</strong>. Notice how each role is handled seamlessly through its own factory class? If we ever need to support a new role with its own specific permissions and behavior, we can simply create a new <strong>role_name.py</strong> file, define a factory by extending the base class, and decorate it with <strong>@register_factory</strong> —<strong>no need to modify existing logic</strong>, ensuring a low-coupling, scalable architecture.</p><h3>Main Usage in Further Development</h3><p>In our case, our client’s main need for our registration module is that it could be adjusted to additional role efficiently. Meaning that if they were to create a new role, we have to ensure that they won’t change any existing logic and only added lines as minimum as possible.</p><p>In our case, a new role called “<strong>tenaga_medis</strong>” will be added. This role should have an access to view the dashboard but unable to submit report. How to do it? Do we need to configure another design pattern or construct a new independent logic for registering this new role? NO!</p><p>We only need to add a new file called <em>tenaga_medis.py </em>in /factories folder. The content will look as follows:</p><pre>from ..base import AbstractRegistrationFactory<br>from ..registry import register_factory<br><br><br>@register_factory<br>class TenagaAhliFactory(AbstractRegistrationFactory):<br>    base_role_name = &quot;TENAGA_MEDIS&quot;<br>    initial_permission_names = (&quot;view_dashboard&quot;)</pre><h3>Implementation In Other Scenario</h3><p>We have another service implemented in design pattern as follows:</p><pre>from abc import ABC, abstractmethod<br>import os<br>import logging<br><br>import sib_api_v3_sdk<br>from sib_api_v3_sdk.rest import ApiException<br>from sib_api_v3_sdk import TransactionalEmailsApi, ApiClient, SendSmtpEmail<br><br>from django.core.mail import EmailMultiAlternatives<br>from django.template.loader import render_to_string<br>from django.template import TemplateDoesNotExist<br><br>logger = logging.getLogger(__name__)<br><br># Strategy Pattern for email content<br>class EmailContentStrategy(ABC):<br>    &quot;&quot;&quot;Strategy interface for different types of email content&quot;&quot;&quot;<br>    <br>    @abstractmethod<br>    def get_subject(self):<br>        &quot;&quot;&quot;Get the email subject line&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def get_template_name(self):<br>        &quot;&quot;&quot;Get the template name for this email type&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def get_context_data(self, **kwargs):<br>        &quot;&quot;&quot;Get the template context data&quot;&quot;&quot;<br>        pass<br><br>class PasswordResetEmailStrategy(EmailContentStrategy):<br>    &quot;&quot;&quot;Strategy for password reset emails&quot;&quot;&quot;<br>    <br>    def get_subject(self):<br>        return &quot;Password Reset Request&quot;<br>    <br>    def get_template_name(self):<br>        return &quot;email_reset_password.html&quot;<br>    <br>    def get_context_data(self, **kwargs):<br>        reset_link = kwargs.get(&#39;reset_link&#39;)<br>        if not reset_link:<br>            raise ValueError(&quot;Reset link is required for password reset emails&quot;)<br>        <br>        return {&quot;reset_link&quot;: reset_link}<br><br># Email Provider Interface<br>class EmailProvider(ABC):<br>    &quot;&quot;&quot;Interface for classes that can send emails.&quot;&quot;&quot;<br>    <br>    @abstractmethod<br>    def send_email(self, recipient_email, subject, template_name, context):<br>        &quot;&quot;&quot;Send an email with the given subject, template and context&quot;&quot;&quot;<br>        pass<br><br># Concrete email providers<br>class BrevoEmailProvider(EmailProvider):<br>    &quot;&quot;&quot;Brevo-specific email service implementation&quot;&quot;&quot;<br><br>    def __init__(self, api_key=None, sender_name=&quot;PPL BRIN&quot;, sender_email=&quot;pplbrin02@gmail.com&quot;):<br>        self.api_key = api_key or os.getenv(&quot;BREVO_API_KEY&quot;)<br>        self.sender = {&quot;name&quot;: sender_name, &quot;email&quot;: sender_email}<br>        <br>    def send_email(self, recipient_email, subject, template_name, context):<br>        configuration = sib_api_v3_sdk.Configuration()<br>        configuration.api_key[&#39;api-key&#39;] = self.api_key<br>        api_instance = TransactionalEmailsApi(ApiClient(configuration))<br><br>        recipients = [{&quot;email&quot;: recipient_email}]<br>        params = context  # Pass the context as params<br><br>        send_smtp_email = SendSmtpEmail(<br>            to=recipients,<br>            sender=self.sender,<br>            template_id=1,<br>            params=params<br>        )<br><br>        try:<br>            return api_instance.send_transac_email(send_smtp_email)<br>        except ApiException as e:<br>            logger.error(f&quot;Exception when calling TransactionalEmailsApi: {e}&quot;)<br>            raise<br><br>class DjangoEmailProvider(EmailProvider):<br>    &quot;&quot;&quot;Django&#39;s built-in email service implementation&quot;&quot;&quot;<br>    <br>    def __init__(self, from_email=None):<br>        self.from_email = from_email or f&quot;PantauTular &lt;{os.getenv(&#39;EMAIL_HOST_USER&#39;)}&gt;&quot;<br><br>    def send_email(self, recipient_email, subject, template_name, context):<br>        from_email = self.from_email<br>        to = [recipient_email]<br><br>        try:<br>            html_content = render_to_string(template_name, context)<br>        except TemplateDoesNotExist:<br>            raise FileNotFoundError(f&quot;The template &#39;{template_name}&#39; does not exist.&quot;)<br>        <br>        <br>        text_content = &quot;Please view this email in an HTML-capable client to see the content.&quot;<br>        if &quot;reset_link&quot; in context:<br>            text_content = f&quot;Reset your password by visiting this link: {context[&#39;reset_link&#39;]}&quot;<br>            <br>        msg = EmailMultiAlternatives(subject, text_content, from_email, to)<br>        msg.attach_alternative(html_content, &quot;text/html&quot;)<br>        <br>        try:<br>            msg.send()<br>            return True<br>        except Exception as e:<br>            logger.error(f&quot;Failed to send email: {e}&quot;)<br>            raise<br><br># Email Service with fallback mechanism<br>class EmailService:<br>    &quot;&quot;&quot;Service that manages multiple email providers with fallback capability&quot;&quot;&quot;<br>    <br>    def __init__(self, providers=None):<br>        &quot;&quot;&quot;<br>        Initialize with a list of email providers<br>        <br>        Args:<br>            providers: List of EmailProvider implementations to try in order<br>        &quot;&quot;&quot;<br>        self.providers = providers or self._get_default_providers()<br>    <br>    def send_email(self, recipient_email, strategy, **kwargs):<br>        &quot;&quot;&quot;<br>        Send an email using the given strategy, trying each provider until one succeeds<br>        <br>        Args:<br>            recipient_email: Recipient&#39;s email address<br>            strategy: EmailContentStrategy to use for content preparation<br>            **kwargs: Additional data needed by the strategy<br>        &quot;&quot;&quot;<br>        subject = strategy.get_subject()<br>        template_name = strategy.get_template_name()<br>        context = strategy.get_context_data(**kwargs)<br>        <br>        last_error = None<br>        <br>        for provider in self.providers:<br>            try:<br>                provider.send_email(recipient_email, subject, template_name, context)<br>                logger.info(f&quot;Email sent successfully using {provider.__class__.__name__}&quot;)<br>                print(f&quot;Email sent successfully using {provider.__class__.__name__}&quot;)<br>                return True<br>            except Exception as e:<br>                logger.warning(f&quot;{provider.__class__.__name__} failed to send email: {e}&quot;)<br>                last_error = e<br>                continue<br>        <br>        # If we get here, all providers failed<br>        logger.error(&quot;All email providers failed to send email&quot;)<br>        raise RuntimeError(f&quot;Failed to send email: {str(last_error)}&quot;)<br>    <br>    @staticmethod<br>    def _get_default_providers():<br>        &quot;&quot;&quot;Get the default list of email providers&quot;&quot;&quot;<br>        return [<br>            DjangoEmailProvider(),<br>            BrevoEmailProvider(),<br>        ]</pre><p>Notice that this design pattern wasn’t constructed by me, rather it was implemented by a team mate. Notice that one of my future works in the registration service is to implement an email verification method for each registration, meaning we will be needing this email service to handle the situation. Now for me to implement the new email service for register validation, I won’t be needing to change any existing logic. All I need to do is to understand the design pattern, and then extend it’s usage. So in my case, I will only be implementing a new method called <em>VerificationEmailStrategy. </em>Here is the example:</p><pre>class VerificationEmailStrategy(EmailContentStrategy):<br>    &quot;&quot;&quot;Strategy for account-activation / e-mail-verification messages.&quot;&quot;&quot;<br><br>    def get_subject(self):<br>        return &quot;Please confirm your e-mail&quot;<br><br>    def get_template_name(self):<br>        return &quot;verification_email.html&quot;<br><br>    def get_context_data(self, **kwargs):<br>        verify_url = kwargs.get(&quot;verify_url&quot;)<br>        if not verify_url:<br>            raise ValueError(&quot;verify_url is required for verification e-mails&quot;)<br>        return {&quot;verify_url&quot;: verify_url}</pre><p>Now all we need is to modify service.py in our registration factory pattern to align the new logic, we don’t need to change anything else:</p><pre>from __future__ import annotations<br>from django.contrib.auth.password_validation import validate_password<br>from django.core.exceptions import ValidationError<br>from django.db import transaction<br>from ..registration import get_factory<br>from .dto import RegisteredUserDTO<br>from pt_backend.models import User  <br>from authentication.email_services import VerificationEmailStrategy, EmailService<br>from django.utils.encoding import force_bytes<br>from django.utils.http import urlsafe_base64_encode<br>from django.conf import settings<br>from django.contrib.auth.tokens import default_token_generator<br>import threading<br><br>class RegistrationError(Exception):<br>    &quot;&quot;&quot;Raised when the registration flow cannot complete.&quot;&quot;&quot;<br><br><br>class RegistrationService:<br>    &quot;&quot;&quot;<br>    Creates a user, sets `is_active=False`, then fires an e-mail-verification<br>    message in a background thread *after* the DB commit succeeds.<br>    &quot;&quot;&quot;<br><br>    @classmethod<br>    @transaction.atomic<br>    def register_user(<br>        cls,<br>        *,<br>        role_name: str,<br>        name: str,<br>        email: str,<br>        password: str,<br>        **extra_user_fields,<br>    ) -&gt; RegisteredUserDTO:<br>        try:<br>            cls._ensure_email_unused(email)<br>            validate_password(password)<br><br>            factory = get_factory(role_name)<br>            dto = factory.register(<br>                name=name,<br>                email=email,<br>                raw_password=password,<br>                **extra_user_fields,<br>            )<br><br>            dto.user.is_active = False<br>            dto.user.save(update_fields=[&quot;is_active&quot;])<br><br>            # queue the e-mail *after* commit<br>            transaction.on_commit(<br>                lambda: threading.Thread(<br>                    target=cls._send_verification_email,<br>                    args=(dto.user,),<br>                    daemon=True,<br>                ).start()<br>            )<br><br>            return dto<br><br>        except (ValidationError, Exception) as exc:<br>            raise RegistrationError(str(exc)) from exc<br><br>    # ----------------------- Internal helpers ----------------------- #<br><br>    @staticmethod<br>    def _ensure_email_unused(email: str) -&gt; None:<br>        if User.objects.filter(email__iexact=email).exists():<br>            raise ValidationError(&quot;A user with this e-mail already exists.&quot;)<br><br>    @staticmethod<br>    def _build_verify_url(/service/user: User) -&gt; str:<br>        uid   = urlsafe_base64_encode(force_bytes(user.pk))<br>        token = default_token_generator.make_token(user)<br>        base  = getattr(settings, &quot;SITE_URL&quot;, &quot;http://localhost:8000&quot;)<br>        return f&quot;{base}/authentication/verify-email/?uid={uid}&amp;token={token}&quot;<br><br>    @classmethod<br>    def _send_verification_email(cls, user: User) -&gt; None:<br>        verify_url  = cls._build_verify_url(https://medium.com/user)<br>        strategy    = VerificationEmailStrategy()<br>        EmailService().send_email(<br>            recipient_email=user.email,<br>            strategy=strategy,<br>            verify_url=verify_url,<br>        )</pre><h3>Tradeoffs in Implementing Design Pattern</h3><p>I’m not going to lie — applying design patterns in a software development project can be more stressful than simply diving into a solution without them. It often requires extra time, careful planning, and the patience to overcome steep learning curves before the benefits become apparent. At first, it might feel like an unnecessary burden, especially when you’re under pressure to deliver quickly. However, from my personal experience, these patterns pay off significantly in the long run. You may not immediately notice their advantages, but as the project scales or undergoes further development, their value becomes clear.</p><p>At the very least, design patterns provide a mental “template” or intuitive guide for solving recurring problems. Once you’re familiar with them, it’s easy to get hooked — the structured thinking they encourage actually makes you more agile and efficient as a developer. Take the Repository and Service patterns, for example: they not only separate concerns cleanly but also improve error traceability. If something breaks, the problem is usually isolated in either the data or business logic layer, reducing debugging time. When combined with other development practices like Test-Driven Development (TDD), the codebase becomes even more robust and maintainable.</p><p>In conclusion, while design patterns may introduce complexity upfront, they are invaluable tools that enhance the clarity, scalability, and professionalism of your software. Once adopted, they can transform your development approach from reactive to strategic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4fada7c3a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Frustration to Foundation: A Developer’s Shift Toward Clean Code (SOLID Principle and Design…]]></title>
            <link>https://medium.com/@kenbalya27/from-frustration-to-foundation-a-developers-shift-toward-clean-code-solid-principle-and-design-ce05ef3a7445?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce05ef3a7445</guid>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 21:08:19 GMT</pubDate>
            <atom:updated>2025-05-15T04:59:21.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Frustration to Foundation: A Developer’s Shift Toward Clean Code (SOLID Principle and Design Patterns)</h3><p>In my project, I’m required to strictly follow programming principles and apply design patterns — which, to be honest, felt pretty annoying at first. Imagine just wanting to build a simple GET ALL API. Normally, you’d probably throw some queries directly into the views and handle everything there, right? Well, not in my case. I have to stick to the repository pattern and uphold the SOLID principles. Here’s how the task breaks down:</p><h3>1. S — Single Responsibility Principle (SRP)</h3><p>Each class should focus on doing one thing well.</p><h3>2. O — Open/Closed Principle (OCP)</h3><p>You should be able to add new features or behavior without changing existing code. This helps reduce the risk of breaking things when updating code.</p><h3>3. L — Liskov Substitution Principle (LSP)</h3><p>If a class inherits from another, it should behave in a way that doesn’t break the parent class’s expected behavior. Basically, your derived classes should fit perfectly into the place of their parent.</p><h3>4. D — Dependency Inversion Principle (DIP)</h3><p>High-level modules shouldn’t rely on low-level modules directly. Instead, both should depend on abstractions (like interfaces). This decouples the system and makes it easier to change components.</p><p>So here is what I did to fulfill the requirements above (only for a single get request):</p><ol><li>Create an interface for a further high-level usage (like implementing API’s) as a contract to lower level implementations:</li></ol><pre>class CaseRetrievalInterface(ABC):<br>    @abstractmethod<br>    def get_all_case_locations(self):<br>        pass<br><br>class CaseRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_all_locations(self):<br>        pass</pre><p>At this point, we have implemented <strong>Interface Segregation Principle</strong>, as well as a contract template for each classes <strong>SRP</strong> that will be implemented later on.</p><p>2. Implement repository pattern:</p><pre>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_locations(self):<br>        return Case.get_all_locations()<br></pre><p>Make sure each class has only one responsibility to fulfill <strong>Single Responsibilty Principle</strong>. The use of abstract base classes ( like CaseRepositoryInterface) allows new implementations to extend functionality without modifying existing code, fulfilling <strong>Open-Closed Principle</strong>.</p><p>3. Implement services:</p><pre>class CaseService(CaseRetrievalInterface):<br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br><br>    def get_all_case_locations(self):<br>         locations = self.repository.get_all_locations()<br>       return locations if locations else []</pre><p>Notice that this class has dependencies, for each class with dependencies make sure to always inject the dependency at the classes definition, hence fulfilling <strong>Dependency Inversion Principle</strong>. CaseService depends on abstractions (CaseRepositoryInterface and CacheInterface), which means any subclass or implementation of these interfaces can be substituted in. Meaning we have fulfill <strong>LSP</strong> as well.</p><p>Finally, we can use it in the views:</p><pre>class CaseLocationsAPIView(APIView):<br>    &quot;&quot;&quot;<br>    API view to retrieve all case locations.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        # Instantiate lower-level modules: repository and cache service.<br>        self.repository = CaseRepository()<br>        # Create the CaseService with its dependencies injected.<br>        self.case_service = CaseService(<br>            repository=self.repository,<br>        )<br><br>    def get(self, request, *args, **kwargs):<br>        # Use the service to retrieve case locations.<br>        locations = self.case_service.get_all_case_locations()<br>        return Response(locations, status=status.HTTP_200_OK)</pre><p>At first glance, it’s clear this approach takes more effort than simply dumping all the logic into the views, right? But everything started to make sense when I had to add more features. In my case, I needed to implement a new feature to extract cases based on multiple attributes and also add caching.</p><ol><li>Implement interfaces: For case extraction feature it’s related to Case Retrieval, so we just need to add the method’s abstraction to the interface we used before. For caching, we make a new contract.</li></ol><pre>class CaseRetrievalInterface(ABC):<br>    @abstractmethod<br>    def get_all_cases(self):<br>        pass<br>    @abstractmethod<br>    def get_all_case_locations(self):<br>        pass<br><br>class CaseRepositoryInterface(ABC):<br>    @abstractmethod<br>    def get_all_cases(self):<br>        pass<br>    <br>    @abstractmethod<br>    def get_all_locations(self):<br>        pass<br><br>class CacheInterface(ABC):<br>    @abstractmethod<br>    def get(self, key):<br>        pass<br><br>    @abstractmethod<br>    def set(self, key, value, timeout):<br>        pass<br><br>    @abstractmethod<br>    def delete(self, key):<br>        pass</pre><p>2. Implement it’s repository:</p><pre>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_cases(self):<br>        return Case.objects.all().values(<br>            &quot;id&quot;,<br>            &quot;location__province&quot;,<br>            &quot;location__city&quot;,<br>            &quot;news__portal&quot;,<br>            &quot;severity&quot;,<br>            &quot;news__date_published&quot;<br>        )<br>    def get_all_locations(self):<br>        return Case.get_all_locations()</pre><p>3. Implement the service:</p><pre>class CaseService(CaseRetrievalInterface):<br>    CACHE_KEY_ALL_CASES = &quot;all_cases&quot;<br>    CACHE_TIMEOUT = 300 <br><br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br>        self.cache_service = cache_service<br><br>    def get_all_cases(self):<br>        cases = self.cache_service.get(self.CACHE_KEY_ALL_CASES)<br>        if cases is None:<br>            cases = self.repository.get_all_cases()<br>            self.cache_service.set(self.CACHE_KEY_ALL_CASES, cases, timeout=self.CACHE_TIMEOUT)<br>        return cases if cases else []<br>    <br>    def get_all_case_locations(self):<br>        locations = self.cache_service.get(self.CACHE_KEY)<br>        if locations is None:<br>            locations = self.repository.get_all_locations()<br>            self.cache_service.set(self.CACHE_KEY, locations, timeout=self.CACHE_TIMEOUT)<br>        return locations if locations else []<br><br><br>class CacheService(CacheInterface):<br>    def get(self, key):<br>        return cache.get(key)<br><br>    def set(self, key, value, timeout):<br>        cache.set(key, value, timeout)<br><br>    def delete(self, key):<br>        cache.delete(key)</pre><p>With this approach, we can build on top of it for more advanced implementations later. And guess what? We’re done! If we had implemented those features directly in the views, we might’ve run into integration issues. But by structuring it this way, we can safely ignore previously implemented features — adding new ones won’t interfere with what’s already working!</p><p>Below is an explanation that breaks down the design patterns and SOLID principles used in the code, along with why these practices are useful:</p><h3>1. Abstraction and Interfaces</h3><p>The code starts by defining several abstract base classes (interfaces):</p><ul><li><strong>CaseRetrievalInterface</strong></li><li><strong>CaseRepositoryInterface</strong></li></ul><p>Each of these declares methods (using the @abstractmethod decorator) that must be implemented by any concrete subclass. This creates a clear contract for behavior.</p><p><strong>Why is this useful?</strong><br> By programming to an interface rather than a concrete implementation, you decouple your code. This makes it easier to swap implementations (for instance, using a different caching mechanism) without changing the higher-level business logic.</p><h3>2. Design Patterns in Action</h3><h4>Repository Pattern<strong>Example:</strong> CaseRepository implements CaseRepositoryInterface.</h4><ul><li><strong>Purpose:</strong> The repository pattern provides a layer of abstraction over data storage, hiding the details of data access. This way, the rest of the application doesn’t have to worry about whether data comes from a database, an API, or another source.</li></ul><h4>Service Pattern with Caching</h4><ul><li><strong>Example:</strong> CaseService implements CaseRetrievalInterface and uses a caching strategy.</li><li><strong>How it works:</strong></li></ul><ol><li><strong>Cache Check:</strong> When fetching all cases, the service first checks if the data is available in the cache.</li><li><strong>Data Retrieval &amp; Cache Update:</strong> If the data isn’t cached, it retrieves the cases from the repository, caches them, and then returns the data.</li></ol><ul><li><strong>Purpose:</strong> This pattern improves performance and scalability by reducing repetitive calls to the underlying data source and efficiently reusing cached data.</li></ul><h4>Dependency Injection</h4><ul><li>Example: The CaseService constructor takes a repository (of type CaseRepositoryInterface) and a cache_service (of type CacheInterface).</li><li>Purpose: Dependency Injection means that CaseService is not responsible for creating its dependencies. Instead, these dependencies are “injected” into it. This leads to:</li><li>Loose Coupling: The service isn’t tightly bound to any specific repository or cache implementation.</li><li>Testability: You can easily substitute mocks or stubs during testing.</li></ul><h3>When Changes Occurred</h3><p>This is the part where our programming principles really played their role. Implementing coding principles like SOLID, can ensure one thing. If the behavior of a class needs to be adjusted, then it will only affect that class alone and higher level logic which depend on it. The role of Single Responsibility Principle and Dependency Injection Principle play a pivotal role here. Lets pick an example:</p><pre>class AverageSeverityByProvince:<br>    STATUS_ENCODING = {<br>        &quot;minimal&quot;: 1,<br>        &quot;biasa&quot;: 2,<br>        &quot;bahaya&quot;: 3,<br>        &quot;katastropik&quot;: 4<br>    }<br><br>    def __init__(self, case_service):<br>        self.case_service = case_service<br>        self.PROVINCE_TO_CODE = PROVINCE_TO_CODE<br><br>    def compute(self):<br>        &quot;&quot;&quot;<br>        Hitung weighted severity score dan kategorisasi status untuk setiap provinsi.<br>        Output: list of dicts [{ &quot;id&quot;: province_code, &quot;value&quot;: float, &quot;status&quot;: str }, ...]<br>        &quot;&quot;&quot;<br>        data = self.case_service.get_status_and_province()<br>        province_scores = defaultdict(list)<br><br>        for record in data:<br>            status = record.get(&quot;status&quot;)<br>            province = record.get(&quot;location__province&quot;)<br><br>            if status and province:<br>                status = status.lower()<br>                if status in self.STATUS_ENCODING:<br>                    encoded = self.STATUS_ENCODING[status]<br>                    province_scores[province].append(encoded)<br><br>        if not province_scores:<br>            return []<br><br>        weighted_result = {}<br>        all_scores = []<br><br>        for province, scores in province_scores.items():<br>            avg = sum(scores) / len(scores)<br>            weight = math.log(len(scores) + 1)<br>            weighted_score = round(avg * weight, 2)<br>            weighted_result[province] = {&quot;value&quot;: weighted_score}<br>            all_scores.append(weighted_score)<br><br><br>        q1 = np.percentile(all_scores, 25)<br>        q2 = np.percentile(all_scores, 50)<br>        q3 = np.percentile(all_scores, 75)<br><br>        for province, result in weighted_result.items():<br>            score = result[&quot;value&quot;]<br>            if score &lt;= q1:<br>                result[&quot;status&quot;] = &quot;minimal&quot;<br>            elif score &lt;= q2:<br>                result[&quot;status&quot;] = &quot;biasa&quot;<br>            elif score &lt;= q3:<br>                result[&quot;status&quot;] = &quot;bahaya&quot;<br>            else:<br>                result[&quot;status&quot;] = &quot;katastropik&quot;<br>                <br>            # Add province code<br>            result[&quot;id&quot;] = self.PROVINCE_TO_CODE.get(province, province)<br><br>        # Convert dictionary to list format<br>        formatted_result = [<br>            {<br>                &quot;id&quot;: data[&quot;id&quot;],<br>                &quot;value&quot;: data[&quot;value&quot;],<br>                &quot;status&quot;: data[&quot;status&quot;]<br>            } for province, data in weighted_result.items()<br>        ]<br><br>        return formatted_result</pre><p>The AverageSeverityByProvince class is designed to compute a weighted severity score and classify health status levels for each Indonesian province based on case data. It uses an encoding scheme to numerically represent qualitative severity labels (minimal, biasa, bahaya, katastropik) and retrieves data via a case_service interface. For each province, it calculates the average encoded score of cases and applies a logarithmic weight based on the number of cases to emphasize more representative samples. These weighted scores are then segmented into four status categories using quartiles (Q1, Q2, Q3) to assign relative severity levels across provinces. The final output is a list of dictionaries containing the province code, weighted score, and categorized status, enabling geographic severity mapping.</p><p>The service will be consumed by one of our views:</p><pre>class WeightedSeverityAnalysisView(APIView):<br>    authentication_classes = [APIKeyAuthentication]<br>    permission_classes = []<br>    <br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        self.case_service = CaseService(<br>            repository=CaseRepository(),<br>            cache_service=CacheService()<br>        )<br>        self.severity_analyzer = AverageSeverityByProvince(self.case_service)<br>    <br>    def get(self, request):<br>        try:<br>            result = self.severity_analyzer.compute()<br>            <br>            if not result:<br>                return Response(<br>                    {&quot;error&quot;: &quot;No case data available&quot;},<br>                    status=status.HTTP_404_NOT_FOUND<br>                )<br>            <br>            return Response(result, status=status.HTTP_200_OK)<br>            <br>        except Exception:<br>            return Response(<br>                {&quot;error&quot;: INTERNAL_SERVER_ERR_MSG},<br>                status=status.HTTP_500_INTERNAL_SERVER_ERROR<br>            )</pre><p>Now lets assume we want to use other techniques to determine the severity status of each province, maybe we can use Machine Learning techniques like clustering. What we need to do is just change the behavior of AverageSeverityByProvince:</p><pre>from collections import defaultdict<br>import math<br>import numpy as np<br>from sklearn.cluster import KMeans<br><br>class AverageSeverityByProvince:<br>    STATUS_ENCODING = {<br>        &quot;minimal&quot;: 1,<br>        &quot;biasa&quot;: 2,<br>        &quot;bahaya&quot;: 3,<br>        &quot;katastropik&quot;: 4<br>    }<br><br>    CLUSTER_TO_STATUS = {<br>        0: &quot;minimal&quot;,<br>        1: &quot;biasa&quot;,<br>        2: &quot;bahaya&quot;,<br>        3: &quot;katastropik&quot;<br>    }<br><br>    def __init__(self, case_service):<br>        self.case_service = case_service<br><br>    def compute(self):<br>        &quot;&quot;&quot;<br>        Hitung weighted severity score dan kategorisasi status untuk setiap provinsi<br>        menggunakan KMeans clustering.<br>        Output: list of dicts [{ &quot;id&quot;: province_name, &quot;value&quot;: float, &quot;status&quot;: str }, ...]<br>        &quot;&quot;&quot;<br>        data = self.case_service.get_status_and_province()<br>        province_scores = defaultdict(list)<br><br>        for record in data:<br>            status = record.get(&quot;status&quot;)<br>            province = record.get(&quot;location__province&quot;)<br><br>            if status and province:<br>                status = status.lower()<br>                if status in self.STATUS_ENCODING:<br>                    encoded = self.STATUS_ENCODING[status]<br>                    province_scores[province].append(encoded)<br><br>        if not province_scores:<br>            return []<br><br>        weighted_result = {}<br>        all_scores = []<br><br>        for province, scores in province_scores.items():<br>            avg = sum(scores) / len(scores)<br>            weight = math.log(len(scores) + 1)<br>            weighted_score = round(avg * weight, 2)<br>            weighted_result[province] = {&quot;value&quot;: weighted_score}<br>            all_scores.append([weighted_score])  # 2D array for KMeans<br><br>        # Apply KMeans clustering<br>        kmeans = KMeans(n_clusters=4, random_state=0, n_init=&quot;auto&quot;)<br>        cluster_labels = kmeans.fit_predict(all_scores)<br><br>        # Sort cluster centers to map them consistently to severity levels<br>        centers = kmeans.cluster_centers_.flatten()<br>        sorted_indices = np.argsort(centers)<br>        label_to_status = {<br>            label: self.CLUSTER_TO_STATUS[idx]<br>            for idx, label in enumerate(sorted_indices)<br>        }<br><br>        # Assign status based on cluster<br>        for (province, result), cluster_label in zip(weighted_result.items(), cluster_labels):<br>            result[&quot;status&quot;] = label_to_status[cluster_label]<br>            result[&quot;id&quot;] = province  # No conversion to code<br><br>        # Format result as list<br>        formatted_result = [<br>            {<br>                &quot;id&quot;: data[&quot;id&quot;],<br>                &quot;value&quot;: data[&quot;value&quot;],<br>                &quot;status&quot;: data[&quot;status&quot;]<br>            } for data in weighted_result.values()<br>        ]<br><br>        return formatted_result</pre><p>Now what happened here, is that only this class behavior that changes. The API Views will change as well but it’s only due to the different output given by the service. Any other class within the same level with, lower, or higher level classes that doesn’t depend on it will not change. Hence, we ensured that changes are made with minimal lines of codes and minimal effect to the whole system.</p><h3>In Summary</h3><p>This experience of mine is an excellent example of how design patterns (like the repository and service patterns) can be combined with SOLID principles to create robust, maintainable, and flexible applications. By using abstraction and dependency injection, the design ensures that components remain decoupled, making future enhancements or changes simpler and less risky.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce05ef3a7445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profiling in Django]]></title>
            <link>https://medium.com/@kenbalya27/profiling-in-django-6f6a7b41d296?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f6a7b41d296</guid>
            <category><![CDATA[profiling]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 20:14:49 GMT</pubDate>
            <atom:updated>2025-05-20T03:58:40.894Z</atom:updated>
            <content:encoded><![CDATA[<p>Profiling is the process of measuring the performance characteristics of a program — such as execution time, memory usage, and function call frequency — to identify bottlenecks or inefficiencies. It helps developers understand how their code behaves in real-world scenarios, allowing them to pinpoint specific areas that require optimization. By revealing which functions consume the most resources or slow down execution, profiling enables informed decisions to improve speed, reduce memory footprint, and enhance overall application performance. This is especially important for large-scale or resource-intensive applications, where even minor inefficiencies can significantly impact user experience or system stability.</p><p>In my PantauTular project, I will use do request/response profiling using <a href="https://github.com/jazzband/django-silk">django-silk</a>, a powerful profiling and inspection tool for Django applications. With this addition, we can monitor and optimize our API performance, identify slow queries, and analyze request handling efficiency.</p><p>Here is how I implement it:</p><ol><li>Install silk:</li></ol><pre>pip install django-silk</pre><p>2. Configure django-silk to capture request/response data, SQL queries, and execution times.</p><pre>INSTALLED_APPS = [<br>   &#39;silk&#39;,<br>]<br>MIDDLEWARE = [<br>    &#39;silk.middleware.SilkyMiddleware&#39;,<br>]</pre><p>3. Migrate silk:</p><pre>python manage.py migrate silk</pre><p>4. Run the server and access silk in /silk, initial page looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2qZ-zrrmjoo1tZQfovZ-A.png" /></figure><p>5. Lets try to test it with API</p><p>First, we will throw a Get request to <a href="http://127.0.0.1:8000/cases/locations/">http://127.0.0.1:8000/cases/locations/</a>, the request will be captured as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwlqoIouOEOGl-wLLfivvQ.png" /></figure><p>We can also view all requests on the requests tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYDYThE7FLKEYbSeoaUhTg.png" /></figure><p>Lets do several more requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtrILXXcN0oGhmqzgHmjkQ.png" /></figure><p>Notice that the GET methods after the first one did the query by 0 ms. This happened due to the backend app had already implemented caching, so that the retrieved data will be kept in the server’s cache within a limited time. Meaning, the backend doesn’t need to do any kind of query to the database.</p><h3>Usage For Optimization</h3><p>We have this service:</p><pre>class CaseService(CaseRetrievalInterface):<br><br>    def __init__(self, repository: CaseRepositoryInterface):<br>        self.repository = repository<br><br>    def get_all_case_locations(self):<br>        locations = self.repository.get_all_locations()<br>        return locations if locations else []</pre><p>Which implements this repository:</p><pre>class CaseRepository(CaseRepositoryInterface):<br>    def get_all_locations(self):<br>        return Case.get_all_locations()</pre><p>The service’s purpose is to return available cases data’s location from a get request, which calls a query to get all cases locations. This is the profiling result after 5 API calls to the service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW4ZCw6wEseX9Ds0rauz9g.png" /><figcaption>5 API CALLS</figcaption></figure><p>Now in a production environment, hundreds or even thousands of users will use this service. So one optimization we can do is by adding caching to the service so that database query will only took place in the first request, which can boost the performance in the 2nd, 3rd, and next API calls.</p><pre>class CaseService(CaseRetrievalInterface):<br>    CACHE_KEY = &quot;all_case_locations&quot;<br>    CACHE_TIMEOUT = 300 <br><br>    def __init__(self, repository: CaseRepositoryInterface, cache_service: CacheInterface):<br>        self.repository = repository<br>        self.cache_service = cache_service<br><br>    def get_all_case_locations(self):<br>        locations = self.cache_service.get(self.CACHE_KEY)<br>        if locations is None:<br>            locations = self.repository.get_all_locations()<br>            self.cache_service.set(self.CACHE_KEY, locations, timeout=self.CACHE_TIMEOUT)<br>        return locations if locations else []<br><br><br>class CacheService(CacheInterface):<br>    def get(self, key):<br>        return cache.get(key)<br><br>    def set(self, key, value, timeout):<br>        cache.set(key, value, timeout)<br><br>    def delete(self, key):<br>        cache.delete(key)</pre><p>Result after caching:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T_mL6jquE-1R3Dihv1XGw.png" /><figcaption>5 API CALLS</figcaption></figure><p>Notice that after the first call, no query was made for the next requests. Now it might only reduce several hundred ms in our scenario, but it will definitely affect more in a production scenario full of data.</p><h3>Usage and Benefits:</h3><p>✅ Performance Profiling — Measures execution time for each request and detects slow API endpoints.<br>✅ SQL Query Analysis — Identifies inefficient or redundant queries that impact database performance.<br>✅ Debugging &amp; Optimization — Tracks middleware execution and response times, providing actionable insights.<br>✅ UI Dashboard — Provides an intuitive web-based dashboard for monitoring profiling data (/silk/).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f6a7b41d296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Secure Programming: OWASP]]></title>
            <link>https://medium.com/@kenbalya27/implementing-secure-programming-f66a18dc25af?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66a18dc25af</guid>
            <category><![CDATA[secure-programming]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 06:55:35 GMT</pubDate>
            <atom:updated>2025-05-28T16:15:34.605Z</atom:updated>
            <content:encoded><![CDATA[<p>OWASP (Open Web Application Security Project) is an organization that develops security standards for web applications. In this project, we will implement some best practices from the OWASP Top 10 to ensure that the Django application we develop is safe from various cyber threats.</p><p>When developing an application, most developers will focus on implementing the business logic in order to fulfill the requirements of the product. However, besides the logical flow security is also a crucial part in an application. Hence implementing business logic must be integrated with ensuring the security of the program. Let me share my journey on implementing this approach.</p><ol><li>Always Seal Secrets in Environment Variables</li></ol><p>Make sure to not hard code secrets as a variable in a program file, always store it in the environment variable and then load it to the program. This is how I do it:</p><p>.env:</p><pre>SECRET_KEY=your_secret_key<br>SECRET_API_KEY=your_secret_api_key</pre><p>settings.py:</p><pre>import os<br>from dotenv import load_dotenv<br><br>SECRET_KEY = os.getenv(&#39;SECRET_KEY&#39;)</pre><p>2. Prevent Broken Access Control</p><p>Broken Access Control is one of the biggest risks in web applications. We must ensure that only authorized users can access certain data and features.</p><p>As mentioned on my previous blog, I have implemented an API service to fetch all cases. Here is the code:</p><pre>class AllCaseLocationsView(APIView):<br>    serializer_class = CaseLocationSerializer<br>    service = CaseService()<br>    def get(self, request):<br>        try:<br>            cases = self.service.get_all_case_locations()<br>            if cases is None:<br>                return Response({&quot;error&quot;: &quot;No case locations found&quot;}, status=status.HTTP_404_NOT_FOUND)<br>            serialized_data = self.serializer_class(cases, many=True).data<br>            return Response(serialized_data, status=status.HTTP_200_OK)<br>        except Exception: <br>            return Response({&quot;An unexpected error occurred. Please try again later.&quot;}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</pre><p>We can use DRF Permissions to ensure that the API can only be accessed by authorized parties.</p><p>Step 1: add authenticate.py</p><pre>from rest_framework.authentication import BaseAuthentication<br>from rest_framework.exceptions import AuthenticationFailed<br>import os<br><br>class APIKeyAuthentication(BaseAuthentication):<br>    def authenticate(self, request):<br>        api_key = request.headers.get(&quot;X-API-KEY&quot;)  <br>        secret_key = os.getenv(&quot;SECRET_API_KEY&quot;)<br><br>        if not api_key or api_key != secret_key:<br>            raise AuthenticationFailed(&quot;Invalid API Key&quot;)<br><br>        return (None, None)</pre><p>Step 2: Refactor views.py</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br>from .serializers import CaseLocationSerializer<br>from .services import CaseService<br>from .authentication import APIKeyAuthentication<br><br><br>class AllCaseLocationsView(APIView):<br>    authentication_classes = [APIKeyAuthentication]  <br>    permission_classes = []  <br><br>    serializer_class = CaseLocationSerializer<br>    service = CaseService()<br>    def get(self, request):<br>        try:<br>            cases = self.service.get_all_case_locations()<br>            if cases is None:<br>                return Response({&quot;error&quot;: &quot;No case locations found&quot;}, status=status.HTTP_404_NOT_FOUND)<br>            serialized_data = self.serializer_class(cases, many=True).data<br>            return Response(serialized_data, status=status.HTTP_200_OK)<br>        except Exception: <br>            return Response({&quot;An unexpected error occurred. Please try again later.&quot;}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)<br></pre><p>With the additional security above, API request can only be done when the requester’s header contains X-API-KEY: SECRET_KEY.</p><p>3. Prevent Injection Attacks:</p><p>Injection (SQL Injection, XSS, and others) can cause data leakage or database manipulation.</p><p>To handle prevent this threat, we can do the following:</p><ul><li>Make sure to always use Django’s ORM, never use raw query:</li></ul><pre># ❌ <br>Product.objects.raw(f&quot;SELECT * FROM product WHERE name = &#39;{user_input}&#39;&quot;)<br><br># ✅<br>Product.objects.filter(name=user_input)</pre><ul><li>Use Serializer Validation:</li></ul><pre>from rest_framework import serializers<br>from .models import Product<br><br>class ProductSerializer(serializers.ModelSerializer):<br>    name = serializers.CharField(max_length=255)<br>    price = serializers.DecimalField(max_digits=10, decimal_places=2, min_value=0)<br><br>    class Meta:<br>        model = Product<br>        fields = &#39;__all__&#39;</pre><p>4. Prevent Security Misconfiguration:</p><p>Misconfigurations can leave applications vulnerable to attacks.</p><p>To resolve this, make sure to configure the following in settings.py:</p><pre>DEBUG = False  # NEVER DO DEBUG=True IN PRODUCTION ENVIRONMENT!<br><br>ALLOWED_HOSTS = [&#39;yourdomain.com&#39;]  # Restrict access to specific domains only<br><br>SECURE_BROWSER_XSS_FILTER = True  # Prevent XSS<br>SECURE_CONTENT_TYPE_NOSNIFF = True  # Prevent MIME-sniffing<br>SECURE_SSL_REDIRECT = True  # Force the usage HTTPS<br>SESSION_COOKIE_SECURE = True  # Only use Cookie in HTTPS<br>CSRF_COOKIE_SECURE = True  #Secure CSRF cook<br>ie with HTTPS</pre><h3>Now after configuring, lets head to the test!</h3><p>The easiest way to do it is by security scanner tools, since I assume most of us developers aren’t familiar with penetration testing in cyber security style. Therefore, I’m going to use Bandit to do the local scanning:</p><p>Installation:</p><pre>pip install bandit</pre><p>Analyze the project:</p><pre>bandit -r path/to/your/project/</pre><p>This is the output from my local:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1CTbnJlqLDy094af8R9ZQ.png" /></figure><p>Notice that it detected some issues, however it has low severity and it only came from a test file. Therefore we can conclude that the whole implementation of our project is safe.</p><p>Besides using bandit, we can also see security hotspots via static analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*KJBWeYfo5asJYS3eCv8mPQ.png" /></figure><p>Notice that 0 security hotspots means that there are no possible threats based on our raw coding implementation.</p><p>For further analysis, I used SSL Labs to see potential issues in the production environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dr19Gf1TNBJJ_XzzY37ETg.png" /></figure><p>An overall A rating in SSL Labs indicates that a website has strong SSL/TLS security, using modern encryption protocols, secure configurations, and a valid certificate. It means the server is well-protected against common vulnerabilities and follows best practices for HTTPS.</p><h3>Further Testing</h3><p>Here, I will do some simple testing via API calls with postman.</p><ol><li>Lets try it simple, access the API without using the API-KEY:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5WhlBBBlRS_p826ldoHgg.png" /><figcaption>Sending API Request without API KEY</figcaption></figure><p>Notice that it responded with a forbidden message due to not having the API key.</p><p>2. Lets use some SQL Injection payloads for the API KEY</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugwYd0SxwZ_xZeQmmAXm9g.png" /></figure><p>The SQL snippet OR ‘1’ = ‘1’ is used in SQL injection to always evaluate the condition as true, effectively bypassing authentication or conditional checks. For example, in a login query, it can trick the system into logging in without valid credentials by returning all rows or bypassing password verification.</p><p>3. Lets try to apply SQL Injection payloads on POST method payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-esIELs1KqNod5SidP8kQ.png" /></figure><p>The payload { “location”: “UNION SELECT * FROM USERS — “} attempts a SQL injection by using UNION SELECT to append the results of a query that selects all records from the USERS table. The — is a comment sequence in SQL that ignores the rest of the original query, allowing the injected query to run independently and potentially expose sensitive user data.</p><p>However, it doesn’t respond with any user-related data but only returning an un-filtered locations. Which means the payload doesn’t work here, the backend is still safe!</p><p>Note that the valid API-KEY is applied here, so the backend will not respond with a forbidden message.</p><p>But it still returned a data, which isn’t good. Now lets create a module to intercept SQL Injections payload. To do that, we can check the payload’s content and search for some well-known SQL Injection patterns within the request. Lets implement a module named payload_scanner.py:</p><pre>import re<br>import unicodedata<br>from rest_framework.exceptions import ValidationError<br><br>class SQLInjectionDetector:<br>    &quot;&quot;&quot;<br>    Stronger SQL Injection Detector with input normalization.<br>    &quot;&quot;&quot;<br><br>    SUSPICIOUS_PATTERNS = [<br>        r&quot;(?i)(select\s.+\sfrom)&quot;,             # SELECT ... FROM<br>        r&quot;(?i)(union\s+select)&quot;,                # UNION SELECT<br>        r&quot;(?i)(insert\s+into)&quot;,                 # INSERT INTO<br>        r&quot;(?i)(update\s+\w+\s+set)&quot;,             # UPDATE table SET<br>        r&quot;(?i)(delete\s+from)&quot;,                 # DELETE FROM<br>        r&quot;(?i)(drop\s+table|drop\s+database)&quot;,   # DROP TABLE or DATABASE<br>        r&quot;(?i)(create\s+table|create\s+database)&quot;, # CREATE TABLE or DATABASE<br>        r&quot;(?i)(exec\s+\()&quot;,                     # EXEC(<br>        r&quot;(?i)(--|#)&quot;,                          # Comment injections<br>        r&quot;(?i)(;)&quot;,                             # Multiple queries<br>    ]<br><br>    @classmethod<br>    def normalize(cls, value: str) -&gt; str:<br>        # Convert special unicode to ascii<br>        value = unicodedata.normalize(&#39;NFKD&#39;, value).encode(&#39;ascii&#39;, &#39;ignore&#39;).decode(&#39;ascii&#39;)<br>        # Remove extra spaces and lower the string<br>        value = re.sub(r&#39;\s+&#39;, &#39; &#39;, value)<br>        return value.lower()<br><br>    @classmethod<br>    def _is_suspicious(cls, value: str) -&gt; bool:<br>        if not isinstance(value, str):<br>            return False<br>        <br>        normalized_value = cls.normalize(value)<br><br>        for pattern in cls.SUSPICIOUS_PATTERNS:<br>            if re.search(pattern, normalized_value):<br>                return True<br>        return False<br><br>    @classmethod<br>    def check(cls, request):<br>        &quot;&quot;&quot;<br>        Check request.query_params (GET) and request.data (POST/PUT) for SQL injection attempts.<br>        &quot;&quot;&quot;<br>        for key, value in request.query_params.items():<br>            if cls._is_suspicious(value):<br>                raise ValidationError(f&quot;Input for &#39;{key}&#39; contains suspicious SQL injection pattern.&quot;)<br><br>        if hasattr(request, &quot;data&quot;):<br>            for key, value in request.data.items():<br>                if isinstance(value, str) and cls._is_suspicious(value):<br>                    raise ValidationError(f&quot;Input for &#39;{key}&#39; contains suspicious SQL injection pattern.&quot;)<br>                if isinstance(value, list):<br>                    for item in value:<br>                        if isinstance(item, str) and cls._is_suspicious(item):<br>                            raise ValidationError(f&quot;Input list for &#39;{key}&#39; contains suspicious SQL injection pattern.&quot;)</pre><p>After implementing it, integrate the method with the API views. After that we can try to use the same payload, however this time the project is still in my local device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NYy_V2whRDhMeTMY6NSjA.png" /></figure><p>Notice that now the backend responded with suspicious error message, from here we can use this approach to expand our security. For example, we can store the data of suspicious request senders and block it’s access if suspicious attempts are made continuously.</p><h3>Security Across the Software Development Lifecycle (SDLC)</h3><p>True application security requires a holistic approach that goes beyond writing secure code. It involves considering security at every stage of the development lifecycle:</p><h4>Secure Programming</h4><p>The one we have discussed above, fulfilling OWASP top 10 or at least threats that may appear in our scenario.</p><h4>Secure Deployment</h4><p>Deploy the application to a secure hosting environment with properly configured firewalls and access controls to prevent unauthorized access. Ensure all sensitive information, such as database credentials and API keys used by backend API routes is managed securely using environment variables provided by the hosting platform, rather than hardcoding them into the codebase.</p><h4>Code/Commit Signing using GPG</h4><p>Code and commit signing using GPG (GNU Privacy Guard) is a vital security measure in the Software Development Life Cycle (SDLC) to ensure the authenticity and integrity of source code. By cryptographically signing Git commits with a developer’s private GPG key, each commit is verifiably linked to its true author. This prevents impersonation and guarantees that the code has not been altered since it was signed. When integrated into platforms like GitHub or GitLab, signed commits are marked with a “Verified” badge, offering clear visual assurance to reviewers and collaborators that the commit comes from a trusted source.</p><h4>Monitoring and Logging</h4><p>Implement robust logging and monitoring with tools like LogRocket for frontend, or Sentry for backend to detect suspicious activity or security incidents in the deployed application.</p><h4>Further Penetration Testing: A bit knowledge of cybersecurity won’t harm</h4><p>Since I have tested SQL Injections in all API endpoints and none of them managed to bypass the security measures, it doesn’t mean that our application is free from vulnerabilities. From a cybersecurity point of view, no matter how strong an application’s security appears to be, there will always be the possibility of weaknesses. This is rooted in the fact that every security system is built by humans, and human work is never without limitations. Unless it were secured by God Himself, we must always assume that some form of vulnerability could exist within the system. Therefore, our responsibility is not to aim for a flawless system — which is unrealistic — but to continuously minimize risks and reduce the surface area of potential attacks.</p><p>To support this mindset, I used one of the most powerful tools available for security testing: <strong>Burp Suite</strong>. This tool allows us to intercept, analyze, and manipulate the traffic between the client and server, offering deep insights into what is happening behind the scenes in a web application. While automated scanners are helpful, manual inspection using Burp Suite often reveals subtle security flaws that automated tools might overlook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKP9MO9h03HHwcLs.png" /></figure><h4>Api-Key exposed!</h4><p>During testing, one such issue I discovered was the exposure of an <strong>API key in the request headers</strong>, and yes this is the exact same API key as discussed earlier. As I analyzed the outgoing HTTP requests captured by Burp Suite, I noticed that every authenticated API call included an API key sent in plaintext. This means that if an attacker were to intercept this traffic for instance, over an unsecured public Wi-Fi network or from a compromised device they could easily extract this key and use it to access protected endpoints. Even though HTTPS encrypts traffic in transit, relying solely on encryption is not enough if the application exposes sensitive information in places where it shouldn’t.</p><p>The issue is within the code in api.ts:</p><pre>import type { NextApiRequest, NextApiResponse } from &#39;next&#39;;<br><br>const API_BASE_URL = process.env.API_BASE_URL;<br>const API_KEY = process.env.API_KEY;<br><br>export default async function handler(req: NextApiRequest, res: NextApiResponse) {<br>  try {<br>    const response = await fetch(`${API_BASE_URL}/cases/locations/`, {<br>      method: &#39;GET&#39;,<br>      headers: {<br>        &#39;Accept&#39;: &#39;application/json&#39;,<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        &#39;x-api-key&#39;: String(API_KEY),<br>      },<br>    });<br><br>    if (!response.ok) {<br>      return res.status(response.status).json({ error: `Upstream error: ${response.statusText}` });<br>    }<br><br>    const data = await response.json();<br>    return res.status(200).json(data);<br>  } catch (error) {<br>    console.error(&#39;Error in API route /api/locations:&#39;, error);<br>    return res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>  }<br>}</pre><p>To resolve this, we can keep the main api call on the Next JS server-side.</p><p>Create a Next JS API route in In pages/api/locations.ts:</p><pre>import type { NextApiRequest, NextApiResponse } from &#39;next&#39;;<br><br>const API_BASE_URL = process.env.API_BASE_URL;<br>const API_KEY = process.env.API_KEY;<br><br>export default async function handler(req: NextApiRequest, res: NextApiResponse) {<br>  try {<br>    const response = await fetch(`${API_BASE_URL}/cases/locations/`, {<br>      method: &#39;GET&#39;,<br>      headers: {<br>        &#39;Accept&#39;: &#39;application/json&#39;,<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        &#39;x-api-key&#39;: String(API_KEY),<br>      },<br>    });<br><br>    if (!response.ok) {<br>      return res.status(response.status).json({ error: `Upstream error: ${response.statusText}` });<br>    }<br><br>    const data = await response.json();<br>    return res.status(200).json(data);<br>  } catch (error) {<br>    console.error(&#39;Error in API route /api/locations:&#39;, error);<br>    return res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>  }<br>}</pre><p>Update mapAPI, instead directly consuming the backend code we use the pre-defined server-side API call:</p><pre>export const mapApi = {<br>  async getLocations(): Promise&lt;MapLocation[]&gt; {<br>    try {<br>      const response = await fetch(&#39;/api/locations&#39;, {<br>        method: &#39;GET&#39;,<br>        headers: {<br>          &#39;Accept&#39;: &#39;application/json&#39;,<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        credentials: &#39;include&#39;,<br>      });<br><br>      if (!response.ok) {<br>        throw new Error(`HTTP error! status: ${response.status}`);<br>      }<br><br>      return await response.json();<br>    } catch (error) {<br>      console.error(&#39;Error fetching locations:&#39;, error);<br>      throw error;<br>    }<br>  },<br>};</pre><h4>Summary of improvements:</h4><ul><li><strong>API key</strong> stays on the server.</li><li>Frontend only talks to Next.js → Next.js talks securely to the real backend.</li><li>Works both in dev &amp; production (if env variables are set properly).</li><li>Minimal change to the frontend logic.</li></ul><h4>Tradeoffs to be Considered</h4><p>Using a Next.js API route to handle sensitive API keys provides a strong security benefit by keeping secrets on the server side, ensuring they are never exposed to the client or browser — which is critical to prevent interception through tools like BurpSuite or browser dev tools. However, this approach comes with important deployment tradeoffs depending on the hosting environment. On platforms like Vercel or Netlify, these API routes run as serverless functions, meaning each request spins up a fresh instance that processes the API call and then shuts down, leading to cold starts, limited execution time, and request quotas — all of which can become bottlenecks or cost drivers under heavy traffic, especially on free plans.</p><p>In contrast, traditional backend frameworks like Django or Spring, deployed on dedicated servers or VPS, maintain persistent long-running processes and can handle backend logic more efficiently for high-throughput or stateful tasks without per-request cold start penalties. Therefore, while the serverless API route approach increases security for API keys, it also introduces scalability and cost tradeoffs, making it best suited for lightweight or moderate-use cases rather than heavy backend processing or high-frequency API mediation.</p><h4>Why is the discovery still important?</h4><p>This discovery highlights a broader concern in security: the mismanagement of secrets on the client side. API keys should be treated as highly sensitive credentials. They should be stored securely on the backend and never be exposed in the frontend code or transmitted in headers unless absolutely necessary and with proper protection in place. Using static keys that never expire makes the situation even riskier. Instead, applications should implement short-lived tokens such as JWTs with expiration and limit their scope and usage. Additionally, practices like IP whitelisting, rate limiting, and regular key rotation can significantly reduce the risk of key leakage.</p><p>In conclusion, Burp Suite proved to be more than just a tool for injection testing — it served as a critical lens through which we could identify insecure practices that might otherwise go unnoticed. This reinforces an essential truth in cybersecurity: perfect security doesn’t exist, but by being proactive and detail-oriented, we can continually move closer to a system that is resilient and well-defended.</p><h3>Conclusion</h3><p>A programmer is always demanded to implement secure programming because, in today’s interconnected and data-driven world, even small vulnerabilities can lead to massive breaches, financial losses, reputational damage, and exploitation by malicious actors. Writing secure code is not just about following best practices — it’s about taking responsibility for protecting users, systems, and data against constantly evolving threats. By proactively embedding security into every stage of development, programmers help ensure the reliability, trustworthiness, and long-term sustainability of the software they build, ultimately upholding both ethical and professional standards in an increasingly hostile digital landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66a18dc25af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Development Team Work With Tools]]></title>
            <link>https://medium.com/@kenbalya27/software-development-team-work-with-tools-6c6d5b805598?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6d5b805598</guid>
            <category><![CDATA[software-development-firm]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 05:21:09 GMT</pubDate>
            <atom:updated>2025-05-08T06:52:03.354Z</atom:updated>
            <content:encoded><![CDATA[<p>In a software development process, the usage of tools such as scrum boards, git branching, and others are necessary to enhance the efficiency of the development process. In this blog, I would like to tell my experience in integrating some tools to enhance the work of my team.</p><ol><li>Scrum Board</li></ol><p>Scrum Board is the soul of our project in scrum project management scenario. A Scrum Board is a visual tool used in Agile project management to track the progress of tasks in a Sprint, typically divided into columns like “To Do,” “In Progress,” and “Done.” It helps teams manage workflows, improve transparency, and ensure efficient collaboration. In my case, we used notion as our Scrum Board tools due to it’s simplicity, user-friendly interface, and also free!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RH9iIvCEK2_VRUbmuuMSIQ.png" /></figure><p>Above is the example of notion’s Scrum Board, we can easily breakdown backlogs into several small tasks and assign them. Besides that, the amount of breakdowns can be determined by the amount of story points and can be tracked progressively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdaPdzDJPV_rLr5REVzi5g.png" /></figure><p>This transparency by visually displaying the progress of tasks, making it easy for the team to track work status. It also ensures efficiency by facilitating collaboration, identifying bottlenecks, and helping teams stay aligned with Sprint goals.</p><p>2. Git Branching</p><p>Git branching allows developers to create separate lines of development, enabling them to work on features, bug fixes, or experiments without affecting the main codebase. It helps in parallel development, code isolation, and smooth integration of changes through merges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXllIiNLUDkM0lQQYIAIQg.png" /></figure><p>In our scenario, we used branching as stated by the picture above. We divide the branches per backlog, and divided it further per accumulated task per person.</p><p>Git branching ensures code stability by isolating new features or bug fixes from the main codebase until they are fully tested and ready for integration. It also ensures efficient collaboration by allowing multiple developers to work on different tasks simultaneously without conflicts.</p><p>3. Commit Message</p><p>A commit message describes the changes made in a specific commit, helping developers understand the purpose and context of the update. It ensures better collaboration, traceability, and easier debugging by providing clear documentation of code history.</p><p>Commit messages are crucial in a Test-Driven Development scenario like ours. Hence delivering useful messages in each commits that describes the changes that were made is a must.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*iUUwm56vqdv1uGRO-Gf9MA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3nWIZu5ng-kbyeMaS01oA.png" /></figure><p>Above are my recent commit messages. This ensure clarity by documenting the purpose of code changes, making it easier for developers to understand past modifications. They also ensure better collaboration and maintainability by providing a clear history of updates, aiding in debugging and project tracking.</p><p>4. Merge Request</p><p>A merge request (MR) is used to propose and review code changes before integrating them into the main branch. It allows team members to collaborate, provide feedback, and ensure code quality through discussions and reviews. Merge requests help maintain code integrity by preventing untested or incomplete changes from being merged into the main project.</p><p>In our scenario, merge request is also used to explain the key details of changes prior. We are also obliged to ensure other developers to be able to test our newly program so that the merged quality is as expected. In my case, I did it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*iYFyxOsTw4BFfFYWGPhiXg.png" /><figcaption>First Merge Request</figcaption></figure><p>However, I’ve decided to add some security related elements to my branch, in which I have to make another merge request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*dB0Y6MtC2HzswICQNHeY6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*rsyzMFnS8SAxFCrB7nrp0A.png" /></figure><p>Besides that, I usually gave several feedbacks on my team mates merge request as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*kMcD8zX4nQ_tjmqDuWNopQ.png" /></figure><p>Hence, a merge request ensures that code changes are reviewed, tested, and meet project standards before being merged into the main branch. Merge request comments ensure effective collaboration by allowing team members to provide feedback, suggest improvements, and discuss potential issues. Together, they ensure code quality, maintainability, and prevent errors from being introduced into the project.</p><p>5. Git Integration With Discord</p><p>Integrating Git with Discord allows teams to receive real-time notifications about commits, merges, and other repository activities directly in a Discord channel. This enhances collaboration by keeping team members informed about code changes, improving transparency and workflow efficiency as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*wNMR5NXljiiw9g0lnXqEoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*1kWoWlu1r7VPok5QCknA5Q.png" /></figure><p>Integrating Git with Discord ensures better team communication by providing instant updates on repository activities, reducing the chances of missed changes. It also ensures workflow efficiency by keeping developers aligned and enabling faster collaboration on code reviews and issue resolution.</p><p>6. Tools Usage Evaluation up to Sprint 3</p><p>After using these tools for 3 sprints, there are extraordinary results that we felt by using these tools. With notion scrum board, we can distribute our tasks evenly and track the task based on difficulty, status, etc. Here is an example of todo-list and their status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_L7GVPgVybsho7hfTFpdQ.png" /></figure><p>Besides, we can also sort the task based on the dependency, where tasks with lower dependency are done first. This is due to task with higher dependency implies having to consume some of the lower dependency task results. For instance, we have a task to implement login feature. We break it down into login backend API and frontend login user interface. The backend part will have lower dependency, meaning it must be done before starting the frontend part. This ensures logical consistency, because we haven’t implemented this system on our first sprint, hence we experienced some logical conflicts.</p><p>Besides notion, github pull request also helped a lot in our development process. Each member will have to write a comprehensive PR so that other members will understand it’s usage and intuition, especially for those who took tasks that are dependent with that PR. Here is an example: <a href="https://github.com/PPL-BRIN/pantautular-be/pull/62">https://github.com/PPL-BRIN/pantautular-be/pull/62</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*6qOXVjMuhy1MIxi7aAIczA.png" /><figcaption>PR Example</figcaption></figure><p>Other team members can comment on our PR suggesting fixes, performance optimization, etc. As follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Hbl0Y0JdtMlCoFJ1qaE-Fw.png" /></figure><p>As developers, we have our strength and weaknesses, Therefore we need each other’s strength to complement the weaknesses. This is the most crucial role of github PR.</p><p>What’s the result? After 3 sprints these happened:</p><ol><li>Sprint 1: Only used built in tools like scrum board, etc. Not customizations (like task dependency and others), only 37 story points were finished.</li><li>Sprint 2: Tasks customization like dependency, defining task’s acceptance criteria directly on the scrum board, writing wikis for knowledge sharing, etc. 78 story points are done!</li><li>Sprint 3: A more mature approach in using sprint 2’s system, better understanding and more adaptable to the system, we managed to finish 80 story points. Not only that, all of those including deployments and fixes were done a few days before the sprint review! Where on the previous sprints we only deployed our updates within the same day as sprint review or only a day before.</li></ol><p>7. Conclusion</p><p>Integrating the tools mentioned above as software development tools enhances collaboration, transparency, and efficiency in project management. Git manages version control, ensuring structured code development and seamless collaboration among developers. The Scrum Board provides a visual workflow, helping teams track progress, prioritize tasks, and maintain an Agile development process. Discord facilitates real-time communication, ensuring that updates, discussions, and issue resolutions happen quickly, leading to a more streamlined and productive development cycle. My experience above is just the prove.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6d5b805598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realizing How Important Static Analysis of Program Quality Is]]></title>
            <link>https://medium.com/@kenbalya27/realizing-how-important-static-analysis-of-program-quality-is-a0ef8aaf4707?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0ef8aaf4707</guid>
            <category><![CDATA[static-code-analysis]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 04:44:11 GMT</pubDate>
            <atom:updated>2025-05-20T04:22:40.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Static analysis is the process of examining code without executing it to detect potential errors, security vulnerabilities, and code quality issues. It is important because it helps developers identify bugs early in the development cycle, improving code reliability, maintainability, and security while reducing debugging costs.</p><p>As mentioned earlier, I’m currently working on my software development project on implementing a health application supported by real time map disease case distribution. At the moment, I’m working on creating some backend API services. However, I’ve just realized how poor was my previous projects code quality are that it can cause security trouble.</p><p>When starting a new project in django, people often care about the project’s configuration in which they make sure that the initialized project could be run smoothly. However, there are several key points that needs to have more attention, like managing the projects secrets etc.</p><p>At the initial state of our django application, we will have SECRET_KEY hardcoded in settings.py as follows:</p><pre># SECURITY WARNING: keep the secret key used in production secret!<br>SECRET_KEY = &#39;your_secret_key&#39;</pre><p>However, this may cause a security issue and a static analysis tools like sonarqube may recognize it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*ZnCQrXl-7Dr25eFEdCkPrg.png" /></figure><p>The failed condition was caused by the hardcoded SECRET_KEY. If it wasn’t handled properly, it might haunted our application in the future due to having a huge vulnerability. To handle this issue, we need to store all secrets in the environment variable (.env file if in local) and assign the variables by loading the environment variable. One of the possible way is as follows:</p><pre>from dotenv import load_dotenv<br>import os<br>load_dotenv()<br>SECRET_KEY = os.getenv(&#39;SECRET_KEY&#39;)<br></pre><p>Besides that, static cloud analysis also provides details in which we may enhance the quality of our program, such as detecting unused variables, import, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*32LxZ95yMx_A4ao7eOnRdQ.png" /></figure><p>Even though the quality gate passed, it detected 2 issues. Those 2 issues are detected in the following code lines:</p><pre>  except Exception as e: <br>       return Response({f&quot;An unexpected error occurred. Please try again later.&quot;}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</pre><p>The issue is quite simple, and unused variable e from the Exception, and using f-string in a scenario where we don’t need to since we can always achieve the program goal with normal strings. Hence, it caused a minor issue. But notice that these kind of issues didn’t affect the code quality, why? Because it doesn’t posses any kinds of threat to our application in the future.</p><p>By refactoring the codes that were issued by the static analysis tools, we will get the following respond:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmtX56Ia_AuNibZfRChBLQ.png" /></figure><p>The picture above is the desired quality of a production-ready program.</p><p>From my experience, we can see how much of a poor coder we are when we thought we’ve done good. Hence, we have also learned of how important static analysis are in a real-world scenario.</p><h3>Branch Merging Guard</h3><p>To ensure maintainability and reliability across the entire codebase, it is essential that code quality remains consistent in all branches. Without proper quality checks, poorly written or untested code may be merged, introducing technical debt and potential bugs. Therefore, implementing a merge request guard based on code quality is a critical step in safeguarding long-term project integrity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*fpy2ilUs-Nnsj_ssRWwf7Q.png" /><figcaption>Merging Cannot Automatically Be Done Due To Failing Checks</figcaption></figure><h3>Additional Guard For FE: Pre-Deployment Preview:</h3><p>Pre-deployment preview environments are essential for quality assurance in frontend development because they allow teams to validate UI behavior and design consistency in a production-like setting before going live. These previews help catch visual bugs, responsiveness issues, broken user flows, and integration mismatches that may not be evident during local development or in isolation. By testing features in context with real backend data and deployment configurations, teams can ensure higher confidence, reduce regressions, and accelerate stakeholder feedback cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*fXcf1G4RbG1Oy_QLY3BQQg.png" /></figure><h3>Husky For Pre-Commit Checking:</h3><p>Husky serves as the first guard of our static code analysis, primarily to ensure our Next JS code’s in following the framework’s required coding styles. Here are the details:</p><ul><li><strong>Automated Enforcement</strong><br> Husky hooks into Git events (e.g., pre-commit, pre-push) to automatically run linters and formatters before code is committed or pushed.</li><li><strong>Prevents Low-Quality Code</strong><br> It stops bad code (e.g., lint errors, formatting issues) from entering the codebase by rejecting commits that don’t meet defined standards.</li><li><strong>Reduces Manual Review Overhead</strong><br> Ensures basic quality checks are handled automatically, so code reviewers can focus on logic and architecture instead of style or minor issues.</li><li><strong>Team-Wide Consistency</strong><br> Guarantees consistent coding styles and rules across all contributors, regardless of their local editor or setup.</li><li><strong>Early Feedback Loop</strong><br> Developers receive instant feedback on code quality during commit, reducing time spent on fixing issues post-merge.</li><li><strong>Improves CI/CD Efficiency</strong><br> By catching issues early locally, it reduces the number of failed builds or rejected pull requests in the CI pipeline.</li><li><strong>Customizable Workflows</strong><br> Easily integrates with tools like ESLint, Prettier, TypeScript, and even test suites, adapting to project-specific quality needs.</li><li>ESLint and Prettier are important because they enforce consistent code quality and style, reducing bugs and improving readability across the codebase.</li></ul><h3>LightHouse: Audit Your App Like Google Does</h3><p>Google Lighthouse is crucial for performance optimization and static code analysis because it provides automated audits that identify inefficiencies in page load, accessibility, SEO, and best practices, helping developers improve overall user experience. By analyzing metrics like render-blocking resources, unused JavaScript, and accessibility violations, Lighthouse offers actionable insights to enhance both front-end performance and code quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTTFOVg9myiGnvIY1zuFpw.png" /></figure><p>The Lighthouse audit for the our appshows excellent results: 95 in Performance, 96 in Accessibility, and perfect scores (100) in Best Practices and SEO. Key performance metrics like First Contentful Paint (0.6s), Speed Index (1.2s), and Cumulative Layout Shift (0.001) indicate a fast, stable, and user-friendly experience with minimal room for improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ul3K_36YrBC5AttyVGIPw.png" /><figcaption>Treemap</figcaption></figure><h4>Actionable Insights From The Treemap</h4><ul><li><strong>Reduce Largest Bundle (</strong><strong>175-...js, 218 KiB)</strong>: Split or lazy-load modules to minimize initial load size.</li><li><strong>Optimize Third-Party Scripts</strong>: Defer or remove heavy scripts like logger-1.min.js and amcharts if not essential.</li><li><strong>Tree-shake and Code-split AmCharts</strong>: Import only required chart modules to avoid loading unused internal components.</li><li><strong>Deduplicate Monitoring Scripts</strong>: Ensure New Relic agents aren’t loaded multiple times with slightly different paths.</li><li><strong>Audit and Remove Unused Code</strong>: Use tools like webpack-bundle-analyzer to eliminate dead weight across small chunks.</li></ul><p>By applying those actions and further optimization, our frontend’s performance can be boost further to reach 100 performance score.</p><h3>Conclusion</h3><p>Static code analysis is important because it helps catch problems in the code like errors, bad practices, or messy structure before the app is even run. Tools like <strong>SonarQube</strong> review the code and give it a grade based on its quality. By setting up a rule that only code with a grade of <strong>A</strong> or better can be merged into the main project, teams can make sure that only clean, safe, and efficient code goes live. This keeps the app stable, easy to maintain, and secure from hidden bugs.</p><p>When this is combined with tools like <strong>Husky</strong>, which checks for mistakes before developers even save their changes, <strong>Netlify</strong>, which shows a live preview of what the app will look like before launch, and <strong>Lighthouse</strong>, which measures speed, accessibility, and best practices, the team gets a powerful safety net. This system ensures every update is carefully reviewed from different angles code quality, performance, and user experience, so nothing broken or sloppy makes it into the final product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0ef8aaf4707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Test Driven Development To Implement Backend Services: Exhausting But Fun!]]></title>
            <link>https://medium.com/@kenbalya27/implementing-test-driven-development-to-implement-backend-services-exhausting-but-fun-e807ddffdbfc?source=rss-29e0e45b570c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e807ddffdbfc</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-deve-training]]></category>
            <dc:creator><![CDATA[Kenbalya]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 17:00:40 GMT</pubDate>
            <atom:updated>2025-05-14T17:24:27.860Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to fulfill the requirements of my 6th semester Software Development Project course, my team was assign to implement a certain business requirement for The National Research Organization of Indonesia (BRIN) in a form web application that visualized chart and map based data visualization about diseases in Indonesia. One of the challenge is to implement Test Driven Development(TDD) as an essential part of building the application. By that, I would like to share my journey in implementing TDD to fulfill one of the application’s backend service.</p><h3><strong>Part 1: The Setup</strong></h3><p>In this project, my development team uses Django as the backend framework. I assume that Django has been installed and configured at this point. So, we move on in installing the dependencies for TDD. The dependencies are stored in requirements.txt are as follows:</p><pre>djangorestframework==3.14.0<br>coverage==7.6.11</pre><p>To install it, run:</p><pre>pip install -r requirements.txt</pre><p>Django REST Framework will be useful for handling API requests more efficiently, and coverage will be useful in reporting code coverage in each modules.</p><h3>Part 2: Problem Statement</h3><p>One of the feature requested by BRIN is to visualize cases in a map format, in which the backend needs to organize the data in order to fulfill the requirement of the front end page in visualizing the data. Therefore, we will implement a service to organize and send the data to the front end part in the backend. We will divide it into 3 parts:</p><ol><li>Implement Repository Pattern: the place where queries and data organization take place.</li><li>Implement Serializers: Essential for Django Rest Framework to organize response format</li><li>Implement API View: the place where requests and response cycle took place</li></ol><p>In addition, 3 models from the database will play an important role here:</p><pre>class Disease(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    name = models.CharField(max_length=255)<br>    level_of_alertness = models.IntegerField()<br><br>    def get_disease_by_id(disease_id):<br>        return Disease.objects.filter(disease_id=disease_id).first()<br><br>    def get_disease_cases(self):<br>        return self.case_set.all()  # Mengambil semua kasus terkait penyakit ini<br><br>    def __str__(self):<br>        return self.name<br><br><br>class Case(models.Model):<br>    STATUS_CHOICES = [<br>        (&quot;confirmed&quot;, &quot;Confirmed&quot;),<br>        (&quot;recovered&quot;, &quot;Recovered&quot;),<br>        (&quot;deceased&quot;, &quot;Deceased&quot;),<br>    ]<br><br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    gender = models.CharField(max_length=10)<br>    age = models.IntegerField()<br>    city = models.CharField(max_length=255)<br>    status = models.CharField(max_length=20, choices=STATUS_CHOICES)<br>    disease = models.ForeignKey(Disease, on_delete=models.CASCADE)<br><br>    def get_all_cases_locations():<br>        return Location.objects.filter(case__isnull=False)<br><br>    def __str__(self):<br>        return f&quot;Case {self.id} - {self.city}&quot;<br><br><br>class Location(models.Model):<br>    latitude = models.DecimalField(max_digits=8, decimal_places=6)<br>    longitude = models.DecimalField(max_digits=9, decimal_places=6)<br>    name = models.CharField(max_length=255, unique=True)<br>    case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name=&quot;locations&quot;)<br><br>    def get_location_by_name(name):<br>        return Location.objects.filter(name=name).first()<br><br>    def get_all_locations():<br>        return Location.objects.all()<br><br>    def __str__(self):<br>        return self.name</pre><h3>Part 4: CaseRepository Class</h3><p>In doing TDD, we have to define the test cases based on our product’s acceptance criteria. We want ClassRepository to act as a query agent and data organizer. Therefore, we define several test cases to ensure that ClassRepository acts accordingly, which is to return the organized data of all cases’ locations:</p><ol><li>Test Setup</li></ol><pre>class CaseRepositoryTestCase(TestCase):<br>    def setUp(self):<br>        self.disease = Disease.objects.create(name=&quot;COVID-19&quot;, level_of_alertness=5)<br>        self.case = Case.objects.create(<br>            id=uuid.uuid4(),<br>            gender=&quot;Female&quot;,<br>            age=25,<br>            city=&quot;Bandung&quot;,<br>            status=&quot;recovered&quot;,<br>            disease=self.disease<br>        )<br>        self.location = Location.objects.create(<br>            latitude=-6.9175, longitude=107.6191, name=&quot;Bandung&quot;, case=self.case<br>        )<br>        self.repository = CaseRepository()</pre><p>2. Define the positive case scenario:</p><pre>def test_get_all_case_locations(self):<br>        locations = self.repository.get_all_case_locations()<br>        expected = [<br>            {<br>                &quot;id&quot;: str(self.case.id),<br>                &quot;city&quot;: &quot;Bandung&quot;,<br>                &quot;latitude&quot;: f&quot;{float(self.location.latitude):.6f}&quot;, <br>                &quot;longitude&quot;: f&quot;{float(self.location.longitude):.6f}&quot;,<br>            }<br>        ]<br>        self.assertEqual(locations, expected)</pre><p>The code above checks that whether the case that we setup along with it’s location detail could be fetched by our ClassRepository. After this, try to run the test and it will fail. We call this phase Red phase.</p><p>3. Implement CaseRepository to fulfill the test case:</p><pre>def get_all_case_locations(self):<br>    locations = Case.get_all_cases_locations()<br>        return [<br>               {<br>                    &quot;id&quot;: str(location.case.id),<br>                    &quot;city&quot;: location.case.city,<br>                    &quot;latitude&quot;: f&quot;{float(location.latitude):.6f}&quot;,<br>                    &quot;longitude&quot;: f&quot;{float(location.longitude):.6f}&quot;,<br>               }<br>                for location in locations<br>           ]</pre><p>4. Run the test again:</p><pre>python manage.py test</pre><p>If it passed the test, than our goal for this chunk has been achieved! We call this phase “Green Phase”. If it doesn’t, then try to debug your code further!</p><p>5. What if the query returned an empty list? It’s possible right?</p><pre>def test_get_all_case_locations_empty(self):<br>        Location.objects.all().delete() <br><br>        locations = self.repository.get_all_case_locations()<br>        self.assertEqual(locations, [])</pre><p>6. Update CaseRepository’s function:</p><pre>       def get_all_case_locations(self):<br>            locations = Case.get_all_cases_locations()<br>            if not locations.exists():<br>                return []<br>            return [<br>                {<br>                    &quot;id&quot;: str(location.case.id),<br>                    &quot;city&quot;: location.case.city,<br>                    &quot;latitude&quot;: f&quot;{float(location.latitude):.6f}&quot;,<br>                    &quot;longitude&quot;: f&quot;{float(location.longitude):.6f}&quot;,<br>                }<br>                for location in locations<br>            ]</pre><p>7. What if an error occured like object does not exist? We cook it as well of course:</p><pre>@patch(&#39;pt_backend.models.Case.get_all_cases_locations&#39;, side_effect=ObjectDoesNotExist)<br>    def test_get_all_case_locations_exception(self, mock_get_all_cases_locations):<br>        result = self.repository.get_all_case_locations()<br>        self.assertEqual(result, {&quot;error&quot;: &quot;Error retrieving case locations&quot;})</pre><p>8. Handle with exceptions:</p><pre>def get_all_case_locations(self):<br>        try:<br>            locations = Case.get_all_cases_locations()<br>            if not locations.exists():<br>                return []<br>            return [<br>                {<br>                    &quot;id&quot;: str(location.case.id),<br>                    &quot;city&quot;: location.case.city,<br>                    &quot;latitude&quot;: f&quot;{float(location.latitude):.6f}&quot;,<br>                    &quot;longitude&quot;: f&quot;{float(location.longitude):.6f}&quot;,<br>                }<br>                for location in locations<br>            ]<br>        except ObjectDoesNotExist:  <br>            return {&quot;error&quot;: &quot;Error retrieving case locations&quot;}</pre><p>Now we are done in implementing CaseRepository</p><p>Part 5: Do the same scenario for the API View:</p><p>Test:</p><pre>class CaseAPITest(TestCase):<br>    def setUp(self):<br>        self.client = APIClient()<br><br>        self.disease1 = Disease.objects.create(name=&quot;Flu&quot;, level_of_alertness=2)<br>        self.disease2 = Disease.objects.create(name=&quot;COVID-19&quot;, level_of_alertness=5)<br><br>        self.case1 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Male&quot;, age=30, city=&quot;Jakarta&quot;, status=&quot;confirmed&quot;, disease=self.disease1<br>        )<br>        self.case2 = Case.objects.create(<br>            id=uuid.uuid4(), gender=&quot;Female&quot;, age=25, city=&quot;Bandung&quot;, status=&quot;recovered&quot;, disease=self.disease2<br>        )<br><br>        self.location1 = Location.objects.create(latitude=-6.2088, longitude=106.8456, name=&quot;Jakarta&quot;, case=self.case1)<br>        self.location2 = Location.objects.create(latitude=-6.9175, longitude=107.6191, name=&quot;Bandung&quot;, case=self.case2)<br><br>    def test_get_all_case_locations(self):<br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_200_OK)<br>        self.assertEqual(response.json(), [<br>            {&quot;id&quot;: str(self.case1.id), &quot;city&quot;: &quot;Jakarta&quot;, &quot;latitude&quot;: &quot;-6.208800&quot;, &quot;longitude&quot;: &quot;106.845600&quot;},<br>            {&quot;id&quot;: str(self.case2.id), &quot;city&quot;: &quot;Bandung&quot;, &quot;latitude&quot;: &quot;-6.917500&quot;, &quot;longitude&quot;: &quot;107.619100&quot;}<br>        ])<br><br>    def test_get_all_case_locations_empty(self):<br>        Location.objects.all().delete()  <br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_200_OK)<br>        self.assertEqual(response.json(), [])  <br><br>    @patch(&#39;pt_backend.repositories.CaseRepository.get_all_case_locations&#39;, side_effect=Exception(&quot;Database error&quot;))<br>    def test_get_all_case_locations_exception(self, mock_get_all_case_locations):<br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)<br>        self.assertIn(&quot;error&quot;, response.json())<br>    <br>    @patch(&#39;pt_backend.repositories.CaseRepository.get_all_case_locations&#39;, side_effect=ObjectDoesNotExist)<br>    def test_get_all_case_locations_not_found(self, mock_get_all_case_locations):<br>        response = self.client.get(&#39;/cases/locations/&#39;)<br>        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)<br>        self.assertEqual(response.json(), {&quot;error&quot;: &quot;No case locations found&quot;})</pre><p>Code:</p><pre>class AllCaseLocationsView(APIView):<br>    def get(self, request):<br>        repository = CaseRepository()<br>        try:<br>            locations = repository.get_all_case_locations()<br>            return Response(locations, status=status.HTTP_200_OK)<br>        except ObjectDoesNotExist:<br>            return Response({&quot;error&quot;: &quot;No case locations found&quot;}, status=status.HTTP_404_NOT_FOUND)<br>        except Exception as e:<br>            return Response({&quot;error&quot;: str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</pre><p>After all test cases are done, we can run: coverage run manage.py test and then coverage html, it will give us the following report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*AX6yfW6YBfhAeBKawdTulg.png" /></figure><p>Those are the 4 modules that I used in implementing this use case. If the approach was right, code coverage should be 100%.</p><h3>Lets Use It in Other Features</h3><p>Now lets do it for other features that I have done, the method is very similar to the one above, write test that includes positive, negative, and corner cases, and write code that fulfill the expected output.</p><h4>Data Visualization Feature (Backend)</h4><p>One of the functionality we need is visualizing data based on severity, which means we need to implement a class to handle grouping counts based on severity:</p><p>test:</p><pre>class TestSeverityGroupingReport(unittest.TestCase):<br>    def setUp(self):<br>        # Create a dummy CaseFilterService with a filter_cases method.<br>        self.dummy_filter_service = MagicMock(name=&quot;CaseFilterService&quot;)<br>        self.report_service = SeverityGroupingReport()<br><br>    def test_empty_filtered_cases(self):<br>        &quot;&quot;&quot;<br>        When no cases are returned by the filter service,<br>        the report should show 0 total cases and an empty severity count.<br>        &quot;&quot;&quot;<br>        self.dummy_filter_service.filter_cases.return_value = []<br>        report = self.report_service.generate_report()<br>        self.assertEqual(report[&quot;total_cases&quot;], 0)<br>        self.assertEqual(report[&quot;severity_counts&quot;], {})<br><br>    def test_all_same_severity(self):<br>        &quot;&quot;&quot;<br>        When all filtered cases have the same severity,<br>        the report should correctly count the total and group by that severity.<br>        &quot;&quot;&quot;<br>        cases = [<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;},<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;},<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;}<br>        ]<br>        self.dummy_filter_service.filter_cases.return_value = cases<br>        report = self.report_service.generate_report(cases)<br>        self.assertEqual(report[&quot;total_cases&quot;], 3)<br>        self.assertEqual(report[&quot;severity_counts&quot;], {&quot;hospitalisasi&quot;: 3})<br><br>    def test_multiple_severities(self):<br>        &quot;&quot;&quot;<br>        When filtered cases contain multiple severities,<br>        the report should aggregate counts correctly.<br>        Note: Cases with None for severity are ignored.<br>        &quot;&quot;&quot;<br>        cases = [<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;},<br>            {&quot;severity&quot;: &quot;insiden&quot;},<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;},<br>            {&quot;severity&quot;: &quot;mortalitas&quot;},<br>            {&quot;severity&quot;: &quot;insiden&quot;},<br>            {&quot;severity&quot;: &quot;hospitalisasi&quot;},<br>            {&quot;severity&quot;: None}  # This case should be ignored.<br>        ]<br>        self.dummy_filter_service.filter_cases.return_value = cases<br>        report = self.report_service.generate_report(cases)<br>        self.assertEqual(report[&quot;total_cases&quot;], 7)<br>        self.assertEqual(report[&quot;severity_counts&quot;], {<br>            &quot;hospitalisasi&quot;: 3,<br>            &quot;insiden&quot;: 2,<br>            &quot;mortalitas&quot;: 1<br>        })</pre><p>code:</p><pre>class SeverityGroupingReport:<br> <br>    def generate_report(self, filtered_cases = None):<br>        severity_counts = Counter()<br>        total_cases = 0<br>        <br>        if filtered_cases:<br>            for case in filtered_cases:<br>                total_cases += 1<br>                severity = case.get(&quot;severity&quot;)<br>                if severity is not None:<br>                    severity_counts[severity] += 1<br>        <br>        return {<br>            &quot;total_cases&quot;: total_cases,<br>            &quot;severity_counts&quot;: dict(severity_counts)<br>        }</pre><h4>Registration Feature</h4><p>Here, we will make a comprehensive registration service with factory pattern, but for simplicity I will only demonstrate the service layer</p><p>test:</p><pre>from unittest.mock import patch<br>from django.test import TestCase<br>from django.core.exceptions import ValidationError<br>from ...registration.service import RegistrationService, RegistrationError<br>from ...registration import get_factory                   <br>from pt_backend.models import Role, Permission, UserRole   <br><br><br>class RegistrationServiceTests(TestCase):<br>    &quot;&quot;&quot;Covers success &amp; failure scenarios of the service layer.&quot;&quot;&quot;<br><br>    def setUp(self) -&gt; None:<br>        self.factory = get_factory(&quot;TENAGA_AHLI&quot;)<br><br>    def test_register_tenaga_ahli_success(self):<br>        dto = RegistrationService.register_user(<br>            role_name=&quot;TENAGA_AHLI&quot;,<br>            name=&quot;Dr. Rahma&quot;,<br>            email=&quot;rahma@corp.id&quot;,<br>            password=&quot;Sup3rSafe!&quot;,# NOSONAR – test data, not a real secret<br>        )<br><br>        self.assertEqual(dto.user.email, &quot;rahma@corp.id&quot;)<br>        self.assertEqual(dto.role.name, &quot;TENAGA_AHLI&quot;)<br><br>        self.assertTrue(<br>            UserRole.objects.filter(user=dto.user, role=dto.role).exists()<br>        )<br><br>        self.assertSetEqual(<br>            set(dto.role.permissions.values_list(&quot;permission__name&quot;, flat=True)),<br>            {&quot;submit_report&quot;, &quot;view_dashboard&quot;},<br>        )<br><br>    def test_duplicate_email_raises_error(self):<br>        RegistrationService.register_user(<br>            role_name=&quot;TENAGA_AHLI&quot;,<br>            name=&quot;First&quot;,<br>            email=&quot;dup@example.com&quot;,<br>            password=&quot;Sup3rSafe!&quot;, # NOSONAR – test data, not a real secret<br>        )<br><br>        with self.assertRaises(RegistrationError) as ctx:<br>            RegistrationService.register_user(<br>                role_name=&quot;TENAGA_AHLI&quot;,<br>                name=&quot;Second&quot;,<br>                email=&quot;dup@example.com&quot;,        # duplicate<br>                password=&quot;AnotherSafe123!&quot;,# NOSONAR – test data, not a real secret<br>            )<br>        self.assertIn(&quot;already exists&quot;, str(ctx.exception))<br><br>    def test_unknown_role_raises_error(self):<br>        with self.assertRaises(RegistrationError):<br>            RegistrationService.register_user(<br>                role_name=&quot;NON_EXISTENT&quot;,<br>                name=&quot;Ghost&quot;,<br>                email=&quot;ghost@void.id&quot;,<br>                password=&quot;Sup3rSafe!&quot;,# NOSONAR – test data, not a real secret<br>            )<br>    def test_weak_password_raises_error(self):<br>        with patch(<br>            &quot;authentication.registration.service.validate_password&quot;,<br>            side_effect=ValidationError(&quot;Too weak&quot;),<br>        ):<br>            with self.assertRaises(RegistrationError) as ctx:<br>                RegistrationService.register_user(<br>                    role_name=&quot;TENAGA_AHLI&quot;,<br>                    name=&quot;Weakling&quot;,<br>                    email=&quot;weak@corp.id&quot;,<br>                    password=&quot;123&quot;, # NOSONAR – test data, not a real secret<br>                )<br>            self.assertIn(&quot;Too weak&quot;, str(ctx.exception))</pre><p>code:</p><pre>from __future__ import annotations<br>from django.contrib.auth.password_validation import validate_password<br>from django.core.exceptions import ValidationError<br>from django.db import transaction<br>from ..registration import get_factory<br>from .dto import RegisteredUserDTO<br>from pt_backend.models import User  <br><br><br>class RegistrationError(Exception):<br>    &quot;&quot;&quot;Raised when the registration flow cannot complete.&quot;&quot;&quot;<br><br><br>class RegistrationService:<br><br>    @classmethod<br>    @transaction.atomic<br>    def register_user(<br>        cls,<br>        *,<br>        role_name: str,<br>        name: str,<br>        email: str,<br>        password: str,<br>        **extra_user_fields,<br>    ) -&gt; RegisteredUserDTO:<br>        try:<br>            cls._ensure_email_unused(email)<br>            validate_password(password)<br><br>            factory = get_factory(role_name)<br>            dto = factory.register(<br>                name=name,<br>                email=email,<br>                raw_password=password,<br>                **extra_user_fields,<br>            )<br><br>            cls._send_welcome_email(dto)<br><br>            return dto<br><br>        except (ValidationError, Exception) as exc:<br>            raise RegistrationError(str(exc)) from exc<br><br>    @staticmethod<br>    def _ensure_email_unused(email: str) -&gt; None:<br>        if User.objects.filter(email__iexact=email).exists():<br>            raise ValidationError(&quot;A user with this e-mail already exists.&quot;)<br>        <br>    @staticmethod<br>    def _send_welcome_email(dto: RegisteredUserDTO) -&gt; None:<br>        &quot;&quot;&quot;For further development process&quot;&quot;&quot;<br>        pass</pre><h4>Reset Password Service</h4><p>Now we need to create a service layer for reseting password purposes.</p><p>test:</p><pre>class TestPasswordResetService(TestCase):<br>    def setUp(self):<br>        &quot;&quot;&quot;Set up test environment for PasswordResetService&quot;&quot;&quot;<br>        # Create mocks for dependencies<br>        self.user_finder = MagicMock()<br>        self.password_token_service = MagicMock()<br>        self.reset_link_service = MagicMock()<br>        self.email_service = MagicMock()<br>        <br>        # Create a test user<br>        self.user = MagicMock()<br>        self.user.email = &quot;test@example.com&quot;<br>        self.user.pk = 123<br>        <br>        # Create the service with mock dependencies<br>        self.service = PasswordResetService(<br>            user_finder=self.user_finder,<br>            password_token_service=self.password_token_service,<br>            reset_link_service=self.reset_link_service,<br>            email_service=self.email_service<br>        )<br>        <br>        # Set up common mock returns<br>        self.user_finder.find_user_by_email.return_value = self.user<br>        self.password_token_service.generate_password_reset_token.return_value = (&quot;test-uid&quot;, &quot;test-token&quot;)<br>        self.reset_link_service.create_password_reset_link.return_value = &quot;https://example.com/reset/test-uid/test-token&quot;<br>    <br>    def test_initiate_password_reset_successful(self):<br>        &quot;&quot;&quot;Test successful password reset email sending&quot;&quot;&quot;<br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify dependencies were called with correct parameters<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_called_once_with(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        <br>        # Verify email service was called with strategy pattern<br>        self.email_service.send_email.assert_called_once()<br>        call_kwargs = self.email_service.send_email.call_args.kwargs<br>        self.assertEqual(call_kwargs[&quot;recipient_email&quot;], &quot;test@example.com&quot;)<br>        self.assertEqual(call_kwargs[&quot;reset_link&quot;], &quot;https://example.com/reset/test-uid/test-token&quot;)<br>        self.assertIsInstance(call_kwargs[&quot;strategy&quot;], PasswordResetEmailStrategy)<br>        <br>        # Verify success result<br>        self.assertTrue(result)<br>    <br>    def test_initiate_password_reset_nonexistent_email(self):<br>        &quot;&quot;&quot;Test handling non-existent email&quot;&quot;&quot;<br>        # Setup mock to return None for the email<br>        self.user_finder.find_user_by_email.return_value = None<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;nonexistent@example.com&quot;)<br>        <br>        # Verify only user finder was called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;nonexistent@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_not_called()<br>        self.reset_link_service.create_password_reset_link.assert_not_called()<br>        self.email_service.send_email.assert_not_called()<br>        <br>        # Verify true is returned (for security reasons)<br>        self.assertTrue(result)<br>    <br>    def test_initiate_password_reset_link_creation_fails(self):<br>        &quot;&quot;&quot;Test handling when reset link creation fails&quot;&quot;&quot;<br>        # Setup mock to return None for link creation<br>        self.reset_link_service.create_password_reset_link.return_value = None<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify all dependencies except email service were called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_called_once_with(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        self.email_service.send_email.assert_not_called()<br>        <br>        # Verify false is returned<br>        self.assertFalse(result)<br>    <br>    def test_initiate_password_reset_email_service_runtime_error(self):<br>        &quot;&quot;&quot;Test handling when email service throws RuntimeError&quot;&quot;&quot;<br>        # Setup mock to raise RuntimeError<br>        self.email_service.send_email.side_effect = RuntimeError(&quot;Email service failed&quot;)<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify all dependencies were called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_called_once_with(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        self.email_service.send_email.assert_called_once()<br>        <br>        # Verify false is returned<br>        self.assertFalse(result)<br>    <br>    def test_initiate_password_reset_email_service_generic_exception(self):<br>        &quot;&quot;&quot;Test handling when email service throws a generic exception&quot;&quot;&quot;<br>        # Setup mock to raise Exception<br>        self.email_service.send_email.side_effect = Exception(&quot;Unexpected error&quot;)<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify all dependencies were called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_called_once_with(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        self.email_service.send_email.assert_called_once()<br>        <br>        # Verify false is returned<br>        self.assertFalse(result)<br>    <br>    def test_initiate_password_reset_token_generation_exception(self):<br>        &quot;&quot;&quot;Test handling when token generation fails&quot;&quot;&quot;<br>        # Setup mock to raise Exception<br>        self.password_token_service.generate_password_reset_token.side_effect = Exception(&quot;Token generation failed&quot;)<br>        <br>        # Call the service<br>        result = self.service.initiate_password_reset(&quot;test@example.com&quot;)<br>        <br>        # Verify only user finder and token generation were called<br>        self.user_finder.find_user_by_email.assert_called_once_with(&quot;test@example.com&quot;)<br>        self.password_token_service.generate_password_reset_token.assert_called_once_with(self.user)<br>        self.reset_link_service.create_password_reset_link.assert_not_called()<br>        self.email_service.send_email.assert_not_called()<br>        <br>        # Verify false is returned<br>        self.assertFalse(result)<br>    <br>    def test_verify_reset_attempt_successful(self):<br>        &quot;&quot;&quot;Test successful reset attempt verification&quot;&quot;&quot;<br>        # Setup mocks<br>        self.password_token_service.get_user_from_uidb64.return_value = self.user<br>        self.password_token_service.validate_token.return_value = True<br>        <br>        # Call the service<br>        result = self.service.verify_reset_attempt(&quot;test-uid&quot;, &quot;test-token&quot;)<br>        <br>        # Verify dependencies were called with correct parameters<br>        self.password_token_service.get_user_from_uidb64.assert_called_once_with(&quot;test-uid&quot;)<br>        self.password_token_service.validate_token.assert_called_once_with(self.user, &quot;test-token&quot;)<br>        <br>        # Verify user was returned<br>        self.assertEqual(result, self.user)<br>    <br>    def test_verify_reset_attempt_invalid_uid(self):<br>        &quot;&quot;&quot;Test verification with invalid UID&quot;&quot;&quot;<br>        # Setup mock to return None for UID<br>        self.password_token_service.get_user_from_uidb64.return_value = None<br>        <br>        # Call the service<br>        result = self.service.verify_reset_attempt(&quot;invalid-uid&quot;, &quot;test-token&quot;)<br>        <br>        # Verify only get_user_from_uidb64 was called<br>        self.password_token_service.get_user_from_uidb64.assert_called_once_with(&quot;invalid-uid&quot;)<br>        self.password_token_service.validate_token.assert_not_called()<br>        <br>        # Verify None was returned<br>        self.assertIsNone(result)<br>    <br>    def test_verify_reset_attempt_invalid_token(self):<br>        &quot;&quot;&quot;Test verification with invalid token&quot;&quot;&quot;<br>        # Setup mocks<br>        self.password_token_service.get_user_from_uidb64.return_value = self.user<br>        self.password_token_service.validate_token.return_value = False<br>        <br>        # Call the service<br>        result = self.service.verify_reset_attempt(&quot;test-uid&quot;, &quot;invalid-token&quot;)<br>        <br>        # Verify both dependencies were called<br>        self.password_token_service.get_user_from_uidb64.assert_called_once_with(&quot;test-uid&quot;)<br>        self.password_token_service.validate_token.assert_called_once_with(self.user, &quot;invalid-token&quot;)<br>        <br>        # Verify None was returned<br>        self.assertIsNone(result)</pre><p>code:</p><pre>class PasswordResetService:<br>    def __init__(self, user_finder, password_token_service, reset_link_service, email_service=None):<br>        self.user_finder = user_finder<br>        self.password_token_service = password_token_service<br>        self.reset_link_service = reset_link_service<br>        self.email_service = email_service or EmailService()<br>        self.reset_strategy = PasswordResetEmailStrategy()<br>    <br>    def initiate_password_reset(self, email):<br>        &quot;&quot;&quot;<br>        Orchestrates the process of sending a password reset email.<br>        Returns True if the email was successfully dispatched, False otherwise.<br>        &quot;&quot;&quot;<br>        user = self.user_finder.find_user_by_email(email)<br>        if not user:<br>            logger.info(f&quot;Password reset requested for non-existent email: {email}&quot;)<br>            return True<br>        <br>        try:<br>            uid, token = self.password_token_service.generate_password_reset_token(user)<br>            reset_link = self.reset_link_service.create_password_reset_link(uid, token)<br>            if not reset_link:<br>                logger.error(f&quot;Failed to create password reset link for user: {user.email}. Check base URL config.&quot;)<br>                return False<br>            <br>            # Use the email service with strategy pattern<br>            try:<br>                self.email_service.send_email(<br>                    recipient_email=email,<br>                    strategy=self.reset_strategy,<br>                    reset_link=reset_link<br>                )<br>                logger.info(f&quot;Password reset email sent to {email}.&quot;)<br>                return True<br>            except RuntimeError as e:<br>                logger.error(f&quot;Email service failed for {email}: {e}&quot;)<br>                return False<br>            except Exception as e:<br>                logger.error(f&quot;Unexpected error in email service for {email}: {e}&quot;)<br>                return False<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Error generating password reset token for {email}: {e}&quot;)<br>            return False<br><br>    def verify_reset_attempt(self, uidb64, token):<br>        &quot;&quot;&quot;<br>        Verify token and uid from password reset link.<br>        Returns the User object if valid, None otherwise.<br>        &quot;&quot;&quot;<br>        user = self.password_token_service.get_user_from_uidb64(uidb64)<br>        if not user:<br>            logger.warning(f&quot;Invalid UID: {uidb64}&quot;)<br>            return None<br>        <br>        if self.password_token_service.validate_token(user, token):<br>            print(f&quot;Token is valid for user: {user.email}&quot;)<br>            return user<br>        else:<br>            logger.warning(f&quot;Invalid token for user: {user.email if user else &#39;unknown&#39;} or token expired.&quot;)<br>            return None</pre><h4>API Security</h4><p>We have to implement a module which acts as an authentication for API calls that was made to our backend, which includes API Key authentication and JWT authentication.</p><p>test:</p><pre><br><br><br>class APIKeyAuthenticationTests(TestCase):<br><br>    def setUp(self):<br>        self.auth = APIKeyAuthentication()<br><br>    # ─────────────────────────── positive / happy path ────────────────────<br>    @override_settings(SECRET_API_KEYS=[&quot;foo&quot;, &quot;bar&quot;])<br>    def test_valid_key_returns_anonymous_user_and_key(self):<br>        request = factory.get(&quot;/&quot;, HTTP_X_API_KEY=&quot;bar&quot;)<br>        user, key = self.auth.authenticate(request)<br><br>        self.assertIsInstance(user, AnonymousUser)<br>        self.assertEqual(key, &quot;bar&quot;)<br><br>    # ────────────────────────────── negative cases ────────────────────────<br>    @override_settings(SECRET_API_KEYS=[&quot;onlykey&quot;])<br>    def test_missing_header_raises_authentication_failed(self):<br>        request = factory.get(&quot;/&quot;)<br>        with self.assertRaises(AuthenticationFailed) as ctx:<br>            self.auth.authenticate(request)<br>        self.assertEqual(str(ctx.exception), &quot;API key missing.&quot;)<br><br>    @override_settings(SECRET_API_KEYS=[&quot;rightkey&quot;])<br>    def test_invalid_key_raises_authentication_failed(self):<br>        request = factory.get(&quot;/&quot;, HTTP_X_API_KEY=&quot;wrongkey&quot;)<br>        with self.assertRaises(AuthenticationFailed) as ctx:<br>            self.auth.authenticate(request)<br>        self.assertEqual(str(ctx.exception), &quot;Invalid API key.&quot;)<br><br>    # ─────────────────────────── corner / env-var fallback ────────────────<br>    def test_env_variable_key_is_accepted_when_settings_absent(self):<br>        os.environ[&quot;SECRET_API_KEY&quot;] = &quot;envkey&quot;<br>        try:<br>            with override_settings(SECRET_API_KEYS=None):<br>                request = factory.get(&quot;/&quot;, HTTP_X_API_KEY=&quot;envkey&quot;)<br>                _, key = self.auth.authenticate(request)<br>                self.assertEqual(key, &quot;envkey&quot;)<br>        finally:<br>            os.environ.pop(&quot;SECRET_API_KEY&quot;, None)  # clean up<br><br>    # ─────────────────────────── header helper string ─────────────────────<br>    def test_authenticate_header_returns_realm(self):<br>        header = self.auth.authenticate_header(factory.get(&quot;/&quot;))<br>        self.assertEqual(header, &#39;X-API-KEY realm=&quot;api&quot;&#39;)<br><br><br>class CustomJWTAuthenticationTests(TestCase):<br>    <br>    def setUp(self):<br>        self.auth = CustomJWTAuthentication()<br>        <br>        from pt_backend.models import User<br>        self.test_user = User.objects.create(<br>            email=&#39;test@example.com&#39;,<br>            password=&#39;password123&#39;,<br>            name=&#39;Test User&#39;,<br>            role=&#39;user&#39;<br>        )<br><br>    def test_get_user_returns_correct_user(self):<br>        &quot;&quot;&quot;Test that get_user returns the correct user when a valid token is provided&quot;&quot;&quot;<br>        mock_token = {&#39;user_id&#39;: self.test_user.id}<br>        <br>        user = self.auth.get_user(mock_token)<br>        <br>        self.assertEqual(user.id, self.test_user.id)<br>        self.assertEqual(user.email, self.test_user.email)<br>        self.assertEqual(user.name, self.test_user.name)<br><br>    def test_get_user_raises_error_on_missing_user_id(self):<br>        &quot;&quot;&quot;Test that get_user raises InvalidToken when user_id is missing in token&quot;&quot;&quot;<br>        mock_token = {&#39;other_field&#39;: &#39;some_value&#39;}<br>        <br>        from rest_framework_simplejwt.exceptions import InvalidToken<br>        with self.assertRaises(InvalidToken) as ctx:<br>            self.auth.get_user(mock_token)<br>        <br>        self.assertEqual(<br>            ctx.exception.detail[&#39;detail&#39;], <br>            &#39;Token contained no recognizable user identification&#39;<br>        )<br><br>    def test_get_user_raises_error_on_nonexistent_user(self):<br>        &quot;&quot;&quot;Test that get_user raises AuthenticationFailed when user does not exist&quot;&quot;&quot;<br>        mock_token = {&#39;user_id&#39;: 99999}<br>        <br>        from rest_framework.exceptions import AuthenticationFailed<br>        with self.assertRaises(AuthenticationFailed) as ctx:<br>            self.auth.get_user(mock_token)<br>        <br>        self.assertEqual(str(ctx.exception), &#39;User not found&#39;)<br>        self.assertEqual(ctx.exception.code, &#39;user_not_found&#39;)<br><br>    def test_get_user_handles_database_error(self):<br>        &quot;&quot;&quot;Test that get_user gracefully handles database errors&quot;&quot;&quot;<br>        mock_token = {&#39;user_id&#39;: self.test_user.id}<br>        <br>        from pt_backend.models import User<br>        from unittest.mock import patch<br>        with patch.object(User.objects, &#39;get&#39;, side_effect=Exception(&#39;Database connection error&#39;)):<br>            from rest_framework.exceptions import AuthenticationFailed<br>            with self.assertRaises(AuthenticationFailed) as ctx:<br>                self.auth.get_user(mock_token)<br>            <br>            self.assertEqual(str(ctx.exception), &#39;Error finding user: Database connection error&#39;)<br><br>    def tearDown(self):<br>        self.test_user.delete()</pre><p>code:</p><pre>class APIKeyAuthentication(BaseAuthentication):<br><br>    HEADER_NAME = &quot;X-API-KEY&quot;<br>    def authenticate(self, request):<br>        api_key = request.headers.get(self.HEADER_NAME)<br>        if not api_key:<br>            raise AuthenticationFailed(&quot;API key missing.&quot;)<br><br>        if not self._key_is_valid(api_key):<br>            raise AuthenticationFailed(&quot;Invalid API key.&quot;)<br>        return (AnonymousUser(), api_key)<br><br>    def authenticate_header(self, request):<br>        return f&#39;{self.HEADER_NAME} realm=&quot;api&quot;&#39;<br><br>    def _get_expected_keys(self) -&gt; Iterable[str]:<br>        keys = getattr(settings, &quot;SECRET_API_KEYS&quot;, None)<br>        if keys:<br>            return keys<br>        env_key = os.getenv(&quot;SECRET_API_KEY&quot;)<br>        return (env_key,) if env_key else ()<br><br>    def _key_is_valid(self, candidate: str) -&gt; bool:<br>        for expected in self._get_expected_keys():<br>            if expected and hmac.compare_digest(candidate, expected):<br>                return True<br>        return False<br><br>class CustomJWTAuthentication(JWTAuthentication):<br>    def get_user(self, validated_token):<br>        &quot;&quot;&quot;<br>        Attempt to find and return a user using the given validated token.<br>        &quot;&quot;&quot;<br>        try:<br>            user_id = validated_token[&#39;user_id&#39;]<br>        except KeyError:<br>            raise InvalidToken(&#39;Token contained no recognizable user identification&#39;)<br><br>        try:<br>            user = User.objects.get(id=user_id)<br>            return user<br>        except User.DoesNotExist:<br>            exception = AuthenticationFailed(&#39;User not found&#39;)<br>            exception.code = &#39;user_not_found&#39;<br>            raise exception<br>        except Exception as e:<br>            raise AuthenticationFailed(f&#39;Error finding user: {str(e)}&#39;)</pre><h4>Final Code Coverage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*ByJZio_rqctZEBRKDSD-SQ.png" /></figure><h4>Total Code Coverage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*bkYBXHU6Qf-WLXvCndZe7Q.png" /></figure><h3>CodeCov For Coverage Monitoring</h3><p>Codecov is a powerful tool that integrates seamlessly with CI/CD pipelines to measure and visualize code coverage, helping enforce Test-Driven Development (TDD) practices. By automatically analyzing how much of the source code is exercised by tests after every commit or pull request, Codecov provides clear insights into which parts of the codebase lack sufficient testing. This immediate feedback loop allows developers to maintain high test coverage, identify untested logic early, and ensure that new features or changes are backed by robust tests. Ultimately, it strengthens code reliability, reduces bugs in production, and reinforces the core principles of TDD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*SuU3huLz97fF8V7-Yj_mJg.png" /><figcaption>CodeCov in our project</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e807ddffdbfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>