]> git.scottworley.com Git - paperdoorknob/commitdiff
Extract fake webserver
authorScott Worley <scottworley@scottworley.com>
Tue, 19 Dec 2023 08:36:35 +0000 (00:36 -0800)
committerScott Worley <scottworley@scottworley.com>
Wed, 20 Dec 2023 01:37:10 +0000 (17:37 -0800)
paperdoorknob_test.py
testing/__init__.py [new file with mode: 0644]
testing/fakeserver.py [new file with mode: 0644]

index 9ea877daa77ffdbe27469abaefc32ace1b493d4a..c8968108472b675bb127bd29a003064de83650c8 100644 (file)
 import unittest
 import io
 import subprocess
 import unittest
 import io
 import subprocess
-import threading
-from http.server import BaseHTTPRequestHandler, HTTPServer
 import requests
 import requests_cache
 import paperdoorknob
 import requests
 import requests_cache
 import paperdoorknob
+from testing.fakeserver import FakeGlowficServer
 
 TIMEOUT = 8
 
 
 
 TIMEOUT = 8
 
 
-class FakeGlowficHTTPRequestHandler(BaseHTTPRequestHandler):
-
-    def _notify_test(self) -> None:
-        raise NotImplementedError()
-
-    def _response_code(self) -> int:
-        if self.path == "/not_found":
-            return 404
-        if self.path == "/server_error":
-            return 500
-        return 200
-
-    def do_GET(self) -> None:
-        body = b'''<html>
-  <body>
-    <div class="post-container post-post">
-      <div class="post-edit-box">We don't want edit boxes</div>
-      This is glowfic
-      <div class="post-footer">We don't want footers</div>
-    </div>
-    <div class="flat-post-replies">
-      <div class="post-container post-reply">
-        <div class="post-edit-box">We don't want edit boxes</div>
-        You <em>sure</em>?
-        <div class="post-footer">We don't want footers</div>
-      </div>
-      <div class="post-container post-reply">
-        Pretty sure.
-      </div>
-    </div>
-  </body>
-</html>'''
-        self.send_response(self._response_code())
-        self.send_header("Content-type", "text/html")
-        self.send_header("Content-Length", str(len(body)))
-        self.end_headers()
-        self.wfile.write(body)
-        self._notify_test()
-
-
 class TestFetch(unittest.TestCase):
 class TestFetch(unittest.TestCase):
-    def _port(self) -> int:
-        port = self._web_server.socket.getsockname()[1]
-        assert isinstance(port, int)
-        return port
-
-    def _count_request(self) -> None:
-        self._request_counter += 1
-
     def setUp(self) -> None:
     def setUp(self) -> None:
-        self._request_counter = 0
-        handler = type("Handler", (FakeGlowficHTTPRequestHandler,), {
-                       '_notify_test': lambda _: self._count_request()})
-        self._web_server = HTTPServer(('', 0), handler)
-        self._thread = threading.Thread(target=self._web_server.serve_forever)
-        self._thread.start()
-
-    def tearDown(self) -> None:
-        self._web_server.shutdown()
-        self._thread.join()
-        self._web_server.server_close()
+        self._server = self.enterContext(FakeGlowficServer())
+        self._port = self._server.port()
 
     def testFetch(self) -> None:
         with requests.session() as s:
 
     def testFetch(self) -> None:
         with requests.session() as s:
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 1)
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 2)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 1)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 2)
 
     def testFetchCaching(self) -> None:
         with requests_cache.CachedSession() as s:
 
     def testFetchCaching(self) -> None:
         with requests_cache.CachedSession() as s:
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 1)
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 1)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 1)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 1)
 
     def testFetchPersistentCaching(self) -> None:
         with requests_cache.CachedSession() as s:
 
     def testFetchPersistentCaching(self) -> None:
         with requests_cache.CachedSession() as s:
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 1)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 1)
         with requests_cache.CachedSession() as s:
         with requests_cache.CachedSession() as s:
