Mastering Automated Tests With GitHub Actions

Alex Johnson
-
Mastering Automated Tests With GitHub Actions

Hey @kiet-nguyenletuan, and welcome to the world of automated testing! In this guide, we'll dive deep into using GitHub Actions to safeguard your code with unit tests and coverage reports. Think of this as your interactive, hands-on adventure to leveling up your development skills. Let's get started!

original github octocat

Why Automated Tests Matter

Automated tests are the unsung heroes of robust software development. At its core, automated testing involves writing code that tests your actual code. This process helps catch bugs early, ensures that new changes don't break existing functionality, and ultimately leads to more reliable software. So, why should you care about automated tests?

  • Early Bug Detection: Imagine finding a critical bug before your users do. Automated tests can help you achieve just that by running tests every time you make changes to your code.
  • Regression Prevention: Ever fixed a bug only to accidentally introduce another one later? Automated tests act as a safety net, ensuring that new features or fixes don't break existing functionality.
  • Improved Code Quality: Writing tests forces you to think about your code from different angles, leading to cleaner, more modular, and ultimately better code.
  • Faster Development Cycles: While it might seem counterintuitive, automated tests can actually speed up development by reducing the time spent debugging and fixing issues.
  • Confidence in Your Code: Knowing that your code is thoroughly tested gives you the confidence to make changes and deploy new features without fear of breaking things.

Getting Started with GitHub Actions

So, what exactly are GitHub Actions? GitHub Actions are a powerful automation platform built directly into GitHub. They allow you to automate various tasks in your software development workflow, including building, testing, and deploying your code. They are event-driven, meaning you can trigger them based on events like pushing code, creating a pull request, or even on a schedule.

To get started with GitHub Actions, you'll need to create a workflow file in your repository. A workflow file is a YAML file that defines the steps you want to automate. These files live in the .github/workflows directory of your repository. Let's create a basic workflow file to run our tests.

  1. Create a new file named .github/workflows/test.yml in your repository.

  2. Add the following code to the file:

    name: Test
    
    on:
      push:
        branches: [ main ]
      pull_request:
        branches: [ main ]
    
    jobs:
      build:
        runs-on: ubuntu-latest
    
        steps:
        - uses: actions/checkout@v2
        - name: Set up Python 3.9
          uses: actions/setup-python@v2
          with:
            python-version: 3.9
        - name: Install dependencies
          run: |
            python -m pip install --upgrade pip
            pip install -r requirements.txt
        - name: Run tests
          run: pytest
    

Let's break down this workflow file:

  • name: Test: This gives your workflow a name, which will be displayed in the GitHub Actions UI.
  • on:: This specifies the events that trigger the workflow. In this case, it's triggered on push and pull_request events to the main branch.
  • jobs:: This defines the jobs that will be executed in the workflow. In this case, we have a single job named build.
  • runs-on: ubuntu-latest: This specifies the operating system to run the job on. We're using the latest version of Ubuntu.
  • steps:: This defines the steps that will be executed in the job. Each step is executed in order.
    • uses: actions/checkout@v2: This checks out your code into the workflow environment.
    • name: Set up Python 3.9: This sets up Python 3.9 for the job.
    • name: Install dependencies: This installs the dependencies listed in your requirements.txt file.
    • name: Run tests: This runs your tests using pytest.

Writing Unit Tests

Unit tests are small, isolated tests that verify the behavior of individual units of code, such as functions or methods. They are an essential part of any automated testing strategy. To write effective unit tests, follow these best practices:

  • Test One Thing at a Time: Each test should focus on verifying a single aspect of the code's behavior.
  • Keep Tests Isolated: Tests should not depend on external resources or other tests. Use mocks or stubs to isolate the code being tested.
  • Write Clear and Concise Tests: Tests should be easy to understand and maintain. Use descriptive names and comments to explain what each test is doing.
  • Follow the Arrange-Act-Assert Pattern:
    • Arrange: Set up the necessary preconditions for the test.
    • Act: Execute the code being tested.
    • Assert: Verify that the code behaves as expected.

Here's an example of a simple unit test written using the pytest framework in Python:

# my_module.py
def add(x, y):
    return x + y
# test_my_module.py
from my_module import add

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

In this example, we're testing the add function to ensure that it returns the correct result for different inputs. Each assert statement verifies a specific aspect of the function's behavior.

Generating Coverage Reports

Coverage reports provide insights into how much of your code is covered by your tests. They help you identify areas of your code that are not being tested, allowing you to write more comprehensive tests and reduce the risk of bugs. Several tools can generate coverage reports, such as pytest-cov in Python.

To generate a coverage report with pytest-cov, you'll need to install it first:

pip install pytest-cov

Then, you can run your tests with the --cov flag to generate a coverage report:

pytest --cov=my_module

This will generate a coverage report that shows the percentage of lines covered by your tests. You can also generate an HTML report for a more detailed view of the coverage:

pytest --cov=my_module --cov-report html

This will generate an HTML report in the htmlcov directory, which you can open in your browser to view the coverage details.

Integrating Coverage Reports with GitHub Actions

To integrate coverage reports with GitHub Actions, you can use the codecov action. This action uploads your coverage data to Codecov, a popular code coverage service, where you can track your coverage over time and identify areas for improvement. To use the codecov action, you'll need to sign up for a free Codecov account and obtain a repository token.

Once you have your repository token, you can add the following step to your workflow file:

- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v2
  with:
    token: ${{ secrets.CODECOV_TOKEN }}

This step uploads your coverage data to Codecov, where you can view detailed coverage reports and track your coverage over time. Remember to store your Codecov token as a secret in your GitHub repository to prevent it from being exposed in your workflow file.

Tips and Tricks for Effective Testing

  • Write Tests Early and Often: Don't wait until the end of the development cycle to write tests. Write tests as you write code to catch bugs early and ensure that your code is testable.
  • Use Test-Driven Development (TDD): TDD is a development approach where you write tests before you write code. This helps you clarify your requirements and ensure that your code meets those requirements.
  • Strive for High Coverage: Aim for high test coverage to reduce the risk of bugs and ensure that your code is thoroughly tested.
  • Use Mocking and Stubbing: Use mocking and stubbing to isolate your tests and avoid dependencies on external resources.
  • Continuously Improve Your Tests: Regularly review and improve your tests to ensure that they are effective and up-to-date.

Conclusion

So, there you have it, guys! You've taken your first steps towards mastering automated tests with GitHub Actions. You've learned how to write unit tests, generate coverage reports, and integrate them with GitHub Actions. By following these practices, you can improve the quality of your code, reduce the risk of bugs, and develop more reliable software. Now go forth and conquer the testing world!

For more in-depth information on GitHub Actions and best practices, check out the official documentation on GitHub Actions Documentation. Happy testing!

You may also like