From df3a2dee7642ff9927ee7a3e7e33fbdde96db6f0 Mon Sep 17 00:00:00 2001 From: Toni Kangas Date: Wed, 16 Jul 2025 22:17:28 +0300 Subject: [PATCH] Add django testcase --- .github/workflows/back-end.yml | 8 ++++ back-end/feedback/tests.py | 68 +++++++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/.github/workflows/back-end.yml b/.github/workflows/back-end.yml index 0d32b69..8f6bcbb 100644 --- a/.github/workflows/back-end.yml +++ b/.github/workflows/back-end.yml @@ -18,6 +18,14 @@ jobs: steps: - name: Checkout uses: actions/checkout@v3 + - uses: actions/setup-python@v2 + with: + python-version: "3.11" + - name: Run django tests + run: | + cd back-end + pip install -r requirements.txt + python manage.py test - name: Test back-end image run: | docker build back-end/ -t back-end diff --git a/back-end/feedback/tests.py b/back-end/feedback/tests.py index 7ce503c..2e6669e 100644 --- a/back-end/feedback/tests.py +++ b/back-end/feedback/tests.py @@ -1,3 +1,69 @@ +import json + from django.test import TestCase -# Create your tests here. +from .models import Question + + +def json_data(**data): + return dict( + data=json.dumps(data), + content_type='application/json', + ) + + +class TestFeedback(TestCase): + def setUp(self): + Question.objects.create( + key="thumbs", + type="thumbs", + choice_text="How are you feeling?", + with_comment=True, + comment_text="Do you want to provide additional comments?", + ) + + def assertOk(self, response): + self.assertEqual( + response.status_code, 200, + f"Expected HTTP 200, got {response.status_code}. " + f"Body: {response.content.decode('utf-8')}") + + def assertCount(self, total): + answers = self.client.get('/question/thumbs/answer').json() + self.assertEqual(len(answers), total) + + def assertSummary(self, positive, negative, empty): + summary = self.client.get('/question/thumbs/summary').json() + self.assertEqual(summary['values']['1'], positive) + self.assertEqual(summary['values']['-1'], negative) + self.assertEqual(summary['values'][''], empty) + + def test_submit_and_summary(self): + self.assertCount(0) + + for value in [1, -1, 1, -1]: + response = self.client.post( + '/question/thumbs/answer', + **json_data(value=value, submit=True)) + self.assertOk(response) + + self.assertCount(4) + self.assertSummary(2, 2, 0) + + id_ = response.json()['id'] + + response = self.client.patch( + f'/answer/{id_}', + **json_data(value=1, submit=True)) + self.assertOk(response) + + self.assertCount(4) + self.assertSummary(3, 1, 0) + + response = self.client.post( + '/question/thumbs/answer', + **json_data()) + self.assertOk(response) + + self.assertCount(5) + self.assertSummary(3, 1, 1)