<?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 Haddad on Medium]]></title>
        <description><![CDATA[Stories by Haddad on Medium]]></description>
        <link>https://medium.com/@haddad-tech?source=rss-61025f2e133------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ytDySVk8_SwncCrRWlLUDg.jpeg</url>
            <title>Stories by Haddad on Medium</title>
            <link>https://medium.com/@haddad-tech?source=rss-61025f2e133------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:05:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haddad-tech/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[Software Testing Literature: Guiding Principles for Mocking in Modern React Applications]]></title>
            <link>https://haddad-tech.medium.com/software-testing-literature-guiding-principles-for-mocking-in-modern-react-applications-a9b55666a5aa?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b55666a5aa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 12:33:46 GMT</pubDate>
            <atom:updated>2023-06-01T12:33:46.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Software testing is an essential process in the software development lifecycle. It guarantees the functional correctness and reliability of software, enhancing the overall quality and user satisfaction. This article will provide insights into software testing literature, focusing on a critical concept in the testing ecosystem, “Mocking,” using a practical example.</p><h3>Understanding Mocking</h3><p>Mocking is a testing technique where we replace real objects with fake objects that mimic the behavior of the real ones. This technique is widely used when the real objects are impractical or impossible to incorporate into the unit test.</p><p>Mocking becomes essential when we have external dependencies, like API calls, database connections, or even system-specific behavior that might not be available in the testing environment.</p><h3>Best Practices for Mocking</h3><p>When using mocking in tests, it’s essential to follow best practices to ensure that your tests are effective and manageable. Here are a few key points to consider:</p><ol><li>Isolate Units: When writing unit tests, make sure to mock all dependencies to ensure you’re only testing a single unit of code.</li><li>Avoid Excessive Mocking: While it’s essential to mock dependencies to isolate the code you’re testing, over-mocking can lead to tests that are too tied to the implementation, making them brittle and less effective. It can also mask issues that could occur in the interaction between components.</li><li>Mock with Realism: When you’re creating mock responses, they should be as close as possible to the real data your application will handle. This means considering edge cases and potential error states. This helps ensure your tests are reliable and relevant.</li><li>Clean Up: After each test, reset your mocks to ensure that the state from one test doesn’t leak into another. In your example, you’ve done this with the mockNavigate.mockReset(); and server.resetHandlers(); calls in the afterEach block.</li></ol><h3>Mocking in Action</h3><p>Let’s understand this using an example of a testing script for a React application. This is the working code that we’re going to breakdown</p><p><em>FormInput.jsx</em></p><p>This is the test file for the FormInput.jsx:<br><em>FormInput.test.jsx</em></p><pre>import { render, fireEvent, waitFor, screen } from &#39;@testing-library/react&#39;;<br>import { BrowserRouter as MockRouter } from &#39;react-router-dom&#39;;<br>import { rest } from &#39;msw&#39;;<br>import { setupServer } from &#39;msw/node&#39;;<br>import { useNavigate } from &#39;react-router-dom&#39;;<br><br>import FormInput from &#39;../Components/FormInput&#39;;<br><br>// Mock the API endpoint<br>const server = setupServer(<br>  rest.put(&#39;http://localhost:8000/api/vessel-systems/4f52682e-f0d0-4d75-aa36-a17417dd68c9&#39;, (req, res, ctx) =&gt; {<br>    return res(ctx.json({ success: true }));<br>  })<br>);<br><br>// Mock navigate function<br>const mockNavigate = jest.fn();<br><br>jest.mock(&#39;react-router-dom&#39;, () =&gt; ({<br>    ...jest.requireActual(&#39;react-router-dom&#39;),<br>    useNavigate: () =&gt; mockNavigate,<br>}));<br><br>beforeAll(() =&gt; server.listen());<br>afterEach(() =&gt; {<br>  server.resetHandlers();<br>  mockNavigate.mockReset();<br>});<br>afterAll(() =&gt; server.close());<br><br>test(&#39;renders FormInput without crashing&#39;, () =&gt; {<br>  render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>});<br><br>test(&#39;handles input changes&#39;, () =&gt; {<br>  render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>  <br>  const plannedRunningHourInput = screen.getByLabelText(&#39;Planned Running Hour (Hour) *&#39;);<br>  fireEvent.change(plannedRunningHourInput, { target: { value: &#39;500&#39; } });<br>  expect(plannedRunningHourInput.value).toBe(&#39;500&#39;);<br>  <br>  const mainEngineHourInput = screen.getByLabelText(&#39;Main Engine (Hour) *&#39;);<br>  fireEvent.change(mainEngineHourInput, { target: { value: &#39;300&#39; } });<br>  expect(mainEngineHourInput.value).toBe(&#39;300&#39;);<br><br>  const gearboxHourInput = screen.getByLabelText(&#39;Gearbox (Hour) *&#39;);<br>  fireEvent.change(gearboxHourInput, { target: { value: &#39;200&#39; } });<br>  expect(gearboxHourInput.value).toBe(&#39;200&#39;);<br><br>  const auxiliaryEngineHourInput = screen.getByLabelText(&#39;Auxiliary Engine (Hour) *&#39;);<br>  fireEvent.change(auxiliaryEngineHourInput, { target: { value: &#39;100&#39; } });<br>  expect(auxiliaryEngineHourInput.value).toBe(&#39;100&#39;);<br><br>  const shaftGeneratorHourInput = screen.getByLabelText(&#39;Shaft Generator (Hour) *&#39;);<br>  fireEvent.change(shaftGeneratorHourInput, { target: { value: &#39;100&#39; } });<br>  expect(shaftGeneratorHourInput.value).toBe(&#39;100&#39;);<br>});<br><br>test(&#39;submits form and shows notification&#39;, async () =&gt; {<br>  render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>  <br>  const plannedRunningHourInput = screen.getByLabelText(&#39;Planned Running Hour (Hour) *&#39;);<br>  fireEvent.change(plannedRunningHourInput, { target: { value: &#39;500&#39; } });<br><br>  const mainEngineHourInput = screen.getByLabelText(&#39;Main Engine (Hour) *&#39;);<br>  fireEvent.change(mainEngineHourInput, { target: { value: &#39;300&#39; } });<br><br>  const gearboxHourInput = screen.getByLabelText(&#39;Gearbox (Hour) *&#39;);<br>  fireEvent.change(gearboxHourInput, { target: { value: &#39;200&#39; } });<br><br>  const auxiliaryEngineHourInput = screen.getByLabelText(&#39;Auxiliary Engine (Hour) *&#39;);<br>  fireEvent.change(auxiliaryEngineHourInput, { target: { value: &#39;100&#39; } });<br><br>  const shaftGeneratorHourInput = screen.getByLabelText(&#39;Shaft Generator (Hour) *&#39;);<br>  fireEvent.change(shaftGeneratorHourInput, { target: { value: &#39;100&#39; } });<br><br>  const submitButton = screen.getByRole(&#39;button&#39;, { name: /Generate Forecast Maintenance/i });<br>  fireEvent.click(submitButton);<br><br><br>  // Here you could also check whether the correct path is shown in the URL<br>  // but this would require further mocking of the react-router-dom useHistory hook.<br>});<br><br><br>test(&#39;handles server error response&#39;, async () =&gt; {<br>  server.use(<br>    rest.put(&#39;http://localhost:8000/api/vessel-systems/4f52682e-f0d0-4d75-aa36-a17417dd68c9&#39;, (req, res, ctx) =&gt; {<br>      return res(ctx.status(500));<br>    })<br>  );<br><br>  render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>  <br>  // fill in form inputs...<br>  const plannedRunningHourInput = screen.getByLabelText(&#39;Planned Running Hour (Hour) *&#39;);<br>  fireEvent.change(plannedRunningHourInput, { target: { value: &#39;500&#39; } });<br><br>  const mainEngineHourInput = screen.getByLabelText(&#39;Main Engine (Hour) *&#39;);<br>  fireEvent.change(mainEngineHourInput, { target: { value: &#39;300&#39; } });<br><br>  const gearboxHourInput = screen.getByLabelText(&#39;Gearbox (Hour) *&#39;);<br>  fireEvent.change(gearboxHourInput, { target: { value: &#39;200&#39; } });<br><br>  const auxiliaryEngineHourInput = screen.getByLabelText(&#39;Auxiliary Engine (Hour) *&#39;);<br>  fireEvent.change(auxiliaryEngineHourInput, { target: { value: &#39;100&#39; } });<br><br>  const shaftGeneratorHourInput = screen.getByLabelText(&#39;Shaft Generator (Hour) *&#39;);<br>  fireEvent.change(shaftGeneratorHourInput, { target: { value: &#39;100&#39; } });<br>  const submitButton = screen.getByRole(&#39;button&#39;, { name: /Generate Forecast Maintenance/i });<br>  fireEvent.click(submitButton);<br><br>  await screen.findByText(&#39;Update failed. Please try again.&#39;);<br>});<br><br>test(&#39;handles fetch error&#39;, async () =&gt; {<br>  server.use(<br>    rest.put(&#39;http://localhost:8000/api/vessel-systems/4f52682e-f0d0-4d75-aa36-a17417dd68c9&#39;, (req, res, ctx) =&gt; {<br>      throw new Error(&#39;Mock fetch error&#39;);<br>    })<br>  );<br><br>  render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>  <br>  // fill in form inputs...<br>  const plannedRunningHourInput = screen.getByLabelText(&#39;Planned Running Hour (Hour) *&#39;);<br>  fireEvent.change(plannedRunningHourInput, { target: { value: &#39;500&#39; } });<br><br>  const mainEngineHourInput = screen.getByLabelText(&#39;Main Engine (Hour) *&#39;);<br>  fireEvent.change(mainEngineHourInput, { target: { value: &#39;300&#39; } });<br><br>  const gearboxHourInput = screen.getByLabelText(&#39;Gearbox (Hour) *&#39;);<br>  fireEvent.change(gearboxHourInput, { target: { value: &#39;200&#39; } });<br><br>  const auxiliaryEngineHourInput = screen.getByLabelText(&#39;Auxiliary Engine (Hour) *&#39;);<br>  fireEvent.change(auxiliaryEngineHourInput, { target: { value: &#39;100&#39; } });<br><br>  const shaftGeneratorHourInput = screen.getByLabelText(&#39;Shaft Generator (Hour) *&#39;);<br>  fireEvent.change(shaftGeneratorHourInput, { target: { value: &#39;100&#39; } });<br>  const submitButton = screen.getByRole(&#39;button&#39;, { name: /Generate Forecast Maintenance/i });<br>  fireEvent.click(submitButton);<br><br>  await screen.findByText(&#39;Update failed. Please try again.&#39;);<br><br>});<br><br><br>test(&#39;submits form and navigates&#39;, async () =&gt; {<br>    render(&lt;MockRouter&gt;&lt;FormInput /&gt;&lt;/MockRouter&gt;);<br>        <br>    const submitButton = screen.getByRole(&#39;button&#39;, { name: /Generate Forecast Maintenance/i });<br>    fireEvent.click(submitButton);<br>  <br>    // Wait for navigation<br>    await waitFor(() =&gt; expect(mockNavigate).not.toHaveBeenCalledWith(&#39;/dashboard&#39;));<br>  });</pre><p>The application allows input of vessel parameters, performs some calculation based on the input, and updates the same in a database through an API call.</p><p>In the test script, we are using the ‘msw’ (Mock Service Worker) library to intercept and mock the network requests. The ‘msw’ library provides an easy-to-use setup for creating a mock server that intercepts the network requests the application makes and returns controlled responses.</p><pre>const server = setupServer(<br>  rest.put(&#39;http://localhost:8000/api/vessel-systems/4f52682e-f0d0-4d75-aa36-a17417dd68c9&#39;, (req, res, ctx) =&gt; {<br>    return res(ctx.json({ success: true }));<br>  })<br>);</pre><p>Here we are mocking a ‘PUT’ request to a specific API endpoint and returning a controlled response — a JSON object with a key ‘success’ set to true.</p><h3>Mocking Navigation</h3><p>Often, we may also need to mock behaviors that are outside the scope of the component that we are testing. A classic example is navigation using the ‘react-router-dom’ library in React.</p><p>In our example, we mock the useNavigate hook from ‘react-router-dom’ using jest.mock, which allows us to intercept and modify the behavior of this hook in our test environment.</p><pre>jest.mock(&#39;react-router-dom&#39;, () =&gt; ({<br>    ...jest.requireActual(&#39;react-router-dom&#39;),<br>    useNavigate: () =&gt; mockNavigate,<br>}));</pre><h3>Error Handling in Mocking</h3><p>Mocking also allows you to test the error handling capabilities of your application. You can mock a server response to return an error, allowing you to check if your application handles it correctly.</p><pre>server.use(<br>    rest.put(&#39;http://localhost:8000/api/vessel-systems/4f52682e-f0d0-4d75-aa36-a17417dd68c9&#39;, (req, res, ctx) =&gt; {<br>      return res(ctx.status(500));<br>    })<br>  );</pre><p>In this mock, we change the server response to return a 500 status code, simulating a server error.</p><h3>Conclusion</h3><p>In the dynamic world of software development, testing strategies must evolve to match the pace and complexity of application development. One such strategy is mocking, a powerful technique that has proven to be a game-changer in creating efficient, comprehensive, and robust test suites.</p><p>Using mocking, we can simulate real-world scenarios, isolate components for precise unit testing, and ensure our applications handle both successful and erroneous outcomes gracefully. Libraries like jest and msw have equipped developers with advanced mocking capabilities, making the process more streamlined and effective.</p><p>However, it’s essential to remember the guiding principles of mocking. These include isolating units, avoiding excessive mocking, striving for realism in mock responses, and cleaning up after each test. Adhering to these best practices allows us to maximize the benefits of mocking and maintain high-quality, reliable tests.</p><p>While mocking does introduce an additional layer of complexity to our tests, the ability to control and predict every aspect of the system during the testing phase is an undeniable advantage. It allows us to build software that is more resilient, more reliable, and better suited to meet user expectations.</p><p>As we continue to innovate and develop more complex applications, effective mocking will remain a cornerstone of successful testing strategies. So, let’s embrace it and remember that “With great mocking power, comes great testing responsibility!” Because, at the end of the day, the quality of our software is determined not just by the functionality it delivers, but also by its reliability, durability, and ability to handle unexpected situations gracefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*F4zInw3pwGRXhYLfaJVCNQ.png" /><figcaption>“With great mocking power, comes great testing responsibility!”</figcaption></figure><p>That is the true power and promise of effective software testing and, in particular, effective mocking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b55666a5aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CI/CD for React Apps Using GitHub Actions, S3, CloudFront, and Route53]]></title>
            <link>https://haddad-tech.medium.com/aws-ci-cd-for-react-apps-using-github-actions-s3-cloudfront-and-route53-3d2bb6e00597?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2bb6e00597</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 12:05:29 GMT</pubDate>
            <atom:updated>2023-06-12T08:18:08.549Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep hands-on understanding on React deployment steps using AWS resources</h4><h3>Introduction</h3><p>The modern web development landscape is changing at a rapid pace, and developers are leveraging numerous technologies to improve their workflow and productivity. One such practice is Continuous Integration and Continuous Deployment (CI/CD). In conjunction with cloud storage solutions and Content Delivery Networks (CDNs), CI/CD practices can significantly enhance the development process.</p><p>In this article, we’ll explore the CI/CD pipeline for a React application, deploying the application on Amazon S3, and delivering it via Amazon CloudFront using GitHub Actions.</p><h3>The Role of GitHub Actions</h3><p>GitHub Actions provides developers with powerful CI/CD capabilities directly within GitHub. It allows automatic execution of software pipelines whenever there’s a trigger like a push or a pull request to specific branches. For a React application, this could mean automatically installing dependencies, running tests, building the application, and deploying it to the desired hosting platform.</p><h3>The Workflow YAML File</h3><p>A GitHub Actions workflow is defined in a YAML file. The file contains the steps required to build, test, and deploy your application. For our React app, the file could look something like this:</p><pre>name: Node CI-CD for build, test, and deploy<br>on:<br>  push:<br>    branches: <br>      - main<br>      - production<br>      - PBI-**<br>      - coldfix<br>  pull_request:<br>    branches: <br>      - production<br>jobs:<br>  install:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Use node 16.x<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: 16.15.1<br>      - run: npm ci<br>build:<br>    needs: install<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        node-version: [ 16.x]<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Use node ${{ matrix.node-version }}<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: ${{ matrix.node-version }}<br>- run: npm install<br>      - run: npm run build<br>  <br>  sonarscan:<br>    needs: build<br>    runs-on: ubuntu-latest<br>    steps:<br>    - uses: actions/checkout@v3<br>      with:<br>        fetch-depth: 0<br>    - name: run test and coverage<br>      run: |<br>        npm install<br>        npm test<br>    - name: SonarQube Scan<br>      uses: sonarsource/sonarqube-scan-action@master<br>      env:<br>        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>        SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}<br>deploy:<br>    needs: build<br>    runs-on: ubuntu-latest<br>    if: github.ref == &#39;refs/heads/main&#39; || github.ref == &#39;refs/heads/production&#39; || github.ref == &#39;refs/heads/coldfix&#39;<br>    steps:<br>    - uses: actions/checkout@v3<br>      with:<br>        python-version: 3.9<br>    - name: Cofig AWS Cred<br>      run: |<br>        pip install awscli<br>        aws configure set region ap-southeast-2<br>        aws configure set output json<br>        aws configure set aws_access_key_id ${{ secrets.AWS_ACCESS_KEY }} <br>        aws configure set aws_secret_access_key ${{ secrets.AWS_SECRET_KEY }}<br>- name: deploy with s3 sync and Invalidate CloudFront cache<br>      run: |<br>        npm install<br>        if [ ${{ github.ref }} = &#39;refs/heads/main&#39; ]<br>        then<br>         export REACT_APP_BACKEND_URL=${{ secrets.REACT_APP_BACKEND_URL_STAGING }}<br>         npm run build<br>         aws s3 sync ./build s3://${{ secrets.S3_BUCKET_NAME_STAGING }}/<br>         aws cloudfront create-invalidation --distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID_STAGING }} --paths &quot;/*&quot;<br>        elif [ ${{ github.ref }} = &#39;refs/heads/production&#39; ]<br>        then<br>           export REACT_APP_BACKEND_URL=${{ secrets.REACT_APP_BACKEND_URL_PRODUCTION }}<br>           npm run build<br>           aws s3 sync ./build s3://${{ secrets.S3_BUCKET_NAME_PROD }}/ <br>           aws cloudfront create-invalidation --distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID_PROD }} --paths &quot;/*&quot;<br>        fi</pre><p>This YAML file defines a workflow that installs the required Node.js version, installs project dependencies, builds the React app, and then deploys the application to Amazon S3. After that, it invalidates the CloudFront cache to ensure that the latest version of the app is served to users.</p><h3>Understanding <em>{Secrets}</em> Environment Variable</h3><p>Secrets are encrypted environment variables that you create in an environment, organization, repository, or repository environment in GitHub. They can be used to manage sensitive data, such as access tokens, passwords, or environment variables, that your project needs to function.</p><p>Secrets are used in GitHub Actions workflows to provide these sensitive details without exposing them in your code or log files. In a YAML file, secrets are accessed via the secrets context. For example, secrets.AWS_ACCESS_KEY would access the secret named AWS_ACCESS_KEY.</p><p>In your CI/CD workflow, secrets are used to store sensitive information needed for deploying your React application to AWS. Specifically:</p><ul><li>AWS_ACCESS_KEY and AWS_SECRET_KEY are your AWS credentials. They are necessary to authenticate with AWS and perform operations, such as syncing your build files to S3 or invalidating a CloudFront cache.</li><li>S3_BUCKET_NAME_STAGING and S3_BUCKET_NAME_PROD are the names of your S3 buckets for the staging and production environments, respectively. These are the destinations for your built React application.</li><li>CLOUDFRONT_DISTRIBUTION_ID_STAGING and CLOUDFRONT_DISTRIBUTION_ID_PROD are the IDs of your CloudFront distributions for the staging and production environments, respectively. They are needed to invalidate the CloudFront cache for the corresponding environment after deployment.</li><li>REACT_APP_BACKEND_URL_STAGING and REACT_APP_BACKEND_URL_PRODUCTION are likely the URLs of your backend API for the staging and production environments, respectively. These are set as environment variables during the build process, and they are probably used by your React application to make API calls.</li></ul><p>It’s essential to use secrets to store this kind of sensitive information. Exposing such details publicly could lead to unauthorized access to your AWS resources, and potential misuse. By using secrets, these details are encrypted and kept safe, and they can only be accessed by authorized GitHub Actions workflows.</p><h3>Staging-Production Separation</h3><p>In our GitHub Actions workflow, the staging and production environments are defined by specific branches in your Git repository: main represents the staging environment, while production represents the production environment. These branches are typically used to manage different versions of your application during the development process.</p><p>When a push is made to the main branch, it&#39;s assumed that this represents a change meant for the staging environment. The staging environment is usually a replica of the production environment, used for testing and verifying changes before they are pushed to production.</p><p>Likewise, when a push is made to the production branch, this triggers a deployment to the production environment. The production environment is where your live application resides. Changes here will be visible to your end-users.</p><h4>In our YAML workflow:</h4><ul><li>When a push is made to the main branch, the environment variable REACT_APP_BACKEND_URL is set to secrets.REACT_APP_BACKEND_URL_STAGING. This probably changes the API endpoint that your React application uses during the build process. The built application is then synced to the staging S3 bucket (secrets.S3_BUCKET_NAME_STAGING), and the CloudFront cache for the staging environment is invalidated.</li><li>If a push is made to the production branch, REACT_APP_BACKEND_URL is set to secrets.REACT_APP_BACKEND_URL_PRODUCTION. The application is built, synced to the production S3 bucket (secrets.S3_BUCKET_NAME_PROD), and the CloudFront cache for the production environment is invalidated.</li></ul><p>This process allows for different versions of your React application to exist simultaneously in different environments, facilitating testing and deployment.</p><h3>AWS IAM Access Key for Simplicity</h3><p>AWS IAM, or Identity and Access Management, is a key service within AWS that allows you to manage access to your AWS services and resources securely. Using IAM, you can create and manage AWS users and groups and use permissions to allow and deny their access to AWS resources.</p><p>When it comes to using AWS in your CI/CD pipeline, like in this GitHub Actions workflow, you’re interacting with various AWS services such as S3 for storage and CloudFront for content delivery. To do this securely, you need a way to authenticate and authorize these interactions. This is where IAM comes in, particularly with the concept of IAM Users and Access Keys. Each IAM user can have access keys associated with it — an access key ID and a secret access key. These are used to perform programmatic calls to AWS, which is exactly what you’re doing in your GitHub Actions workflow. When setting up AWS CLI in the CI/CD pipeline, the aws_access_key_id and aws_secret_access_key are set using these access keys.</p><p>In the context of our GitHub Actions workflow, we’re using secrets (secrets.AWS_ACCESS_KEY and secrets.AWS_SECRET_KEY) to store the IAM user&#39;s access key ID and secret access key. This is excellent because it&#39;s crucial to keep these credentials secure - they should never be hardcoded into your codebase, as they can provide access to your AWS resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cRSPOwhTOjq7wlRIuU9Ww.png" /><figcaption>Create an Access Key on IAM User Section</figcaption></figure><p>When the CI/CD pipeline runs, it retrieves these credentials from the secrets and uses them to set up the AWS CLI configuration. This enables the pipeline to interact securely with your AWS services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyUFX5nF59VREs7RPQcJyA.png" /><figcaption>Updating The Key to the repository secrets and variables so it can be accessed on the YAML</figcaption></figure><h3>Preparing Deployment to Amazon S3 and CloudFront</h3><p>Amazon S3 (Simple Storage Service) is a storage service that allows you to store and retrieve any amount of data at any time from anywhere on the web. It is ideal for hosting static websites or web applications like a React app.</p><p>The built React application is a collection of static files, which are uploaded to an S3 bucket. The bucket is configured to behave as a web host, serving the application’s static files. Create an S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc8VHUsKEA21m9EGivcBxA.png" /><figcaption>Create an S3 Bucket AWS</figcaption></figure><p>Amazon CloudFront is a CDN service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds. After deploying the application to an S3 bucket, a CloudFront distribution is used to deliver the application to end-users. CloudFront ensures that the application loads quickly, no matter where users are located globally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGXwUNL-U9J5q2PXauhIww.png" /><figcaption>Create CloudFront pointing to our S3 Bucket</figcaption></figure><p>When the application is updated, the CloudFront cache needs to be invalidated to ensure that users receive the latest version of the app. Invalidation removes the files from CloudFront edge locations, and the next time a viewer requests the invalidated files, CloudFront returns to the origin (the S3 bucket in this case) to fetch the latest version of the invalidated files.</p><h3>AWS Route53 for cleaning the mess</h3><p>Amazon Route 53 is a scalable and highly available Domain Name System (DNS) web service offered by AWS. It is designed to give developers and businesses an extremely reliable and cost-effective way to route end users to Internet applications by translating human-readable domain names (like <a href="http://www.example.com/">www.example.com</a>) into the numeric IP addresses (like 192.0.2.1) that computers use to connect to each other.</p><p>Here’s a deeper look at its functionalities:</p><p><strong>Domain Registration</strong>: Route 53 lets you register domain names under a variety of top-level domains (like .com, .net, .org) and ensures the domain’s DNS settings are correctly configured.</p><p><strong>DNS Routing</strong>: After a domain is registered, Route 53 helps route traffic to your application or website by translating friendly domain names to numerical IP addresses, facilitating connections between users and your application.</p><p><strong>Health Checking</strong>: It can also perform health checks to monitor the health and performance of your application and its endpoints. If an outage should occur, Route 53 can automatically route traffic to healthy endpoints or to resources in a different location.</p><p><strong>Integration with AWS Services:</strong> Route 53 is integrated with other AWS services such as AWS CloudFront, S3, and EC2, making it easy to route global traffic to your AWS resources.</p><p>In the context of your GitHub Actions workflow for a React application, after your application is built and deployed to an S3 bucket, and the CloudFront distribution cache is invalidated, the final step would be to ensure that your Route 53 records are correctly pointing to your CloudFront distribution.</p><p>Now lets create a hosted zone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joh-HY_M5zAENzEDiOLSvQ.png" /><figcaption>kapal.tech as a hosted zone on AWS rout3 53</figcaption></figure><p>Next step, create an a record A on the hosted zone pointing to our resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoUKKv8YMJd2xq8AWRqFoA.png" /><figcaption>Create a record for staging</figcaption></figure><p>‘<em>Value</em>’ on the right side is the url of our CloudFront CDN that point to the S3 Bucket.</p><p>This way, when a user enters our ‘vessel-staging.kapal.tech’ domain into their web browser, Route 53 correctly routes the request to the CloudFront distribution, which fetches the latest version of your application from the S3 bucket, ensuring that your users always have access to the most recent version of your application.</p><h3>Conclusion</h3><p>This is the final look of the architecture that we’ve built so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFX8JXFHj8Rt29xYRlBjGQ.png" /><figcaption>Infrastructure Design for React using AWS resources</figcaption></figure><p>In conclusion, automating the CI/CD pipeline using GitHub Actions for a React application and deploying it with AWS services, including S3, CloudFront, and Route 53, can greatly enhance the development and deployment process. This workflow not only ensures a consistent and reliable build process but also delivers the application with high availability and performance.</p><p>By segregating staging and production environments through different branches and buckets, we can efficiently manage and test our application before it reaches the end-users. The use of AWS IAM for secure AWS access and environment secrets for secure storage of sensitive information fortify the security of our pipeline.</p><p>This setup not only brings robustness to our React application’s deployment but also frees up developers’ time by reducing manual deployment efforts and focusing more on feature development and enhancements.</p><p>Remember, automating processes is a key aspect of contemporary web development, and tools like GitHub Actions and AWS Services make it more achievable than ever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2bb6e00597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Built an App with Object-Oriented an SOLID principles Using Django]]></title>
            <link>https://haddad-tech.medium.com/built-an-app-with-object-oriented-an-solid-principles-using-django-39ce842d5904?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ce842d5904</guid>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Wed, 24 May 2023 10:00:10 GMT</pubDate>
            <atom:updated>2023-05-24T10:00:10.227Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction:</h4><p>Object-Oriented Programming (OOP) is a programming paradigm that offers numerous advantages in software development. By organizing code into objects with properties and behaviors, OOP promotes modularity, reusability, and maintainability. On the other hands, The SOLID principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — provide valuable guidelines for designing software architectures that are maintainable, extensible, and scalable. Incorporating these principles into your Django projects helps ensure clean code organization, reusability, and flexibility. By embracing SOLID, you establish solid foundations for software development, enabling easier collaboration, efficient maintenance, and future growth. Let’s go into project implementation to understand all the terms</p><h4>Project Design — Vessel Automated Maintenance System</h4><p>The Vessel Automated Maintenance System is an information system for ships designed to determine the budget required for maintenance over a specific period and identify the necessary equipment and maintenance services. This system provides a visualization of the estimated total maintenance budget over a given time range for ship owners. It also assists the chief engineer assigned to a ship in monitoring the ship’s status to quickly detect issues and plan maintenance work for a specific operational period.</p><p>The system utilizes a database to store data related to ships, owners, and chief engineers. More detailed information, such as the usage hours of ship components, can be periodically updated by the assigned chief engineer. The system then performs computations and presents the results related to maintenance work through a web application.</p><p>In summary, the Vessel Automated Maintenance System serves as a comprehensive tool for ship owners and chief engineers. It facilitates budget estimation, helps track the ship’s status, identifies necessary maintenance tasks, and provides relevant information for planning and executing maintenance work. The system enhances efficiency, enables proactive maintenance, and improves decision-making in ship maintenance processes. Let’s create the database design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gglz_2nvMlmTl14kenl1xA.png" /><figcaption>Vessel Database Design</figcaption></figure><p>The provided describes a data logic on vessel maintenance system. We can analyze how these principles can be applied in the context of these databases:</p><h4>Single Responsibility Principle (SRP):</h4><p>Each use case represents a specific functionality or action performed by a primary actor (e.g., Ship Owner, Chief Engineer, Admin). This aligns with the SRP as each use case has a clear responsibility and encapsulates a single action.</p><h4>Open/Closed Principle (OCP):</h4><p>The use cases describe the ability to view maintenance cost overviews, vessel status, search and filter vessels, generate maintenance forecasts, input vessel and component running hours, and modify data in the database. These use cases demonstrate the system’s openness for extension by accommodating various maintenance-related functionalities.</p><h4>Liskov Substitution Principle (LSP):</h4><p>The use cases involve different actors interacting with the system, such as Ship Owners, Chief Engineers, and Admins. The LSP would apply by allowing subclasses or specific actor roles to substitute the base actor role when interacting with the system.</p><h4>Interface Segregation Principle (ISP):</h4><p>The use cases cater to the specific needs of different actors, such as Ship Owners wanting to view cost overviews, Chief Engineers monitoring vessel status, and Admins modifying database data. This aligns with the ISP as the system provides interfaces tailored to the requirements of each actor.</p><h4>Dependency Inversion Principle (DIP):</h4><p>The use cases involve interactions between actors and the system, where dependencies on specific implementations (e.g., database) are abstracted through interfaces. This promotes flexibility, allowing different implementations to be used without affecting the use cases’ functionality.</p><p>Overall, while the provided design on the functional aspects of the vessel maintenance system, we can observe how OO principles and SOLID principles can be applied to ensure proper design, modularity, and extensibility of the system. By adhering to these principles, the system can be built with code that is easier to maintain, test, and evolve over time. Now let’s look implement it on the Django</p><h3>Django Implementation</h3><p>To implement the vessel maintenance system described earlier in Django, you would need to create Django apps to held the models, views, templates, and forms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*lfkuQTNsaMFS3gHhq8XX2A.png" /></figure><p>Certainly! Let’s dive deeper into the OOP aspects of the Django project based on the provided folder structure:</p><h4>Models:</h4><ul><li>The “models.py” file in each app’s directory (e.g., “vessels”, “users”, “work_orders”) contains Django model classes. These model classes define the structure and behavior of the application’s data entities, such as vessels, users, and work orders.</li><li>Each model class represents a table in the database, and its attributes define the fields/columns of that table. The attributes can include fields like CharField, IntegerField, DateTimeField, ForeignKey, etc., representing the data types and relationships between entities.</li><li>The model classes encapsulate the data and provide methods to interact with the database, such as creating, retrieving, updating, and deleting records. They allow for object-oriented manipulation of data and follow the principles of encapsulation and data abstraction.</li></ul><h4>Views:</h4><ul><li>The “views.py” file in each app’s directory contains view functions or classes that handle HTTP requests and define the logic for processing those requests.</li><li>Each view function or class represents a specific endpoint or URL pattern and performs actions based on the request type (GET, POST, etc.). These views interact with models to retrieve data, perform operations, and render appropriate responses, such as returning HTML templates or JSON data.</li><li>View functions or classes can encapsulate reusable behavior, such as authentication, authorization, input validation, and data transformation, following the principles of modularity and reusability in OOP.</li></ul><h4>Serializers:</h4><ul><li>The “serializers.py” file in each app’s directory contains serializer classes. Serializers handle the conversion of complex data, such as model instances, into formats suitable for transmission over the network, such as JSON.</li><li>Serializers define the structure and rules for data validation, transformation, and serialization/deserialization. They provide methods like “serialize,” “validate,” and “create” to convert complex objects into JSON and vice versa.</li><li>By separating the serialization logic into serializer classes, Django promotes the principles of separation of concerns and single responsibility, making it easier to customize the data representation and handle complex data operations.</li></ul><h4>URLs:</h4><ul><li>The “urls.py” file in each app’s directory contains URL patterns and their associated views. It defines the routes and URL patterns for accessing different views in the application.</li><li>URL patterns map URLs to specific view functions or classes, allowing the application to handle requests based on the provided URL. This mapping follows the principles of encapsulation and loose coupling between the URL structure and view logic.</li><li>The URL patterns can use regular expressions or path patterns to capture dynamic segments of the URL, enabling flexible routing and parameter passing.</li></ul><h4>Apps:</h4><ul><li>Each app’s directory includes the “apps.py” file, which defines the configuration and metadata for that app.</li><li>The app configuration includes settings like the app’s name, label, icon, and other metadata. It allows Django to recognize and manage the app independently, facilitating modular development, pluggability, and code organization.</li><li>The app configuration follows the principles of encapsulation and modularity, enabling easy integration of reusable apps within the Django project and separation of concerns between different functional components.</li></ul><h4>Conclusion</h4><p>Overall, the Django project’s folder structure embraces object-oriented programming principles such as encapsulation, modularity, separation of concerns, and reusability. The structure encourages the creation of self-contained components (models, views, serializers) that encapsulate specific functionality, promoting code organization, maintainability, and extensibility.</p><p>By integrating Object-Oriented Programming (OOP) and SOLID principles in your Django project, you can ensure your codebase is not only easy to maintain and extend, but also that it adheres to best practices in software development. Utilizing the power of Django, a powerful Python web framework, combined with a well-structured and principled approach to design, can help you build robust and efficient applications.</p><p>In the context of the Vessel Automated Maintenance System, we’ve seen how these principles can be applied in database design, use case identification, and implementation. Django’s inherent structure and capabilities already align very well with these principles, providing a solid foundation for your project.</p><p>Models encapsulate the data and its behavior, views handle HTTP requests and response logic, serializers manage data validation and transformation, and URL configurations define routing rules and patterns. All these components work together harmoniously, following principles of encapsulation, modularity, and single responsibility, demonstrating the benefits of OOP and SOLID principles in action.</p><p>The SOLID principles guide you to design classes that are robust, easy to change, and easy to understand. Applying these principles in your Django applications enables you to write clean, maintainable code that can be easily extended or modified without causing a ripple effect of changes.</p><p>Remember, although these principles provide a useful guideline, they are not hard and fast rules. Use them wisely, and always consider the specific requirements and constraints of your project. The ultimate goal is to create software that not only works but is also easy to understand, modify, and maintain.</p><p>By continuously learning and practicing these principles, you can improve your software design skills and become a better programmer. The vessel maintenance system built in Django is just one example. There are many more areas where you can apply these principles to improve your software design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ce842d5904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Code Quality: Unleashing the Power of Sonar in React App Continuous Development]]></title>
            <link>https://haddad-tech.medium.com/maximizing-code-quality-unleashing-the-power-of-sonar-in-react-app-continuous-development-cdbdef569ef6?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdbdef569ef6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Wed, 24 May 2023 09:09:04 GMT</pubDate>
            <atom:updated>2023-05-24T09:09:04.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step by Step on using sonar tools for React development using Github Actions CI/CD</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DPWEKy4MGIQlI56995xF9Q.png" /></figure><h3>Introduction</h3><p>In today’s fast-paced software development landscape, maintaining high-quality code is crucial for the success of any project. Adhering to standard best practices ensures code readability, maintainability, and overall software quality. However, identifying and addressing code quality issues manually can be time-consuming and error-prone. This is where tools like SonarCloud come into play, providing automated code analysis and static code reviews to help developers identify and resolve potential issues early on. In this article, we will explore the importance of awareness to standard best practices supported by tools like SonarQube in the context of developing a React app, along with the benefits it brings to your workflow.</p><p>While React is a powerful JavaScript library for building user interfaces, it presents certain challenges when it comes to code quality. Some common issues include complex component hierarchies, JSX code complexity, and potential performance bottlenecks. SonarQube, with its React-specific rules and analysis capabilities, can help address these challenges. It provides insights into optimizing component structures, identifying potential performance bottlenecks, and enforcing best practices specific to React development. By leveraging SonarQube’s React-specific analysis, developers can ensure that their React applications are not only well-structured and maintainable but also performant and efficient.</p><h3>Setting up SonarQube for React</h3><p>SonarQube is a code analysis platform that integrates with your development workflow to provide continuous code quality monitoring. It offers a wide range of static code analysis rules, covering various programming languages, including JavaScript and TypeScript used in React app development. SonarQube analyzes your code for potential bugs, security vulnerabilities, code smells, and adherence to best practices. It helps you catch issues early, reducing the likelihood of introducing bugs into your application. Let’s get into the code !</p><h4>Prepare your SonarCloud</h4><p>create a new project on SonarQube to import your react app and fill all the form until you get to this page where you get a script to analyze the code on your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiVHzxkVNDn0ev68042Yxw.png" /><figcaption>prepare the sonar project</figcaption></figure><h4>Setting up React</h4><p>Now that you have the variable create a sonar-project.properties on the root folder</p><pre># this is sonar-project.properties<br>sonar.projectKey=ppl-vessel-maintenance-web<br>sonar.sources=src<br>sonar.exclusions= **/*.test.jsx,**/*.css, src/reportWebVitals.js, src/index.js<br>sonar.javascript.lcov.reportPaths=coverage/lcov.info</pre><ol><li>sonar.projectKey=ppl-vessel-maintenance-web: Specifies the unique identifier for the SonarQube project. This key is used to differentiate this project from others in SonarQube.</li><li>sonar.sources=src: Informs SonarQube about the source code directory to be analyzed. In this case, the &quot;src&quot; directory contains the JavaScript source files of the project.</li><li>sonar.exclusions=**/*.test.jsx,**/*.css, src/reportWebVitals.js, src/index.js: Specifies the files or patterns that should be excluded from the analysis. The patterns given here indicate that any file with a &quot;.test.jsx&quot; extension, any file with a &quot;.css&quot; extension, &quot;src/reportWebVitals.js&quot;, and &quot;src/index.js&quot; should be excluded from analysis. Excluding test files, CSS files, and specific entry point files like &quot;index.js&quot; and &quot;reportWebVitals.js&quot; from analysis can help reduce noise in the analysis results and focus on the main codebase</li><li>sonar.javascript.lcov.reportPaths=coverage/lcov.info: Specifies the path to the coverage report file generated by a test coverage tool like Istanbul. In this case, the coverage report is located at &quot;coverage/lcov.info&quot;. SonarQube can utilize this coverage report to provide insights into code coverage and identify areas of the code that lack proper testing.</li></ol><p>Next, let’s edit the test script on our package.json so the React will have a coverage folder to be reported on sonarqube:</p><pre>  &quot;scripts&quot;: {<br>    ...<br>    ...<br>    &quot;test&quot;: &quot;react-scripts test --coverage&quot;,<br>    ...<br>    ...<br>  }</pre><p>add the coverage folder to .gitignore so it won’t be pushed to the repo</p><pre># package directories .gitignore<br>..<br>node_modules<br>jspm_packages<br>coverage<br>..<br>..</pre><p>To this point, we have our react app ready, let’s check the test script is work properly before we move on the next configuration. Run npm test on the terminal and see that the project produce a new folder named coverage.we are good to go if it is exist.</p><h4>Configure CI/CD using Github Actions</h4><p>On the earlier sonar configuration, we have the sonar’s variable to run the analysis, lets put it on our github action workflow. First let prepare the variable on the github secret, create two new repository secrets for your host url and the token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHCkTIxXY1t9Sx22VUu3Vw.png" /><figcaption>repository secrets for workflow</figcaption></figure><p>Next, configure the workflow on the react project, create a file called ci_cd.yml on .github/workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*hSWbtOjJvMByFU3z8Gr8AQ.png" /></figure><p>inside the yml file, configure the job:</p><pre>  sonarscan:<br>    needs: build<br>    runs-on: ubuntu-latest<br>    steps:<br>    - uses: actions/checkout@v3<br>      with:<br>        fetch-depth: 0<br>    - name: run test and coverage<br>      run: |<br>        npm install<br>        npm test<br>    - name: SonarQube Scan<br>      uses: sonarsource/sonarqube-scan-action@master<br>      env:<br>        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>        SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}</pre><p>This code represents a GitHub Actions workflow that includes a SonarQube scan for a project. Let’s go through each section and understand what it does:</p><pre>needs: build<br>runs-on: ubuntu-latest</pre><ul><li>needs: build: Specifies that this workflow depends on another job named &quot;build&quot;. This means that the &quot;build&quot; job must complete successfully before this workflow can start.</li><li>runs-on: ubuntu-latest: Specifies that the workflow will run on a machine with the latest version of the Ubuntu operating system.</li></ul><pre>steps:<br>  - uses: actions/checkout@v3<br>    with:<br>      fetch-depth: 0</pre><ul><li>actions/checkout@v3: This step uses the official GitHub Actions checkout action to fetch the source code of the project onto the runner machine. The @v3 indicates the specific version of the action being used.</li><li>with: fetch-depth: 0: Sets the fetch-depth option to 0, which means it fetches the entire commit history of the repository. This is necessary for SonarQube to analyze the full history of the code.</li></ul><pre>- name: run test and coverage<br>    run: |<br>      npm install<br>      npm test</pre><ul><li>This step installs project dependencies using npm install and runs tests using npm test. It assumes the project is using npm as the package manager. Adjustments may be needed if using a different package manager.</li></ul><pre>- name: SonarQube Scan<br>    uses: sonarsource/sonarqube-scan-action@master<br>    env:<br>      SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>      SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}</pre><ul><li>This step performs the SonarQube scan using the sonarsource/sonarqube-scan-action GitHub Action. The uses key specifies the action and the @master indicates the specific version being used.</li><li>The env section sets the required environment variables for the SonarQube scan. The SONAR_TOKEN and SONAR_HOST_URL are set using GitHub secrets. You need to configure these secrets in the repository settings to securely provide the SonarQube authentication token and host URL.</li></ul><p>Now we have configure all the things, let’s push the code and analyze it!</p><h4>Understanding SonarQube Analysis Report</h4><p>After we push the code to the repository, this is what the workflow should like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*St2gb49tsKHDVwtpsEpqSQ.png" /><figcaption>Sonarscan job on the github actions</figcaption></figure><p>After all the job completed, we can see the report on the sonar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKtboxDnP4y5LVJi8iqrrQ.png" /><figcaption>sonarQube report</figcaption></figure><p>This report from SonarQube provides an overview of the code quality and analysis results for the project. Let’s break down each section of the report:</p><h4>QUALITY GATE STATUS</h4><ul><li>Passed: Indicates that all conditions set in the quality gate have passed. The quality gate defines the criteria for acceptable code quality, including metrics like code bugs, vulnerabilities, code smells, coverage, and more.</li></ul><h4>MEASURES</h4><ul><li>New Code Since April 6, 2023: Specifies the timeframe for which new code metrics are shown. In this case, it shows the metrics for the code written in the past 2 months.</li><li>Overall Code: Total number of code issues found in the project.</li><li>Bugs (Reliability): Number of identified bugs in the code. Bugs represent code that may lead to unexpected behavior or errors.</li><li>Vulnerabilities (Security): Number of security vulnerabilities detected in the code. Vulnerabilities represent potential weaknesses that can be exploited by attackers.</li><li>Security Hotspots (Reviewed): Number of security hotspots identified in the code. Security hotspots are areas of the code that require review and potentially contain security vulnerabilities.</li><li>Debt: Technical debt, measured in minutes, represents the estimated time required to fix all code issues. Lower debt indicates better code quality.</li><li>Code Smells (Maintainability): Code smells are indicators of poor code structure or design that can negatively impact maintainability. This metric represents the number of code smells found in the project.</li><li>Coverage on 134 Lines to cover: Code coverage represents the percentage of code lines covered by automated tests. This metric shows the coverage on a specific number of lines that need to be covered.</li><li>Unit Tests: Percentage of code covered by unit tests. In this case, it shows 0.0%, indicating no unit test coverage.</li><li>Duplications on 468 Lines: This metric represents the number of lines of code that are duplicated within the project.</li><li>Duplicated Blocks: Number of duplicated code blocks found in the project.</li></ul><h4>ACTIVITY</h4><ul><li>Issues: Displays the number of issues found in the project, categorized by bugs, code smells, and vulnerabilities.</li><li>New Code: Graph showing the number of issues introduced in the code over time.</li><li>Activity: Provides a timeline of the project’s activity, including the date and time of quality gate status changes (passed or failed).</li></ul><p>The report shows that the quality gate has passed in some instances and failed in others. It also provides metrics on bugs, vulnerabilities, code smells, coverage, and activity over time. This information helps developers and teams understand the current state of code quality and track progress in improving it over time.</p><h3>Conclusion</h3><p>Conclusion: Implementing SonarQube in your React app development workflow, along with GitHub Actions CI/CD, can significantly enhance code quality and maintainability. By leveraging SonarQube’s powerful code analysis capabilities, you can identify and address bugs, vulnerabilities, code smells, and performance issues early in the development process. This integration helps enforce coding best practices, optimize React-specific code structures, and improve overall code quality.</p><p>The step-by-step process outlined in this article has demonstrated how to set up SonarQube for React development, configure the necessary properties, and integrate it into GitHub Actions CI/CD. By following these steps, you can automate code analysis, run tests, and generate comprehensive reports, allowing you to continuously monitor code quality and make informed decisions for improvements.</p><p>The SonarQube analysis report provides valuable insights into various aspects of code quality, such as bugs, vulnerabilities, code smells, and test coverage. It enables developers to prioritize and address issues effectively, ensuring that the React app is reliable, secure, and maintainable.</p><p>In summary, by leveraging the power of SonarQube in your React app development workflow, you can maximize code quality, improve development efficiency, and deliver high-performing applications. Embracing standard best practices supported by tools like SonarQube empowers developers to build robust and maintainable React applications that meet the highest standards of quality and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdbdef569ef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD: The Counterintuitive Programming Approach That Led to Better Code]]></title>
            <link>https://haddad-tech.medium.com/tdd-the-counterintuitive-programming-approach-that-led-to-better-code-ad44ebc43648?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad44ebc43648</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Tue, 16 May 2023 15:51:31 GMT</pubDate>
            <atom:updated>2023-05-16T15:53:50.538Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hands-on first experience using Test-Driven-Development approach on the project</h4><p>As a software developer constantly on the lookout for methods to refine my coding process, I recently embarked on an intriguing journey with Test-Driven Development (TDD), an approach I initially found counterintuitive. However, as I delved deeper, I discovered its innate genius, and it ultimately transformed not only the quality of my code but also how I approached programming.</p><blockquote>It’s a testament to the saying, “Slow is smooth, and smooth is fast</blockquote><h3>Understanding TDD</h3><p>Test-Driven Development (TDD) is a software development methodology where tests are written before the actual code. This may sound backwards at first, especially for those of us accustomed to writing tests after the code, if at all. TDD follows a simple but powerful cycle: Red-Green-Refactor.</p><ol><li>Red: Write a failing test.</li><li>Green: Write minimal code to make the test pass.</li><li>Refactor: Improve the code while keeping the tests green.</li></ol><p>This methodology ensures each line of code you write is covered by tests, leading to more robust, reliable software.</p><h3><strong>First Experience with TDD</strong></h3><p>My initial experience with TDD came when I was working on a project to develop a restaurant reservation system. The first requirement was to allow users to create a reservation.</p><h4>Red Phase</h4><p>I started by writing a test for this requirement. I was testing the data_seedingapps from my django project, the app that to automate data seeding using custom django-admin command (refer to <a href="https://haddad-tech.medium.com/automatic-data-seeding-using-csv-and-custom-django-admin-command-99b6c3aad819">this article</a> for more detail explanation). It felt strange to write a test for a non-existent function, but I went ahead anyway. Let’s code !</p><pre># file: data_seed/tests.py<br><br>from io import StringIO<br>from django.test import TestCase<br><br>from django.core.management import call_command<br>from django.test import TestCase<br><br>from data_seed.models import DummyShip<br><br>class TestCase(TestCase):<br>    def test_mycommand_POSITIVE(self):<br>        &quot; Test my custom command.&quot;<br><br>        args = [&#39;./importfile.csv&#39;]<br>        opts = {}<br>        out = StringIO()<br>        call_command(&#39;import_data&#39;, *args, **opts, stdout=out)<br>        self.assertIn(&#39;Data imported successfully&#39;, out.getvalue())<br>    <br>    def test_mycommand_NEGATIVE(self):<br>        &quot; Test my custom command.&quot;<br><br>        args = [&#39;./non-exists.csv&#39;]<br>        opts = {}<br>        out = StringIO()<br>        call_command(&#39;import_data&#39;, *args, **opts, stdout=out)<br>        self.assertIn(&#39;Error importing data&#39;, out.getvalue())<br><br>    # test DummyShip model<br>    def test_dummy_ship_model(self):<br>        ship = DummyShip.objects.create(<br>            ship_name=&#39;Test Ship&#39;,<br>            ship_total_vessels=100<br>        )<br>        self.assertEqual(ship.ship_name, &#39;Test Ship&#39;)<br>        self.assertEqual(ship.ship_total_vessels, 100)<br>    <br>    def test_str_method(self):<br>        dummy_ship = DummyShip(ship_name=&#39;Test Ship&#39;, ship_total_vessels=5)<br>        self.assertEqual(str(dummy_ship), &#39;Test Ship&#39;)<br><br>        </pre><p>The provided code imports the necessary modules and functions for creating tests in Django, including TestCase from django.test and call_command from django.core.management. It also imports the DummyShip model from a local module named data_seed.models.</p><p>The script contains a test case class TestCase, which inherits from Django&#39;s TestCase class. Within this class, several methods are defined, each corresponding to a specific test.</p><ol><li>test_mycommand_POSITIVE(): This function tests a custom command import_data that presumably imports data from a file (importfile.csv). Using call_command, the test executes the command and captures its output. The test then checks if the string &#39;Data imported successfully&#39; is in the output, indicating a successful data import.</li><li>test_mycommand_NEGATIVE(): This test is similar to the previous one but uses a non-existent file (non-exists.csv). The expectation here is that the command will fail and return an error message &#39;Error importing data&#39;.</li><li>test_dummy_ship_model(): This function tests the DummyShip model. It creates an instance of DummyShip with a specific ship name and total vessels, and then checks if the created instance&#39;s attributes match the expected values.</li><li>test_str_method(): This test checks the __str__ method of the DummyShip model. It creates an instance of DummyShip and then checks if its string representation is the expected ship name.</li></ol><p>In all these tests, the assertIn and assertEqual methods are used to check if the test conditions are met. If the condition in the assert statement is True, the test passes; otherwise, it fails. As expected, the test failed, marking the ‘Red’ phase of the TDD cycle because we don’t have the implementation yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmYOkkbezpQFRWWclY0SYw.png" /><figcaption>RED phase failed on the CI/CD pipeline</figcaption></figure><h4>Green Phase</h4><p>Next, I wrote just enough code to make the test pass, marking the ‘Green’ phase.</p><pre>from django.core.management.base import BaseCommand<br>from csv import reader<br>from data_seed.models import DummyShip<br>from vessel_systems.models import VesselSystems<br>from vessels.models import Vessel, VesselClass, Rules<br>from users.models import User<br>from work_orders.models import WorkOrder<br>from work_orders_detail.models import WorkOrderDetail<br><br><br><br>class Command(BaseCommand):<br>    help = &quot;Seed data from CSV files&quot;<br><br>    def add_arguments(self, parser):<br>        parser.add_argument(&#39;file_path&#39;, type=str, help=&#39;Path to the CSV file&#39;)<br><br><br>    def handle(self, *args, **kwargs):<br>        file_path = kwargs[&#39;file_path&#39;]<br>        try:<br>            chief_engineer = User.objects.create_user(username=&#39;chief_engineer&#39;, password=&#39;password&#39;, is_chief_engineer=True)<br>            vessel_owner = User.objects.create_user(username=&#39;owner&#39;, password=&#39;password&#39;, is_vessel_owner=True)<br>            system_jayakarta1 = VesselSystems.objects.create()<br>            rule_jayakarta = Rules.objects.create(name=&#39;Rule Jayakarta&#39;)<br>            class_jayakarta = VesselClass.objects.create(name=&#39;Class Jayakarta&#39;, rule=rule_jayakarta)<br>            vessel_obj = Vessel.objects.create(<br>                name=&#39;Jayakarta I&#39;,<br>                vessel_owner=vessel_owner,<br>                vessel_class=class_jayakarta,<br>                chief_engineer=chief_engineer,<br>                vessel_systems=system_jayakarta1,<br>            )<br>            work_order_main_engine = WorkOrder.objects.create(<br>                id = 1,<br>                work_category = &#39;Main Engine&#39;,<br>                total_cost = 450,<br>                vessel_systems = system_jayakarta1,<br>            )<br>            work_order_control = WorkOrder.objects.create(<br>                id = 2,<br>                work_category = &#39;Control&#39;,<br>                total_cost = 60,<br>                vessel_systems = system_jayakarta1,<br>            )<br><br>            with open(file_path, &#39;r&#39;) as csvfile:<br>                csv_reader = reader(csvfile, delimiter=&#39;,&#39;)<br>                next(csv_reader)  # skip header row<br>                work_details= [<br>                    WorkOrderDetail(<br>                        spare_part=&quot;&quot;,<br>                        maintenance_desc=row[0],<br>                        interval_hours=row[1],<br>                        work_days=row[2],<br>                        number=0,<br>                        running_hour_ref=row[3],<br>                        work_orders=work_order_main_engine,<br>                        cost=row[4],<br>                    ) for row in csv_reader<br>                ]<br>                WorkOrderDetail.objects.bulk_create(work_details)<br>                self.stdout.write(self.style.SUCCESS(&#39;Data imported successfully&#39;))<br><br>        except Exception as e:<br>            self.stdout.write(self.style.ERROR(&#39;Error importing data&#39;))<br>            self.stdout.write(self.style.ERROR(str(e)))</pre><p>The provided Python script is a Django management command. It’s designed to read data from a CSV file and seed that data into my database. Here’s a brief explanation of each part of the script:</p><ol><li>Command Class Definition: The script defines a new management command Command that inherits from Django&#39;s BaseCommand. A management command is a command-line utility you can create as part of your Django application.</li><li>add_arguments() method: This method is used to specify the command-line arguments for this command. In this case, it’s expecting one argument: the file path to the CSV file you want to import.</li><li>handle() method: This method contains the main logic of the command. It’s executed when you run the command.</li></ol><ul><li>It begins by extracting the file_path argument.</li><li>Then, it creates a database transaction. This means that all the database changes inside this block will either all succeed, or if there’s an exception, they will all be rolled back. This ensures the consistency of your database.</li><li>It creates several instances of different models, including User, VesselSystems, Rules, VesselClass, Vessel, and WorkOrder.</li><li>It opens the CSV file at the provided file path, reads its content line by line, skipping the first header row.</li><li>For each row, it creates a WorkOrderDetail instance (without saving it to the database yet), with fields populated from the CSV data.</li><li>Once all WorkOrderDetail instances are created, it uses bulk_create to save them all to the database at once, which is more efficient than saving them one by one.</li><li>If everything goes well, it prints a success message. Otheriwise it prints the error message</li></ul><p>The code was not perfect, but it was enough to fulfill the requirement and pass the test. It was a rewarding feeling to see the previously failing test now passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*mw6XXXEvaBTpOS5IdTvg3Q.png" /><figcaption>GREEN phase passed the tests on CI/CD pipeline</figcaption></figure><h4>Refactor Phase</h4><p>Then came the ‘Refactor’ phase. I revisited the code I had written, tidying it up and making improvements. This phase gave me a safety net to clean up the code without fear of breaking anything. As we can see from the last code, our database seeding didn’t have a safety procedure fot the transaction while we are making the bulk insert. This could caused a further error if we have problems in the middle of the transaction meanwhile the inserted data it’s still there. Let’s add the rollback procedure for our database to overcome the problem:</p><pre>from django.core.management.base import BaseCommand<br>from csv import reader<br>from data_seed.models import DummyShip<br>from vessel_systems.models import VesselSystems<br>from vessels.models import Vessel, VesselClass, Rules<br>from users.models import User<br>from work_orders.models import WorkOrder<br>from work_orders_detail.models import WorkOrderDetail<br>from django.db import DatabaseError, transaction<br><br><br><br>class Command(BaseCommand):<br>    help = &quot;Seed data from CSV files&quot;<br><br>    def add_arguments(self, parser):<br>        parser.add_argument(&#39;file_path&#39;, type=str, help=&#39;Path to the CSV file&#39;)<br><br><br>    def handle(self, *args, **kwargs):<br>        file_path = kwargs[&#39;file_path&#39;]<br>        try:<br>            with transaction.atomic(): <br>                chief_engineer = User.objects.create_user(username=&#39;chief_engineer&#39;, password=&#39;password&#39;, is_chief_engineer=True)<br>                vessel_owner = User.objects.create_user(username=&#39;owner&#39;, password=&#39;password&#39;, is_vessel_owner=True)<br>                system_jayakarta1 = VesselSystems.objects.create()<br>                rule_jayakarta = Rules.objects.create(name=&#39;Rule Jayakarta&#39;)<br>                class_jayakarta = VesselClass.objects.create(name=&#39;Class Jayakarta&#39;, rule=rule_jayakarta)<br>                vessel_obj = Vessel.objects.create(<br>                    name=&#39;Jayakarta I&#39;,<br>                    vessel_owner=vessel_owner,<br>                    vessel_class=class_jayakarta,<br>                    chief_engineer=chief_engineer,<br>                    vessel_systems=system_jayakarta1,<br>                )<br>                work_order_main_engine = WorkOrder.objects.create(<br>                    id = 1,<br>                    work_category = &#39;Main Engine&#39;,<br>                    total_cost = 450,<br>                    vessel_systems = system_jayakarta1,<br>                )<br>                work_order_control = WorkOrder.objects.create(<br>                    id = 2,<br>                    work_category = &#39;Control&#39;,<br>                    total_cost = 60,<br>                    vessel_systems = system_jayakarta1,<br>                )<br><br>                with open(file_path, &#39;r&#39;) as csvfile:<br>                    csv_reader = reader(csvfile, delimiter=&#39;,&#39;)<br>                    next(csv_reader)  # skip header row<br>                    work_details= [<br>                        WorkOrderDetail(<br>                            spare_part=&quot;&quot;,<br>                            maintenance_desc=row[0],<br>                            interval_hours=row[1],<br>                            work_days=row[2],<br>                            number=0,<br>                            running_hour_ref=row[3],<br>                            work_orders=work_order_main_engine,<br>                            cost=row[4],<br>                        ) for row in csv_reader<br>                    ]<br>                    WorkOrderDetail.objects.bulk_create(work_details)<br>                    self.stdout.write(self.style.SUCCESS(&#39;Data imported successfully&#39;))<br><br>        except Exception as e:<br>            self.stdout.write(self.style.ERROR(f&#39;Error importing data {e}&#39;))<br>            self.stdout.write(self.style.WARNING(&#39;Database rollbacked successfully!&#39;))<br><br></pre><p>Note that now we have transaction.atomic()that becomes our guard for our failing database transaction. I made sure to rerun the test after each change to ensure it was still passing, and it did!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksSo-66vExT53Nak5B5KiA.png" /><figcaption>The code still passed all the CI/CD pipeline checks on REFACTOR phase</figcaption></figure><p>I found this Red-Green-Refactor cycle to be a paradigm shift. It felt slow at first, writing tests before the actual code, but as I repeated the cycle for each new feature (updating reservations, deleting reservations), I realized I was spending less time debugging and more time building features.</p><h4>The Outcome</h4><p>Using TDD, I noticed a significant improvement in my code quality. Each line of code was tested, making the application robust and largely bug-free. The tests also provided excellent documentation for each function, making it easier to understand what each part of the system was supposed to do.</p><p>Moreover, TDD made me think more about the design and functionality of my code before I even started coding. This helped me break down complex features into smaller, more manageable parts, leading to better code structure and organization.</p><h3>Conclusion</h3><p>My hands-on experience with TDD was transformative. What initially seemed counterintuitive turned out to be a powerful approach that has now become an integral part of my coding process. TDD has not only made me a better programmer but also given me the confidence to tackle more complex projects. It’s a testament to the saying, “Slow is smooth, and smooth is fast,” underscoring the fact that taking time to think through and test our code can lead to better, more reliable software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad44ebc43648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting My Lone-wolf-engineer Soul for The Sake of Collaborative Team Projects]]></title>
            <link>https://haddad-tech.medium.com/converting-my-lone-wolf-engineer-soul-for-the-sake-of-collaborative-team-projects-ec87048d644b?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec87048d644b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Sat, 13 May 2023 13:59:31 GMT</pubDate>
            <atom:updated>2023-05-13T13:59:31.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting My Lone-Wolves-Engineer Soul for The Sake of Collaborative Team Projects</h3><h4>My journey on how embracing efficiency tools from github for collaborative team projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1HJ9TyUaqgU2dxF1" /></figure><p>In the early days of our journey at Software Engineering, I was a compact unit of developer operating on my own sort of like lone wolves. This approach worked well for me in the beginning, my tasks were straightforward, my codebase was small, and I didn’t need any collaboration or let say it was minimal. But as I grew in experiences and taking more complex coding course in my uni, I realized that it was time to transition from individual coding to collaborative team projects. This wasn’t just about and increasing manpower (and, of course, for the sake of finishing mandatory group assignment 🗿) but also about adopting new tools and practices to improve our team’s efficiency to finish the project.</p><p>Let’s start by contrasting the experience of coding alone versus working as a team on a project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qilDsDTWRT20jvvoFBYYEw.png" /><figcaption>this is my code, now it’s your problem ☺️</figcaption></figure><h3>Solo Coding vs Team Projects 🎭</h3><p>When you’re coding on your own, you have total control over your project. You make all the decisions, write all the code, and handle all the debugging. The speed at which you progress depends entirely on you. This can be both liberating and daunting, especially as the complexity of the project grows.</p><p>On the other hand, working on a team project introduces a new set of dynamics. You are no longer the sole decision-maker or coder. The likelihood for seeing a trash code being committed on your repo is quite high. Or let say if you are the problem, the chance that you would be hated is very likely high because it’s not only your trash project alone 😌 it’s no longer a solo endeavor; it’s a team project that everyone cares deeply about (because we don’t want to mess up our GPA in this semester).</p><p>You have to communicate effectively, make collective decisions, distribute tasks, and work together to debug and optimize your code. This might sound challenging, but it also allows for faster development, more robust solutions, and the ability to tackle more complex projects.</p><p>To help us transition to this collaborative model and improve our efficiency, we started adopting several tools and practices such as merge requests, scrum boards, and commit messages. Let’s dive into each one of them.</p><h3>The Heart of Collaboration 🧩</h3><p>Introducing Github Pull Requests into our workflow was indeed a game-changer. It acted as a catalyst for code review and collaboration, creating an environment conducive to maintaining high-quality code and simultaneously facilitating knowledge sharing among our team members.</p><p>Before, handling code contributions from different team members was like juggling multiple balls at once. But with pull requests, this process has become more streamlined and efficient. Each feature, enhancement, or bug fix is developed on a separate branch, distinct from the main codebase. This allows team members to work independently on their respective tasks without disturbing the main codebase.</p><p>When a team member believes their work is ready to be merged into the main codebase, they create a pull request. This pull request acts as a platform for reviewing, discussing, and refining the proposed changes. It’s like a conversation thread tied to the specific code changes, making it easier to track and understand the rationale behind each modification.</p><p>Pull requests have fundamentally changed the way we approach code review. Now, every line of code is scrutinized and constructively critiqued before it’s merged. This rigorous process ensures that the final code is robust, efficient, and adheres to our coding standards. It prevents bugs and errors from creeping into the main codebase and helps us keep technical debt in check. Look how cute we collaborate using pull requests and peacefully giving each other suggestion without hatred 😊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btpeI8JtQ99FHjTWmeZ4Dw.png" /><figcaption>peak peaceful communication on PR thread</figcaption></figure><h3>Visualizing Work 📋</h3><p>Next in our toolbox, we adopted the scrum board using Github Project, a powerful visual tool, for tracking the progress of our projects. This invaluable asset allowed us to effectively organize our tasks into the 5 categories:</p><ul><li><strong>Backlog</strong>: This is where all the tasks or user stories for the project initially reside. The backlog represents work that needs to be done but hasn’t been started yet. It includes all the features, enhancements, and bug fixes that have been identified for the project, but not yet prioritized or scheduled for a particular sprint.</li><li><strong>In Progress</strong>: Once a task or user story is moved from the backlog and the work has started, it goes into the ‘In Progress’ column. It signifies that a team member is currently working on this particular task.</li><li>Ready: This column is typically used for tasks that have been completed by the team member and are ready for review or testing. It indicates that the task is no longer being actively worked on and is waiting for someone from the team to review or test the new changes</li><li><strong>In Review</strong>: this signifies that it is currently being reviewed for quality, accuracy, and completion. This could be a code review by another team developer that is assigned to review the backlog</li><li><strong>Done</strong>: Once a task has been reviewed and approved, it is moved to the ‘Done’ column. This indicates that the task has been completed to satisfaction and requires no further work. It represents a closed task, a completed user story, or a finished feature or bug fix.</li></ul><p>This kind of board mapping providing us with a crystal-clear view of the team’s workflow. Github Project served as a visual representation of our project’s timeline, depicting the flow of work from inception to completion. It transformed the way we worked, making our workflows more transparent, and the status of tasks and responsibilities more apparent to everyone in the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBFIwCDboLMxyH6kuxkkVA.png" /><figcaption>Every backlog of our project features mapped on the scrum board regarding to its current development status</figcaption></figure><p>Moreover, the scrum board played a crucial role in helping us prioritize our tasks. It offered a bird’s-eye view of the entire project, allowing us to easily spot high-priority tasks that needed immediate attention. It also made bottlenecks visible, highlighting areas in our process where work was getting stuck or slowed down.</p><p>During stand-ups, team members could easily refer to the board to discuss what they had completed, what they were working on, and any issues they were facing. For sprint planning, the board was a great tool for visually organizing and assigning tasks for the upcoming sprint.</p><h3>Commit and Comment Messages = Clear Communication 📝</h3><p>Finally, we started paying more attention to another commit messages. When you’re coding alone, it’s easy to overlook the importance of commit messages. But in a team project, clear and descriptive commit messages are crucial.</p><p>Each commit message serves as a log for the changes made, explaining what was done and why. This makes it easier to understand the project’s history and to track down when and why a particular change was made. It’s a small detail that greatly increases the maintainability and understandability of our codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uTzB--OHeMbDCBrcyP1_Q.png" /><figcaption>Clear concise message on every commit</figcaption></figure><p><strong>In conclusion</strong>, the journey from a solitary coder to a team player is not only a necessary transition but also a rewarding one in the field of software engineering. As we navigate through more complex projects, the need for collaboration and efficient teamwork becomes vital. Embracing tools and practices such as Github Pull Requests, Scrum Boards, and clear commit messages not only enhances our team’s efficiency but also promotes a culture of quality, transparency, and continuous learning.</p><p>Through this process, we learn to appreciate the synergy of a team, where collective efforts lead to outcomes greater than the sum of individual contributions. We learn to constructively critique, accept feedback, and constantly evolve our code to meet the highest standards of quality. We also learn to communicate effectively, helping everyone in the team to understand our code and the rationale behind our decisions.</p><p>In essence, this journey is about transforming our engineering mindset. It’s about moving from “my code” to “our code”, recognizing that our success lies not in individual brilliance but in our ability to work together, learn from each other, and deliver robust, efficient solutions as a team. This shift not only makes us better engineers but also prepares us for the collaborative nature of the modern tech industry. So, here’s to teamwork, collaboration, and the endless journey of learning and growth in software engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec87048d644b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Data Seeding using CSV and Custom django-admin Command]]></title>
            <link>https://haddad-tech.medium.com/automatic-data-seeding-using-csv-and-custom-django-admin-command-99b6c3aad819?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b6c3aad819</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Sat, 13 May 2023 09:07:20 GMT</pubDate>
            <atom:updated>2023-05-13T09:07:20.756Z</atom:updated>
            <content:encoded><![CDATA[<h4>step-by-step on using django-admin custom command to automate seeding data to our database</h4><h4>Why? Do we really need it?</h4><p>In the modern landscape of web development, database management often poses significant challenges. One of the most common ones is the need for establishing initial data in databases, especially in new instances or during schema migration. In the nasty complex database relationship, we don’t want to insert our data manually did’t we? This task can be arduous, considering that databases can contain millions of records unreadable relation between tables that we didn’t even realized it exists. To circumvent this problem, developers employ the strategy of automatic data seeding. This technique is particularly relevant when developing, testing, or implementing a new database. It enables developers to insert sample data swiftly into the database, allowing for thorough testing and early detection of potential issues. Moreover, automatic data seeding provides consistency across development, testing, and production environments, as it ensures all team members work with identical data structures. This consistency significantly reduces the risk of human error and streamlines the development process. Additionally, it conserves time by eliminating the need for manual data entry, thereby increasing productivity. In this article, we will create our custom django-admin command to automate data seeding in the project.</p><h4>Introduction on django-admin</h4><p>Django equips developers with a potent tool known as django-admin for managing administrative tasks, including data seeding. This command-line utility executes various tasks, such as creating Django projects or apps, running tests, and migrating databases, can be invoked using django-admin.py or the classing manage.py. A nice thing about it is that we can also add our own commands. Lets start with familiarize our self with the django-admin cli. The most widely used commands are startproject, runserver or collectstatic all other commands can be seen through the command below:</p><pre>python manage.py help</pre><h4>Configure new app for data seeding</h4><p>To set up a custom django-admin command, lets first we Initialize the app on the django project named data_seed:</p><pre>python manage.py startapp data_seed</pre><p>Add our app to the project/settings.py</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;corsheaders&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;data_seed&#39;,  # &lt;-- our new data_seed app<br>]</pre><p>Create a model named DummyShip on data_seed/models.py</p><pre>from django.db import models<br># Create your models here.<br>class DummyShip(models.Model):<br>    ship_name =  models.CharField(max_length=50)<br>    ship_total_vessels = models.IntegerField()<br>def __str__(self):<br>        return f&#39;{self.ship_name}&#39;</pre><p>now that we have a new model, create a db migration using:</p><pre>python3 manage.py makemigrations</pre><p>migrate new model to the db</p><pre>python3 manage.py migrate</pre><p>The migration applied to our database, for our convenience, lets register the DummyShip to the admin page so we can access it with the web interface, on the data_seed/admin.py write:</p><pre>from django.contrib import admin<br>from .models import DummyShip<br>admin.site.register(DummyShip)</pre><p>Lets check that our model is ready to be used, run the django server:</p><pre>python3 manage.py runserver</pre><p>open <a href="http://127.0.0.1:8000/admin">http://127.0.0.1:&lt;port&gt;/admin</a> (note that the &lt;port&gt; depend on your local machine) and make sure we have our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QVX4Ksp66zpaf1Kd" /></figure><h4>django-admin custom command</h4><p>Now that our app is ready, let’s start working on the creation of Custom Django Management Commands:</p><ul><li>Create a folder management/commands on the data_seed apps</li><li>Create a file with the command that we want to register, in this context we want to import a data, name it import_data.py write code to the file:</li></ul><pre>class Command(BaseCommand):<br>    help = &quot;Seed data from CSV files&quot;<br>    def add_arguments(self, parser):<br>        parser.add_argument(&#39;file_path&#39;, type=str, help=&#39;Path to the CSV file&#39;)<br><br><br>    def handle(self, *args, **kwargs):<br>        file_path = kwargs[&#39;file_path&#39;]<br>        try:<br>            with open(file_path, &#39;r&#39;) as csvfile:<br>                csv_reader = reader(csvfile, delimiter=&#39;;&#39;)<br>                next(csv_reader)  # skip header row<br>                dummies = [DummyShip() for row in csv_reader]<br>                DummyShip.objects.bulk_create(dummies)<br>                self.stdout.write(self.style.SUCCESS(&#39;Data imported successfully&#39;))<br>        except Exception:<br>            self.stdout.write(self.style.ERROR(&#39;Error importing data&#39;))</pre><p>This code allows us to import our data on the DummyShip model using CSV file, by this structure our custom command would be:</p><pre>python3 manage.py import_data &lt;path/to/file/csv&gt;</pre><p>Let’s breakdown the code:</p><p>This is a custom Django management command to import data from a CSV file into your Django application’s database. Let’s break down the code:</p><ul><li>class Command(BaseCommand): The class Command inherits from Django&#39;s BaseCommand class, which is the base class for all Django management commands.</li><li>help = &quot;Seed data from CSV files&quot;: This is a short description of what the command does. It&#39;s displayed when you run python manage.py help.</li><li>def add_arguments(self, parser): This method is used to specify the command-line arguments for this management command.</li><li>parser.add_argument(&#39;file_path&#39;, type=str, help=&#39;Path to the CSV file&#39;): This line adds an argument file_path that is expected to be a string. This will be the path to the CSV file that contains the data to be imported.</li><li>def handle(self, *args, **kwargs): This method is the main logic of the management command. It&#39;s called when you run the command.</li><li>file_path = kwargs[&#39;file_path&#39;]: This line retrieves the file_path argument that was passed on the command line.</li><li>with open(file_path, &#39;r&#39;) as csvfile: This line opens the CSV file.</li><li>csv_reader = reader(csvfile, delimiter=&#39;;&#39;): This line creates a CSV reader object that will allow you to iterate over the rows in the CSV file. The delimiter is specified as ;.</li><li>next(csv_reader): This line skips the header row of the CSV file.</li><li>dummies = [DummyShip() for row in csv_reader]: This line creates a list of DummyShip objects. For each row in the CSV file, it creates a new DummyShip object. Note that this line doesn&#39;t do anything with the data in each row -- it just creates an empty DummyShip object.</li><li>DummyShip.objects.bulk_create(dummies): This line saves all of the DummyShip objects to the database in a single query, which is more efficient than saving each object individually.</li><li>self.stdout.write(self.style.SUCCESS(&#39;Data imported successfully&#39;)): If everything went well, this line will print a success message to the console.</li><li>except Exception:: If anything goes wrong during the import process (like if the file can&#39;t be opened, or if there&#39;s an error saving the objects to the database), the code in the except block will be executed.</li><li>self.stdout.write(self.style.ERROR(&#39;Error importing data&#39;)): If there was an error, this line will print an error message to the console.</li></ul><h4>Seed the data!</h4><p>Now that we have prepared all the necessary code, the data that we want to import, lets create a dummy csv file for the sake of testing our custom command. Create importfile.csv on the root project folder write:</p><pre>ID;ship_name;ship_total_vessels<br>0;jayakarta I;15</pre><p>run our custom command:</p><pre>python3 manage.py import_data importfile.csv</pre><p>If you followed it correctly, you will get a successful message on the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-IOoK5YFFqTub2kzDAQZQ.png" /><figcaption>success message on imported data</figcaption></figure><p>Next, lets check on the admin page to ensure the data is imported</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dk_LaF8HzCIzEf4NjTx59A.png" /><figcaption>jayakarta I imported on DummyShip model</figcaption></figure><p>click on the jayakarta I and we will see the detail of the fields is match with the our csv file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_GyfCdkGswrkfOzhtXA1A.png" /><figcaption>jayakarta I detail fields</figcaption></figure><p>We now have our custom command to autmate the data seeding so we don’t have to import it manually</p><h4>Conclusion</h4><p>Automation in data seeding and migration is truly a boon in the landscape of web development. It not only enhances efficiency but also ensures consistency and reliability in the development process. Utilizing tools like Django’s django-admin command-line utility and the ability to create custom commands, developers can save valuable time, reduce errors, and streamline the entire process of database management.</p><p>Whether it’s for initializing test databases, migrating large amounts of data, or setting up production databases, automated data seeding can significantly simplify these tasks. By leveraging Django’s powerful and flexible features, developers can focus more on building robust and efficient applications, knowing that their data management needs are being handled effectively and consistently.</p><p>In summary, automatic data seeding is not just a good-to-have feature but a crucial aspect of modern web development practices. It’s a testament to the constant evolution and progress of development tools and methodologies, aimed at making the life of developers easier and their work more efficient. With Django at the helm, automatic data seeding and migration becomes a smoother, more manageable task, enabling you to deliver better quality applications in less time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b6c3aad819" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrum-on-Agile: an approach to modern software development process]]></title>
            <link>https://haddad-tech.medium.com/scrum-on-agile-an-approach-to-modern-software-development-process-196054582b3a?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/196054582b3a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[scrum]]></category>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 13:13:24 GMT</pubDate>
            <atom:updated>2023-03-02T15:32:33.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rI533P-K8RiUxv-J" /><figcaption>Photo by <a href="https://unsplash.com/@lazizli?utm_source=medium&amp;utm_medium=referral">Lala Azizli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Developing a software product is a complex iteration so there is a well-known standard guideline software development that followed <strong>the waterfall methodology</strong>. It is a software development process model that follows a sequential, linear approach to software development. In this model, the development process is divided into distinct phases, with each phase being completed before moving on to the next one. The phases typically include requirements gathering, design, implementation, testing, deployment, and maintenance. Once a phase is completed, the development team cannot go back to the previous phase without starting the entire process over again. However, with advancements in technology, it has become clear that this method is not always suitable for keeping up with the software development lifecycle. The Waterfall model is often criticized for being inflexible and not allowing for changes or revisions once the development process has begun. One of the main problems is that with the waterfall method, one cannot deliver anything until the end of the development timeline. This becomes an issue when the product requirements become more complex and require more iteration. The more complex the requirements, the more development time is needed, which increases the risk of errors. Developing a complex product with the waterfall method can therefore be costly and time-consuming, with no guarantee that the product will be ready within the specified timeframe.</p><blockquote>“Agile is not a methodology, it’s a mindset. It’s an attitude, a way of thinking that values individuals and interactions over processes and tools, working software over comprehensive documentation, customer collaboration over contract negotiation, and responding to change over following a plan.”</blockquote><blockquote>— Agile Manifesto</blockquote><p>In response to the disadvantages of the traditional methodologies, a group of software developers coined the term “agile” with the realization that waterfall processes were no longer suitable for software development. They came together to create <strong>the Agile Manifesto </strong>outlining a set of new guidelines to follow with values and principles for Agile software development. The most well-known principles as follow:</p><ol><li>Customer involvement: Agile teams prioritize the needs of their customers and involve them throughout the development process to ensure their needs are being met.</li><li>Iterative development: Agile teams work in short iterations or sprints to deliver working software quickly and continuously improve their work.</li><li>Self-organizing teams: Agile teams are self-organizing, meaning they are empowered to make decisions about how they work and how to solve problems.</li><li>Continuous improvement: Agile teams continuously reflect on their work and make improvements to their processes and practices.</li><li>Collaboration: Agile teams emphasize collaboration between team members, stakeholders, and customers to ensure everyone is aligned on goals and priorities.</li><li>Emphasis on working software: Agile teams prioritize delivering working software over documentation or other artifacts to ensure that value is being delivered to customers.</li><li>Face-to-face communication: Agile teams prioritize face-to-face communication to ensure that information is shared effectively and misunderstandings are minimized.</li></ol><p>Agile is an iterative approach to software development that emphasizes collaboration, flexibility, and customer satisfaction. There is no one-size-fits-all set of rules for Agile so along with the time, “Agile Development Process” becomes an umbrella term to cover some framework implementations that follows it principles. One of the framework implementing Agile is, as we already know in this modern era, <em>Scrum.</em></p><p>To achieves the best outcome, implementing <em>Scrum</em> could be tricky because there are severals new components we need to understand the roles and it related activities. So, Lets get into it!</p><p><strong>Scrum Terminologies</strong></p><p>Scrum is a flexible framework that allows change on it processes and some organizations may adapt the terminology to fit their specific needs, but there is common terminology that usually followed to implement a Scrum</p><ul><li>Product Backlog: This is a prioritized list of user stories and product features that need to be completed in a project. The Product Owner is responsible for creating and maintaining the Product Backlog, and it is used to guide the work of the Development Team.</li><li>Sprint Backlog: This is a list of tasks that the Development Team commits to completing during a Sprint. The Sprint Backlog is created during Sprint Planning and is used to guide the work of the Development Team during the Sprint.</li><li>Increment: This is the sum of all the completed Product Backlog items at the end of each Sprint. The Increment is a working version of the product that can be reviewed and tested by stakeholders and customers.</li><li>Sprint: A Sprint is a time-boxed period of one to four weeks during which the Development Team completes a set of tasks from the Sprint Backlog.</li><li>Sprint Planning: This is a meeting held at the beginning of each Sprint to plan the work that will be completed during the Sprint. The Product Owner and Development Team work together to create a Sprint Goal and a list of tasks for the Sprint Backlog.</li><li>Daily Scrum: This is a daily meeting held by the Development Team to review progress and plan for the day. The meeting is time-boxed to 15 minutes and each member of the Development Team answers three questions: What did I do yesterday? What will I do today? Are there any impediments?</li><li>Sprint Review: a meeting held at the end of each Sprint to review the work completed and get feedback from stakeholders and customers. The Product Owner and Development Team present the Increment and discuss what was completed during the Sprint.</li><li>Sprint Retrospective: This is a meeting held at the end of each Sprint to reflect on the previous Sprint and identify areas for improvement. The Development Team discusses what went well, what could have been done better, and identifies action items for improvement.</li></ul><p>Those kind of activities implemented by the three main roles on Scrum:</p><ol><li><strong>Product Owner</strong></li></ol><p>Roles that creates and maintains the Product Backlog, which is a prioritized list of user stories and product features that need to be completed in the project. The Product Owner also communicates with stakeholders and customers to ensure that their needs are met and the product is delivered on time.</p><p>2. <strong>Scrum Master</strong></p><p>Responsible for facilitating the Scrum process, removing any impediments that may be hindering the Developer, ensuring the team adheres to the Scrum framework. The Scrum Master also helps the team to continuously improve their practices and processes.</p><p>3. <strong>Developer</strong></p><p>responsible for delivering a potentially shippable product increment at the end of each Sprint. The team is self-organizing and cross-functional, meaning that they have all the necessary skills to complete the work required in the project.</p><p>On the conclusion, Agile Development is the process to overcome the difficulties of traditional method to keep up with the complex product development. Scrum is one of the framework that follows Agile Development Process. To make it success, there are several roles and activities to follow so it won’t be a chaotic process. By understanding the Scrum framework and its components such as roles (Product Owner, Scrum Master, and Development Team), artifacts (Product Backlog, Sprint Backlog, and Increment), and events (Sprint, Sprint Planning, Daily Scrum, Sprint Review, and Sprint Retrospective), teams can work together more effectively and deliver high-quality products to customers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=196054582b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[le(m)bur]]></title>
            <link>https://haddad-tech.medium.com/le-m-bur-1cd2e453a19?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd2e453a19</guid>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 12:08:52 GMT</pubDate>
            <atom:updated>2019-10-28T12:18:17.777Z</atom:updated>
            <content:encoded><![CDATA[<p>le(<strong><em>m</em></strong>)bur</p><p>07pm.</p><p>le<strong>m</strong>bur dalam suatu hal, dengan segenap angan dan harapan. memperkenalkan manusia pada hakikat pe-<em>lebur</em>-an. hingga muak untuk kembali le<strong>m</strong>bur. serta dituntut pasrah menikmati realitas angan-nya yang mulai <em>lebur</em>.</p><p>atau lebih tepat, di-<em>lebur</em>-kan.</p><p>4 okt. di kampus polteknik negeri jakarta. 2018</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd2e453a19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(fun)-a]]></title>
            <link>https://haddad-tech.medium.com/fun-a-235ce20f4457?source=rss-61025f2e133------2</link>
            <guid isPermaLink="false">https://medium.com/p/235ce20f4457</guid>
            <dc:creator><![CDATA[Haddad]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 12:04:38 GMT</pubDate>
            <atom:updated>2019-10-28T12:04:38.649Z</atom:updated>
            <content:encoded><![CDATA[<p>1pm.</p><p>Kesadaran akan <strong>fana</strong> menyanggupkan-mu menatap cermin seraya mer<strong>ana</strong>.</p><p>“ kau menyiksa diriku ! ”</p><p>disertai menampakkan seringai sinis. menghina sosok dibalik cermin, bahwa selama ini ia memang bodoh. serta tersakiti.</p><p>“semua impianmu-mu tentang kesenangan telah lenyap dan <strong><em>fana, </em></strong>bodoh ! ”</p><p><em>diketik di pesantren alhikam depok. sebelum tgl empat oktober, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235ce20f4457" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>