Implement test storage and test path validation
authorJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 18:58:29 +0000 (13:58 -0500)
committerJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 18:58:29 +0000 (13:58 -0500)
main.py

diff --git a/main.py b/main.py
index 0900e8f182473295b202a74bf1ea495dfd3db22e..f0857767074f07ba17760381c4367aef989f0beb 100644 (file)
--- a/main.py
+++ b/main.py
@@ -1,10 +1,11 @@
 import logging
 import json
+import uuid
 
 from typing import Optional
 
 import redis
-from flask import Flask, Response
+from flask import Flask, Response, request
 
 redis_client = redis.Redis(host="redis", port=6379, decode_responses=True)
 
@@ -56,7 +57,22 @@ def api(subpath: Optional[str] = None):
             ),
             status=400,
         )
-    # TODO check that the subpath contains no more than 3 unique subpath strings
+    # ASSUMPTION: The test runner will provide the api context to retrieve valid path components from the database
+    test_id = request.args.get("test")
+    if test_id:
+        app.logger.debug("Under test %s", test_id)
+        if test_parts := redis_client.smembers(f"test:{test_id}"):
+            if any([part not in test_parts for part in path_parts]):
+                return Response(
+                    response=json.dumps(
+                        {
+                            "error": f"Invalid API path ({subpath}). All segments in test {test_id} must be in {test_parts}"
+                        }
+                    ),
+                    status=400,
+                )
+        else:
+            app.logger.debug("Test '%s' not found", test_id)
     hits = increment_hits(subpath)
     return {"hits": hits}
 
@@ -64,4 +80,9 @@ def api(subpath: Optional[str] = None):
 @app.route("/test/<int:num_requests>/", methods=["POST"])
 def test(num_requests: int):
     increment_hits("test")
-    return {}
+    # ASSUMPTION: The requirements don't specify if the test runner or the api path under test specify
+    # which 3 path parts are valid, so I will have the test runner generate and store them.
+    test_id = str(uuid.uuid4())
+    paths = ["abc", "def", "ghi"]
+    redis_client.sadd(f"test:{test_id}", *paths)
+    return {"test_id": test_id}