Skip to main content

Ralsina.Me — Roberto Alsina's website

Posts about tests

Generic run-my-tests-please GitHub Workflow

This post has on­ly one ob­jec­tive. The next per­son who wants to run the tests on his Python project host­ed on GitHub should be able to read it and get his tests run­ning in 15 min­utes or less us­ing GitHub Ac­tion­s.

So, con­cept­s:

  • Github Ac­tion­s: A free (most­ly) con­tin­u­ous in­te­gra­tion thing GitHub gives you so you can run your tests au­to­mat­i­cal­ly, so peo­ple know your project kin­da work­s.
  • Test­s: you should have them.

This as­sumes your project is "mod­ern" in that it us­es Po­et­ry for de­pen­den­cy man­age­ment and pack­ag­ing. Of course maybe it does­n't, but don't wor­ry, that on­ly is im­por­tant for maybe 3 lines of YAM­L.

So, Github Actions runs what's called "workflows". You define these in YAML files in .github/workflows/whatever.yml in your repo.

Here's the orig­i­nal ver­sion of the work­flow we'll be study­ing to­day: test.yml

Don't wor­ry about the project it's in, it re­al­ly does­n't mat­ter.

Now, let's ex­am­ine that file bit by bit with ex­pla­na­tion­s, so you can see if some­thing needs chang­ing for you.

name: CI

on:
  [push, pull_request]

This work­flow is called "CI" and it runs on ev­ery push to any branch.

jobs:
  build:
    strategy:
      matrix:
        python-version: ["3.10"]
    runs-on: ubuntu-latest

Put all the versions of Python you want to test in python-versions. This will run the tests in Ubuntu.

    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
          
      - name: Switch to Current Branch
        run: git checkout ${{ env.BRANCH }}

Check­out this re­po we are test­ing, go to the right branch.

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v1
        with:
          python-version: ${{ matrix.python-version }}

In­stall what­ev­er Python ver­sion we are test­ing.

      - name: Install dependencies
        run: |
          pip install poetry
          poetry install

In­stall what­ev­er you need. Since this project us­es po­et­ry, I in­stall po­et­ry and then use po­et­ry to set­up things. If you are us­ing some­thing else, then change it ac­cord­ing­ly.

      - name: Run unit tests
        run: |
          poetry run pytest

Run the tests in what­ev­er way they need to run. Again, since I am us­ing po­et­ry, this work­s. If you are not, then change this as need­ed.

So, put this file in .github/workflows/test.yml, modify as needed. Commit. Push. Now your tests run on every push.

And that's it. If your project us­es po­et­ry, then this work­flow may work un­changed (ex­cept maybe for Python ver­sion­s?)

Good luck!


Contents © 2000-2022 Roberto Alsina