-
Notifications
You must be signed in to change notification settings - Fork 37
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
feat: basic websocket support #65
Open
kvalev
wants to merge
2
commits into
h2non:master
Choose a base branch
from
kvalev:websocket-interceptor
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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,110 @@ | ||
import tempfile | ||
from ..request import Request | ||
from .base import BaseInterceptor | ||
|
||
# Support Python 2/3 | ||
try: | ||
import mock | ||
except Exception: | ||
from unittest import mock | ||
|
||
|
||
class MockFrame(object): | ||
def __init__(self, opcode, data, fin=1): | ||
self.opcode = opcode | ||
self.data = data | ||
self.fin = fin | ||
|
||
|
||
class MockHandshakeResponse(object): | ||
|
||
def __init__(self, status, headers, subprotocol): | ||
self.status = status | ||
self.headers = headers | ||
self.subprotocol = subprotocol | ||
|
||
|
||
class WebSocketInterceptor(BaseInterceptor): | ||
|
||
def _handshake(self, sock, hostname, port, resource, **options): | ||
return MockHandshakeResponse(200, {}, "") | ||
|
||
def _connect(self, url, options, proxy, socket): | ||
req = Request() | ||
req.headers = {} # TODO | ||
req.url = url | ||
|
||
# TODO does this work multithreaded?!? | ||
self._mock = self.engine.match(req) | ||
if not self._mock: | ||
# we cannot forward, as we have mocked away the connection | ||
raise ValueError( | ||
"Request to '%s' could not be matched or forwarded" % url | ||
) | ||
|
||
# make the body always a list to simplify our lives | ||
body = self._mock._response._body | ||
if not isinstance(body, list): | ||
self._mock._response._body = [body] | ||
|
||
# We have to return a valid file descriptor, not just a random integer. | ||
# Source: https://docs.python.org/3/library/select.html#select.select | ||
sock = tempfile.TemporaryFile() | ||
addr = ("hostname", "port", "resource") | ||
|
||
return sock, addr | ||
|
||
def _send(self, data): | ||
# mock as if all data has been sent | ||
return len(data) | ||
|
||
def _recv_frame(self): | ||
# alias | ||
body = self._mock._response._body | ||
|
||
idx = getattr(self, "_data_index", 0) | ||
if len(body) <= idx: | ||
# close frame | ||
return MockFrame(0x8, None) | ||
|
||
# data frame | ||
self._data_index = idx + 1 | ||
return MockFrame(0x1, body[idx].encode("utf-8"), 1) | ||
|
||
def _patch(self, path, handler): | ||
try: | ||
# Create a new patcher for Urllib3 urlopen function | ||
# used as entry point for all the HTTP communications | ||
patcher = mock.patch(path, handler) | ||
# Retrieve original patched function that we might need for real | ||
# networking | ||
# request = patcher.get_original()[0] | ||
# Start patching function calls | ||
patcher.start() | ||
except Exception: | ||
# Exceptions may accur due to missing package | ||
# Ignore all the exceptions for now | ||
pass | ||
else: | ||
self.patchers.append(patcher) | ||
|
||
def activate(self): | ||
""" | ||
Activates the traffic interceptor. | ||
This method must be implemented by any interceptor. | ||
""" | ||
patches = [ | ||
('websocket._core.connect', self._connect), | ||
('websocket._core.handshake', self._handshake), | ||
('websocket.WebSocket._send', self._send), | ||
('websocket.WebSocket.recv_frame', self._recv_frame), | ||
] | ||
|
||
[self._patch(path, handler) for path, handler in patches] | ||
|
||
def disable(self): | ||
""" | ||
Disables the traffic interceptor. | ||
This method must be implemented by any interceptor. | ||
""" | ||
[patch.stop() for patch in self.patchers] |
This file contains 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 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 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,13 @@ | ||
from websocket import WebSocket | ||
import pook | ||
|
||
|
||
@pook.on | ||
def test_websocket(): | ||
(pook.get('ws://some-non-existing.org') | ||
.reply(204) | ||
.body('test')) | ||
|
||
socket = WebSocket() | ||
socket.connect('ws://some-non-existing.org/', header=['x-custom: header']) | ||
socket.send('test') |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It will not work. Mutex synchronization is required to make it safe. However, I feel that's another feature that has to be implemented in a separate PR.