Skip to content

Bug Fixes #9

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions aiohttp_mock/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
from aiohttp_mock.exceptions import *
from aiohttp_mock.router import ConnectionRouter
from aiohttp.client_reqrep import ClientResponse
Expand Down Expand Up @@ -122,31 +123,38 @@ def get_instance():

:returns: instance of ConnectionManager
"""
print('ConnectionManager.get_instance() - entering - id = {0}'.format(id(ConnectionManager.instance)))
if ConnectionManager.instance is None:
return ConnectionManager()

else:
return ConnectionManager.instance
print('ConnectionManager.get_instance() - returning - id = {0}'.format(id(ConnectionManager.instance)))
return ConnectionManager.instance

def __init__(self):
self.managed_urls = []
self.router = ConnectionRouter()
self.globify()

def __del__(self):
self.reset()

def reset(self):
"""Reset Manager State

Clear the known route supports
"""
print('ConnectionManager - Resettings - id {0}'.format(id(self)))
self.deglobify()
self.router.reset()

@staticmethod
def reset_global():
"""Reset the global variables
"""
print('ConnectionManager.reset_global() - entering - id = {0}'.format(id(ConnectionManager.instance)))
if ConnectionManager.instance is not None:
ConnectionManager.instance = None
print('ConnectionManager.reset_global() - exiting - id = {0}'.format(id(ConnectionManager.instance)))

def deglobify(self):
"""De-register the global instance
Expand All @@ -155,8 +163,11 @@ def deglobify(self):
reset the global instance
"""
# if this is the official instance, then clear it
print('ConnectionManager.deglobify() - self = {0}'.format(id(self)))
print('ConnectionManager.deglobify() - entering - global id = {0}'.format(id(ConnectionManager.instance)))
if ConnectionManager.instance == self:
ConnectionManager.instance = None
print('ConnectionManager.deglobify() - exiting - global id = {0}'.format(id(ConnectionManager.instance)))

def globify(self, force=False):
"""Register the global instance
Expand All @@ -168,20 +179,33 @@ def globify(self, force=False):
the official one
"""
# if this is the first instance, then make it the official one
print('ConnectionManager.globify() - self = {0}'.format(id(self)))
print('ConnectionManager.globify() - entering - global id = {0}'.format(id(ConnectionManager.instance)))
if ConnectionManager.instance is None or force == True:
ConnectionManager.instance = self
print('ConnectionManager.globify() - exiting - global id = {0}'.format(id(ConnectionManager.instance)))

def is_managed(self, url):
def is_managed(self, uri):
"""Checks if the specific URL is managed by the instance

:param url: string - URI of the route to check
:param uri: string - URI of the route to check
:returns: boolean - True if the URL is managed, otherwise False
"""
print('ConnectionManager.is_managed() - self = {0}'.format(id(self)))
print('ConnectionManager.is_managed() - checking uri - {0}'.format(uri))
print('ConnectionManager.is_managed() - router - {0}'.format(id(self.router)))
if self.router is None:
print('ConnectionManager.is_managed() - no router')
return False

try:
self.router.get_route(url)
print('ConnectionManager.is_managed() - checking route')
self.router.get_route(uri)
print('ConnectionManager.is_managed() - found route')
return True

except RouteNotHandled:
print('ConnectionManager.is_managed() - no route')
return False

@staticmethod
Expand Down Expand Up @@ -213,8 +237,13 @@ def make_response(uri, method, status_code=200, body=None, add_headers=None):
content_length = len(body)

response = ClientResponse(method, uri, host='aiohttp_mock')
response._post_init(loop=asyncio.get_event_loop())
response._continue = None
response.status = status_code
response.reason = ConnectionManager.get_reason_for_status(status_code)
response.content = body

response._closed = True
response._should_code = False
response._headers = cidict({
'x-agent': 'aiohttp-mock',
Expand All @@ -237,20 +266,28 @@ def register(self, uri, method, response):
if not hasattr(response, '__call__'):
raise ConnectionManagerInvalidHandler

self.router.add_route_handler(method, uri, response)
print('ConnectionManager.register() - self = {0}'.format(id(self)))
print('ConnectionManager.register() - uri = {0}'.format(uri))
print('ConnectionManager.register() - method = {0}'.format(method))
print('ConnectionManager.register() - response = {0}'.format(id(response)))
self.router.add_route_handler(uri, method, response)
print('ConnectionManager.register() - route added')

def intercept(self, request):
"""Request Intercept Handler

:param request: aiohttp.client_reqrep.ClientRequest the request is for
:returns: aiohttp.client_reqrep.ClientResponse
"""
print('Managed URL!')
print('ConnectionManager.intercept() - self = {0}'.format(id(self)))
print('ConnectionManager.intercept() - request = {0}'.format(id(request)))

uri = request.url
method = request.method
try:
print('ConnectionManager.intercept() - attempting to route')
return self.router.handle(method, uri, request)

except RouteNotHandled:
print('ConnectionManager.intercept() - no route')
raise ConnectionManagerUnhandled('no configured handler')
6 changes: 5 additions & 1 deletion aiohttp_mock/monkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ def send_interceptor(*args):
# Access the aiohttp-mock framework
# if the URI is managed by it then pass it off to the framework
import aiohttp_mock.manager
mocker = aiohttp_mock.manager.ConnectionManager.instance
mocker = aiohttp_mock.manager.ConnectionManager.get_instance()
print('send_interceptor() - Found Mocker - id {0}'.format(id(mocker)))
if mocker is not None:
print('send_interceptor() - Checking URL: {0}'.format(args[0].url))
if mocker.is_managed(args[0].url):
print('send_interceptor() - URI is managed')
try:
print('send_interceptor() - Attempting to intercept URI')
return mocker.intercept(args[0])
except ConnectionManagerUnhandled:
print('ConnectionManager not configured.')
Expand Down
21 changes: 21 additions & 0 deletions aiohttp_mock/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def handle(self, method, request):
response.status = 405
response.reason = 'Method Not Supported'
response._should_close = False
response._closed = True
response._headers = cidict({
'x-agent': 'aiohttp-mock',
'content-length': 0
Expand All @@ -79,16 +80,22 @@ def __init__(self):
def reset(self):
"""Reset all the routes
"""
print('ConnectionRouter.reset() - self - {0}'.format(id(self)))
self._routes = {}

def add_route(self, uri):
"""Add a route to be managed

