def test_simple_path_two_steps(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self): pass @app.path(model=Model, path='one/two') def get_model(): return Model() @app.view(model=Model) def default(self, request): return "View" @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/one/two') assert response.body == b'View' response = c.get('/one/two/link') assert response.body == b'http://localhost/one/two'
def test_expires(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'session.cookie_expires': datetime.timedelta(days=1)} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'expires=' in res.headers.getall('Set-Cookie')[0] assert 'current value is: 1' in res
def test_magical_methods(self): class MyKule(Kule): def get_documents_list(self): return {"foo": "bar"} kule = MyKule(database="kule_test", collections=["documents"]) app = TestApp(kule.get_bottle_app()) self.assertEqual(app.get("/documents").json, {"foo": "bar"})
def test_variable_path_parameter_required_with_default(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self, id): self.id = id @app.path(model=Model, path='', required=['id']) def get_model(id='b'): return Model(id) @app.view(model=Model) def default(self, request): return "View: %s" % self.id @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/?id=a') assert response.body == b"View: a" response = c.get('/', status=400)
class IntegrationTests(unittest.TestCase): def setUp(self): from webtest import TestApp from pyramid.paster import get_app app = get_app('development.ini') self.app = TestApp(app) def tearDown(self): testing.tearDown() def test_login_view(self): self.app.authorization = ('Basic', ('user', 'password')) response = self.app.get('/login') self.assertEqual(response.status_int, 200) def test_logout_view(self): # run login to start session self.app.authorization = ('Basic', ('user', 'password')) self.app.get('/login') response = self.app.get('/logout') self.assertEqual(response.status_int, 200) def test_logout_not_loggedin(self): # expect 403 when trying to log out again from pyramid.httpexceptions import HTTPForbidden response = self.app.get('/logout', expect_errors=True) self.assertEqual(response.status_int, 401)
def _RunCompleterCommand_GoTo_all_Clang(filename, command, test): contents = open( PathToTestFile( filename ) ).read() app = TestApp( handlers.app ) common_request = { 'completer_target' : 'filetype_default', 'command_arguments' : command, 'compilation_flags' : ['-x', 'c++', '-std=c++11'], 'line_num' : 10, 'column_num' : 3, 'contents' : contents, 'filetype' : 'cpp' } common_response = { 'filepath' : os.path.abspath( '/foo' ), } request = common_request request.update({ 'line_num' : test['request'][0], 'column_num': test['request'][1], }) response = common_response response.update({ 'line_num' : test['response'][0], 'column_num': test['response'][1], }) goto_data = BuildRequest( **request ) eq_( response, app.post_json( '/run_completer_command', goto_data ).json )
def test_enforce_https_wrong(self): config = copy.deepcopy(SHARED_DEFAULTS) config["enforce_https"] = True application = RoutingApplication(config) app = TestApp(application, extra_environ={"REMOTE_ADDR": "127.0.0.1"}) app.get("/", status=406) app.post("/connect", status=406)
def RunCompleterCommand_GetType_TypescriptCompleter_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'test.ts' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'typescript', contents = contents, event_name = 'BufferVisit' ) app.post_json( '/event_notification', event_data ) gettype_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GetType'], line_num = 12, column_num = 1, contents = contents, filetype = 'typescript', filepath = filepath ) eq_( { 'message': 'var foo: Foo' }, app.post_json( '/run_completer_command', gettype_data ).json )
def _RunCompleterCommand_Message_Clang(filename, test, command): contents = open( PathToTestFile( filename ) ).read() app = TestApp( handlers.app ) common_args = { 'completer_target' : 'filetype_default', 'command_arguments' : command, 'compilation_flags' : ['-x', 'c++', '-std=c++11'], 'line_num' : 10, 'column_num' : 3, 'contents' : contents, 'filetype' : 'cpp' } args = test[0] expected = test[1]; request = common_args request.update( args ) request_data = BuildRequest( **request ) eq_( {'message': expected}, app.post_json( '/run_completer_command', request_data ).json )
def GetCompletions_ClangCompleter_WorksWithExplicitFlags_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ # 0-based line and column! completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', contents = contents, line_num = 10, column_num = 6, start_column = 6, compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_items( CompletionEntryMatcher( 'c' ), CompletionEntryMatcher( 'x' ), CompletionEntryMatcher( 'y' ) ) )
def GetCompletions_ClangCompleter_ForceSemantic_OnlyFileteredCompletions_test(): app = TestApp( handlers.app ) contents = """ int main() { int foobar; int floozar; int gooboo; int bleble; fooar } """ # 0-based line and column! completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', force_semantic = True, contents = contents, line_num = 8, column_num = 7, start_column = 7, query = 'fooar', compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json assert_that( results, contains_inanyorder( CompletionEntryMatcher( 'foobar' ), CompletionEntryMatcher( 'floozar' ) ) )
class TestResource(unittest.TestCase): def setUp(self): from pyramid.renderers import JSONP self.config = testing.setUp() self.config.add_renderer("jsonp", JSONP(param_name="callback")) self.config.include("cornice") self.config.scan("cornice.tests.test_resource") self.app = TestApp(CatchErrors(self.config.make_wsgi_app())) def tearDown(self): testing.tearDown() def test_basic_resource(self): self.assertEquals(self.app.get("/users").json, {"status": "ok", "result": {"users": [1, 2]}}) self.assertEquals(self.app.get("/users/1").json, {"status": "ok", "result": {"name": "gawel"}}) resp = self.app.get("/users/1?callback=test") self.assertEquals(resp.body, 'test({"status": "ok", "result": {"name": "gawel"}})', resp.body) def test_accept_headers(self): # the accept headers should work even in case they're specified in a # resource method self.assertEquals( self.app.post("/users", headers={"Accept": "text/json"}, params=json.dumps({"test": "yeah"})).json, {"status": "ok", "result": {"test": "yeah"}}, )
def test_extra_predicates(): config = setup() app = App(testing_config=config) @app.path(path='{id}') class Model(object): def __init__(self, id): self.id = id @app.view(model=Model, name='foo', id='a') def get_a(self, request): return 'a' @app.view(model=Model, name='foo', id='b') def get_b(self, request): return 'b' @app.predicate(name='id', order=2, default='') def get_id(self, request): return self.id config.commit() c = Client(app) response = c.get('/a/foo') assert response.body == 'a' response = c.get('/b/foo') assert response.body == 'b'
class ImperativeIncludeConfigurationTest(unittest.TestCase): def setUp(self): from pyramid.config import Configurator config = Configurator() from pyramid.tests.pkgs.includeapp1.root import configure configure(config) app = config.make_wsgi_app() from webtest import TestApp self.testapp = TestApp(app) self.config = config def tearDown(self): self.config.end() def test_root(self): res = self.testapp.get('/', status=200) self.assertTrue(b'root' in res.body) def test_two(self): res = self.testapp.get('/two', status=200) self.assertTrue(b'two' in res.body) def test_three(self): res = self.testapp.get('/three', status=200) self.assertTrue(b'three' in res.body)
def test_create_hosted_zone_xml(): app = TestApp(api.api) request = open('createhostedzone.xml', 'r').read() response = app.post('/hostedzone', request) #reply = open('createhostedzone_response.xml', 'r').read() assert response.status == '201 Created' print response.body
def test_post_task_invalid(): test_app = TestApp(app) assert test_app.post_json('/task', expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'task_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 'invalid_version', 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'task_id': 'de305d54-75b4-431b-adb2-eb6b9e546013_not_valid', 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 1, 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 1, 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400
def test_pull_task(): test_app = TestApp(app) session = create_session() task1 = Task() task1.uuid = 'de305d54-75b4-431b-adb2-eb6b9e546018' task1.test_id = 'de305d54-75b4-431b-adb2-eb6b9e546018' task1.claimed = datetime.utcnow() task1.data = json.dumps({'wait_time': 123}) session.add(task1) task2 = Task() task2.uuid = 'de305d54-75b4-431b-adb2-eb6b9e546019' task2.test_id = 'de305d54-75b4-431b-adb2-eb6b9e546019' task2.claimed = datetime.utcnow() task2.completed = datetime.utcnow() task2.result_data = json.dumps({'result': 'epic success'}) session.add(task2) task3 = Task() task3.uuid = 'de305d54-75b4-431b-adb2-eb6b9e546020' task3.test_id = 'de305d54-75b4-431b-adb2-eb6b9e546020' task3.claimed = datetime.utcnow() task3.failed = datetime.utcnow() task3.error = 'unknown error' session.add(task3) session.commit() test_app.get('/task/de305d54-75b4-431b-adb2-eb6b9e546018') test_app.get('/task/de305d54-75b4-431b-adb2-eb6b9e546019') test_app.get('/task/de305d54-75b4-431b-adb2-eb6b9e546020')
def test_get_with_var_args(self): class OthersController(object): @expose() def index(self, one, two, three): return 'NESTED: %s, %s, %s' % (one, two, three) class ThingsController(RestController): others = OthersController() @expose() def get_one(self, *args): return ', '.join(args) class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get request r = app.get('/things/one/two/three') assert r.status_int == 200 assert r.body == b_('one, two, three') # test nested get request r = app.get('/things/one/two/three/others/') assert r.status_int == 200 assert r.body == b_('NESTED: one, two, three')
def test_404_with_lookup(self): class LookupController(RestController): def __init__(self, _id): self._id = _id @expose() def get_all(self): return 'ID: %s' % self._id class ThingsController(RestController): @expose() def _lookup(self, _id, *remainder): return LookupController(_id), remainder class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # these should 404 for path in ('/things', '/things/'): r = app.get(path, expect_errors=True) assert r.status_int == 404 r = app.get('/things/foo') assert r.status_int == 200 assert r.body == b_('ID: foo')
def test_config_hooks(self): class RootController(TGController): @expose() def test(self): return 'HI!' visited_hooks = [] def before_config_hook(app): visited_hooks.append('before_config') return app def after_config_hook(app): visited_hooks.append('after_config') return app def configure_new_app_hook(app): assert isinstance(app, TGApp) visited_hooks.append('configure_new_app') conf = AppConfig(minimal=True, root_controller=RootController()) conf.register_hook('before_config', before_config_hook) conf.register_hook('after_config', after_config_hook) conf.register_hook('configure_new_app', configure_new_app_hook) app = conf.make_wsgi_app() app = TestApp(app) assert 'HI!' in app.get('/test') assert 'before_config' in visited_hooks assert 'after_config' in visited_hooks assert 'configure_new_app' in visited_hooks
def get(self, url, headers): app = TestApp(wsgi.create_app(self.minion)) response = app.get( url, headers=[(k, ",".join(v)) for k , v in headers.canonicalized()], ) return response.body
def RunCompleterCommand_GoTo_Clang_ZeroBasedLineAndColumn_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; return 0; } """ goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToDefinition'], compilation_flags = ['-x', 'c++'], line_num = 10, column_num = 3, contents = contents, filetype = 'cpp' ) eq_( { 'filepath': '/foo', 'line_num': 2, 'column_num': 8 }, app.post_json( '/run_completer_command', goto_data ).json )
def test_view_after_doesnt_apply_to_exception_view(): config = setup() class App(morepath.App): testing_config = config class Root(object): pass class MyException(Exception): pass @App.path(model=Root, path='') def get_root(): return Root() @App.view(model=Root) def view(self, request): @request.after def set_header(response): response.headers.add('Foo', 'FOO') raise MyException() @App.view(model=MyException) def exc_view(self, request): return "My exception" config.commit() c = Client(App()) response = c.get('/') assert response.body == b'My exception' assert response.headers.get('Foo') is None
def test_path_and_url_parameter_converter(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self, id, param): self.id = id self.param = param from datetime import date @app.path(model=Model, path='/{id}', converters=dict(param=date)) def get_model(id=0, param=None): return Model(id, param) @app.view(model=Model) def default(self, request): return "View: %s %s" % (self.id, self.param) @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/1/link') assert response.body == b'http://localhost/1'
def test_view_after_doesnt_apply_to_exception(): config = setup() class App(morepath.App): testing_config = config class Root(object): pass @App.path(model=Root, path='') def get_root(): return Root() @App.view(model=Root) def view(self, request): @request.after def set_header(response): response.headers.add('Foo', 'FOO') raise HTTPNotFound() config.commit() c = Client(App()) response = c.get('/', status=404) assert response.headers.get('Foo') is None
def test_type_hints_and_converters(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self, d): self.d = d from datetime import date @app.path(model=Model, path='', converters=dict(d=date)) def get_model(d): return Model(d) @app.view(model=Model) def default(self, request): return "View: %s" % self.d @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/?d=20140120') assert response.body == b"View: 2014-01-20" response = c.get('/link?d=20140120') assert response.body == b'http://localhost/?d=20140120'
def test_link_for_none_means_no_parameter(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self, id): self.id = id @app.path(model=Model, path='') def get_model(id): return Model(id) @app.view(model=Model) def default(self, request): return "View: %s" % self.id @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/') assert response.body == b"View: None" response = c.get('/link') assert response.body == b'http://localhost/'
def test_simple_generic(self): class RootController(object): @expose(generic=True) def index(self): pass @index.when(method="POST", template="json") def do_post(self): return dict(result="POST") @index.when(method="GET") def do_get(self): return "GET" app = TestApp(Pecan(RootController())) r = app.get("/") assert r.status_int == 200 assert r.body == "GET" r = app.post("/") assert r.status_int == 200 assert r.body == dumps(dict(result="POST")) r = app.get("/do_get", status=404) assert r.status_int == 404
def test_variable_path_one_step(): config = setup() class app(morepath.App): testing_config = config class Model(object): def __init__(self, name): self.name = name @app.path(model=Model, path='{name}') def get_model(name): return Model(name) @app.view(model=Model) def default(self, request): return "View: %s" % self.name @app.view(model=Model, name='link') def link(self, request): return request.link(self) config.commit() c = Client(app()) response = c.get('/foo') assert response.body == b'View: foo' response = c.get('/foo/link') assert response.body == b'http://localhost/foo'
def test_disconnect_hooks_multiple_listener(self): hook1_has_been_called = [] def hook1_listener(): hook1_has_been_called.append(True) hook2_has_been_called = [] def hook2_listener(): hook2_has_been_called.append(True) class RootController(TGController): @expose() def test(self): tg.hooks.notify('custom_hook', controller=RootController.test) return 'HI!' conf = AppConfig(minimal=True, root_controller=RootController()) tg.hooks.register('custom_hook', hook1_listener) tg.hooks.register('custom_hook', hook2_listener) conf.package = PackageWithModel() app = conf.make_wsgi_app() app = TestApp(app) app.get('/test') app.get('/test') tg.hooks.disconnect('custom_hook', hook2_listener) app.get('/test') # Disconnecting an unregistered hook should do nothing. tg.hooks.disconnect('unregistered', hook1_listener) assert len(hook1_has_been_called) == 3, hook1_has_been_called assert len(hook2_has_been_called) == 2, hook2_has_been_called
def test_SyncEntity(self): """Synchronizing an entity.""" from gaesynkit import handlers from webtest import AppError, TestApp # Initialize app app = TestApp(handlers.app) # Make a request res = app.post( '/gaesynkit/rpc/', '{"jsonrpc":"2.0","method":"syncEntity","params":[{"kind":"Book","key":"dGVzdEBkZWZhdWx0ISFCb29rCjI=","version":0,"id":2,"properties":{"title":{"type":"string","value":"The Catcher in the Rye"},"date":{"type":"gd:when","value":"1951/7/16 0:0:0"},"classic":{"type":"bool","value":true},"pages":{"type":"int","value":288},"tags":{"type":"string","value":["novel","identity"]}}},"6eb9a4d405f3ee6c67e965b7693108d2"],"id":3}' ) self.assertEqual("200 OK", res.status) self.assertEqual( simplejson.loads(res.body), { u'jsonrpc': u'2.0', u'result': { u'status': 3, u'version': 1, u'key': u'dGVzdEBkZWZhdWx0ISFCb29rCjI=' }, u'id': 3 }) res = app.post( '/gaesynkit/rpc/', '{"jsonrpc":"2.0","method":"syncEntity","params":[{"kind":"Book","key":"dGVzdEBkZWZhdWx0ISFCb29rCjI=","version":1,"id":2,"properties":{"title":{"type":"string","value":"The Catcher in the Rye"},"date":{"type":"gd:when","value":"1951/7/16 0:0:0"},"classic":{"type":"bool","value":true},"pages":{"type":"int","value":287},"tags":{"type":"string","value":["novel","identity"]}}},"7ec49827a52b56fdd24b07410c9bf0d6"],"id":4}' ) self.assertEqual("200 OK", res.status) self.assertEqual( simplejson.loads(res.body), { u'jsonrpc': u'2.0', u'result': { u'status': 2, u'entity': { u'kind': u'Book', u'version': 2, u'properties': { u'date': { u'type': u'gd:when', u'value': u'1951/07/16 00:00:00' }, u'classic': { u'type': u'bool', u'value': True }, u'pages': { u'type': u'int', u'value': 287 }, u'tags': { u'type': u'string', u'value': [u'novel', u'identity'] }, u'title': { u'type': u'string', u'value': u'The Catcher in the Rye' } }, u'key': u'dGVzdEBkZWZhdWx0ISFCb29rCjI=', u'id': 1 } }, u'id': 4 }) res = app.post( '/gaesynkit/rpc/', '{"jsonrpc":"2.0","method":"syncEntity","params":[{"kind":"Book","key":"dGVzdEBkZWZhdWx0ISFCb29rCjI=","version":0,"id":2,"properties":{"title":{"type":"string","value":"The Catcher in the Rye"},"date":{"type":"gd:when","value":"1951/7/16 0:0:0"},"classic":{"type":"bool","value":true},"pages":{"type":"int","value":287},"tags":{"type":"string","value":["novel","identity"]}}},"7ec49827a52b56fdd24b07410c9bf0d6"],"id":4}' ) self.assertEqual("200 OK", res.status)
class TestFulltext(TestCase): """Test that our fulltext classes function""" def setUp(self): """Setup Tests""" from pyramid.paster import get_app from bookie.tests import BOOKIE_TEST_INI app = get_app(BOOKIE_TEST_INI, 'main') from webtest import TestApp self.testapp = TestApp(app) testing.setUp() global API_KEY if API_KEY is None: res = DBSession.execute( "SELECT api_key FROM users WHERE username = '******'").\ fetchone() API_KEY = res['api_key'] def tearDown(self): """Tear down each test""" testing.tearDown() empty_db() def _get_good_request(self, new_tags=None): """Return the basics for a good add bookmark request""" session = DBSession() prms = { 'url': u'http://google.com', 'description': u'This is my google desc SEE', 'extended': u'And some extended notes about it in full form', 'tags': u'python search', 'api_key': API_KEY, } if new_tags: prms['tags'] = new_tags req_params = urllib.urlencode(prms) res = self.testapp.post('/api/v1/admin/bmark', params=req_params) session.flush() transaction.commit() return res def test_get_handler(self): """Verify we get the right type of full text store object""" handler = get_fulltext_handler("") ok_(isinstance(handler, WhooshFulltext), "Should get a whoosh fulltext by default") def test_sqlite_save(self): """Verify that if we store a bookmark we get the fulltext storage""" # first let's add a bookmark we can search on self._get_good_request() search_res = self.testapp.get('/api/v1/admin/bmarks/search/google') ok_(search_res.status == '200 OK', "Status is 200: " + search_res.status) ok_('my google desc' in search_res.body, "We should find our description on the page: " + search_res.body) search_res = self.testapp.get('/api/v1/admin/bmarks/search/python') ok_(search_res.status == '200 OK', "Status is 200: " + search_res.status) ok_('my google desc' in search_res.body, "Tag search should find our description on the page: " + \ search_res.body) search_res = self.testapp.get( '/api/v1/admin/bmarks/search/extended%20notes') ok_(search_res.status == '200 OK', "Status is 200: " + search_res.status) ok_('extended notes' in search_res.body, "Extended search should find our description on the page: " + \ search_res.body) def test_sqlite_update(self): """Verify that if we update a bookmark, fulltext is updated We need to make sure that updates to the record get cascaded into the fulltext table indexes """ self._get_good_request() # now we need to do another request with updated tag string self._get_good_request(new_tags="google books icons") search_res = self.testapp.get('/admin/results?search=icon') ok_(search_res.status == '200 OK', "Status is 200: " + search_res.status) ok_('icon' in search_res.body, "We should find the new tag icon on the page: " + search_res.body) def test_ajax_search(self): """Verify that we can get a json MorJSON response when ajax search""" # first let's add a bookmark we can search on self._get_good_request() search_res = self.testapp.get('/admin/results/google', headers={ 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }) ok_(search_res.status == '200 OK', "Status is 200: " + search_res.status) ok_('my google desc' in search_res.body, "We should find our description on the page: " + search_res.body) # also check for our specific json bits ok_('success' in search_res.body, "We should see a success bit in the json: " + search_res.body) ok_('payload' in search_res.body, "We should see a payload bit in the json: " + search_res.body) ok_('message' in search_res.body, "We should see a message bit in the json: " + search_res.body)
def testapp(app): """Create Webtest app.""" return TestApp(app)
def setUp(self): super(FunctionalTestBase, self).setUp() self.settings = self.get_settings() app = main(None, **self.settings) self.testapp = TestApp(app)
def setUp(self): from restful_auto_service import main app = main({}) from webtest import TestApp self.testapp = TestApp(app)
def setUp(self): from tutorial import main app = main({}) from webtest import TestApp self.testapp = TestApp(app)
def setUp(self): app = create_app self.client = TestApp(app)
def test_accept(self): # tests that the accept headers are handled the proper way app = TestApp(main({})) # requesting the wrong accept header should return a 406 ... response = app.get('/service2', headers={'Accept': 'audio/*'}, status=406) # ... with the list of accepted content-types error_location = response.json['errors'][0]['location'] error_name = response.json['errors'][0]['name'] error_description = response.json['errors'][0]['description'] self.assertEquals('header', error_location) self.assertEquals('Accept', error_name) self.assertTrue('application/json' in error_description) self.assertTrue('text/json' in error_description) self.assertTrue('text/plain' in error_description) # requesting a supported type should give an appropriate response type response = app.get('/service2', headers={'Accept': 'application/*'}) self.assertEqual(response.content_type, "application/json") response = app.get('/service2', headers={'Accept': 'text/plain'}) self.assertEqual(response.content_type, "text/plain") # it should also work with multiple Accept headers response = app.get('/service2', headers={ 'Accept': 'audio/*, application/*' }) self.assertEqual(response.content_type, "application/json") # and requested preference order should be respected headers = {'Accept': 'application/json; q=1.0, text/plain; q=0.9'} response = app.get('/service2', headers=headers) self.assertEqual(response.content_type, "application/json") headers = {'Accept': 'application/json; q=0.9, text/plain; q=1.0'} response = app.get('/service2', headers=headers) self.assertEqual(response.content_type, "text/plain") # test that using a callable to define what's accepted works as well response = app.get('/service3', headers={'Accept': 'audio/*'}, status=406) error_description = response.json['errors'][0]['description'] self.assertTrue('text/json' in error_description) response = app.get('/service3', headers={'Accept': 'text/*'}) self.assertEqual(response.content_type, "text/json") # if we are not asking for a particular content-type, # we should get one of the two types that the service supports. response = app.get('/service2') self.assertTrue(response.content_type in ("application/json", "text/plain"))
def make_app_with_deserializer(self, deserializer): config = Configurator(settings={}) config.include(includeme) config.add_cornice_deserializer('text/dummy', deserializer) return TestApp(CatchErrors(config.make_wsgi_app()))
def setUp(self): from ogcpywps import main app = main({}) from webtest import TestApp self.testapp = TestApp(app)
def test_content_type_on_get(self): # test that a Content-Type request header is not # checked on GET requests, they don't usually have a body app = TestApp(main({})) response = app.get('/service5') self.assertEqual(response.json, "some response")
def test_validation_hooked_error_response(self): app = TestApp(main({})) response = app.post('/service4', status=400) self.assertTrue(b'<errors>' in response.body)
def test_filters(self): app = TestApp(main({})) # filters can be applied to all the methods of a service self.assertTrue(b"filtered response" in app.get('/filtered').body) self.assertTrue(b"unfiltered" in app.post('/filtered').body)
def make_ordinary_app(self): return TestApp(main({}))
def test_accept_issue_113_text_application_json(self): app = TestApp(main({})) response = app.get('/service3', headers={'Accept': 'application/json'}) self.assertEqual(response.content_type, "application/json")
def test_email_field(self): app = TestApp(main({})) content = {'email': '*****@*****.**'} app.post_json('/newsletter', params=content)
def __init__(self): self.test_core = TestApp(Core().execute_wsgi())
def test_accept_issue_113_text_html_not_acceptable(self): app = TestApp(main({})) # requesting an unsupported content type should return a HTTP 406 (Not # Acceptable) app.get('/service3', headers={'Accept': 'text/html'}, status=406)
class Cs_Subcommands_test(Cs_Handlers_test): def GoTo_Basic_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GoTo'], line_num=9, column_num=15, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'Program.cs'), 'line_num': 7, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementation_Basic_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=13, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 30, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementation_NoImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=17, column_num=13, contents=contents, filetype='cs', filepath=filepath) try: self._app.post_json('/run_completer_command', goto_data).json raise Exception("Expected a 'No implementations found' error") except AppError as e: if 'No implementations found' in str(e): pass else: raise finally: self._StopOmniSharpServer(filepath) def CsCompleter_InvalidLocation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=2, column_num=1, contents=contents, filetype='cs', filepath=filepath) try: self._app.post_json('/run_completer_command', goto_data).json raise Exception( 'Expected a "Can\\\'t jump to implementation" error') except AppError as e: if 'Can\\\'t jump to implementation' in str(e): pass else: raise finally: self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_NoImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=17, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 35, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_SingleImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=13, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 30, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_MultipleImplementations_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=21, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_([{ 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 43, 'column_num': 3 }, { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 48, 'column_num': 3 }], self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GetType_EmptyMessage_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=1, column_num=1, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u""}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_VariableDeclaration_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=4, column_num=5, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"string"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_VariableUsage_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=5, column_num=5, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"string str"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_Constant_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=4, column_num=14, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"System.String"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_DocsIgnored_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=9, column_num=34, contents=contents, filetype='cs', filepath=filepath) eq_({ u'message': u"int GetTypeTestCase.an_int_with_docs;", }, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetDoc_Variable_test(self): filepath = self._PathToTestFile('testy', 'GetDocTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) getdoc_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetDoc'], line_num=13, column_num=28, contents=contents, filetype='cs', filepath=filepath) eq_( { 'detailed_info': 'int GetDocTestCase.an_int;\n' 'an integer, or something', }, self._app.post_json('/run_completer_command', getdoc_data).json) self._StopOmniSharpServer(filepath) def GetDoc_Function_test(self): filepath = self._PathToTestFile('testy', 'GetDocTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) getdoc_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetDoc'], line_num=33, column_num=27, contents=contents, filetype='cs', filepath=filepath) # It seems that Omnisharp server eats newlines eq_( { 'detailed_info': 'int GetDocTestCase.DoATest();\n' ' Very important method. With multiple lines of ' 'commentary And Format- -ting', }, self._app.post_json('/run_completer_command', getdoc_data).json) self._StopOmniSharpServer(filepath) def _RunFixIt(self, line, column, expected_result): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) fixit_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['FixIt'], line_num=line, column_num=column, contents=contents, filetype='cs', filepath=filepath) eq_(expected_result, self._app.post_json('/run_completer_command', fixit_data).json) self._StopOmniSharpServer(filepath) def FixIt_RemoveSingleLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 11, 1, { u'fixits': [{ u'location': { u'line_num': 11, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': '', u'range': { u'start': { u'line_num': 10, u'column_num': 20, u'filepath': filepath }, u'end': { u'line_num': 11, u'column_num': 30, u'filepath': filepath }, } }] }] }) def FixIt_MultipleLines_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 19, 1, { u'fixits': [{ u'location': { u'line_num': 19, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': "return On", u'range': { u'start': { u'line_num': 20, u'column_num': 13, u'filepath': filepath }, u'end': { u'line_num': 21, u'column_num': 35, u'filepath': filepath }, } }] }] }) def FixIt_SpanFileEdge_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 1, 1, { u'fixits': [{ u'location': { u'line_num': 1, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': 'System', u'range': { u'start': { u'line_num': 1, u'column_num': 7, u'filepath': filepath }, u'end': { u'line_num': 3, u'column_num': 18, u'filepath': filepath }, } }] }] }) def FixIt_AddTextInLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 9, 1, { u'fixits': [{ u'location': { u'line_num': 9, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': ', StringComparison.Ordinal', u'range': { u'start': { u'line_num': 9, u'column_num': 29, u'filepath': filepath }, u'end': { u'line_num': 9, u'column_num': 29, u'filepath': filepath }, } }] }] }) def FixIt_ReplaceTextInLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 10, 1, { u'fixits': [{ u'location': { u'line_num': 10, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': 'const int', u'range': { u'start': { u'line_num': 10, u'column_num': 13, u'filepath': filepath }, u'end': { u'line_num': 10, u'column_num': 16, u'filepath': filepath }, } }] }] }) def StopServer_NoErrorIfNotStarted_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') self._StopOmniSharpServer(filepath) # Success = no raise def StopServer_KeepLogFiles_test(self): yield self._StopServer_KeepLogFiles, True yield self._StopServer_KeepLogFiles, False def _StopServer_KeepLogFiles(self, keeping_log_files): self._ChangeSpecificOptions( {'server_keep_logfiles': keeping_log_files}) self._app = TestApp(handlers.app) self._app.post_json( '/ignore_extra_conf_file', {'filepath': self._PathToTestFile('.ycm_extra_conf.py')}) filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) event_data = self._BuildRequest(filetype='cs', filepath=filepath) debuginfo = self._app.post_json('/debug_info', event_data).json log_files_match = re.search("^OmniSharp logfiles:\n(.*)\n(.*)", debuginfo, re.MULTILINE) stdout_logfiles_location = log_files_match.group(1) stderr_logfiles_location = log_files_match.group(2) try: ok_(os.path.exists(stdout_logfiles_location), "Logfile should exist at {0}".format(stdout_logfiles_location)) ok_(os.path.exists(stderr_logfiles_location), "Logfile should exist at {0}".format(stderr_logfiles_location)) finally: self._StopOmniSharpServer(filepath) if keeping_log_files: ok_( os.path.exists(stdout_logfiles_location), "Logfile should still exist at " "{0}".format(stdout_logfiles_location)) ok_( os.path.exists(stderr_logfiles_location), "Logfile should still exist at " "{0}".format(stderr_logfiles_location)) else: ok_( not os.path.exists(stdout_logfiles_location), "Logfile should no longer exist at " "{0}".format(stdout_logfiles_location)) ok_( not os.path.exists(stderr_logfiles_location), "Logfile should no longer exist at " "{0}".format(stderr_logfiles_location))
def test_accept_issue_113_text_star(self): app = TestApp(main({})) response = app.get('/service3', headers={'Accept': 'text/*'}) self.assertEqual(response.content_type, "text/json")
def testapp(app): """A Webtest app.""" return TestApp(app)
class Client(object): def __init__(self): self.test_core = TestApp(Core().execute_wsgi()) def get_api(self, api_url, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.get(__api_url) response.json = test_core_response.json response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body response.content_type = test_core_response.content_type return response def post_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.post_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def patch_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.patch_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def put_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.put_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def delete_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.delete_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response
def test_custom_delete(self): class OthersController(object): @expose() def index(self): return 'DELETE' @expose() def reset(self, id): return str(id) class ThingsController(RestController): others = OthersController() @expose() def delete_fail(self): abort(500) class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test bad delete r = app.delete('/things/delete_fail', status=405) assert r.status_int == 405 # test bad delete with _method parameter and GET r = app.get('/things/delete_fail?_method=delete', status=405) assert r.status_int == 405 # test bad delete with _method parameter and POST r = app.post('/things/delete_fail', {'_method': 'delete'}, status=405) assert r.status_int == 405 # test custom delete without ID r = app.delete('/things/others/') assert r.status_int == 200 assert r.body == b_('DELETE') # test custom delete without ID with _method parameter and GET r = app.get('/things/others/?_method=delete', status=405) assert r.status_int == 405 # test custom delete without ID with _method parameter and POST r = app.post('/things/others/', {'_method': 'delete'}) assert r.status_int == 200 assert r.body == b_('DELETE') # test custom delete with ID r = app.delete('/things/others/reset/1') assert r.status_int == 200 assert r.body == b_('1') # test custom delete with ID with _method parameter and GET r = app.get('/things/others/reset/1?_method=delete', status=405) assert r.status_int == 405 # test custom delete with ID with _method parameter and POST r = app.post('/things/others/reset/1', {'_method': 'delete'}) assert r.status_int == 200 assert r.body == b_('1')
def setUpClass(cls): cls.app = TestApp(app)
def test_complicated_nested_rest(self): class BarsController(RestController): data = [['zero-zero', 'zero-one'], ['one-zero', 'one-one']] @expose() def get_one(self, foo_id, id): return self.data[int(foo_id)][int(id)] @expose('json') def get_all(self, foo_id): return dict(items=self.data[int(foo_id)]) @expose() def new(self, foo_id): return 'NEW FOR %s' % foo_id @expose() def post(self, foo_id, value): foo_id = int(foo_id) if len(self.data) < foo_id + 1: self.data.extend([[]] * (foo_id - len(self.data) + 1)) self.data[foo_id].append(value) response.status = 302 return 'CREATED FOR %s' % foo_id @expose() def edit(self, foo_id, id): return 'EDIT %s' % self.data[int(foo_id)][int(id)] @expose() def put(self, foo_id, id, value): self.data[int(foo_id)][int(id)] = value return 'UPDATED' @expose() def get_delete(self, foo_id, id): return 'DELETE %s' % self.data[int(foo_id)][int(id)] @expose() def delete(self, foo_id, id): del self.data[int(foo_id)][int(id)] return 'DELETED' class FoosController(RestController): data = ['zero', 'one'] bars = BarsController() @expose() def get_one(self, id): return self.data[int(id)] @expose('json') def get_all(self): return dict(items=self.data) @expose() def new(self): return 'NEW' @expose() def edit(self, id): return 'EDIT %s' % self.data[int(id)] @expose() def post(self, value): self.data.append(value) response.status = 302 return 'CREATED' @expose() def put(self, id, value): self.data[int(id)] = value return 'UPDATED' @expose() def get_delete(self, id): return 'DELETE %s' % self.data[int(id)] @expose() def delete(self, id): del self.data[int(id)] return 'DELETED' class RootController(object): foos = FoosController() # create the app app = TestApp(make_app(RootController())) # test get_all r = app.get('/foos') assert r.status_int == 200 assert r.body == b_(dumps(dict(items=FoosController.data))) # test nested get_all r = app.get('/foos/1/bars') assert r.status_int == 200 assert r.body == b_(dumps(dict(items=BarsController.data[1]))) # test get_one for i, value in enumerate(FoosController.data): r = app.get('/foos/%d' % i) assert r.status_int == 200 assert r.body == b_(value) # test nested get_one for i, value in enumerate(FoosController.data): for j, value in enumerate(BarsController.data[i]): r = app.get('/foos/%s/bars/%s' % (i, j)) assert r.status_int == 200 assert r.body == b_(value) # test post r = app.post('/foos', {'value': 'two'}) assert r.status_int == 302 assert r.body == b_('CREATED') # make sure it works r = app.get('/foos/2') assert r.status_int == 200 assert r.body == b_('two') # test nested post r = app.post('/foos/2/bars', {'value': 'two-zero'}) assert r.status_int == 302 assert r.body == b_('CREATED FOR 2') # make sure it works r = app.get('/foos/2/bars/0') assert r.status_int == 200 assert r.body == b_('two-zero') # test edit r = app.get('/foos/1/edit') assert r.status_int == 200 assert r.body == b_('EDIT one') # test nested edit r = app.get('/foos/1/bars/1/edit') assert r.status_int == 200 assert r.body == b_('EDIT one-one') # test put r = app.put('/foos/2', {'value': 'TWO'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/foos/2') assert r.status_int == 200 assert r.body == b_('TWO') # test nested put r = app.put('/foos/2/bars/0', {'value': 'TWO-ZERO'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/foos/2/bars/0') assert r.status_int == 200 assert r.body == b_('TWO-ZERO') # test put with _method parameter and GET r = app.get('/foos/2?_method=put', {'value': 'TWO!'}, status=405) assert r.status_int == 405 # make sure it works r = app.get('/foos/2') assert r.status_int == 200 assert r.body == b_('TWO') # test nested put with _method parameter and GET r = app.get( '/foos/2/bars/0?_method=put', {'value': 'ZERO-TWO!'}, status=405 ) assert r.status_int == 405 # make sure it works r = app.get('/foos/2/bars/0') assert r.status_int == 200 assert r.body == b_('TWO-ZERO') # test put with _method parameter and POST r = app.post('/foos/2?_method=put', {'value': 'TWO!'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/foos/2') assert r.status_int == 200 assert r.body == b_('TWO!') # test nested put with _method parameter and POST r = app.post('/foos/2/bars/0?_method=put', {'value': 'TWO-ZERO!'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/foos/2/bars/0') assert r.status_int == 200 assert r.body == b_('TWO-ZERO!') # test get delete r = app.get('/foos/2/delete') assert r.status_int == 200 assert r.body == b_('DELETE TWO!') # test nested get delete r = app.get('/foos/2/bars/0/delete') assert r.status_int == 200 assert r.body == b_('DELETE TWO-ZERO!') # test nested delete r = app.delete('/foos/2/bars/0') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/foos/2/bars') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 0 # test delete r = app.delete('/foos/2') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/foos') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 2 # test nested delete with _method parameter and GET r = app.get('/foos/1/bars/1?_method=DELETE', status=405) assert r.status_int == 405 # make sure it works r = app.get('/foos/1/bars') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 2 # test delete with _method parameter and GET r = app.get('/foos/1?_method=DELETE', status=405) assert r.status_int == 405 # make sure it works r = app.get('/foos') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 2 # test nested delete with _method parameter and POST r = app.post('/foos/1/bars/1?_method=DELETE') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/foos/1/bars') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 1 # test delete with _method parameter and POST r = app.post('/foos/1?_method=DELETE') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/foos') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 1
def __init__(self, *args, **kwargs): wsgiapp = pylons.test.pylonsapp config = wsgiapp.config self.app = TestApp(wsgiapp) url._push_object(URLGenerator(config['routes.map'], environ))
def test_dynamic_rest_lookup(self): class BarController(RestController): @expose() def get_all(self): return "BAR" @expose() def put(self): return "PUT_BAR" @expose() def delete(self): return "DELETE_BAR" class BarsController(RestController): @expose() def _lookup(self, id_, *remainder): return BarController(), remainder @expose() def get_all(self): return "BARS" @expose() def post(self): return "POST_BARS" class FooController(RestController): bars = BarsController() @expose() def get_all(self): return "FOO" @expose() def put(self): return "PUT_FOO" @expose() def delete(self): return "DELETE_FOO" class FoosController(RestController): @expose() def _lookup(self, id_, *remainder): return FooController(), remainder @expose() def get_all(self): return "FOOS" @expose() def post(self): return "POST_FOOS" class RootController(RestController): foos = FoosController() app = TestApp(make_app(RootController())) r = app.get('/foos') assert r.status_int == 200 assert r.body == b_('FOOS') r = app.post('/foos') assert r.status_int == 200 assert r.body == b_('POST_FOOS') r = app.get('/foos/foo') assert r.status_int == 200 assert r.body == b_('FOO') r = app.put('/foos/foo') assert r.status_int == 200 assert r.body == b_('PUT_FOO') r = app.delete('/foos/foo') assert r.status_int == 200 assert r.body == b_('DELETE_FOO') r = app.get('/foos/foo/bars') assert r.status_int == 200 assert r.body == b_('BARS') r = app.post('/foos/foo/bars') assert r.status_int == 200 assert r.body == b_('POST_BARS') r = app.get('/foos/foo/bars/bar') assert r.status_int == 200 assert r.body == b_('BAR') r = app.put('/foos/foo/bars/bar') assert r.status_int == 200 assert r.body == b_('PUT_BAR') r = app.delete('/foos/foo/bars/bar') assert r.status_int == 200 assert r.body == b_('DELETE_BAR')
def test_bad_rest(self): class ThingsController(RestController): pass class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get_all r = app.get('/things', status=405) assert r.status_int == 405 # test get_one r = app.get('/things/1', status=405) assert r.status_int == 405 # test post r = app.post('/things', {'value': 'one'}, status=405) assert r.status_int == 405 # test edit r = app.get('/things/1/edit', status=405) assert r.status_int == 405 # test put r = app.put('/things/1', {'value': 'ONE'}, status=405) # test put with _method parameter and GET r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405) assert r.status_int == 405 # test put with _method parameter and POST r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=405) assert r.status_int == 405 # test get delete r = app.get('/things/1/delete', status=405) assert r.status_int == 405 # test delete r = app.delete('/things/1', status=405) assert r.status_int == 405 # test delete with _method parameter and GET r = app.get('/things/1?_method=DELETE', status=405) assert r.status_int == 405 # test delete with _method parameter and POST r = app.post('/things/1?_method=DELETE', status=405) assert r.status_int == 405 # test "RESET" custom action with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things', method='RESET', status=405) assert r.status_int == 405
def test_nested_rest_with_lookup(self): class SubController(RestController): @expose() def get_all(self): return "SUB" class FinalController(RestController): def __init__(self, id_): self.id_ = id_ @expose() def get_all(self): return "FINAL-%s" % self.id_ @expose() def post(self): return "POST-%s" % self.id_ class LookupController(RestController): sub = SubController() def __init__(self, id_): self.id_ = id_ @expose() def _lookup(self, id_, *remainder): return FinalController(id_), remainder @expose() def get_all(self): raise AssertionError("Never Reached") @expose() def post(self): return "POST-LOOKUP-%s" % self.id_ @expose() def put(self, id_): return "PUT-LOOKUP-%s-%s" % (self.id_, id_) @expose() def delete(self, id_): return "DELETE-LOOKUP-%s-%s" % (self.id_, id_) class FooController(RestController): @expose() def _lookup(self, id_, *remainder): return LookupController(id_), remainder @expose() def get_one(self, id_): return "GET ONE" @expose() def get_all(self): return "INDEX" @expose() def post(self): return "POST" @expose() def put(self, id_): return "PUT-%s" % id_ @expose() def delete(self, id_): return "DELETE-%s" % id_ class RootController(RestController): foo = FooController() app = TestApp(make_app(RootController())) r = app.get('/foo') assert r.status_int == 200 assert r.body == b_('INDEX') r = app.post('/foo') assert r.status_int == 200 assert r.body == b_('POST') r = app.get('/foo/1') assert r.status_int == 200 assert r.body == b_('GET ONE') r = app.post('/foo/1') assert r.status_int == 200 assert r.body == b_('POST-LOOKUP-1') r = app.put('/foo/1') assert r.status_int == 200 assert r.body == b_('PUT-1') r = app.delete('/foo/1') assert r.status_int == 200 assert r.body == b_('DELETE-1') r = app.put('/foo/1/2') assert r.status_int == 200 assert r.body == b_('PUT-LOOKUP-1-2') r = app.delete('/foo/1/2') assert r.status_int == 200 assert r.body == b_('DELETE-LOOKUP-1-2') r = app.get('/foo/1/2') assert r.status_int == 200 assert r.body == b_('FINAL-2') r = app.post('/foo/1/2') assert r.status_int == 200 assert r.body == b_('POST-2')
def test_basic_rest(self): class OthersController(object): @expose() def index(self): return 'OTHERS' @expose() def echo(self, value): return str(value) class ThingsController(RestController): data = ['zero', 'one', 'two', 'three'] _custom_actions = {'count': ['GET'], 'length': ['GET', 'POST']} others = OthersController() @expose() def get_one(self, id): return self.data[int(id)] @expose('json') def get_all(self): return dict(items=self.data) @expose() def length(self, id, value=None): length = len(self.data[int(id)]) if value: length += len(value) return str(length) @expose() def get_count(self): return str(len(self.data)) @expose() def new(self): return 'NEW' @expose() def post(self, value): self.data.append(value) response.status = 302 return 'CREATED' @expose() def edit(self, id): return 'EDIT %s' % self.data[int(id)] @expose() def put(self, id, value): self.data[int(id)] = value return 'UPDATED' @expose() def get_delete(self, id): return 'DELETE %s' % self.data[int(id)] @expose() def delete(self, id): del self.data[int(id)] return 'DELETED' @expose() def reset(self): return 'RESET' @expose() def post_options(self): return 'OPTIONS' @expose() def options(self): abort(500) @expose() def other(self): abort(500) class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get_all r = app.get('/things') assert r.status_int == 200 assert r.body == b_(dumps(dict(items=ThingsController.data))) # test get_one for i, value in enumerate(ThingsController.data): r = app.get('/things/%d' % i) assert r.status_int == 200 assert r.body == b_(value) # test post r = app.post('/things', {'value': 'four'}) assert r.status_int == 302 assert r.body == b_('CREATED') # make sure it works r = app.get('/things/4') assert r.status_int == 200 assert r.body == b_('four') # test edit r = app.get('/things/3/edit') assert r.status_int == 200 assert r.body == b_('EDIT three') # test put r = app.put('/things/4', {'value': 'FOUR'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/things/4') assert r.status_int == 200 assert r.body == b_('FOUR') # test put with _method parameter and GET r = app.get('/things/4?_method=put', {'value': 'FOUR!'}, status=405) assert r.status_int == 405 # make sure it works r = app.get('/things/4') assert r.status_int == 200 assert r.body == b_('FOUR') # test put with _method parameter and POST r = app.post('/things/4?_method=put', {'value': 'FOUR!'}) assert r.status_int == 200 assert r.body == b_('UPDATED') # make sure it works r = app.get('/things/4') assert r.status_int == 200 assert r.body == b_('FOUR!') # test get delete r = app.get('/things/4/delete') assert r.status_int == 200 assert r.body == b_('DELETE FOUR!') # test delete r = app.delete('/things/4') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/things') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 4 # test delete with _method parameter and GET r = app.get('/things/3?_method=DELETE', status=405) assert r.status_int == 405 # make sure it works r = app.get('/things') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 4 # test delete with _method parameter and POST r = app.post('/things/3?_method=DELETE') assert r.status_int == 200 assert r.body == b_('DELETED') # make sure it works r = app.get('/things') assert r.status_int == 200 assert len(loads(r.body.decode())['items']) == 3 # test "RESET" custom action r = app.request('/things', method='RESET') assert r.status_int == 200 assert r.body == b_('RESET') # test "RESET" custom action with _method parameter r = app.get('/things?_method=RESET') assert r.status_int == 200 assert r.body == b_('RESET') # test the "OPTIONS" custom action r = app.request('/things', method='OPTIONS') assert r.status_int == 200 assert r.body == b_('OPTIONS') # test the "OPTIONS" custom action with the _method parameter r = app.post('/things', {'_method': 'OPTIONS'}) assert r.status_int == 200 assert r.body == b_('OPTIONS') # test the "other" custom action with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things/other', method='MISC', status=405) assert r.status_int == 405 # test the "other" custom action with the _method parameter r = app.post('/things/other', {'_method': 'MISC'}, status=405) assert r.status_int == 405 # test the "others" custom action with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things/others/', method='MISC') assert r.status_int == 200 assert r.body == b_('OTHERS') # test the "others" custom action missing trailing slash with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things/others', method='MISC', status=302) assert r.status_int == 302 # test the "others" custom action with the _method parameter r = app.get('/things/others/?_method=MISC') assert r.status_int == 200 assert r.body == b_('OTHERS') # test an invalid custom action r = app.get('/things?_method=BAD', status=405) assert r.status_int == 405 # test custom "GET" request "count" r = app.get('/things/count') assert r.status_int == 200 assert r.body == b_('3') # test custom "GET" request "length" r = app.get('/things/1/length') assert r.status_int == 200 assert r.body == b_(str(len('one'))) # test custom "GET" request through subcontroller r = app.get('/things/others/echo?value=test') assert r.status_int == 200 assert r.body == b_('test') # test custom "POST" request "length" r = app.post('/things/1/length', {'value': 'test'}) assert r.status_int == 200 assert r.body == b_(str(len('onetest'))) # test custom "POST" request through subcontroller r = app.post('/things/others/echo', {'value': 'test'}) assert r.status_int == 200 assert r.body == b_('test')