-            paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
-            self.assertEqual(self._request_counter, 1)
+            paperdoorknob.fetch(f"http://localhost:{self._port}", s, TIMEOUT)
+            self.assertEqual(self._server.request_count(), 1)
 
     def testReplies(self) -> None:
         with requests.session() as s:
             replies = paperdoorknob.replies(
                 paperdoorknob.clean(
                     paperdoorknob.fetch(
 
     def testReplies(self) -> None:
         with requests.session() as s:
             replies = paperdoorknob.replies(
                 paperdoorknob.clean(
                     paperdoorknob.fetch(
-                        f"http://localhost:{self._port()}",
+                        f"http://localhost:{self._port}",
                         s,
                         TIMEOUT)))
             self.assertEqual([r.text.strip() for r in replies],
                         s,
                         TIMEOUT)))
             self.assertEqual([r.text.strip() for r in replies],
@@ -116,16 +58,16 @@ class TestFetch(unittest.TestCase):
         with requests.session() as s:
             with self.assertRaises(requests.HTTPError):
                 paperdoorknob.fetch(
         with requests.session() as s:
             with self.assertRaises(requests.HTTPError):
                 paperdoorknob.fetch(
-                    f"http://localhost:{self._port()}/not_found", s, TIMEOUT)
+                    f"http://localhost:{self._port}/not_found", s, TIMEOUT)
             with self.assertRaises(requests.HTTPError):
                 paperdoorknob.fetch(
             with self.assertRaises(requests.HTTPError):
                 paperdoorknob.fetch(
-                    f"http://localhost:{self._port()}/server_error", s, TIMEOUT)
+                    f"http://localhost:{self._port}/server_error", s, TIMEOUT)
 
     def testProcess(self) -> None:
         with requests.session() as s:
             buf = io.BytesIO()
             paperdoorknob.process(
 
     def testProcess(self) -> None:
         with requests.session() as s:
             buf = io.BytesIO()
             paperdoorknob.process(
-                f"http://localhost:{self._port()}",
+                f"http://localhost:{self._port}",
                 s,
                 TIMEOUT,
                 buf,
                 s,
                 TIMEOUT,
                 buf,
@@ -142,11 +84,7 @@ Pretty sure.
         with requests.session() as s:
             with open("test.tex", 'wb') as out:
                 paperdoorknob.process(
         with requests.session() as s:
             with open("test.tex", 'wb') as out:
                 paperdoorknob.process(
-                    f"http://localhost:{self._port()}",
-                    s,
-                    TIMEOUT,
-                    out,
-                    'pandoc')
+                    f"http://localhost:{self._port}", s, TIMEOUT, out, 'pandoc')
             subprocess.run(['pdflatex', 'test.tex'],
                            stdin=subprocess.DEVNULL, check=True)
 
             subprocess.run(['pdflatex', 'test.tex'],
                            stdin=subprocess.DEVNULL, check=True)
 
diff --git a/testing/__init__.py b/testing/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/testing/fakeserver.py b/testing/fakeserver.py
new file mode 100644 (file)
index 0000000..2ed8149
--- /dev/null
@@ -0,0 +1,72 @@
+from typing import Any, Self
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+
+class FakeGlowficHTTPRequestHandler(BaseHTTPRequestHandler):
+
+    def _notify_server(self) -> None:
+        raise NotImplementedError()
+
+    def _response_code(self) -> int:
+        if self.path == "/not_found":
+            return 404
+        if self.path == "/server_error":
+            return 500
+        return 200
+
+    def do_GET(self) -> None:
+        body = b'''<html>
+  <body>
+    <div class="post-container post-post">
+      <div class="post-edit-box">We don't want edit boxes</div>
+      This is glowfic
+      <div class="post-footer">We don't want footers</div>
+    </div>
+    <div class="flat-post-replies">
+      <div class="post-container post-reply">
+        <div class="post-edit-box">We don't want edit boxes</div>
+        You <em>sure</em>?
+        <div class="post-footer">We don't want footers</div>
+      </div>
+      <div class="post-container post-reply">
+        Pretty sure.
+      </div>
+    </div>
+  </body>
+</html>'''
+        self.send_response(self._response_code())
+        self.send_header("Content-type", "text/html")
+        self.send_header("Content-Length", str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+        self._notify_server()
+
+
+class FakeGlowficServer():
+    def __init__(self) -> None:
+        self._request_counter = 0
+        handler = type("Handler", (FakeGlowficHTTPRequestHandler,), {
+                       '_notify_server': lambda _: self._count_request()})
+        self._web_server = HTTPServer(('', 0), handler)
+        self._thread = threading.Thread(target=self._web_server.serve_forever)
+
+    def __enter__(self) -> Self:
+        self._thread.start()
+        return self
+
+    def __exit__(self, *_: Any) -> None:
+        self._web_server.shutdown()
+        self._thread.join()
+        self._web_server.server_close()
+
+    def _count_request(self) -> None:
+        self._request_counter += 1
+
+    def port(self) -> int:
+        p = self._web_server.socket.getsockname()[1]
+        assert isinstance(p, int)
+        return p
+
+    def request_count(self) -> int:
+        return self._request_counter