:param uri: string - URI to be handled
"""
print('ConnectionRouter.add_route() - self - {0}'.format(id(self)))
print('ConnectionRouter.add_route() - uri - {0}'.format(uri))
if uri not in self._routes:
print('ConnectionRouter.add_route() - adding route')
self._routes[uri] = ConnectionRouterHandler(uri)

print('ConnectionRouter.add_route() - router = {0}'.format(id(self._routes[uri])))

def get_route(self, uri):
"""Access the handler for a URI

Expand All @@ -97,9 +104,12 @@ def get_route(self, uri):
:returns: ConnectionRouterHandler instance managing the route
:raises: RouteNotHandled if the route is not handled
"""
print('ConnectionRouter.get_route() - self - {0}'.format(id(self)))
if uri in self._routes:
print('ConnectionRouter.get_route() - router = {0}'.format(id(self._routes[uri])))
return self._routes[uri]
else:
print('ConnectionRouter.get_route() - no router')
raise RouteNotHandled('{0} not handled'.format(uri))

def add_route_handler(self, uri, method, handler):
Expand All @@ -109,12 +119,18 @@ def add_route_handler(self, uri, method, handler):
:param method: string - HTTP Verb the handler is for
:param handle: ClientResponse or callable that will handle the request
"""
print('ConnectionRouter.add_route_handler() - self - {0}'.format(id(self)))
try:
router = self.get_route(uri)

except RouteNotHandled:
self.add_route(uri)
router = self.get_route(uri)

print('ConnectionRouter.add_route_handler() - router = {0}'.format(id(router)))
print('ConnectionRouter.add_route_handler() - uri - {0}'.format(uri))
print('ConnectionRouter.add_route_handler() - method - {0}'.format(method))
print('ConnectionRouter.add_route_handler() - handler - {0}'.format(id(handler)))
router.add_method_handler(method, handler)

def handle(self, method, uri, request):
Expand All @@ -128,6 +144,11 @@ def handle(self, method, uri, request):
:returns: aiohttp.client_reqrep.ClientResponse instance
:raises: RouteNotHandled if the route is not handled
"""
print('ConnectionRouter.handle() - self - {0}'.format(id(self)))
print('ConnectionRouter.handle() - uri - {0}'.format(uri))
print('ConnectionRouter.handle() - method - {0}'.format(method))
print('ConnectionRouter.handle() - request - {0}'.format(id(request)))
router = self.get_route(uri)
print('ConnectionRouter.handle() - router = {0}'.format(id(router)))

return router.handle(method, request)
55 changes: 41 additions & 14 deletions tests/make_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,62 @@
import unittest

@asyncio.coroutine
def make_url_call():
def make_url_call(instance, response_code):
session = aiohttp.ClientSession()
resp = yield from session.get('http://www.google.com')
data = yield from resp.read()
session.close()
print('resp type is: {0}'.format(type(resp)))
#print(dir(resp))
print('data type is: {0}'.format(type(data)))
print('make_url_call - resp status is: {0}'.format(resp.status))
print('make_url_call - resp type is: {0}'.format(type(resp)))
print('make_url_call - data type is: {0}'.format(type(data)))
instance.assertEqual(resp.status, response_code)
return resp

def make_async_call(loop, fn):
if hasattr(loop, 'create_task'):
return loop.create_task(fn)
else:
return asyncio.async(fn)


class TestEssential(unittest.TestCase):

def test_basic():
asyncio.get_event_loop().run_until_complete(make_url_call())
def test_basic(self):

print('test_basic - Initial Check')
loop = asyncio.get_event_loop()
tasks = [
make_async_call(loop, make_url_call(self, 200))
]
loop.run_until_complete(asyncio.wait(tasks))

print('Monkey Patching')
print('\n\ntest_basic - Monkey Patching')
aiohttp_mock.monkey.patch()

asyncio.get_event_loop().run_until_complete(make_url_call())
tasks = [
make_async_call(loop, make_url_call(self, 200))
]
loop.run_until_complete(asyncio.wait(tasks))

print('Creating interceptor')
interceptor = aiohttp_mock.manager.ConnectionManager()
print('\n\ntest_basic - Creating interceptor')
interceptor = aiohttp_mock.manager.ConnectionManager.get_instance()
print('test_basic - id mocker: {0}'.format(id(interceptor)))

asyncio.get_event_loop().run_until_complete(make_url_call())
tasks = [
make_async_call(loop, make_url_call(self, 200))
]
loop.run_until_complete(asyncio.wait(tasks))

print('Adding managed url')
print('\n\ntest_basic - Adding managed url')
response = aiohttp_mock.manager.ConnectionManager.make_response('http://www.google.com/', 'GET', status_code=405)
interceptor.register('http://www.google.com', 'GET', response)
print('test_basic - id mocker: {0}'.format(id(interceptor)))
interceptor.register('http://www.google.com/', 'GET', response)
print('test_basic - id mocker: {0}'.format(id(interceptor)))

asyncio.get_event_loop().run_until_complete(make_url_call())
tasks = [
make_async_call(loop, make_url_call(self, 405))
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

self.assertTrue(False)