generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 189
test(http_request): add integration test for http_request tool #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+156
−6
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| """Integration tests for HTTP request functionality using Strands Agent. | ||
|
|
||
| This module contains integration tests that verify the HTTP request tool's ability | ||
| to handle various HTTP methods (GET, POST, PUT) and operations like downloading | ||
| files and interacting with AWS S3 services. | ||
| """ | ||
|
|
||
| import json | ||
| import os | ||
| import socket | ||
| import threading | ||
| import time | ||
| from http.server import BaseHTTPRequestHandler, HTTPServer | ||
|
|
||
| import pytest | ||
| from strands import Agent | ||
| from strands_tools import http_request | ||
|
|
||
| os.environ["BYPASS_TOOL_CONSENT"] = "true" | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def agent(): | ||
| """Create an Agent instance configured with HTTP request tool.""" | ||
| return Agent(tools=[http_request]) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def http_server(): | ||
| """Create a local HTTP server for testing.""" | ||
| host = "localhost" | ||
| port = _find_free_port() | ||
| server = HTTPServer((host, port), LocalHttpRequestHandler) | ||
|
|
||
| thread = threading.Thread(target=server.serve_forever, daemon=True) | ||
| thread.start() | ||
|
|
||
| if not _wait_for_server(host, port): | ||
| server.shutdown() | ||
| pytest.fail(f"Server failed to start on {host}:{port}") | ||
|
|
||
| server.test_port = port | ||
| yield server | ||
|
|
||
| server.shutdown() | ||
| server.server_close() | ||
|
|
||
|
|
||
| def test_get_http_request(agent, http_server): | ||
| """Test GET request functionality using local test server.""" | ||
| port = http_server.test_port | ||
| response = agent(f"Send a GET request to http://localhost:{port}/repo and show me the number of stars") | ||
| assert "stars" in str(response).lower() and "99999" in str(response).lower() | ||
|
|
||
|
|
||
| def test_post_http_request(agent, http_server): | ||
| """Test POST request functionality using local test server.""" | ||
| port = http_server.test_port | ||
| response = agent(f'Send a POST request to http://localhost:{port} with JSON body {{"foo": "bar"}}') | ||
| assert "foo" in str(response).lower() and "bar" in str(response).lower() | ||
|
|
||
|
|
||
| def test_update_http_request(agent, http_server): | ||
| """Test PUT request functionality using local test server.""" | ||
| port = http_server.test_port | ||
| response = agent(f'Send a PUT request to http://localhost:{port} with JSON body {{"update": true}}') | ||
| assert "update" in str(response).lower() and "true" in str(response).lower() | ||
|
|
||
|
|
||
| def test_download_http_request(agent): | ||
| """Verify that the agent can use tool to download a file from a URL""" | ||
| response = agent("Download the PNG logo from https://www.python.org/static/community_logos/python-logo.png") | ||
| assert "successfully" in str(response).lower() or "image" in str(response).lower(), str(response) | ||
|
|
||
|
|
||
| @pytest.mark.skipif("AWS_ACCESS_KEY_ID" not in os.environ, reason="ACCESS_KEY_ID environment variable missing") | ||
| def test_list_s3_bucket_http_request(agent): | ||
| """Test AWS S3 bucket listing functionality via HTTP requests.""" | ||
| region = os.getenv("AWS_REGION", "us-east-1") | ||
| response = agent(f"List all S3 buckets in region {region}.") | ||
| assert "s3 buckets" in str(response).lower(), str(response) | ||
|
|
||
|
|
||
| # --Helper function & Class-- | ||
|
|
||
|
|
||
| class LocalHttpRequestHandler(BaseHTTPRequestHandler): | ||
| """A simplified HTTP request handler for local testing.""" | ||
|
|
||
| def _send_json_response(self, status_code: int, payload: dict) -> None: | ||
| """Send a JSON response with the given status and payload.""" | ||
| self.send_response(status_code) | ||
| self.send_header("Content-type", "application/json") | ||
| self.end_headers() | ||
| self.wfile.write(json.dumps(payload).encode("utf-8")) | ||
|
|
||
| def do_GET(self) -> None: | ||
| """Handle GET requests.""" | ||
| if self.path == "/repo": | ||
| response_data = {"name": "sdk-python", "stars": 99999} | ||
| self._send_json_response(200, response_data) | ||
| else: | ||
| self._send_json_response(404, {"error": "Not Found"}) | ||
|
|
||
| def _handle_request_with_body(self, success_key: str) -> None: | ||
| """Handle requests with a JSON body (for POST, PUT, etc.).""" | ||
| try: | ||
| content_length = int(self.headers.get("Content-Length", 0)) | ||
| body = self.rfile.read(content_length) | ||
| data = json.loads(body) if body else {} | ||
| response_payload = {success_key: data, "status": "success"} | ||
| self._send_json_response(200, response_payload) | ||
| except json.JSONDecodeError: | ||
| self._send_json_response(400, {"error": "Invalid JSON"}) | ||
| except Exception as e: | ||
| self._send_json_response(500, {"error": str(e)}) | ||
|
|
||
| def do_POST(self) -> None: | ||
| """Handle POST requests by reusing the body handler.""" | ||
| self._handle_request_with_body("received_data") | ||
|
|
||
| def do_PUT(self) -> None: | ||
| """Handle PUT requests by reusing the body handler.""" | ||
| self._handle_request_with_body("updated_data") | ||
|
|
||
|
|
||
| def _find_free_port() -> int: | ||
| """Find and return an available port.""" | ||
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | ||
| s.bind(("", 0)) | ||
| return s.getsockname()[1] | ||
|
|
||
|
|
||
| def _wait_for_server(host: str, port: int, timeout: int = 5) -> bool: | ||
| """Wait for the local test server to become available.""" | ||
| start_time = time.monotonic() | ||
| while time.monotonic() - start_time < timeout: | ||
| try: | ||
| with socket.create_connection((host, port), timeout=0.1): | ||
| return True | ||
| except (ConnectionRefusedError, socket.timeout): | ||
| time.sleep(0.1) | ||
| return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.