本文整理汇总了Python中webtest.TestApp.options方法的典型用法代码示例。如果您正苦于以下问题:Python TestApp.options方法的具体用法?Python TestApp.options怎么用?Python TestApp.options使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webtest.TestApp
的用法示例。
在下文中一共展示了TestApp.options方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestAuthenticatedCORS
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestAuthenticatedCORS(TestCase):
def setUp(self):
def check_cred(username, *args, **kwargs):
return [username]
@implementer(IAuthorizationPolicy)
class AuthorizationPolicy(object):
def permits(self, context, principals, permission):
return permission in principals
self.config = testing.setUp()
self.config.include('cornice')
self.config.add_route('noservice', '/noservice')
self.config.set_authorization_policy(AuthorizationPolicy())
self.config.set_authentication_policy(BasicAuthAuthenticationPolicy(
check_cred))
self.config.set_default_permission('readwrite')
self.config.scan('cornice.tests.test_cors')
self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))
def tearDown(self):
testing.tearDown()
def test_post_on_spam_should_be_forbidden(self):
self.app.post('/spam', status=403)
def test_preflight_does_not_need_authentication(self):
self.app.options('/spam', status=200,
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'})
示例2: test_singular_resource
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
def test_singular_resource(self, *a):
View = get_test_view_class()
config = _create_config()
root = config.get_root_resource()
root.add('thing', view=View)
grandpa = root.add('grandpa', 'grandpas', view=View)
wife = grandpa.add('wife', view=View, renderer='string')
wife.add('child', 'children', view=View)
config.begin()
app = TestApp(config.make_wsgi_app())
self.assertEqual(
'/grandpas/1/wife',
route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1)
)
self.assertEqual(
'/grandpas/1',
route_path('grandpa', testing.DummyRequest(), id=1)
)
self.assertEqual(
'/grandpas/1/wife/children/2',
route_path('grandpa_wife:child', testing.DummyRequest(),
grandpa_id=1, id=2)
)
self.assertEqual(app.put('/grandpas').body, six.b('update_many'))
self.assertEqual(app.head('/grandpas').body, six.b(''))
self.assertEqual(app.options('/grandpas').body, six.b(''))
self.assertEqual(app.delete('/grandpas/1').body, six.b('delete'))
self.assertEqual(app.head('/grandpas/1').body, six.b(''))
self.assertEqual(app.options('/grandpas/1').body, six.b(''))
self.assertEqual(app.put('/thing').body, six.b('replace'))
self.assertEqual(app.patch('/thing').body, six.b('update'))
self.assertEqual(app.delete('/thing').body, six.b('delete'))
self.assertEqual(app.head('/thing').body, six.b(''))
self.assertEqual(app.options('/thing').body, six.b(''))
self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace'))
self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update'))
self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete'))
self.assertEqual(app.head('/grandpas/1/wife').body, six.b(''))
self.assertEqual(app.options('/grandpas/1/wife').body, six.b(''))
self.assertEqual(six.b('show'), app.get('/grandpas/1').body)
self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body)
self.assertEqual(
six.b('show'), app.get('/grandpas/1/wife/children/1').body)
示例3: test_web_basic
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
def test_web_basic():
"""The web basic test
"""
class TestService(Service):
"""The test service
"""
@get('/test/get')
@post('/test/post')
@put('/test/put')
@delete('/test/delete')
@head('/test/head')
@patch('/test/patch')
@options('/test/options')
@endpoint()
def test(self):
"""Test
"""
return 'OK'
@get('/test2')
@endpoint()
def test2(self, param):
"""Test 2
"""
return 'OK'
adapter = WebAdapter()
server = Server([ TestService() ], [ adapter ])
server.start()
# Test
app = TestApp(adapter)
rsp = app.get('/test', expect_errors = True)
assert rsp.status_int == 404
rsp = app.get('/test/get')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
rsp = app.post('/test/post')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
rsp = app.put('/test/put')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
rsp = app.delete('/test/delete')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
rsp = app.head('/test/head')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain'
rsp = app.patch('/test/patch')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
rsp = app.options('/test/options')
assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
# Too many parameters
rsp = app.get('/test/get?a=1', expect_errors = True)
assert rsp.status_int == 400
# Lack of parameters
rsp = app.get('/test2', expect_errors = True)
assert rsp.status_int == 400
rsp = app.get('/test2?param=1')
assert rsp.status_int == 200 and rsp.text == 'OK'
示例4: TestCORS
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestCORS(TestCase):
def setUp(self):
self.config = testing.setUp()
self.config.include("cornice")
self.config.add_route('noservice', '/noservice')
self.config.scan("cornice.tests.test_cors")
self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))
def tearDown(self):
testing.tearDown()
def test_preflight_cors_klass_post(self):
resp = self.app.options('/cors_klass',
status=200,
headers={
'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'POST'})
def test_preflight_cors_klass_put(self):
resp = self.app.options('/cors_klass',
status=400,
headers={
'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'PUT'})
def test_preflight_missing_headers(self):
# we should have an OPTION method defined.
# If we just try to reach it, without using correct headers:
# "Access-Control-Request-Method"or without the "Origin" header,
# we should get a 400.
resp = self.app.options('/squirel', status=400)
self.assertEqual(len(resp.json['errors']), 2)
def test_preflight_missing_origin(self):
resp = self.app.options(
'/squirel',
headers={'Access-Control-Request-Method': 'GET'},
status=400)
self.assertEqual(len(resp.json['errors']), 1)
def test_preflight_missing_request_method(self):
resp = self.app.options(
'/squirel',
headers={'Origin': 'foobar.org'},
status=400)
self.assertEqual(len(resp.json['errors']), 1)
def test_preflight_incorrect_origin(self):
# we put "lolnet.org" where only "notmyidea.org" is authorized
resp = self.app.options(
'/squirel',
headers={'Origin': 'lolnet.org',
'Access-Control-Request-Method': 'GET'},
status=400)
self.assertEqual(len(resp.json['errors']), 1)
def test_preflight_correct_origin(self):
resp = self.app.options(
'/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})
self.assertEqual(
resp.headers['Access-Control-Allow-Origin'],
'notmyidea.org')
allowed_methods = (resp.headers['Access-Control-Allow-Methods']
.split(','))
self.assertNotIn('POST', allowed_methods)
self.assertIn('GET', allowed_methods)
self.assertIn('PUT', allowed_methods)
self.assertIn('HEAD', allowed_methods)
allowed_headers = (resp.headers['Access-Control-Allow-Headers']
.split(','))
self.assertIn('X-My-Header', allowed_headers)
self.assertNotIn('X-Another-Header', allowed_headers)
def test_preflight_deactivated_method(self):
self.app.options('/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'POST'},
status=400)
def test_preflight_origin_not_allowed_for_method(self):
self.app.options('/squirel',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'PUT'},
status=400)
def test_preflight_credentials_are_supported(self):
resp = self.app.options('/spam',
headers={'Origin': 'notmyidea.org',
'Access-Control-Request-Method': 'GET'})
#.........这里部分代码省略.........
示例5: TestHttplib
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestHttplib(unittest.TestCase):
client = 'httplib'
client_options = {}
def setUp(self):
self.server = StopableWSGIServer.create(debug_app)
self.application_url = self.server.application_url.rstrip('/')
self.proxy = proxies.HostProxy(self.application_url,
client=self.client,
**self.client_options)
self.app = TestApp(self.proxy)
def test_form(self):
resp = self.app.get('/form.html')
resp.mustcontain('</form>')
form = resp.form
form['name'] = 'gawel'
resp = form.submit()
resp.mustcontain('name=gawel')
def test_head(self):
resp = self.app.head('/form.html')
self.assertEqual(resp.status_int, 200)
self.assertEqual(len(resp.body), 0)
def test_webob_error(self):
req = Request.blank('/')
req.content_length = '-1'
resp = req.get_response(self.proxy)
self.assertEqual(resp.status_int, 500, resp)
def test_not_allowed_method(self):
resp = self.app.options('/', status='*')
self.assertEqual(resp.status_int, 405)
def test_status(self):
resp = self.app.get('/?status=404', status='*')
self.assertEqual(resp.status_int, 404)
def test_redirect(self):
location = self.application_url + '/form.html'
resp = self.app.get(
'/?status=301%20Redirect&header-location=' + location,
status='*')
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
location = 'http://foo.com'
resp = self.app.get(
'/?status=301%20Redirect&header-location=' + location,
status='*')
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
location = '/foo'
resp = self.app.get(
'/?status=301%20Redirect&header-location=' + location,
status='*')
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, self.application_url + location)
location = self.application_url + '/script_name/form.html'
self.proxy.strip_script_name = False
resp = self.app.get(
'/?status=301%20Redirect&header-Location=' + location,
status='*', extra_environ={'SCRIPT_NAME': '/script_name'})
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
def test_chunked(self):
resp = self.app.get('/',
headers=[('Transfer-Encoding', 'chunked')])
resp.mustcontain(no='chunked')
def tearDown(self):
self.server.shutdown()
示例6: __init__
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class AppUser:
""":class:`webtest.TestApp` wrapper for backend functional testing."""
def __init__(self, app,
rest_url: str='http://localhost',
base_path: str='/',
header: dict=None):
"""Initialize self."""
self.app = TestApp(app)
""":class:`webtest.TestApp`to send requests to the backend server."""
self.rest_url = rest_url
"""backend server url to generate request urls."""
self.base_path = base_path
"""path prefix to generate request urls."""
self.header = header or {}
"""default header for requests, mostly for authentication."""
self._resolver = DottedNameResolver()
def post_resource(self, path: str,
iresource: IInterface,
cstruct: dict) -> TestResponse:
"""Build and post request to create a new resource."""
url = self._build_url(path)
props = self._build_post_body(iresource, cstruct)
resp = self.app.post_json(url, props, headers=self.header,
expect_errors=True)
return resp
def put(self, path: str, cstruct: dict={}) -> TestResponse:
"""Put request to modify a resource."""
url = self._build_url(path)
resp = self.app.put_json(url, cstruct, headers=self.header,
expect_errors=True)
return resp
def post(self, path: str, cstruct: dict={}) -> TestResponse:
"""Post request to create a new resource."""
url = self._build_url(path)
resp = self.app.post_json(url, cstruct, headers=self.header,
expect_errors=True)
return resp
def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict:
return {'content_type': iresource.__identifier__,
'data': cstruct}
def _build_url(self, path: str) -> str:
if path.startswith('http'):
return path
return self.rest_url + self.base_path + path
def batch(self, subrequests: list):
"""Build and post batch request to the backend rest server."""
resp = self.app.post_json(batch_url, subrequests, headers=self.header,
expect_errors=True)
return resp
def get(self, path: str, params={}) -> TestResponse:
"""Send get request to the backend rest server."""
url = self._build_url(path)
resp = self.app.get(url,
headers=self.header,
params=params,
expect_errors=True)
return resp
def options(self, path: str) -> TestResponse:
"""Send options request to the backend rest server."""
url = self._build_url(path)
resp = self.app.options(url, headers=self.header, expect_errors=True)
return resp
def get_postable_types(self, path: str) -> []:
"""Send options request and return the postable content types."""
resp = self.options(path)
if 'POST' not in resp.json:
return []
post_request_body = resp.json['POST']['request_body']
type_names = sorted([r['content_type'] for r in post_request_body])
iresources = [self._resolver.resolve(t) for t in type_names]
return iresources
示例7: TestUserAPI
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestUserAPI(unittest.TestCase):
"""Tests API functions associated with actions a regular user can take.
Note that all tests are in-process, we don't actually start a HTTP server.
All administrative requirements will be set up with direct calls
to eos_db.server, and all user calls will be done via self.app.
"""
def setUp(self):
"""Launch app using webtest with test settings"""
self.appconf = get_app(test_ini)
self.app = TestApp(self.appconf)
#All auth via BasicAuth - never return the session cookie.
self.app.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[]))
# This sets global var "engine" - in the case of SQLite this is a fresh RAM
# DB each time. If we only did this on class instantiation the database would
# be dirty and one test could influence another.
# TODO - add a test that tests this.
server.choose_engine("SQLite")
# Punch in new user account with direct server call
# This will implicitly generate the tables.
user_id = self.create_user("testuser")
#Here is what the user should look like when inspected
self.user_json = { "name" : "testuser testuser",
"handle" : "[email protected]",
"id" : 1,
"credits" : 0,
"username": "testuser"}
#print("user_id is %s" % str(user_id))
#print("user_from_db_is %s" % server.get_user_id_from_name("testuser"))
server.touch_to_add_password(user_id, "asdf")
# And log in as this user for all tests (via BasicAuth)
# FIXME - switch to token auth to speed up the tests.
self.app.authorization = ('Basic', ('testuser', 'asdf'))
"""Unauthenticated API functions.
Should respond the same regardless of authentication.
"""
def test_home_view(self):
""" Home view should respond with 200 OK. """
response = self.app.get('/', status=200)
# Not sure why Ben implemented options, but it should still work.
def test_options(self):
""" Options should respond with 200 OK. """
response = self.app.options('/', status=200)
"""User API functions.
The user functions in the API are primarily used by system utilities.
Creating a user and password, and validating against the database in
order to receive an access token, are prerequisites for using functions
in later sections of the API. These can only be called by an
administrator."""
def test_whoami(self):
""" How do I find out who I am? """
response = self.app.get('/user')
#We expect to be user 1, as the database is fresh.
#All other items should be as per create_user("testuser")
self.assertEqual( response.json, self.user_json )
def test_retrieve_my_info(self):
""" Retrieving my own user info by name should give the same result
as above."""
response = self.app.get('/users/testuser', status=200)
#We expect to be user 1, as the database is fresh.
#All other items should be as per create_user("testuser")
self.assertEqual( response.json, self.user_json )
def test_retrieve_other_user_info(self):
""" Retrieving info for another user should respond 200 OK. """
self.create_user("anotheruser")
self.assertEqual(self.app.get('/users/anotheruser').json['name'], "anotheruser anotheruser")
def test_retrieve_users(self):
""" Add another couple of users. Three records should be returned, as
there is already a testuser. """
self.create_user("foo")
self.create_user("bar")
response = self.app.get('/users')
self.assertEqual(len(response.json), 3)
#Unimplemented just now.
@unittest.expectedFailure
def test_delete_user(self):
#.........这里部分代码省略.........
示例8: TestCORS
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestCORS(TestCase):
def setUp(self):
self.config = testing.setUp()
self.config.include("cornice")
self.config.scan("cornice.tests.test_cors")
self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))
def tearDown(self):
testing.tearDown()
def test_preflight_missing_headers(self):
# we should have an OPTION method defined.
# If we just try to reach it, without using correct headers:
# "Access-Control-Request-Method"or without the "Origin" header,
# we should get a 400.
resp = self.app.options("/squirel", status=400)
self.assertEquals(len(resp.json["errors"]), 2)
def test_preflight_missing_origin(self):
resp = self.app.options("/squirel", headers={"Access-Control-Request-Method": "GET"}, status=400)
self.assertEquals(len(resp.json["errors"]), 1)
def test_preflight_missing_request_method(self):
resp = self.app.options("/squirel", headers={"Origin": "foobar.org"}, status=400)
self.assertEquals(len(resp.json["errors"]), 1)
def test_preflight_incorrect_origin(self):
# we put "lolnet.org" where only "notmyidea.org" is authorized
resp = self.app.options(
"/squirel", headers={"Origin": "lolnet.org", "Access-Control-Request-Method": "GET"}, status=400
)
self.assertEquals(len(resp.json["errors"]), 1)
def test_preflight_correct_origin(self):
resp = self.app.options("/squirel", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "GET"})
self.assertEquals(resp.headers["Access-Control-Allow-Origin"], "notmyidea.org")
allowed_methods = resp.headers["Access-Control-Allow-Methods"].split(",")
self.assertNotIn("POST", allowed_methods)
self.assertIn("GET", allowed_methods)
self.assertIn("PUT", allowed_methods)
self.assertIn("HEAD", allowed_methods)
allowed_headers = resp.headers["Access-Control-Allow-Headers"].split(",")
self.assertIn("X-My-Header", allowed_headers)
self.assertNotIn("X-Another-Header", allowed_headers)
def test_preflight_deactivated_method(self):
self.app.options(
"/squirel", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "POST"}, status=400
)
def test_preflight_origin_not_allowed_for_method(self):
self.app.options(
"/squirel", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "PUT"}, status=400
)
def test_preflight_credentials_are_supported(self):
resp = self.app.options("/spam", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "GET"})
self.assertIn("Access-Control-Allow-Credentials", resp.headers)
self.assertEquals(resp.headers["Access-Control-Allow-Credentials"], "true")
def test_preflight_credentials_header_not_included_when_not_needed(self):
resp = self.app.options("/spam", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "POST"})
self.assertNotIn("Access-Control-Allow-Credentials", resp.headers)
def test_preflight_contains_max_age(self):
resp = self.app.options("/spam", headers={"Origin": "notmyidea.org", "Access-Control-Request-Method": "GET"})
self.assertIn("Access-Control-Max-Age", resp.headers)
self.assertEquals(resp.headers["Access-Control-Max-Age"], "42")
def test_resp_dont_include_allow_origin(self):
resp = self.app.get("/squirel") # omit the Origin header
self.assertNotIn("Access-Control-Allow-Origin", resp.headers)
self.assertEquals(resp.json, "squirels")
def test_responses_include_an_allow_origin_header(self):
resp = self.app.get("/squirel", headers={"Origin": "notmyidea.org"})
self.assertIn("Access-Control-Allow-Origin", resp.headers)
self.assertEquals(resp.headers["Access-Control-Allow-Origin"], "notmyidea.org")
def test_credentials_are_included(self):
resp = self.app.get("/spam", headers={"Origin": "notmyidea.org"})
self.assertIn("Access-Control-Allow-Credentials", resp.headers)
self.assertEquals(resp.headers["Access-Control-Allow-Credentials"], "true")
def test_headers_are_exposed(self):
resp = self.app.get("/squirel", headers={"Origin": "notmyidea.org"})
self.assertIn("Access-Control-Expose-Headers", resp.headers)
headers = resp.headers["Access-Control-Expose-Headers"].split(",")
self.assertIn("X-My-Header", headers)
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
#.........这里部分代码省略.........
self._resolver = DottedNameResolver()
def _get_token_and_user_path(self, login: str, password: str) -> tuple:
login_page = self.rest_url + '/login_username'
data = {'name': login,
'password': password}
resp = self.app.post_json(login_page, data).json
return resp['user_token'], resp['user_path']
def post_resource(self, path: str,
iresource: IInterface,
cstruct: dict) -> TestResponse:
"""Build and post request to create a new resource."""
url = self._build_url(path)
props = self._build_post_body(iresource, cstruct)
resp = self.app.post_json(url, props, headers=self.header,
expect_errors=True)
return resp
def put(self,
path: str,
cstruct: dict={},
upload_files: [(str, str, bytes)]=None,
) -> TestResponse:
"""Put request to modify a resource."""
url = self._build_url(path)
kwargs = {'headers': self.header,
'expect_errors': True,
}
if upload_files:
kwargs['upload_files'] = upload_files
resp = self.app.put(url, cstruct, **kwargs)
else:
resp = self.app.put_json(url, cstruct, **kwargs)
return resp
def post(self,
path: str,
cstruct: dict={},
upload_files: [(str, str, bytes)]=None,
) -> TestResponse:
"""Post request to create a new resource."""
url = self._build_url(path)
kwargs = {'headers': self.header,
'expect_errors': True,
}
if upload_files:
kwargs['upload_files'] = upload_files
resp = self.app.post(url, cstruct, **kwargs)
else:
resp = self.app.post_json(url, cstruct, **kwargs)
return resp
def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict:
return {'content_type': iresource.__identifier__,
'data': cstruct}
def _build_url(self, path: str) -> str:
if path.startswith('http'):
return path
return self.rest_url + self.base_path + path
def batch(self, subrequests: list):
"""Build and post batch request to the backend rest server."""
resp = self.app.post_json(batch_url, subrequests, headers=self.header,
expect_errors=True)
return resp
def get(self, path: str, params={}) -> TestResponse:
"""Send get request to the backend rest server."""
url = self._build_url(path)
resp = self.app.get(url,
headers=self.header,
params=params,
expect_errors=True)
return resp
def delete(self, path: str) -> TestResponse:
"""Send delete request to the backend rest server."""
url = self._build_url(path)
resp = self.app.delete(url,
headers=self.header,
expect_errors=True)
return resp
def options(self, path: str) -> TestResponse:
"""Send options request to the backend rest server."""
url = self._build_url(path)
resp = self.app.options(url, headers=self.header, expect_errors=True)
return resp
def get_postable_types(self, path: str) -> []:
"""Send options request and return the postable content types."""
resp = self.options(path)
if 'POST' not in resp.json:
return []
post_request_body = resp.json['POST']['request_body']
type_names = sorted([r['content_type'] for r in post_request_body])
iresources = [self._resolver.resolve(t) for t in type_names]
return iresources
示例10: TestHttplib
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
class TestHttplib(unittest.TestCase):
client = "httplib"
client_options = {}
def setUp(self):
self.server = StopableWSGIServer.create(debug_app)
self.application_url = self.server.application_url.rstrip("/")
self.proxy = proxies.HostProxy(self.application_url, client=self.client, **self.client_options)
self.app = TestApp(self.proxy)
def test_form(self):
resp = self.app.get("/form.html")
resp.mustcontain("</form>")
form = resp.form
form["name"] = "gawel"
resp = form.submit()
resp.mustcontain("name=gawel")
def test_head(self):
resp = self.app.head("/form.html")
self.assertEqual(resp.status_int, 200)
self.assertEqual(len(resp.body), 0)
def test_webob_error(self):
req = Request.blank("/")
req.content_length = "-1"
resp = req.get_response(self.proxy)
self.assertEqual(resp.status_int, 500, resp)
def test_not_allowed_method(self):
resp = self.app.options("/", status="*")
self.assertEqual(resp.status_int, 405)
def test_status(self):
resp = self.app.get("/?status=404", status="*")
self.assertEqual(resp.status_int, 404)
def test_redirect(self):
location = self.application_url + "/form.html"
resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
location = "http://foo.com"
resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
location = "/foo"
resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, self.application_url + location)
location = self.application_url + "/script_name/form.html"
self.proxy.strip_script_name = False
resp = self.app.get(
"/?status=301%20Redirect&header-Location=" + location,
status="*",
extra_environ={"SCRIPT_NAME": "/script_name"},
)
self.assertEqual(resp.status_int, 301, resp)
self.assertEqual(resp.location, location)
def test_chunked(self):
resp = self.app.get("/", headers=[("Transfer-Encoding", "chunked")])
resp.mustcontain(no="chunked")
def test_quoted_utf8_url(self):
path = "/targets/NR2F1%C3%82-human/"
resp = self.app.get(path)
resp.mustcontain(b"PATH_INFO: /targets/NR2F1\xc3\x82-human/")
def tearDown(self):
self.server.shutdown()
示例11: TestCorkscrew
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import options [as 别名]
#.........这里部分代码省略.........
self.assertEqual(inc["id"], ref["id"])
# the self link must be valid and refer to the same object
subresult = self.app.get(inc["links"]["self"])
self.assertEqual(subresult.json["data"], inc)
def testIncludeParameterReverseRelationship(self):
result = self.app.get("/articles/1?include=comments")
JsonAPIValidator.validate(result.json)
self.assertIn("included", result.json)
# the server must not return any other fields than requested
self.assertIs(len(result.json["included"]), len(COMMENT_BODIES))
refs = result.json["data"]["relationships"]["comments"]["data"]
for inc in result.json["included"]:
self.assertIn({"id": inc["id"], "type": inc["type"]}, refs)
# the self link must be valid and refer to the same object
subresult = self.app.get(inc["links"]["self"])
self.assertEqual(subresult.json["data"], inc)
self.assertEqual(
subresult.json["links"]["self"],
inc["links"]["self"]
)
def testIncludeParameterWithInvalidFields(self):
self.app.get("/articles/1?include=invalid-field", status=400)
self.app.get("/articles/1?include=author,invalid-field", status=400)
def testIncludeParameterWithCircularRelationships(self):
self.app.get("/articles/1?include=comments.articles", status=400)
self.app.get(
"/articles/1?include=comments.articles.comments",
status=400
)
def testSparseFieldsets(self):
result = self.app.get("/people/1?fields[person]=age")
JsonAPIValidator.validate(result.json)
self.assertNotIn("name", result.json["data"]["attributes"])
self.assertIn("age", result.json["data"]["attributes"])
def testSparseFieldsetsWithIncludedObjects(self):
result = self.app.get("/articles/1?include=comments&fields[comment]=")
JsonAPIValidator.validate(result.json)
for inc in result.json["included"]:
self.assertNotIn("attributes", inc)
result = self.app.get(
"/comments/1?include=article.author&fields[person]=age"
)
JsonAPIValidator.validate(result.json)
is_included = False
for inc in result.json["included"]:
if inc["type"] == "person":
is_included = True
self.assertIn("age", inc["attributes"])
self.assertNotIn("name", inc["attributes"])
self.assertIsNotNone(is_included)
def testLinkWithSpecifiedField(self):
result = self.app.get("/articles/1/relationships/revisions")
JsonAPIValidator.validate(result.json)
def testOPTIONSRequest(self):
# all of these should return all 200 OK code
self.app.options("/articles")
self.app.options("/articles/1")
self.app.options("/articles/1/cover")
self.app.options("/articles/1/relationships/cover")
self.app.options("/photos/2/tags")
self.app.options("/articles/1?include=author")
def testCORSHeaders(self):
# simulate a browser
result = self.app.options("/articles", headers={
"Origin": "http://example.org",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Requested-With"
})
self.assertIn("Access-Control-Allow-Origin", result.headers)
self.assertIn("Access-Control-Allow-Methods", result.headers)
self.assertEqual(result.headers["Access-Control-Allow-Origin"], "*")
methods = map(
lambda x: x.strip(),
result.headers["Access-Control-Allow-Methods"].split(",")
)
self.assertIn("GET", methods)
self.assertIn(
"X-Requested-With".lower(),
result.headers["Access-Control-Allow-Headers"].lower()
)