Add GitHub Actions CI and run tests with Docker
cover Add GitHub Actions CI and run tests with Docker
Add .github/workflows/ci.yml and run tests with docker/run-tests.sh script. This has been run on https://github.com/moto-timo/error-report-web master-next branch.
Tim Orling (5):
Use django.test.TestCase so tests run against a test database. Add docker/run-tests.sh to run the tests in a container. Add a GitHub Actions workflow to run the tests.
Port culldb and purge.py to Python 3.
Add a ruff lint job to CI and fix its findings.
.dockerignore | 10 ++++++ .github/workflows/ci.yml | 31 +++++++++++++++++++ .gitignore | 1 + Post/createStatistics.py | 6 ++-- Post/management/commands/culldb.py | 36 +++++++++------------- Post/models.py | 4 +-- Post/parser.py | 5 +-- Post/purge.py | 4 +-- Post/templatetags/projecttags.py | 4 --- Post/test.py | 49 ++++++++++++++++++++++++------ Post/views.py | 10 +++--- docker/run-tests.sh | 32 +++++++++++++++++++ project/settings.py.docker | 2 +- ruff.toml | 5 +++ test-data/test-send-error.py | 4 ++- 15 files changed, 149 insertions(+), 54 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/ci.yml create mode 100755 docker/run-tests.sh create mode 100644 ruff.toml
base-commit: 752b7188d04c2fd0e2f32f0cd2dd437c43058d82
Signature · 1 line
2.56.0
PATCH 1/5 Use django.test.TestCase so tests run against a test database.
unittest.TestCase gets no test database, so the tests used the configured one and failed against a fresh database. Also allow CSPTest's "testhost" in ALLOWED_HOSTS.
AI-Generated: Claude Opus 5.5
--- Post/test.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-)
Post/test.py +6 -9
@@ -1,8 +1,7 @@ -import unittest import urllib.request, urllib.parse, urllib.error import json import re -from django.test import Client, override_settings +from django.test import Client, TestCase, override_settings from Post.models import BuildFailure, Build from Post.validators import clean_link_back
@@ -64,7 +63,7 @@ def compare_db_obj_with_payload(self, bf_object): f.close() -class SimpleTest(unittest.TestCase): +class SimpleTest(TestCase): def setUp(self): # The test clients submit with HTTP_HOST="testhost", so allow it here # instead of hardcoding a test host into the project settings.
@@ -248,7 +247,8 @@ class SimpleTest(unittest.TestCase): response = self.client.get("/Errors/Details/9898989898/") self.assertEqual(response.status_code, 200) -class CSPTest(unittest.TestCase): +@override_settings(ALLOWED_HOSTS=["testhost"]) +class CSPTest(TestCase): def setUp(self): self.client = Client(HTTP_HOST="testhost")
@@ -307,7 +307,7 @@ class CSPTest(unittest.TestCase): Build.objects.all().delete() -class LinkBackValidatorTest(unittest.TestCase): +class LinkBackValidatorTest(TestCase): def test_allows_http(self): self.assertEqual(clean_link_back("http://example.com/build/1"),
@@ -350,7 +350,7 @@ class LinkBackValidatorTest(unittest.TestCase): self.assertIsNone(clean_link_back(123)) -class LinkBackSubmissionTest(unittest.TestCase): +class LinkBackSubmissionTest(TestCase): def setUp(self): # The test client submits with HTTP_HOST="testhost"; allow it here.
@@ -358,9 +358,6 @@ class LinkBackSubmissionTest(unittest.TestCase): override.enable() self.addCleanup(override.disable) self.client = Client(HTTP_HOST="testhost") - # Start from a clean slate; other unittest.TestCase tests commit rows. - Build.objects.all().delete() - BuildFailure.objects.all().delete() with open("test-data/test-payload.json") as f: self.base_payload = json.loads(f.read())
Signature · 1 line
2.56.0
PATCH 2/5 Add docker/run-tests.sh to run the tests in a container.
In reply to Tim OrlingBuild the image and test against a throwaway MySQL, as layerindex-web does. -Wa shows deprecation warnings. Read SECRET_KEY from the environment in settings.py.docker, and keep .git and .env out of the image and .env out of git.
AI-Generated: Claude Opus 5.5
--- .dockerignore | 10 ++++++++++ .gitignore | 1 + docker/run-tests.sh | 32 ++++++++++++++++++++++++++++++++ project/settings.py.docker | 2 +- 4 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 .dockerignore create mode 100755 docker/run-tests.sh
.dockerignore new file +10 -0
@@ -0,0 +1,10 @@ +.git +.env +.devcontainer +.ruff_cache +__pycache__ +*.pyc +*.sqlite3 +*.patch +venv +.venv
.gitignore +1 -0
@@ -7,3 +7,4 @@ pull-*/ venv *.sqlite3 +.env
docker/run-tests.sh new file +32 -0
@@ -0,0 +1,32 @@ +#!/bin/sh +# Run the tests in the app image against a throwaway MySQL. Used by CI. +# +# SPDX-License-Identifier: MIT + +set -e + +IMAGE=${IMAGE:-error-report-web-test} +NET=error-report-web-test +DB=error-report-web-test-db + +docker build -t "$IMAGE" . + +docker network create $NET >/dev/null +trap 'docker rm -f $DB >/dev/null; docker network rm $NET >/dev/null' EXIT + +# Root so Django can create the test database; testingpw isn't a secret. +docker run -d --name $DB --network $NET --network-alias db \ + -e MYSQL_ROOT_PASSWORD=testingpw -e MYSQL_DATABASE=errorreport \ + mysql:8.0.36 >/dev/null +until docker exec $DB mysql -h127.0.0.1 -uroot -ptestingpw -e 'SELECT 1' >/dev/null 2>&1; do + if [ "$(docker inspect -f '{{.State.Running}}' $DB)" != true ]; then + docker logs $DB | tail -5; exit 1 + fi + sleep 1 +done + +# -Wa shows deprecation warnings, i.e. what breaks on the next Django. +docker run --rm --network $NET \ + -e SECRET_KEY=ci-only \ + -e MYSQL_DATABASE=errorreport -e MYSQL_USER=root -e MYSQL_PASSWORD=testingpw \ + "$IMAGE" python3 -Wa manage.py test --noinput Post
project/settings.py.docker +1 -1
@@ -127,7 +127,7 @@ STATICFILES_FINDERS = ( ) # Make this unique, and don't share it with anybody. -SECRET_KEY = 'changeme' +SECRET_KEY = os.environ.get('SECRET_KEY', 'changeme') MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware',
Signature · 1 line
2.56.0
PATCH 3/5 Add a GitHub Actions workflow to run the tests.
In reply to Tim OrlingRuns docker/run-tests.sh, as layerindex-web does.
AI-Generated: Claude Opus 5.5
--- .github/workflows/ci.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/ci.yml
.github/workflows/ci.yml new file +22 -0
@@ -0,0 +1,22 @@ +# SPDX-License-Identifier: MIT + +name: CI + +on: + push: + branches: [master,master-next] + pull_request: + branches: [master] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + + - name: Build image and run tests + run: docker/run-tests.sh
Signature · 1 line
2.56.0
PATCH 4/5 Port culldb and purge.py to Python 3.
In reply to Tim OrlingBoth used Python 2 print and failed with SyntaxError. culldb also used option_list and optparse, removed in Django 1.10; declare the same arguments with add_arguments(). Add culldb tests. Found by ruff.
AI-Generated: Claude Opus 5.5
--- Post/management/commands/culldb.py | 36 +++++++++++++----------------- Post/purge.py | 2 +- Post/test.py | 21 +++++++++++++++++ 3 files changed, 37 insertions(+), 22 deletions(-)
Post/management/commands/culldb.py +15 -21
@@ -9,44 +9,38 @@ # Create your views here. # vi: tabstop=8 expandtab shiftwidth=4 softtabstop=4 -from django.core.management.base import BaseCommand, CommandError -from Post.models import Build, BuildFailure -from optparse import make_option +from django.core.management.base import BaseCommand +from Post.models import Build import time import sys class Command(BaseCommand): help = 'Culls the database to size in rows' - args = '<size>' - option_list = BaseCommand.option_list + ( - make_option('-i', - '--info', - dest='info', - action="store_true", - help='Show the current database size'), - ) + + def add_arguments(self, parser): + parser.add_argument('size', nargs='?', type=int, + help='Number of builds to keep') + parser.add_argument('-i', + '--info', + action="store_true", + help='Show the current database size') def handle(self, *args, **options): count = Build.objects.count() if options['info']: - print "Current builds table size: %d" % Build.objects.count() + print("Current builds table size: %d" % Build.objects.count()) return - if len(args) > 0 and args[0]: - try: - new_size = int(args[0]) - except ValueError: - print "Not a valid size" - return - + if options['size'] is not None: + new_size = options['size'] num_to_delete = count - new_size - print "\nReducing the database size to %d which will DELETE %d rows" % (new_size, num_to_delete) + print("\nReducing the database size to %d which will DELETE %d rows" % (new_size, num_to_delete)) i = 1 while i != 0: i = i-1 - print 'Ctrl+c TO CANCEL. Executing in... %d \r' % i, + print('Ctrl+c TO CANCEL. Executing in... %d \r' % i, end='') sys.stdout.flush() time.sleep(1)
Post/purge.py +1 -1
@@ -20,7 +20,7 @@ def main(): #print query items = BuildFailure.objects.raw(query) for item in items: - print "Deleting: ", item.id + print("Deleting: ", item.id) item.delete() if __name__ == "__main__":
Post/test.py +21 -0
@@ -1,5 +1,7 @@ import urllib.request, urllib.parse, urllib.error import json +from unittest.mock import patch +from django.core.management import call_command import re from django.test import Client, TestCase, override_settings from Post.models import BuildFailure, Build
@@ -385,3 +387,22 @@ class LinkBackSubmissionTest(TestCase): bf = self._submit("http://example.com/build/42") self.assertEqual(bf.BUILD.LINK_BACK, "http://example.com/build/42") + + +@patch("Post.management.commands.culldb.time.sleep") +class CullDbTest(TestCase): + def setUp(self): + for _ in range(3): + Build.objects.create() + + def test_culls_to_size(self, _sleep): + call_command("culldb", "1") + self.assertEqual(Build.objects.count(), 1) + + def test_zero_culls_everything(self, _sleep): + call_command("culldb", "0") + self.assertEqual(Build.objects.count(), 0) + + def test_info_deletes_nothing(self, _sleep): + call_command("culldb", "--info") + self.assertEqual(Build.objects.count(), 3)
Signature · 1 line
2.56.0
PATCH 5/5 Add a ruff lint job to CI and fix its findings.
In reply to Tim OrlingPin ruff and select its classic rules, which find bugs; newer defaults are mostly style. Fix the findings. The paginator now catches InvalidPage, and the JSON parser Exception, so deeply nested JSON (RecursionError) is still reported as invalid. Test bad page numbers.
AI-Generated: Claude Opus 5.5
--- .github/workflows/ci.yml | 9 +++++++++ Post/createStatistics.py | 6 ++---- Post/models.py | 4 +--- Post/parser.py | 5 +++-- Post/purge.py | 2 +- Post/templatetags/projecttags.py | 4 ---- Post/test.py | 13 ++++++++++++- Post/views.py | 10 ++++------ ruff.toml | 5 +++++ test-data/test-send-error.py | 4 +++- 10 files changed, 40 insertions(+), 22 deletions(-) create mode 100644 ruff.toml
.github/workflows/ci.yml +9 -0
@@ -20,3 +20,12 @@ jobs: - name: Build image and run tests run: docker/run-tests.sh + + lint: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v5 + + - name: Ruff + run: pipx run ruff==0.17.0 check --output-format=github .
Post/createStatistics.py +2 -4
@@ -8,11 +8,9 @@ # # Licensed under the MIT license, see COPYING.MIT for details -import sys, os from Post.models import Build, BuildFailure from django.db.models import Count -import re -from datetime import datetime, timedelta +from datetime import timedelta from django import utils class Statistics:
@@ -52,7 +50,7 @@ class Statistics: elif string == "NATIVELSBSTRING": errors = Build.objects.filter(DATE__range=[enddate, startdate]).values('NATIVELSBSTRING').annotate(dcount=Count('NATIVELSBSTRING')).order_by('-dcount')[:6] items = list(errors) - return items; + return items elif string == "TARGET_SYS": errors = Build.objects.filter(DATE__range=[enddate, startdate]).values('TARGET_SYS').annotate(dcount=Count('TARGET_SYS')).order_by('-dcount')[:6] items = list(errors)
Post/models.py +1 -3
@@ -7,9 +7,7 @@ # Licensed under the MIT license, see COPYING.MIT for details from django.db import models -from django.db.models.signals import post_save from django.conf import settings -from datetime import datetime import Levenshtein
@@ -117,7 +115,7 @@ class BuildFailure(models.Model): recalc_lev_distance = kwargs.pop('recalc_lev_distance', False) - if self.LEV_DISTANCE == None or recalc_lev_distance: + if self.LEV_DISTANCE is None or recalc_lev_distance: self.LEV_DISTANCE = self.calc_lev_distance() super(BuildFailure, self).save(*args, **kwargs)
Post/parser.py +3 -2
@@ -8,7 +8,8 @@ # # Licensed under the MIT license, see COPYING.MIT for details -import json, re +import json +import re import bleach from Post.models import Build, BuildFailure, ErrorType from Post.validators import clean_link_back
@@ -26,7 +27,7 @@ class Parser: try: jsondata = json.loads(self.data) - except: + except Exception: return { 'error' : 'Invalid json' } # Bleach data going directly into the database so that
Post/purge.py +1 -1
@@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import timedelta from django.utils import timezone import os import sys
Post/templatetags/projecttags.py +0 -4
@@ -1,8 +1,4 @@ -from datetime import datetime, timedelta -import re from django import template -from django.utils import timezone -from django.template.defaultfilters import filesizeformat from Post.validators import clean_link_back register = template.Library()
Post/test.py +12 -1
@@ -1,4 +1,6 @@ -import urllib.request, urllib.parse, urllib.error +import urllib.request +import urllib.parse +import urllib.error import json from unittest.mock import patch from django.core.management import call_command
@@ -389,6 +391,15 @@ class LinkBackSubmissionTest(TestCase): +@override_settings(ALLOWED_HOSTS=["testhost"]) +class PaginationTest(TestCase): + def test_invalid_page_shows_last_page(self): + client = Client(HTTP_HOST="testhost") + for page in ("999", "abc"): + response = client.get("/Errors/Latest/", {"page": page}) + self.assertEqual(response.status_code, 200) + + @patch("Post.management.commands.culldb.time.sleep") class CullDbTest(TestCase): def setUp(self):
Post/views.py +4 -6
@@ -10,19 +10,17 @@ # vi: tabstop=8 expandtab shiftwidth=4 softtabstop=4 from __future__ import division -from django.shortcuts import get_object_or_404 from django.shortcuts import HttpResponse, render from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect -from Post.models import BuildFailure, Build, ErrorType +from Post.models import BuildFailure, ErrorType from Post.parser import Parser from django.conf import settings from Post.createStatistics import Statistics -from django.core.paginator import Paginator, EmptyPage +from django.core.paginator import InvalidPage, Paginator from django.core.exceptions import FieldError, ObjectDoesNotExist, RequestDataTooBig from django.http import JsonResponse from django.db.models import Q -import json import re import urllib from urllib.parse import urlparse
@@ -76,7 +74,7 @@ def addData(request, return_json=False): if return_json: response = JsonResponse(result) else: - if not 'error' in result: + if 'error' not in result: response = HttpResponse("Your entry can be found here: "+result['build_url']) else: response = HttpResponse(result['error'])
@@ -252,7 +250,7 @@ def search(request, mode=results_mode.LATEST, **kwargs): try: build_failures = build_failures.page(page) - except: + except InvalidPage: build_failures = build_failures.page(build_failures.num_pages) context['build_failures'] = build_failures
ruff.toml new file +5 -0
@@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT + +[lint] +# Ruff's classic defaults: bugs, not style. +select = ["E4", "E7", "E9", "F"]
test-data/test-send-error.py +3 -1
@@ -3,7 +3,9 @@ # test/example script for sending data to error-report-web -import urllib.request, urllib.error, urllib.parse +import urllib.request +import urllib.error +import urllib.parse import sys def send_data (url, data_file):
Signature · 1 line
2.56.0