You've written some unit tests for your Python app. Good for you! There are dozens of us, dozens!You don't always remember to run your tests, or worse, your colleagues don't always remember to run them.
Wouldn't it be nice to automatically run unit tests on every commit to GitHub? What about on every pull request?You can do this with GitHub Actions.You'd be able to hunt down commits that broke the build, and if you're feeling blamey, who broke the build.Sounds complicated, but it's not.Sounds like it might cost money, but the free version has ~30 hours of execution per month.Let me show you how to set this up.
There is example code for this blog post here.
So it might happen than when faced with a mismatch between the version of Python used to create a virtual environment and the version currently in use to run the tests (e.g. Python micro version gets upgraded from 3.6.3 to 3.6.4 and this upgrade reaches your Linux host and/or the repositories used by the django-box VM), weird errors happen. Run tests that failed in the most recent test run. Similar to Python: Run Failed Tests on versions prior to 2021.9. Test: Rerun Last Run: Debug tests that were executed in the most recent test run. Test: Run All Tests: Run all discovered tests. Equivalent to Python: Run All Tests on versions prior to 2021.9. Test: Run Test at Cursor.
Setting up your project
I'm going to assume that:
- You have some Python code
- You use Git, and your code is already in a GitHub repository
If you're already running unit tests locally you can skip this section.Otherwise, your Python project's folder looks something like this:
If you don't have tests already, I recommend trying pytest (and adding it to your requirements.txt).
You'll need at least one test
You'll want to make sure your tests run and pass locally
Set up your Action
You'll need to create new a file in a new folder: .github/workflows/ci.yml
.You can learn more about these config files here.Here's an example file:
Now your project looks like this:
Commit your changes, push it up to GitHub and watch your tests run!
Sometimes they fail:
Run Django Tests With Pytest
Sometimes they pass:
Django Run Tests Without Migrations
Add a badge to your README
Run Django Test
You can add a 'badge' to your project's README.md.Assuming your project was hosted at https://github.com/MyName/my-project/, you can add thisto your README.md file:
Next steps
Django Transactiontestcase
Write some tests, run them locally, and then let GitHub run them for you on every commit from now on.If you get stuck, check out this minimal reference or the Actions docs.