def test_resent_cookie(): """Test that the client resends cookies on subsequent requests """ c = Client(cookie_app) c.open() appiter, code, headers = c.open() assert ''.join(appiter) == 'test=test'
def test_check_login(): from glashammer.bundles.auth import setup_auth, login from glashammer.bundles.sessions import get_session called = [] def check(u, p): called.append((u, p)) return u == p def view(req): login('a') return Response() def setup_app(app): app.add_setup(setup_auth) app.connect_event('password-check', check) app.add_url('/', 'a/b', view=view) app = make_app(setup_app, 'test_output') c = Client(app) c.open() session = get_session() token_key = get_app().conf['auth/token_key'] assert token_key in session assert session[token_key] == 'a'
def test_context_error_propagates(app, environ): # The Protector relies on any errors being raised by a request # context manager being propagated all the way to the application # error handler. Should these test cases fail, then the Protector # will fail to do its job. class CustomErrorClass(Exception): pass err = CustomErrorClass() tracked = [] @app.context def error_func(): raise err yield @app.error_handler.register(CustomErrorClass) def track_error(e): tracked.append(e) return BaseResponse("Foo") client = Client(app) client.open(environ) assert tracked == [err]
class TestJsonRest(object): def setup(self): app = load_app_from_path('examples/jsonrest/run.py') self.c = Client(app) def test_index(self): iter, status, headers = self.c.open() s = ''.join(iter) assert """ <a href="#" id="get_link">GET</a> <a href="#" id="post_link">POST</a> <a href="#" id="put_link">PUT</a> <a href="#" id="delete_link">DELETE</a> """.strip('\n') in s def test_get(self): iter, status, headers = self.c.open('/svc') d = loads(''.join(iter)) assert d['type'] == 'GET' def test_put(self): iter, status, headers = self.c.put('/svc') d = loads(''.join(iter)) assert d['type'] == 'PUT' def test_delete(self): iter, status, headers = self.c.delete('/svc') d = loads(''.join(iter)) assert d['type'] == 'DELETE' def test_post(self): iter, status, headers = self.c.post('/svc') d = loads(''.join(iter)) assert d['type'] == 'POST'
class WsgiAPIClient(BaseAPIClient): wsgi_app = None server_cosmos = None def __init__(self, *args, **kwargs): self.client = WerkzeugTestClient(self.wsgi_app, response_wrapper=Response) spec = self.call(SpecEndpoint()) super(WsgiAPIClient, self).__init__(*args, spec=spec, **kwargs) def make_request(self, endpoint, request): kwargs = { "method": request.method, "data": request.data, "headers": request.headers } # Content-Type should be provided as kwarg because otherwise we can't # access request.mimetype if 'Content-Type' in request.headers: kwargs['content_type'] = request.headers.pop('Content-Type') if self.server_cosmos is None: r = self.client.open(path=request.url, **kwargs) else: with cosmos.swap(self.server_cosmos): r = self.client.open(path=request.url, **kwargs) resp = requests.Response() resp._content = r.data resp.headers = CaseInsensitiveDict(r.headers) resp.status_code = r.status_code return resp
class TestJsonRestService(object): def setup(self): def _setup_json(app): app.add_url('/', '', view=_Service()) app = make_app(_setup_json, 'test_output') self.client = Client(app) def test_get(self): ai, st, h = self.client.open(method='GET') s = list(ai)[0] assert 'GET' in s def test_post(self): ai, st, h = self.client.open(method='POST') s = list(ai)[0] assert 'POST' in s def test_put(self): ai, st, h = self.client.open(method='PUT') s = list(ai)[0] assert 'PUT' in s def test_delete(self): ai, st, h = self.client.open(method='DELETE') s = list(ai)[0] assert 'DELETE' in s
def test_disable_cookies(): """Ensure that cookies are not stored when use_cookies is False in the client """ c = Client(cookie_app, use_cookies=False) c.open() appiter, code, headers = c.open() assert ''.join(appiter) == 'No Cookie'
def test_cookie_for_different_path(): """Test that the client resends cookies on subsequent requests for different paths """ c = Client(cookie_app) c.open('/path1') appiter, code, headers = c.open('/path2') assert ''.join(appiter) == 'test=test'
def test_autorules_client(): app = gh_app(_setup) c = Client(app) i, s, h = c.open('/') assert '404' in s i, s, h = c.open('/pages/') print i, s, h assert '200' in s assert 'hello' in ''.join(i)
def test_session_setup(): def _setup_sessions(app): from glashammer.bundles.sessions import setup_app app.add_setup(setup_app) app.add_url('/', '', view=_sessioned_view) app = make_app(_setup_sessions, 'test_output') c = Client(app) c.open()
def _test_finalized(): def _bview(req): app = get_app() assert_raises((RuntimeError,), app.add_config_var, 'a', str, 'a') return Response('hello') def _setup_app(app): app.add_url('/', 'hoo', _bview) app = make_app(_setup_app, 'test_output') c = Client(app) c.open()
def test_event_log_handler(): logs = [] def log(level, record): logs.append((level, record)) def setup_app(app): app.connect_event('log', log) app = make_app(setup_app, 'test_output') c = Client(app) c.open() assert len(logs) > 5
class TestHelloWorld(object): def setup(self): app = load_app_from_path('examples/helloworld/run.py') self.c = Client(app) def test_index(self): iter, status, headers = self.c.open() assert ' '.join(iter) == '<h1>Hello World</h1>' assert status == '200 OK' def test_notfound(self): iter, status, headers = self.c.open('/blah') assert status == '404 NOT FOUND' assert '404 Not Found' in ' '.join(iter)
def test_api_quota_detail_dates_no_data(self): """ Test the quota details page when there are date but no data """ response = Client.open( self.client, path="/api/quota/wrongguid/2013-12-31/2014-1-1/", headers=valid_header) self.assertEqual(response.status_code, 404)
def open(self, *args, **kwargs): if self.context_preserved: _request_ctx_stack.pop() self.context_preserved = False kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context as_tuple = kwargs.pop('as_tuple', False) buffered = kwargs.pop('buffered', False) follow_redirects = kwargs.pop('follow_redirects', False) builder = EnvironBuilder(*args, **kwargs) if self.application.config.get('SERVER_NAME'): server_name = self.application.config.get('SERVER_NAME') if ':' not in server_name: http_host, http_port = server_name, None else: http_host, http_port = server_name.split(':', 1) if builder.base_url == 'http://localhost/': # Default Generated Base URL if http_port != None: builder.host = http_host + ':' + http_port else: builder.host = http_host old = _request_ctx_stack.top try: return Client.open(self, builder, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects) finally: self.context_preserved = _request_ctx_stack.top is not old
def test_admin_page_rejects_bad_username(self): """ Check that incorrect username won't allow access """ h = Headers() auth = 'foo:{0}'.format(Config.PASSWORD).encode('ascii') h.add('Authorization', b'Basic ' + base64.b64encode(auth)) rv = Client.open(self.client, path='/', headers=h) self.assert_401(rv)
def test_admin_page_rejects_bad_password(self): """ Check that incorrect password won't allow access """ h = Headers() auth = '{0}:foo'.format(Config.USERNAME).encode('ascii') h.add('Authorization', b'Basic ' + base64.b64encode(auth)) rv = Client.open(self.client, path='/', headers=h) self.assert_401(rv)
def test_post_wrong_content_type(simple_app): app_client = simple_app.app.test_client() resp = app_client.post('/v1.0/post_wrong_content_type', content_type="application/xml", data=json.dumps({"some": "data"}) ) assert resp.status_code == 415 resp = app_client.post('/v1.0/post_wrong_content_type', data=json.dumps({"some": "data"}) ) assert resp.status_code == 415 # this test checks exactly what the test directly above is supposed to check, # i.e. no content-type is provided in the header # unfortunately there is an issue with the werkzeug test environment # (https://github.com/pallets/werkzeug/issues/1159) # so that content-type is added to every request, we remove it here manually for our test # this test can be removed once the werkzeug issue is addressed builder = EnvironBuilder(path='/v1.0/post_wrong_content_type', method='POST', data=json.dumps({"some": "data"})) try: environ = builder.get_environ() finally: builder.close() environ.pop('CONTENT_TYPE') # we cannot just call app_client.open() since app_client is a flask.testing.FlaskClient # which overrides werkzeug.test.Client.open() but does not allow passing an environment # directly resp = Client.open(app_client, environ) assert resp.status_code == 415
def open(self, *args, **kwargs): as_tuple = kwargs.pop("as_tuple", False) buffered = kwargs.pop("buffered", False) follow_redirects = kwargs.pop("follow_redirects", False) if (not kwargs and len(args) == 1 and isinstance(args[0], (werkzeug.test.EnvironBuilder, dict))): environ = self.environ_base.copy() if isinstance(args[0], werkzeug.test.EnvironBuilder): environ.update(args[0].get_environ()) else: environ.update(args[0]) environ["flask._preserve_context"] = self.preserve_context else: kwargs.setdefault( "environ_overrides", {})["flask._preserve_context"] = self.preserve_context kwargs.setdefault("environ_base", self.environ_base) builder = EnvironBuilder(self.application, *args, **kwargs) try: environ = builder.get_environ() finally: builder.close() return Client.open( self, environ, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects, )
def send_get_request(self, endpoint): # h = Headers() # h.add('Authorization', 'Bearer {}'.format(self.token)) return Client.open(self.client, method='GET', path=endpoint, content_type='application/json')
def test_vote_page_check_scope(self): cache = StrictRedis(db=config.tokens_cache_redis_db) h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode(config.test_token + ':')) rv = Client.open(self.client, path='/people/v1/vote/hhauer', headers=h) self.assert_200(rv) cache.srem(config.people_scope_vote, 'test@test') rv = Client.open(self.client, path='/people/v1/vote/hhauer', headers=h) self.assert_403(rv) cache.sadd(config.people_scope_vote, 'test@test')
class TestPagination(object): def setup(self): def view(req): return Response(self.p.generate(next_link=True, prev_link=True)) def setup_app(app): app.add_url('/', 'app/page', view=view) app = make_app(setup_app, 'test_output') self.c = Client(app) self.p = Pagination('app/page', 3, 10, 500) def test_generate(self): iter, status, heaaders = self.c.open() s = ''.join(iter) assert s == """ <a href="/?page=2">« Prev</a> <a href="/?page=1">1</a><span class="commata">, </span><a href="/?page=2">2</a><span class="commata">, </span><strong>3</strong><span class="commata">, </span><a href="/?page=4">4</a><span class="commata">, </span><a href="/?page=5">5</a><span class="ellipsis">... </span><a href="/?page=49">49</a><span class="commata">, </span><a href="/?page=50">50</a> <a href="/?page=4">Next »</a> """.strip()
def open(self, *args, **kwargs): as_tuple = kwargs.pop('as_tuple', False) buffered = kwargs.pop('buffered', False) follow_redirects = kwargs.pop('follow_redirects', False) if (not kwargs and len(args) == 1 and isinstance(args[0], (EnvironBuilder, dict))): environ = self.environ_base.copy() if isinstance(args[0], EnvironBuilder): environ.update(args[0].get_environ()) else: environ.update(args[0]) environ['flask._preserve_context'] = self.preserve_context else: kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context kwargs.setdefault('environ_base', self.environ_base) builder = make_test_environ_builder(self.application, *args, **kwargs) try: environ = builder.get_environ() finally: builder.close() return Client.open(self, environ, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects)
class TestRepozeWho(TestCase): def setUp(self): self.app = make_app(_setup) self.c = Client(self.app) def get(self, url='/'): appiter, status, headers = self.c.open(url) return ''.join(appiter) def post(self, login, password, do_login=True, url='/'): if do_login: url = url + '?__do_login=true' appiter, status, headers = self.c.post(url, data=dict(login=login, password=password)) return appiter, status, headers def test_starts(self): assert '<form' in self.get() def test_good_login(self): appiter, status, headers = self.post('admin', 'admin') assert status.startswith('302') assert self.get() == 'ok' def test_bad_login(self): appiter, status, headers = self.post('a', 'a') assert status.startswith('302') assert self.get() != 'ok' def test_nocookie_client(self): self.c = Client(self.app, use_cookies=False) appiter, status, headers = self.post('admin', 'admin') assert status.startswith('302') assert self.get() != 'ok'
def test_admin_page_allows_valid_login(self): """ Check that correct username and password will allow access """ h = Headers() auth = '{0}:{1}'.format( Config.USERNAME, Config.PASSWORD).encode('ascii') h.add('Authorization', b'Basic ' + base64.b64encode(auth)) rv = Client.open(self.client, path='/', headers=h) self.assert_200(rv)
def basic_auth(self, path, key, follow_redirects=True): h = Headers() login = b64encode('api:{}'.format(key)) h.add('Authorization', 'Basic {}'.format(login)) return Client.open(self.client, path=path, headers=h, follow_redirects=follow_redirects)
def send_delete_request(self, endpoint): h = Headers() # h.add('Authorization', 'Bearer {}'.format(self.token)) return Client.open(self.client, method='DELETE', path=endpoint, headers=h, content_type='application/json')
def test_vote_page_allows_valid_login(self): token = config.test_token h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode(token + ':')) rv = Client.open(self.client, path='/people/v1/hold/advise/check/' + config.hhauer_psuid, headers=h) self.assert_200(rv)
def test_api_quota_detail_page(self): """ Test the quota details page """ response = Client.open( self.client, path="/api/quotas/guid/", headers=valid_header) self.assertEqual(response.status_code, 200) # Check if quota was rendered self.assertTrue('guid' in response.json.keys()) # Check if quota data was rendered self.assertEqual(len(response.json['memory']), 1)
def test_api_quota_detail_dates(self): """ Test the quota details date range page functions """ response = Client.open( self.client, path="/api/quotas/guid/?since=2013-12-31&until=2014-1-1", headers=valid_header) self.assertEqual(response.status_code, 200) # Check if quota data was rendered within date range self.assertEqual(len(response.json['memory']), 1)
def test_hold_page_rejects_bad_username(self): h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode('foo:my_password')) rv = Client.open(self.client, path='/people/v1/hold/advise/check/foo', headers=h) self.assert_403(rv) h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode('foo:my_password')) rv = Client.open(self.client, path='/people/v1/hold/advise/auth/foo', headers=h) self.assert_403(rv) h = Headers() h.add('Authorization', 'Basic ' + base64.b64encode('foo:my_password')) rv = Client.post(self.client, path='/people/v1/hold/advise/clear/foo/abc', headers=h) self.assert_403(rv)
def send_put_request(self, endpoint, json_data): h = Headers() # h.add('Authorization', 'Bearer {}'.format(self.token)) return Client.open(self.client, method='PUT', path=endpoint, headers=h, content_type='application/json', data=json.dumps(json_data))
def test_appliance(): yaml = """ appliances: - import: glashammer.utils.appliance._JustForTestingAppliance mountpoint_path: /pages """.strip() fn = _c(yaml) app = declare_app(fn) c = Client(app) i, s, h = c.open('/') assert '404' in s i, s, h = c.open('/pages/') print i, s, h assert '200' in s assert 'hello' in ''.join(i)
def open(self, *args, **kwargs): kwargs.setdefault("environ_overrides", {})["flask._preserve_context"] = self.preserve_context as_tuple = kwargs.pop("as_tuple", False) buffered = kwargs.pop("buffered", False) follow_redirects = kwargs.pop("follow_redirects", False) builder = make_test_environ_builder(self.application, *args, **kwargs) return Client.open(self, builder, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects)
def test_api_quotas_list_page(self): """ Test the quotas list page """ response = Client.open( self.client, path="/api/quotas/", headers=valid_header) self.assertEqual(response.status_code, 200) data = response.json['Quotas'] # Check if all quotas present self.assertEqual(len(data), 2) # Check if quota data contains data details self.assertEqual(len(data[0]['memory']), 1)
def test_get(self): client = Client(self.app) data, status, headers = client.open() data = (b'').join(data) self.assertIn('Hello', str(data)) version, alf = zmq_pull_once(host()) self.assertTrue(alf['har']['log']['entries'][0]['timings']['wait'] >= 10)
def fuzz_request(data, wsgi_app): fdp = atheris.FuzzedDataProvider(data) method = fdp.PickValueInList(["GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE", "PATCH"]) url_length = fdp.ConsumeUInt(2) url = urllib.parse.quote(fdp.ConsumeBytes(url_length), safe='/?&=%') c = Client(wsgi_app, BaseResponse) resp = c.open(path=url, method=method) assert not (500 <= resp.status_code <= 599)
def test_api_quota_detail_page_one_date(self): """ Test the quota details page with only the since parameter """ response = Client.open( self.client, path="/api/quotas/guid/?since=2013-12-31", headers=valid_header) self.assertEqual(response.status_code, 200) # Check if quota was rendered self.assertTrue('guid' in response.json.keys()) # Check if quota data was rendered self.assertEqual(len(response.json['memory']), 1)
def get_with_token_auth(self, path, token): """ Do a request with token auth :param path: :param token: """ h = Headers() h.add('X-Auth-Token', token) response = Client.open(self.client, path=path, headers=h) return response
def test_api_quotas_list_dates(self): """ Test the quotas list page with dates """ response = Client.open( self.client, path="/api/quotas/?since=2012-12-31&until=2013-1-1", headers=valid_header) self.assertEqual(response.status_code, 200) data = response.json['Quotas'] # Check if all quotas present self.assertEqual(len(data), 2) # Check if quota data contains memory data only when inbetween dates self.assertEqual(len(data[0]['memory']), 0)
def open(self, *args, **kwargs): kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context as_tuple = kwargs.pop('as_tuple', False) buffered = kwargs.pop('buffered', False) follow_redirects = kwargs.pop('follow_redirects', False) builder = make_test_environ_builder(self.application, *args, **kwargs) return Client.open(self, builder, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects)
def test_preflight(self): app = CORSMiddleware(hello_world, origin=origin(["http://example.tld"]), allowed=("Foo", ), exposed=("Bar", )) client = Client(app, Response) rv = client.open(method="OPTIONS", path="/", headers={"Origin": "http://example.tld"}) self.assertEqual(rv.status_code, 200) for hdr in ("Origin", "Headers", "Credentials", "Methods"): self.assertIn("Access-Control-Allow-%s" % hdr, rv.headers) self.assertEqual(rv.headers["Access-Control-Allow-Origin"], "http://example.tld")
def test_preflight_CORS(): app = CORSMiddleware(hello_world, hosts=["http://example.tld"]) client = Client(app, Response) rv = client.open(method="OPTIONS", path="/", headers={"ORIGIN": "http://example.tld"}) assert rv.status_code == 200 for hdr in ("Origin", "Headers", "Credentials", "Methods"): assert "Access-Control-Allow-%s" % hdr in rv.headers assert rv.headers["Access-Control-Allow-Origin"] == "http://example.tld"
def get_with_basic_auth(self, path, username='******', password='******'): """ Do a request with ldap auth :param path: :param username: :param password: """ h = Headers() s_auth = base64.b64encode('{u}:{p}'.format(u=username, p=password).encode('utf-8')) h.add('Authorization', 'Basic ' + s_auth.decode('utf-8')) response = Client.open(self.client, path=path, headers=h) return response
def post_with_token_auth(self, path, token, data): """ Do a request with token auth :param token: :param path: """ h = Headers() h.add('X-Auth-Token', token) h.add('Content-Type', 'application/json') response = Client.open(self.client, method='POST', data=data, path=path, headers=h) return response
def test_get(self): status = '200 OK' # HTTP Status headers = [('Content-type', 'application/json')] # HTTP Headers # Mock collector with mock_server(56000, status, headers, 'Yo!') as collector: client = Client(self.app) data, status, headers = client.open() data = (b'').join(data) self.assertIn('Hello', str(data)) request = collector.get() self.assertEqual(request.get('url'), u'http://localhost:56000/1.0.0/single') alf = ujson.loads(request.get('body')) self.assertTrue(alf['har']['log']['entries'][0]['timings']['wait'] >= 10)
def test_follow_redirect(): env = create_environ("/", base_url="http://localhost") c = Client(redirect_with_get_app) response = c.open(environ_overrides=env, follow_redirects=True) assert response.status == "200 OK" assert response.data == b"current url: http://localhost/some/redirect/" # Test that the :cls:`Client` is aware of user defined response wrappers c = Client(redirect_with_get_app) resp = c.get("/", follow_redirects=True) assert resp.status_code == 200 assert resp.data == b"current url: http://localhost/some/redirect/" # test with URL other than '/' to make sure redirected URL's are correct c = Client(redirect_with_get_app) resp = c.get("/first/request", follow_redirects=True) assert resp.status_code == 200 assert resp.data == b"current url: http://localhost/some/redirect/"
def test_follow_redirect(self): env = create_environ('/', base_url='http://localhost') c = Client(redirect_with_get_app) appiter, code, headers = c.open(environ_overrides=env, follow_redirects=True) assert code == '200 OK' assert ''.join(appiter) == 'current url: http://localhost/some/redirect/' # Test that the :cls:`Client` is aware of user defined response wrappers c = Client(redirect_with_get_app, response_wrapper=BaseResponse) resp = c.get('/', follow_redirects=True) assert resp.status_code == 200 assert resp.data == 'current url: http://localhost/some/redirect/' # test with URL other than '/' to make sure redirected URL's are correct c = Client(redirect_with_get_app, response_wrapper=BaseResponse) resp = c.get('/first/request', follow_redirects=True) assert resp.status_code == 200 assert resp.data == 'current url: http://localhost/some/redirect/'