Implement test simulation runner
authorJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 19:29:23 +0000 (14:29 -0500)
committerJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 19:29:23 +0000 (14:29 -0500)
main.py

diff --git a/main.py b/main.py
index f0857767074f07ba17760381c4367aef989f0beb..4ccb1f9739074861db3e3badcf1a3f4245cdf108 100644 (file)
--- a/main.py
+++ b/main.py
@@ -1,5 +1,6 @@
-import logging
 import json
+import logging
+import random
 import uuid
 
 from typing import Optional
@@ -38,7 +39,10 @@ def stats():
 @app.route("/api/", methods=["GET"])
 @app.route("/api/<path:subpath>", methods=["GET"])
 def api(subpath: Optional[str] = None):
-    app.logger.debug("subpath %s", subpath)
+    app.logger.debug("Handling subpath %s", subpath)
+    # ASSUMPTION: As the app code is actually invoked, this path is being "handled".
+    # If paths failing validation needed to not be incremented then I would move this logic after validation.
+    hits = increment_hits(subpath)
     if subpath is None or len(path_parts := subpath.split("/")) > 6:
         return Response(
             response=json.dumps(
@@ -73,7 +77,6 @@ def api(subpath: Optional[str] = None):
                 )
         else:
             app.logger.debug("Test '%s' not found", test_id)
-    hits = increment_hits(subpath)
     return {"hits": hits}
 
 
@@ -85,4 +88,18 @@ def test(num_requests: int):
     test_id = str(uuid.uuid4())
     paths = ["abc", "def", "ghi"]
     redis_client.sadd(f"test:{test_id}", *paths)
+
+    # ASSUMPTION: The test may be run in the context of the test creation, without using a background worker.
+    try:
+        for req_index in range(num_requests):
+            with app.test_request_context(query_string={"test": test_id}):
+                api(
+                    "/".join(
+                        [random.choice(paths) for i in range(random.randint(1, 6))]
+                    )
+                )
+    except Exception as e:
+        # Report, swallow, and return test ID to user for use in reviewing manual testing behavior.
+        app.logger.exception(e)
+
     return {"test_id": test_id}