-
Notifications
You must be signed in to change notification settings - Fork 13
Remove requests as a dependency
#478
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
Merged
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8551cb6
Create and use the requests replacement library
bitterpanda63 fc66e43
Move requests to dev deps
bitterpanda63 8f3e8d2
Add a timeout 5 mock url
bitterpanda63 66aa236
add gzip support
bitterpanda63 5889c8a
catch http errors and give them as a code
bitterpanda63 f43a0d5
Update test cases for http_api
bitterpanda63 567c58c
to_api_response, improve logging
bitterpanda63 2b8b8db
improve logging & test for timeouts
bitterpanda63 21b97b7
Update test casess
bitterpanda63 fbfe311
run mock server during unit tests
bitterpanda63 1f66b96
Update the if headers is not None
bitterpanda63 8405bc9
remove the default values for both get & post
bitterpanda63 cf0c6e2
move mock core to localhost 5050
bitterpanda63 9d76153
add class to debug logs
bitterpanda63 f969259
revert change of port in end2end and do change of port in unit-test.yml
bitterpanda63 c6540a2
create a TimeoutExceeded error
bitterpanda63 c22fe7a
remove default timeout from make_request as well
bitterpanda63 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
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
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
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
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 |
|---|---|---|
| @@ -1,72 +1,60 @@ | ||
| import pytest | ||
| import requests | ||
| from unittest.mock import patch | ||
| from aikido_zen.background_process.api.http_api import ( | ||
| ReportingApiHTTP, | ||
| ) # Replace with the actual module name | ||
| from aikido_zen.background_process.api.http_api import ReportingApiHTTP | ||
|
|
||
| # Sample event data for testing | ||
| sample_event = {"event_type": "test_event", "data": {"key": "value"}} | ||
|
|
||
|
|
||
| def test_report_data_401_code(monkeypatch): | ||
| # Create an instance of ReportingApiHTTP | ||
| api = ReportingApiHTTP("http://mocked-url.com/") | ||
| def test_report_data_401_code(): | ||
| api = ReportingApiHTTP("https://guard.aikido.dev/") | ||
|
|
||
| # Mock the requests.post method to return a successful response | ||
| class MockResponse: | ||
| def __init__(self, json_data, status_code): | ||
| self.json_data = json_data | ||
| self.status_code = status_code | ||
| response = api.report("wrong_token", sample_event, 5) | ||
|
|
||
| def json(self): | ||
| return self.json_data | ||
|
|
||
| def mock_post(url, json, timeout, headers): | ||
| return MockResponse({"success": False}, 401) | ||
|
|
||
| monkeypatch.setattr(requests, "post", mock_post) | ||
|
|
||
| # Call the report method | ||
| response = api.report("mocked_token", sample_event, 5) | ||
|
|
||
| # Assert the response | ||
| assert response == {"success": False, "error": "invalid_token"} | ||
|
|
||
|
|
||
| def test_report_connection_error(monkeypatch): | ||
| # Create an instance of ReportingApiHTTP | ||
| api = ReportingApiHTTP("http://mocked-url.com/") | ||
|
|
||
| # Mock the requests.post method to raise a ConnectionError | ||
| monkeypatch.setattr( | ||
| requests, | ||
| "post", | ||
| lambda *args, **kwargs: (_ for _ in ()).throw( | ||
| requests.exceptions.ConnectionError | ||
| ), | ||
| ) | ||
| def test_report_local_valid(): | ||
| api = ReportingApiHTTP("http://localhost:5050/") | ||
|
|
||
| # Call the report method | ||
| response = api.report("mocked_token", sample_event, 5) | ||
|
|
||
| # Assert the response | ||
| assert response == {"success": False, "error": "timeout"} | ||
|
|
||
|
|
||
| def test_report_other_exception(monkeypatch): | ||
| # Create an instance of ReportingApiHTTP | ||
| api = ReportingApiHTTP("http://mocked-url.com/") | ||
| assert response == { | ||
| "success": True, | ||
| "blockedUserIds": [], | ||
| "endpoints": [ | ||
| { | ||
| "forceProtectionOff": False, | ||
| "graphql": False, | ||
| "method": "*", | ||
| "rateLimiting": { | ||
| "enabled": True, | ||
| "maxRequests": 2, | ||
| "windowSizeInMS": 5000, | ||
| }, | ||
| "route": "/test_ratelimiting_1", | ||
| } | ||
| ], | ||
| "receivedAnyStats": False, | ||
| } | ||
|
|
||
|
|
||
| def test_report_local_timeout(): | ||
| api = ReportingApiHTTP("http://localhost:5050/timeout5/") | ||
|
|
||
| response = api.report("mocked_token", sample_event, 4) | ||
|
|
||
| # Mock the requests.post method to raise a generic exception | ||
| def mock_post(url, json, timeout, headers): | ||
| raise Exception("Some error occurred") | ||
| assert response == {"success": False, "error": "timeout"} | ||
|
|
||
| monkeypatch.setattr(requests, "post", mock_post) | ||
|
|
||
| # Call the report method | ||
| response = api.report("mocked_token", sample_event, 5) | ||
| def test_local_gzip(): | ||
| api = ReportingApiHTTP("http://localhost:5050/") | ||
| response = api.fetch_firewall_lists("token") | ||
|
|
||
| # Assert that the response is None (or however you want to handle it) | ||
| assert response["error"] is "unknown" | ||
| assert not response["success"] | ||
| assert response == { | ||
| "success": True, | ||
| "allowedIPAddresses": [], | ||
| "blockedIPAddresses": [ | ||
| {"description": "geo restrictions", "ips": ["1.2.3.4"], "source": "geoip"} | ||
| ], | ||
| "blockedUserAgents": "", | ||
| } |
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
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,17 @@ | ||
| from aikido_zen.background_process.requests.make_request import make_request | ||
| from json import dumps as json_dumps | ||
|
|
||
|
|
||
| def get(url, headers, timeout): | ||
| return make_request("GET", url, headers=headers, timeout=timeout) | ||
|
|
||
|
|
||
| def post(url, json, headers, timeout): | ||
| data = None | ||
| if headers is None: | ||
| headers = {} | ||
| if json is not None: | ||
| data = json_dumps(json).encode("utf-8") | ||
| headers["Content-Type"] = "application/json" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function modifies the input |
||
|
|
||
| return make_request("POST", url, data, headers, timeout) | ||
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,3 @@ | ||
| class TimeoutExceeded(Exception): | ||
| def __init__(self): | ||
| super().__init__("Aikido internal requests library: timeout was exceeded.") |
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,47 @@ | ||
| import gzip | ||
| import json | ||
| import socket | ||
| import urllib.request | ||
| import urllib.error | ||
|
|
||
| from aikido_zen.background_process.requests.errors import TimeoutExceeded | ||
|
|
||
|
|
||
| def make_request(method, url, data=None, headers=None, timeout=3): | ||
| req = urllib.request.Request(url, data=data, method=method) | ||
|
|
||
| # Add headers | ||
willem-delbare marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if headers: | ||
| for key, value in headers.items(): | ||
| req.add_header(key, value) | ||
| try: | ||
| with urllib.request.urlopen(req, timeout=timeout) as response: | ||
bitterpanda63 marked this conversation as resolved.
Show resolved
Hide resolved
bitterpanda63 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return Response(response) | ||
| except urllib.error.HTTPError as e: | ||
| return FailedResponse(status_code=e.code) | ||
| except socket.timeout: | ||
| raise TimeoutExceeded() | ||
|
|
||
|
|
||
| class Response: | ||
| def __init__(self, response): | ||
| self.status_code = response.getcode() | ||
| if response.info().get("Content-Encoding") == "gzip": | ||
| # we need to do the gzip decoding ourselves, since urllib has no native support. | ||
| self.text = decode_gzip(response.read()) | ||
| else: | ||
| self.text = response.read().decode("utf-8") | ||
|
|
||
| def json(self): | ||
| return json.loads(self.text) | ||
|
|
||
|
|
||
| class FailedResponse: | ||
| def __init__(self, status_code): | ||
| self.status_code = status_code | ||
| self.text = "" | ||
|
|
||
|
|
||
| def decode_gzip(raw_bytes, encoding="utf-8"): | ||
| f = gzip.decompress(raw_bytes) | ||
| return f.decode(encoding) | ||
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
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.