home · contact · privacy
Extend POST tests, and handling of missing form data.
[plomtask] / tests / utils.py
index cd0c457c0b0affb0034f5e81de2bc5d4a6139263..3ca0cb90c8c4ef52519d40a45f5f1e92bbfbbdee 100644 (file)
@@ -1,6 +1,8 @@
 """Shared test utilities."""
 from unittest import TestCase
 from threading import Thread
+from http.client import HTTPConnection
+from urllib.parse import urlencode
 from datetime import datetime
 from os import remove as remove_file
 from plomtask.db import DatabaseFile, DatabaseConnection
@@ -10,13 +12,13 @@ from plomtask.http import TaskHandler, TaskServer
 class TestCaseWithDB(TestCase):
     """Module tests not requiring DB setup."""
 
-    def setUp(self):
+    def setUp(self) -> None:
         timestamp = datetime.now().timestamp()
         self.db_file = DatabaseFile(f'test_db:{timestamp}')
         self.db_file.remake()
         self.db_conn = DatabaseConnection(self.db_file)
 
-    def tearDown(self):
+    def tearDown(self) -> None:
         self.db_conn.close()
         remove_file(self.db_file.path)
 
@@ -24,15 +26,31 @@ class TestCaseWithDB(TestCase):
 class TestCaseWithServer(TestCaseWithDB):
     """Module tests against our HTTP server/handler (and database)."""
 
-    def setUp(self):
+    def setUp(self) -> None:
         super().setUp()
         self.httpd = TaskServer(self.db_file, ('localhost', 0), TaskHandler)
         self.server_thread = Thread(target=self.httpd.serve_forever)
         self.server_thread.daemon = True
         self.server_thread.start()
+        self.conn = HTTPConnection(str(self.httpd.server_address[0]),
+                                   self.httpd.server_address[1])
 
-    def tearDown(self):
+    def tearDown(self) -> None:
         self.httpd.shutdown()
         self.httpd.server_close()
         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)