def test_to_representation_returns_none(self): class FakeModel(object): def __init__(self, pk): self.pk = pk def __str__(self): return "object.pk={}".format(self.pk) class FakeHyperlinkField(self.CustomHyperlinkedRelatedField): def is_saved_in_database(self, obj): return False def get_lookup_value(self, obj): return (1, ) router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = FakeHyperlinkField('test_view', read_only=True) self.assertIsNone(instance.to_representation(FakeModel(1)))
def test_to_internal_value_raises_error_with_fixing_url(self): class FakeModel(object): def __init__(self, pk): self.pk = pk class FakeHyperlinkField(self.CustomHyperlinkedRelatedField): def get_object(self, view_name, view_args, view_kwargs): return FakeModel(1) router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = FakeHyperlinkField('test_view', read_only=True) data = {'url': 'test_view/1'} obj = instance.to_internal_value(data) self.assertIsInstance(obj, FakeModel) self.assertEqual(obj.pk, 1)
def test_to_internal_value_raises_error_for_incorrect_type(self): router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000/', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = self.CustomHyperlinkedRelatedField( 'test_view', read_only=True ) with self.assertRaises(ValidationError): instance.to_internal_value('not a dict')
def test_to_internal_value_raises_error_for_no_primary_key(self): router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = self.CustomHyperlinkedRelatedField( 'test_view', read_only=True ) data = {'wrong_url_name': 'wss://127.0.0.1:8000/test_view/1/'} with self.assertRaises(ValidationError): instance.to_internal_value(data)
def test_to_representation_returns_relative_url(self): class FakeModel(object): def __init__(self, pk): self.pk = pk def __str__(self): return "object.pk={}".format(self.pk) class FakeModelSerializer(object): parent = None _context = {'relative': True} class FakeHyperlinkField(self.CustomHyperlinkedRelatedField): def is_saved_in_database(self, obj): return True def get_lookup_value(self, obj): return (1, ) router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = FakeHyperlinkField('test_view', read_only=True) instance.bind('pk', FakeModelSerializer()) hyperlink_object = instance.to_representation(FakeModel(1)) self.assertEqual(hyperlink_object, '/test_view/1/') self.assertEqual(hyperlink_object.name, 'object.pk=1')
def test_get_url_returns_url_to_an_object(self): class FakeHyperlinkField(self.CustomHyperlinkedRelatedField): def is_saved_in_database(self, obj): return True def get_lookup_value(self, obj): return (1, ) router = SimpleRouter() router.register('/test_view/{pk}', FakeView, 'GET', name='test_view') url_configuration = { 'path': 'wss://127.0.0.1:8000', 'urls': router._urls, 'routes': router._routes } set_urlconf(url_configuration) instance = FakeHyperlinkField('test_view', read_only=True) self.assertEqual( instance.get_url(object(), 'test_view'), 'wss://127.0.0.1:8000/test_view/1/' )
class RestWSRouterTestCase(unittest.TestCase): def setUp(self): super(RestWSRouterTestCase, self).setUp() self.router = SimpleRouter() def test_correct_path(self): broken_path = 'api' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, 'api/') def test_correct_path_2(self): broken_path = ' api ' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, 'api/') def test_correct_path_3(self): broken_path = 'api' correct_path = 'api/' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, correct_path) def test_register(self): self.router.register('/api', FakeView, 'GET') self.assertEqual(FakeView, self.router._urls[0].handler) def test_register_with_list_methods(self): self.router.register('/api', FakeView, ['GET', 'POST', ]) self.assertEqual(FakeView, self.router._urls[0].handler) def test_register_endpoint(self): @endpoint(path='/api', methods='GET') def fake_handler(request, *args, **kwargs): pass self.router.register_endpoint(fake_handler) assert issubclass(self.router._urls[0].handler, MethodBasedView) def test_extract_url(self): data = {} request = Request(**data) self.assertRaises(NotSpecifiedURL, self.router.extract_url, request) def test_extract_url_2(self): data = {'url': '/api'} request = Request(**data) self.assertEqual(self.router.extract_url(request), '/api/') def test_extract_url_3(self): data = {'url': '/api/'} request = Request(**data) self.assertEqual(self.router.extract_url(request), '/api/') def test_search_handler_with_plain_endpoint(self): self.router.register('/api/', FakeView, 'GET') data = {} request = Request(**data) url = '/api/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ()) self.assertEqual(kwargs, {}) def test_search_handler_with_dynamic_endpoint(self): self.router.register('/api/{version}/', FakeView, 'GET') data = {} request = Request(**data) url = '/api/v1/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ('v1',)) self.assertEqual(kwargs, {}) def test_search_handler_with_dynamic_endpoint_2(self): self.router.register('/api/{version}/', FakeView, 'GET') data = {'args': {'format': 'json'}} request = Request(**data) url = '/api/v2/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ('v2',)) self.assertEqual(kwargs, {'format': 'json'}) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_defined_args(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/', 'args': {'format': 'xml'} } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_defined_args_and_event_name(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/', 'args': {'format': 'xml'}, 'event_name': 'test' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertEqual( json_response['event_name'], decoded_json['event_name'] ) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_by_invalid_url(self, log_info, log_exc): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/invalid/' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertEqual( json_response['detail'], "For URL, typed in request, handler not specified." ) self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_without_url(self, log_info, log_exc): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertEqual( json_response['detail'], "In query not specified `url` argument." ) self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_middleware(self, log_info): self.router._middlewares = [FakeTokenMiddleware(), ] self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_with_failed_middleware(self, log_info, log_exc): self.router._middlewares = [FakeTokenMiddlewareWithExc(), ] self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertNotIn('data', json_response.keys()) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_wrapped_function(self, log_info): @endpoint('/api', 'GET') def fake_handler(request, *args, **kwargs): return "fake" self.router.register_endpoint(fake_handler) decoded_json = { 'url': '/api', 'method': 'GET' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) def test_register_url(self): endpoint = FakeEndpoint('/api/', None, 'GET', 'good') self.router._register_url(endpoint) self.assertRaises(EndpointValueError, self.router._register_url, endpoint) def test_register_url_without_endpoint_name(self): endpoint = FakeEndpoint('/api/', None, 'GET', None) self.router._register_url(endpoint) def test_register_url_failed(self): endpoint = InvalidEndpoint self.assertRaises(TypeError, self.router._register_url, endpoint) def test_include(self): class AnotherRouter(SimpleRouter): pass another_router = AnotherRouter() another_router.register('/api', FakeView, 'GET', name='test_api') self.assertEqual(len(self.router._urls), 0) self.assertEqual(len(self.router._routes), 0) self.router.include(another_router) self.assertEqual(len(self.router._urls), 1) self.assertEqual(len(self.router._routes), 1) self.assertEqual(type(self.router._urls[0]), PlainEndpoint) self.assertEqual(type(self.router._routes['test_api']), PlainEndpoint) def test_include_fail(self): another_router = None self.assertRaises(TypeError, self.router.include, another_router)
# -*- coding: utf-8 -*- from aiorest_ws.routers import SimpleRouter from app.views import ManufacturerListView, ManufacturerView, CarListView, \ CarView router = SimpleRouter() router.register('/manufacturer/{name}', ManufacturerView, ['GET', 'PUT'], name='manufacturer-detail') router.register('/manufacturer/', ManufacturerListView, ['POST']) router.register('/cars/{name}', CarView, ['GET', 'PUT'], name='car-detail') router.register('/cars/', CarListView, ['POST'])
# -*- coding: utf-8 -*- from aiorest_ws.routers import SimpleRouter from app.views import UserListView, UserView, CreateUserView, AddressView, \ CreateAddressView router = SimpleRouter() router.register('/user/list', UserListView, 'GET') router.register('/user/{id}', UserView, ['GET', 'PUT'], name='user-detail') router.register('/user/', CreateUserView, ['POST']) router.register('/address/{id}', AddressView, ['GET', 'PUT'], name='address-detail') router.register('/address/', CreateAddressView, ['POST'])
class HelloWorldCustom(MethodBasedView): def get(self, request, user, id, *args, **kwargs): return "Hello, {0} with ID={1}".format(user, id) class CalculateSum(MethodBasedView): def get(self, request, *args, **kwargs): try: digits = kwargs['digits'] except KeyError: digits = [0, ] return {"sum": sum(digits)} router = SimpleRouter() router.register('/hello', HelloWorld, 'GET') router.register('/hello/{user}/{id}', HelloWorldCustom, 'GET') router.register('/calc/sum', CalculateSum, 'GET') if __name__ == '__main__': cmd = CommandLine() cmd.define('-ip', default='127.0.0.1', help='used ip', type=str) cmd.define('-port', default=8080, help='listened port', type=int) args = cmd.parse_command_line() app = Application() app.run(host=args.ip, port=args.port, router=router)
class HelloWorldCustom(MethodBasedView): def get(self, request, user, id, *args, **kwargs): return "Hello, {0} with ID={1}".format(user, id) class CalculateSum(MethodBasedView): def get(self, request, *args, **kwargs): try: digits = kwargs['params']['digits'] except KeyError: digits = [0, ] return {"sum": sum(digits)} router = SimpleRouter() router.register('/hello', HelloWorld, 'GET') router.register('/hello/{user}/{id}', HelloWorldCustom, 'GET') router.register('/calc/sum', CalculateSum, 'GET') if __name__ == '__main__': cmd = CommandLine() cmd.define('-ip', default='127.0.0.1', help='used ip', type=str) cmd.define('-port', default=8080, help='listened port', type=int) args = cmd.parse_command_line() app = Application() app.run(host=args.ip, port=args.port, router=router)
class RestWSRouterTestCase(unittest.TestCase): def setUp(self): super(RestWSRouterTestCase, self).setUp() self.router = SimpleRouter() def test_correct_path(self): broken_path = 'api' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, 'api/') def test_correct_path_2(self): broken_path = ' api ' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, 'api/') def test_correct_path_3(self): broken_path = 'api' correct_path = 'api/' fixed_path = self.router._correct_path(broken_path) self.assertEqual(fixed_path, correct_path) def test_register(self): self.router.register('/api', FakeView, 'GET') self.assertEqual(FakeView, self.router._urls[0].handler) def test_register_with_list_methods(self): self.router.register('/api', FakeView, [ 'GET', 'POST', ]) self.assertEqual(FakeView, self.router._urls[0].handler) def test_register_endpoint(self): @endpoint(path='/api', methods='GET') def fake_handler(request, *args, **kwargs): pass self.router.register_endpoint(fake_handler) assert issubclass(self.router._urls[0].handler, MethodBasedView) def test_extract_url(self): data = {} request = Request(**data) self.assertRaises(NotSpecifiedURL, self.router.extract_url, request) def test_extract_url_2(self): data = {'url': '/api'} request = Request(**data) self.assertEqual(self.router.extract_url(request), '/api/') def test_extract_url_3(self): data = {'url': '/api/'} request = Request(**data) self.assertEqual(self.router.extract_url(request), '/api/') def test_search_handler_with_plain_endpoint(self): self.router.register('/api/', FakeView, 'GET') data = {} request = Request(**data) url = '/api/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ()) self.assertEqual(kwargs, {}) def test_search_handler_with_dynamic_endpoint(self): self.router.register('/api/{version}/', FakeView, 'GET') data = {} request = Request(**data) url = '/api/v1/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ('v1', )) self.assertEqual(kwargs, {}) def test_search_handler_with_dynamic_endpoint_2(self): self.router.register('/api/{version}/', FakeView, 'GET') data = {'args': {'format': 'json'}} request = Request(**data) url = '/api/v2/' handler, args, kwargs = self.router.search_handler(request, url) self.assertIsInstance(handler, FakeView) self.assertEqual(args, ('v2', )) self.assertEqual(kwargs, {'format': 'json'}) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET', 'url': '/api/get/'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_defined_args(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/', 'args': { 'format': 'xml' } } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_defined_args_and_event_name(self, log_info): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = { 'method': 'GET', 'url': '/api/get/', 'args': { 'format': 'xml' }, 'event_name': 'test' } request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertEqual(json_response['event_name'], decoded_json['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_by_invalid_url(self, log_info, log_exc): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET', 'url': '/api/invalid/'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertEqual(json_response['detail'], "For URL, typed in request, handler not specified.") self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_without_url(self, log_info, log_exc): self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertEqual(json_response['detail'], "In query not specified `url` argument.") self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_with_middleware(self, log_info): self.router._middlewares = [ FakeTokenMiddleware(), ] self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET', 'url': '/api/get/'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) @unittest.mock.patch('aiorest_ws.log.logger.info') @unittest.mock.patch('aiorest_ws.log.logger.exception') def test_process_request_with_failed_middleware(self, log_info, log_exc): self.router._middlewares = [ FakeTokenMiddlewareWithExc(), ] self.router.register('/api/get/', FakeGetView, 'GET') decoded_json = {'method': 'GET', 'url': '/api/get/'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('detail', json_response.keys()) self.assertNotIn('data', json_response.keys()) @unittest.mock.patch('aiorest_ws.log.logger.info') def test_process_request_wrapped_function(self, log_info): @endpoint('/api', 'GET') def fake_handler(request, *args, **kwargs): return "fake" self.router.register_endpoint(fake_handler) decoded_json = {'url': '/api', 'method': 'GET'} request = Request(**decoded_json) response = self.router.process_request(request).decode('utf-8') json_response = json.loads(response) self.assertIn('data', json_response.keys()) self.assertEqual(json_response['data'], 'fake') self.assertIn('event_name', json_response) self.assertIsNone(json_response['event_name']) def test_register_url(self): endpoint = FakeEndpoint('/api/', None, 'GET', 'good') self.router._register_url(endpoint) self.assertRaises(EndpointValueError, self.router._register_url, endpoint) def test_register_url_without_endpoint_name(self): endpoint = FakeEndpoint('/api/', None, 'GET', None) self.router._register_url(endpoint) def test_register_url_failed(self): endpoint = InvalidEndpoint self.assertRaises(TypeError, self.router._register_url, endpoint) def test_include(self): class AnotherRouter(SimpleRouter): pass another_router = AnotherRouter() another_router.register('/api', FakeView, 'GET', name='test_api') self.assertEqual(len(self.router._urls), 0) self.assertEqual(len(self.router._routes), 0) self.router.include(another_router) self.assertEqual(len(self.router._urls), 1) self.assertEqual(len(self.router._routes), 1) self.assertEqual(type(self.router._urls[0]), PlainEndpoint) self.assertEqual(type(self.router._routes['test_api']), PlainEndpoint) def test_include_fail(self): another_router = None self.assertRaises(TypeError, self.router.include, another_router)
request.args['username'], with_id=True ) if user.is_authenticated: api_token = self.get_or_create_token(user, *args, **kwargs) else: api_token = None return {'token': api_token} class LogOut(MethodBasedView): auth_required = True def post(self, request, *args, **kwargs): return "Successful log out." router = SimpleRouter() router.register('/auth/user/create', RegisterUser, 'POST') router.register('/auth/login', LogIn, 'POST') router.register('/auth/logout', LogOut, 'POST') if __name__ == '__main__': cmd = CommandLine() cmd.define('-ip', default='127.0.0.1', help='used ip', type=str) cmd.define('-port', default=8080, help='listened port', type=int) args = cmd.parse_command_line() app = Application(middlewares=(JSONWebTokenMiddleware, )) app.run(host=args.ip, port=args.port, router=router)
request.data['username'], with_id=True ) if user.is_authenticated: api_token = self.get_or_create_token(user, *args, **kwargs) else: api_token = None return {'token': api_token} class LogOut(MethodBasedView): auth_required = True def post(self, request, *args, **kwargs): return "Successful log out." router = SimpleRouter() router.register('/auth/user/create', RegisterUser, 'POST') router.register('/auth/login', LogIn, 'POST') router.register('/auth/logout', LogOut, 'POST') if __name__ == '__main__': cmd = CommandLine() cmd.define('-ip', default='127.0.0.1', help='used ip', type=str) cmd.define('-port', default=8080, help='listened port', type=int) args = cmd.parse_command_line() app = Application(middlewares=(JSONWebTokenMiddleware, )) app.run(host=args.ip, port=args.port, router=router)