home · contact · privacy
Catch POSTs to undefined targets, expand and refactor tests.
[plomtask] / tests / utils.py
index 3ca0cb90c8c4ef52519d40a45f5f1e92bbfbbdee..d41e7b39ad5fe07abdc701be674d9f81678cd30f 100644 (file)
@@ -5,6 +5,7 @@ from http.client import HTTPConnection
 from urllib.parse import urlencode
 from datetime import datetime
 from os import remove as remove_file
+from typing import Mapping
 from plomtask.db import DatabaseFile, DatabaseConnection
 from plomtask.http import TaskHandler, TaskServer
 
@@ -41,16 +42,26 @@ class TestCaseWithServer(TestCaseWithDB):
         self.server_thread.join()
         super().tearDown()
 
-    def post_to(self, data: dict[str, object], target: str) -> None:
-        """Post form data to target URL."""
-        encoded_form_data = urlencode(data).encode('utf-8')
-        headers = {'Content-Type': 'application/x-www-form-urlencoded',
-                   'Content-Length': str(len(encoded_form_data))}
-        self.conn.request('POST', target,
-                          body=encoded_form_data, headers=headers)
-
     def check_redirect(self, target: str) -> None:
         """Check that self.conn answers with a 302 redirect to target."""
         response = self.conn.getresponse()
         self.assertEqual(response.status, 302)
         self.assertEqual(response.getheader('Location'), target)
+
+    def check_get(self, target: str, expected_code: int) -> None:
+        """Check that a GET to target yields expected_code."""
+        self.conn.request('GET', target)
+        self.assertEqual(self.conn.getresponse().status, expected_code)
+
+    def check_post(self, data: Mapping[str, object], target: str,
+                   expected_code: int, redirect_location: str = '') -> None:
+        """Check that POST of data to target yields expected_code."""
+        encoded_form_data = urlencode(data).encode('utf-8')
+        headers = {'Content-Type': 'application/x-www-form-urlencoded',
+                   'Content-Length': str(len(encoded_form_data))}
+        self.conn.request('POST', target,
+                          body=encoded_form_data, headers=headers)
+        if 302 == expected_code:
+            self.check_redirect(redirect_location)
+        else:
+            self.assertEqual(self.conn.getresponse().status, expected_code)