From f6dda53922023e9ea736931b88ab802083542e21 Mon Sep 17 00:00:00 2001 From: Marcus Messer Date: Thu, 26 Nov 2026 10:10:03 +0000 Subject: [PATCH 1/3] Invoke symbolicEqual using the execution role Replace EvaluationFunctionClient, which requires static INVOKER_* access keys, with a small boto3-based invoker that uses the default credential chain (the Lambda execution role). The boto3 client is created lazily so importing the module needs no AWS configuration. Co-Authored-By: Claude Opus 5.5 --- app/docs/dev.md | 4 ++- app/evaluation.py | 65 +++++++++++++++++++++++++++++++++-- app/evaluation_tests.py | 75 +++++++++++++++++++++++++++++++---------- app/requirements.txt | 3 +- 4 files changed, 125 insertions(+), 22 deletions(-) diff --git a/app/docs/dev.md b/app/docs/dev.md index 9631f01..9309657 100644 --- a/app/docs/dev.md +++ b/app/docs/dev.md @@ -1,6 +1,8 @@ # ArraySymbolicEqual -This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called using the experimental EvaluationFunctionClient from the evaluation-function-utils library. +This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, invoked directly through the AWS Lambda API. + +The call uses this function's execution role (boto3's default credentials), so no access keys are needed. The role must allow `lambda:InvokeFunction` on the `symbolicEqual` function. ## Inputs This compares cells using the `symbolicEqual` function. Please consult that function's documentation for details on it's allowable parameters, as the ones provided to this function are fed through as they are. diff --git a/app/evaluation.py b/app/evaluation.py index 551b8b2..f6ad33f 100644 --- a/app/evaluation.py +++ b/app/evaluation.py @@ -1,6 +1,6 @@ -import re +import json -from evaluation_function_utils.client import EvaluationFunctionClient +import boto3 from evaluation_function_utils.errors import EvaluationException try: @@ -8,7 +8,66 @@ except ImportError: from shape import shape_feedback -client = EvaluationFunctionClient(env_path=".env") + +class EvaluationFunctionInvoker: + """ + Invokes other deployed evaluation functions via the AWS Lambda API. + + Credentials come from boto3's default chain, which on Lambda is the + function's execution role. That role needs lambda:InvokeFunction on the + functions being called. No access keys are read or required. + """ + + def __init__(self): + self._client = None + + @property + def lambda_client(self): + # Created lazily so importing this module needs no AWS config. + if self._client is None: + self._client = boto3.client("lambda") + return self._client + + def invoke(self, name, response, answer, params=None): + payload = json.dumps({ + "headers": {"command": "eval"}, + "body": { + "response": response, + "answer": answer, + "params": params or {}, + }, + }) + + res = self.lambda_client.invoke(FunctionName=name, + Payload=payload, + InvocationType="RequestResponse") + + if res.get("StatusCode") != 200 or "FunctionError" in res: + raise RuntimeError( + f"{name} invocation failed: StatusCode={res.get('StatusCode')}, " + f"FunctionError={res.get('FunctionError')}") + + decoded_str = res["Payload"].read().decode("utf-8") + try: + decoded = json.loads(decoded_str) + except ValueError: + raise EvaluationException( + f"Payload response from the {name} function could not be parsed.", + raw_response=decoded_str) + + # Re-raise evaluation errors as if the function was run locally. + if "error" in decoded: + raise EvaluationException(**decoded["error"]) + + if "result" in decoded: + return decoded["result"] + + raise EvaluationException( + f"The {name} evaluation function did not return an error or a result.", + raw_response=decoded) + + +client = EvaluationFunctionInvoker() def grade_single_cell(res, ans, params): diff --git a/app/evaluation_tests.py b/app/evaluation_tests.py index eab13ae..af27a0c 100644 --- a/app/evaluation_tests.py +++ b/app/evaluation_tests.py @@ -1,26 +1,67 @@ +import io +import json import unittest from unittest import mock -from evaluation_function_utils.client import MissingCredentials +try: + from . import evaluation +except ImportError: + import evaluation +evaluation_function = evaluation.evaluation_function -def import_evaluation(): - try: - from . import evaluation - except ImportError: - import evaluation - return evaluation +class TestEvaluationFunctionInvoker(unittest.TestCase): + """Tests for invoking other functions with the execution role.""" -# The real client needs AWS credentials on creation. Without them, import -# with a mock client so the tests below (which mock the client) can still run. -try: - evaluation = import_evaluation() -except MissingCredentials: - with mock.patch("evaluation_function_utils.client.EvaluationFunctionClient"): - evaluation = import_evaluation() + def make_invoker(self, payload, **extra): + lambda_client = mock.Mock() + lambda_client.invoke.return_value = { + "StatusCode": 200, + "Payload": io.BytesIO(json.dumps(payload).encode("utf-8")), + **extra, + } + invoker = evaluation.EvaluationFunctionInvoker() + invoker._client = lambda_client + return invoker, lambda_client -evaluation_function = evaluation.evaluation_function + def test_import_does_not_create_boto3_client(self): + with mock.patch.object(evaluation.boto3, "client") as boto3_client: + evaluation.EvaluationFunctionInvoker() + boto3_client.assert_not_called() + + def test_uses_default_credentials(self): + with mock.patch.object(evaluation.boto3, "client") as boto3_client: + evaluation.EvaluationFunctionInvoker().lambda_client + # No explicit access keys: boto3 falls back to the execution role. + boto3_client.assert_called_once_with("lambda") + + def test_returns_result(self): + invoker, lambda_client = self.make_invoker({"result": {"is_correct": True}}) + + result = invoker.invoke("symbolicEqual", "a", "a", params={"x": 1}) + + self.assertEqual(result, {"is_correct": True}) + kwargs = lambda_client.invoke.call_args.kwargs + self.assertEqual(kwargs["FunctionName"], "symbolicEqual") + self.assertEqual(json.loads(kwargs["Payload"]), { + "headers": {"command": "eval"}, + "body": {"response": "a", "answer": "a", "params": {"x": 1}}, + }) + + def test_error_raises_evaluation_exception(self): + invoker, _ = self.make_invoker({"error": {"message": "parse failed"}}) + + with self.assertRaises(evaluation.EvaluationException) as ctx: + invoker.invoke("symbolicEqual", "a", "a") + self.assertEqual(ctx.exception.message, "parse failed") + + def test_function_error_raises(self): + invoker, _ = self.make_invoker({"errorMessage": "boom"}, + FunctionError="Unhandled") + + with self.assertRaises(RuntimeError): + invoker.invoke("symbolicEqual", "a", "a") class TestEvaluationFunction(unittest.TestCase): @@ -111,8 +152,8 @@ def test_answer_not_list(self): evaluation_function(["a"], "a", {}) """ - NOTE: This function was converted to use the experimental - EvaluationFunctionClient which doesn't support testing yet. + NOTE: These tests call the deployed symbolicEqual function, so they + can't run in CI without AWS access. def test_vector_incorrect(self): response = ["a + b - a", "2 + c", "d"] diff --git a/app/requirements.txt b/app/requirements.txt index 7664e06..a7d3515 100755 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -1,2 +1,3 @@ numpy -evaluation-function-utils \ No newline at end of file +boto3 +evaluation-function-utils From b60c8cbfc35da10ebee97346d878caee09dc10af Mon Sep 17 00:00:00 2001 From: Marcus Messer Date: Thu, 26 Nov 2026 10:20:41 +0000 Subject: [PATCH 2/3] Call symbolicEqual through the evaluation function gateway Switch from invoking via the Lambda API to an HTTPS POST to the public evaluation function gateway, so no AWS credentials or IAM permissions are needed. The gateway base URL comes from EVALUATION_FUNCTION_GATEWAY_URL, and the -staging/-dev suffix is taken from this function's own name so calls stay within the same environment. Co-Authored-By: Claude Opus 5.5 --- app/docs/dev.md | 4 +- app/evaluation.py | 89 +++++++++++++++++++++++---------------- app/evaluation_tests.py | 93 ++++++++++++++++++++++++----------------- app/requirements.txt | 1 - 4 files changed, 110 insertions(+), 77 deletions(-) diff --git a/app/docs/dev.md b/app/docs/dev.md index 9309657..63a73ac 100644 --- a/app/docs/dev.md +++ b/app/docs/dev.md @@ -1,8 +1,8 @@ # ArraySymbolicEqual -This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, invoked directly through the AWS Lambda API. +This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called over HTTPS through the evaluation function gateway. -The call uses this function's execution role (boto3's default credentials), so no access keys are needed. The role must allow `lambda:InvokeFunction` on the `symbolicEqual` function. +The gateway base URL is read from the `EVALUATION_FUNCTION_GATEWAY_URL` environment variable (e.g. `https://.execute-api.eu-west-2.amazonaws.com/default`), which must be set on the deployed function. Calls stay in the same environment: if this function's name ends in `-staging` or `-dev`, the same suffix is added to `symbolicEqual`. No AWS credentials or IAM permissions are needed. ## Inputs This compares cells using the `symbolicEqual` function. Please consult that function's documentation for details on it's allowable parameters, as the ones provided to this function are fed through as they are. diff --git a/app/evaluation.py b/app/evaluation.py index f6ad33f..f934694 100644 --- a/app/evaluation.py +++ b/app/evaluation.py @@ -1,6 +1,8 @@ import json +import os +import urllib.error +import urllib.request -import boto3 from evaluation_function_utils.errors import EvaluationException try: @@ -8,51 +10,68 @@ except ImportError: from shape import shape_feedback +# Base URL of the evaluation function gateway, e.g. +# https://.execute-api.eu-west-2.amazonaws.com/default +GATEWAY_URL_ENV = "EVALUATION_FUNCTION_GATEWAY_URL" + +# API Gateway HTTP APIs time out after 30 seconds. +REQUEST_TIMEOUT_SECONDS = 30 -class EvaluationFunctionInvoker: - """ - Invokes other deployed evaluation functions via the AWS Lambda API. - Credentials come from boto3's default chain, which on Lambda is the - function's execution role. That role needs lambda:InvokeFunction on the - functions being called. No access keys are read or required. +def environment_suffix(): """ + Suffix the backend adds to function names outside production + ("-staging" / "-dev"), taken from this function's own name so calls stay + within the same environment. + """ + own_name = os.getenv("AWS_LAMBDA_FUNCTION_NAME", "") + for suffix in ("-staging", "-dev"): + if own_name.endswith(suffix): + return suffix + return "" + - def __init__(self): - self._client = None +class EvaluationFunctionInvoker: + """ + Calls other deployed evaluation functions over HTTPS through the public + evaluation function gateway, the same way any other client does. No AWS + credentials or IAM permissions are needed. + """ - @property - def lambda_client(self): - # Created lazily so importing this module needs no AWS config. - if self._client is None: - self._client = boto3.client("lambda") - return self._client + def gateway_url(self): + url = os.getenv(GATEWAY_URL_ENV) + if not url: + raise RuntimeError(f"{GATEWAY_URL_ENV} is not set") + return url.rstrip("/") def invoke(self, name, response, answer, params=None): - payload = json.dumps({ - "headers": {"command": "eval"}, - "body": { - "response": response, - "answer": answer, - "params": params or {}, - }, - }) - - res = self.lambda_client.invoke(FunctionName=name, - Payload=payload, - InvocationType="RequestResponse") - - if res.get("StatusCode") != 200 or "FunctionError" in res: - raise RuntimeError( - f"{name} invocation failed: StatusCode={res.get('StatusCode')}, " - f"FunctionError={res.get('FunctionError')}") - - decoded_str = res["Payload"].read().decode("utf-8") + url = f"{self.gateway_url()}/{name}{environment_suffix()}" + data = json.dumps({ + "response": response, + "answer": answer, + "params": params or {}, + }).encode("utf-8") + request = urllib.request.Request( + url, + data=data, + method="POST", + headers={"Content-Type": "application/json", "command": "eval"}, + ) + + try: + with urllib.request.urlopen( + request, timeout=REQUEST_TIMEOUT_SECONDS) as res: + decoded_str = res.read().decode("utf-8") + except urllib.error.HTTPError as e: + raise RuntimeError(f"{url} returned HTTP {e.code}") from e + except urllib.error.URLError as e: + raise RuntimeError(f"Request to {url} failed: {e.reason}") from e + try: decoded = json.loads(decoded_str) except ValueError: raise EvaluationException( - f"Payload response from the {name} function could not be parsed.", + f"Response from the {name} function could not be parsed.", raw_response=decoded_str) # Re-raise evaluation errors as if the function was run locally. diff --git a/app/evaluation_tests.py b/app/evaluation_tests.py index af27a0c..ce0524d 100644 --- a/app/evaluation_tests.py +++ b/app/evaluation_tests.py @@ -1,5 +1,6 @@ import io import json +import os import unittest from unittest import mock @@ -11,57 +12,71 @@ evaluation_function = evaluation.evaluation_function +GATEWAY = "https://gateway.example.com/default" + + class TestEvaluationFunctionInvoker(unittest.TestCase): - """Tests for invoking other functions with the execution role.""" - - def make_invoker(self, payload, **extra): - lambda_client = mock.Mock() - lambda_client.invoke.return_value = { - "StatusCode": 200, - "Payload": io.BytesIO(json.dumps(payload).encode("utf-8")), - **extra, - } - invoker = evaluation.EvaluationFunctionInvoker() - invoker._client = lambda_client - return invoker, lambda_client - - def test_import_does_not_create_boto3_client(self): - with mock.patch.object(evaluation.boto3, "client") as boto3_client: - evaluation.EvaluationFunctionInvoker() - boto3_client.assert_not_called() - - def test_uses_default_credentials(self): - with mock.patch.object(evaluation.boto3, "client") as boto3_client: - evaluation.EvaluationFunctionInvoker().lambda_client - # No explicit access keys: boto3 falls back to the execution role. - boto3_client.assert_called_once_with("lambda") + """Tests for calling other functions through the gateway.""" - def test_returns_result(self): - invoker, lambda_client = self.make_invoker({"result": {"is_correct": True}}) + def setUp(self): + self.invoker = evaluation.EvaluationFunctionInvoker() + + def call(self, body, function_name="arraySymbolicEqual", gateway=GATEWAY): + """Invoke with a mocked HTTP response; returns (result, request).""" + env = {"AWS_LAMBDA_FUNCTION_NAME": function_name} + if gateway is not None: + env[evaluation.GATEWAY_URL_ENV] = gateway + + res = mock.MagicMock() + res.read.return_value = json.dumps(body).encode("utf-8") + res.__enter__.return_value = res - result = invoker.invoke("symbolicEqual", "a", "a", params={"x": 1}) + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(evaluation.urllib.request, "urlopen", + return_value=res) as urlopen: + result = self.invoker.invoke("symbolicEqual", "a", "a", + params={"x": 1}) + return result, urlopen.call_args.args[0] + + def test_returns_result(self): + result, request = self.call( + {"command": "eval", "result": {"is_correct": True}}) self.assertEqual(result, {"is_correct": True}) - kwargs = lambda_client.invoke.call_args.kwargs - self.assertEqual(kwargs["FunctionName"], "symbolicEqual") - self.assertEqual(json.loads(kwargs["Payload"]), { - "headers": {"command": "eval"}, - "body": {"response": "a", "answer": "a", "params": {"x": 1}}, + self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual") + self.assertEqual(request.get_method(), "POST") + self.assertEqual(request.get_header("Command"), "eval") + self.assertEqual(json.loads(request.data), { + "response": "a", "answer": "a", "params": {"x": 1}, }) - def test_error_raises_evaluation_exception(self): - invoker, _ = self.make_invoker({"error": {"message": "parse failed"}}) + def test_stays_in_own_environment(self): + _, request = self.call({"result": {}}, + function_name="arraySymbolicEqual-staging", + gateway=GATEWAY + "/") + self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual-staging") + _, request = self.call({"result": {}}, + function_name="arraySymbolicEqual-dev") + self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual-dev") + + def test_error_raises_evaluation_exception(self): with self.assertRaises(evaluation.EvaluationException) as ctx: - invoker.invoke("symbolicEqual", "a", "a") + self.call({"error": {"message": "parse failed"}}) self.assertEqual(ctx.exception.message, "parse failed") - def test_function_error_raises(self): - invoker, _ = self.make_invoker({"errorMessage": "boom"}, - FunctionError="Unhandled") - + def test_missing_gateway_url_raises(self): with self.assertRaises(RuntimeError): - invoker.invoke("symbolicEqual", "a", "a") + self.call({"result": {}}, gateway=None) + + def test_http_error_raises(self): + error = evaluation.urllib.error.HTTPError( + GATEWAY, 500, "Internal Server Error", {}, io.BytesIO(b"")) + with mock.patch.dict(os.environ, {evaluation.GATEWAY_URL_ENV: GATEWAY}), \ + mock.patch.object(evaluation.urllib.request, "urlopen", + side_effect=error): + with self.assertRaises(RuntimeError): + self.invoker.invoke("symbolicEqual", "a", "a") class TestEvaluationFunction(unittest.TestCase): diff --git a/app/requirements.txt b/app/requirements.txt index a7d3515..286a6f5 100755 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -1,3 +1,2 @@ numpy -boto3 evaluation-function-utils From 6a99ecbd2aff12b47504cb7ba0f97003c6432763 Mon Sep 17 00:00:00 2001 From: Marcus Messer Date: Thu, 26 Nov 2026 10:25:54 +0000 Subject: [PATCH 3/3] Call the symbolicEqual URL from SYMBOLIC_EQUAL_URL as given Drop the gateway base URL and environment suffix logic: the env var now holds the full URL of the function to call. Co-Authored-By: Claude Opus 5.5 --- app/docs/dev.md | 4 +-- app/evaluation.py | 43 ++++++++++--------------------- app/evaluation_tests.py | 57 ++++++++++++++++------------------------- 3 files changed, 37 insertions(+), 67 deletions(-) diff --git a/app/docs/dev.md b/app/docs/dev.md index 63a73ac..4d392a3 100644 --- a/app/docs/dev.md +++ b/app/docs/dev.md @@ -1,8 +1,8 @@ # ArraySymbolicEqual -This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called over HTTPS through the evaluation function gateway. +This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called over HTTPS. -The gateway base URL is read from the `EVALUATION_FUNCTION_GATEWAY_URL` environment variable (e.g. `https://.execute-api.eu-west-2.amazonaws.com/default`), which must be set on the deployed function. Calls stay in the same environment: if this function's name ends in `-staging` or `-dev`, the same suffix is added to `symbolicEqual`. No AWS credentials or IAM permissions are needed. +The full URL of the `symbolicEqual` function to call is read from the `SYMBOLIC_EQUAL_URL` environment variable (e.g. `https://.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual`), which must be set on the deployed function. No AWS credentials or IAM permissions are needed. ## Inputs This compares cells using the `symbolicEqual` function. Please consult that function's documentation for details on it's allowable parameters, as the ones provided to this function are fed through as they are. diff --git a/app/evaluation.py b/app/evaluation.py index f934694..2d73728 100644 --- a/app/evaluation.py +++ b/app/evaluation.py @@ -10,42 +10,21 @@ except ImportError: from shape import shape_feedback -# Base URL of the evaluation function gateway, e.g. -# https://.execute-api.eu-west-2.amazonaws.com/default -GATEWAY_URL_ENV = "EVALUATION_FUNCTION_GATEWAY_URL" +# Full URL of the symbolicEqual function to call, e.g. +# https://.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual +SYMBOLIC_EQUAL_URL_ENV = "SYMBOLIC_EQUAL_URL" # API Gateway HTTP APIs time out after 30 seconds. REQUEST_TIMEOUT_SECONDS = 30 -def environment_suffix(): - """ - Suffix the backend adds to function names outside production - ("-staging" / "-dev"), taken from this function's own name so calls stay - within the same environment. - """ - own_name = os.getenv("AWS_LAMBDA_FUNCTION_NAME", "") - for suffix in ("-staging", "-dev"): - if own_name.endswith(suffix): - return suffix - return "" - - class EvaluationFunctionInvoker: """ - Calls other deployed evaluation functions over HTTPS through the public - evaluation function gateway, the same way any other client does. No AWS - credentials or IAM permissions are needed. + Calls another deployed evaluation function over HTTPS, the same way any + other client does. No AWS credentials or IAM permissions are needed. """ - def gateway_url(self): - url = os.getenv(GATEWAY_URL_ENV) - if not url: - raise RuntimeError(f"{GATEWAY_URL_ENV} is not set") - return url.rstrip("/") - - def invoke(self, name, response, answer, params=None): - url = f"{self.gateway_url()}/{name}{environment_suffix()}" + def invoke(self, url, response, answer, params=None): data = json.dumps({ "response": response, "answer": answer, @@ -71,7 +50,7 @@ def invoke(self, name, response, answer, params=None): decoded = json.loads(decoded_str) except ValueError: raise EvaluationException( - f"Response from the {name} function could not be parsed.", + f"Response from {url} could not be parsed.", raw_response=decoded_str) # Re-raise evaluation errors as if the function was run locally. @@ -82,7 +61,7 @@ def invoke(self, name, response, answer, params=None): return decoded["result"] raise EvaluationException( - f"The {name} evaluation function did not return an error or a result.", + f"{url} did not return an error or a result.", raw_response=decoded) @@ -94,8 +73,12 @@ def grade_single_cell(res, ans, params): Attempt to grade a single cell using the SymbolicEqual function, fallback to a local version if the request fails """ + url = os.getenv(SYMBOLIC_EQUAL_URL_ENV) + if not url: + raise RuntimeError(f"{SYMBOLIC_EQUAL_URL_ENV} is not set") + try: - return client.invoke('symbolicEqual', res, ans, params=params) + return client.invoke(url, res, ans, params=params) except EvaluationException as e: return e.error_dict diff --git a/app/evaluation_tests.py b/app/evaluation_tests.py index ce0524d..c060709 100644 --- a/app/evaluation_tests.py +++ b/app/evaluation_tests.py @@ -12,30 +12,22 @@ evaluation_function = evaluation.evaluation_function -GATEWAY = "https://gateway.example.com/default" +URL = "https://gateway.example.com/default/symbolicEqual" class TestEvaluationFunctionInvoker(unittest.TestCase): - """Tests for calling other functions through the gateway.""" + """Tests for calling another function over HTTPS.""" - def setUp(self): - self.invoker = evaluation.EvaluationFunctionInvoker() - - def call(self, body, function_name="arraySymbolicEqual", gateway=GATEWAY): + def call(self, body): """Invoke with a mocked HTTP response; returns (result, request).""" - env = {"AWS_LAMBDA_FUNCTION_NAME": function_name} - if gateway is not None: - env[evaluation.GATEWAY_URL_ENV] = gateway - res = mock.MagicMock() res.read.return_value = json.dumps(body).encode("utf-8") res.__enter__.return_value = res - with mock.patch.dict(os.environ, env, clear=True), \ - mock.patch.object(evaluation.urllib.request, "urlopen", - return_value=res) as urlopen: - result = self.invoker.invoke("symbolicEqual", "a", "a", - params={"x": 1}) + with mock.patch.object(evaluation.urllib.request, "urlopen", + return_value=res) as urlopen: + result = evaluation.EvaluationFunctionInvoker().invoke( + URL, "a", "a", params={"x": 1}) return result, urlopen.call_args.args[0] def test_returns_result(self): @@ -43,40 +35,30 @@ def test_returns_result(self): {"command": "eval", "result": {"is_correct": True}}) self.assertEqual(result, {"is_correct": True}) - self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual") + self.assertEqual(request.full_url, URL) self.assertEqual(request.get_method(), "POST") self.assertEqual(request.get_header("Command"), "eval") self.assertEqual(json.loads(request.data), { "response": "a", "answer": "a", "params": {"x": 1}, }) - def test_stays_in_own_environment(self): - _, request = self.call({"result": {}}, - function_name="arraySymbolicEqual-staging", - gateway=GATEWAY + "/") - self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual-staging") - - _, request = self.call({"result": {}}, - function_name="arraySymbolicEqual-dev") - self.assertEqual(request.full_url, f"{GATEWAY}/symbolicEqual-dev") - def test_error_raises_evaluation_exception(self): with self.assertRaises(evaluation.EvaluationException) as ctx: self.call({"error": {"message": "parse failed"}}) self.assertEqual(ctx.exception.message, "parse failed") - def test_missing_gateway_url_raises(self): - with self.assertRaises(RuntimeError): - self.call({"result": {}}, gateway=None) - def test_http_error_raises(self): error = evaluation.urllib.error.HTTPError( - GATEWAY, 500, "Internal Server Error", {}, io.BytesIO(b"")) - with mock.patch.dict(os.environ, {evaluation.GATEWAY_URL_ENV: GATEWAY}), \ - mock.patch.object(evaluation.urllib.request, "urlopen", - side_effect=error): + URL, 500, "Internal Server Error", {}, io.BytesIO(b"")) + with mock.patch.object(evaluation.urllib.request, "urlopen", + side_effect=error): + with self.assertRaises(RuntimeError): + evaluation.EvaluationFunctionInvoker().invoke(URL, "a", "a") + + def test_missing_url_raises(self): + with mock.patch.dict(os.environ, {}, clear=True): with self.assertRaises(RuntimeError): - self.invoker.invoke("symbolicEqual", "a", "a") + evaluation.grade_single_cell("a", "a", {}) class TestEvaluationFunction(unittest.TestCase): @@ -103,6 +85,11 @@ def setUp(self): self.client = patcher.start() self.addCleanup(patcher.stop) + env = mock.patch.dict(os.environ, + {evaluation.SYMBOLIC_EQUAL_URL_ENV: URL}) + env.start() + self.addCleanup(env.stop) + def assert_size_feedback(self, response, answer, feedback): result = evaluation_function(response, answer, {})