本文整理汇总了Python中flak.Flak.test_client方法的典型用法代码示例。如果您正苦于以下问题:Python Flak.test_client方法的具体用法?Python Flak.test_client怎么用?Python Flak.test_client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flak.Flak
的用法示例。
在下文中一共展示了Flak.test_client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_session_expiration
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_session_expiration():
permanent = True
app = Flak(__name__)
app.secret_key = 'testkey'
@app.route('/')
def index(cx):
cx.session['test'] = 42
cx.session.permanent = permanent
return ''
@app.route('/test')
def test(cx):
return text_type(cx.session.permanent)
client = app.test_client()
rv = client.get('/')
assert 'set-cookie' in rv.headers
match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])
expires = parse_date(match.group())
expected = datetime.utcnow() + app.permanent_session_lifetime
assert expires.year == expected.year
assert expires.month == expected.month
assert expires.day == expected.day
rv = client.get('/test')
assert rv.data == b'True'
permanent = False
rv = app.test_client().get('/')
assert 'set-cookie' in rv.headers
match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])
assert match is None
示例2: test_multi_route_rules
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_multi_route_rules():
app = Flak(__name__)
@app.route('/')
@app.route('/<test>/')
def index(cx, test='a'):
return test
rv = app.test_client().open('/')
assert rv.data == b'a'
rv = app.test_client().open('/b/')
assert rv.data == b'b'
示例3: test_none_response
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_none_response():
app = Flak(__name__)
@app.route('/')
def test(cx):
return None
try:
app.test_client().get('/')
except ValueError as e:
assert str(e) == 'View function did not return a response'
pass
else:
assert "Expected ValueError"
示例4: test_preserve_remembers_exception
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_preserve_remembers_exception():
app = Flak(__name__)
app.debug = True
errors = []
@app.route('/fail')
def fail_func(cx):
1 // 0
@app.route('/success')
def success_func(cx):
return 'Okay'
@app.teardown
def teardown_handler(cx, exc):
errors.append(exc)
c = app.test_client()
# After this failure we did not yet call the teardown handler
with pytest.raises(ZeroDivisionError):
c.get('/fail')
#assert errors == []
assert len(errors) == 1
# But this request triggers it, and it's an error
c.get('/success')
assert len(errors) == 2
# At this point another request does nothing.
c.get('/success')
assert len(errors) == 3
assert errors[1] is None
示例5: test_route_decorator_custom_endpoint
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_route_decorator_custom_endpoint():
app = Flak(__name__)
app.debug = True
@app.route('/foo/')
def foo(cx):
return cx.request.endpoint
@app.route('/bar/', endpoint='bar')
def for_bar(cx):
return cx.request.endpoint
@app.route('/bar/123', endpoint='123')
def for_bar_foo(cx):
return cx.request.endpoint
with app.test_context() as cx:
assert cx.url_for('foo') == '/foo/'
assert cx.url_for('bar') == '/bar/'
assert cx.url_for('123') == '/bar/123'
c = app.test_client()
assert c.get('/foo/').data == b'foo'
assert c.get('/bar/').data == b'bar'
assert c.get('/bar/123').data == b'123'
示例6: test_multi_route_class_views
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_multi_route_class_views():
class View(object):
def __init__(self, app):
app.add_url_rule('/', self.index)
app.add_url_rule('/<test>/', self.index)
def index(self, cx, test='a'):
return test
app = Flak(__name__)
View(app)
rv = app.test_client().get('/')
assert rv.data == b'a'
rv = app.test_client().get('/b/')
assert rv.data == b'b'
示例7: test_error_handler_no_match
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_error_handler_no_match():
app = Flak(__name__)
class CustomException(Exception):
pass
@app.errorhandler(CustomException)
def custom_exception_handler(cx, e):
assert isinstance(e, CustomException)
return 'custom'
@app.errorhandler(500)
def handle_500(cx, e):
return type(e).__name__
@app.route('/custom')
def custom_test(cx):
raise CustomException()
@app.route('/keyerror')
def key_error(cx):
raise KeyError()
c = app.test_client()
assert c.get('/custom').data == b'custom'
assert c.get('/keyerror').data == b'KeyError'
示例8: test_session_special_types
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_session_special_types():
app = Flak(__name__)
app.secret_key = 'development-key'
now = datetime.utcnow().replace(microsecond=0)
the_uuid = uuid.uuid4()
@app.after_request
def modify_session(cx, response):
cx.session['u'] = the_uuid
cx.session['dt'] = now
cx.session['b'] = b'\xff'
cx.session['t'] = (1, 2, 3)
return response
@app.route('/')
def dump_session_contents(cx):
return pickle.dumps(dict(cx.session))
c = app.test_client()
c.get('/')
rv = pickle.loads(c.get('/').data)
assert rv['dt'] == now
assert rv['u'] == the_uuid
assert rv['b'] == b'\xff'
assert type(rv['b']) == bytes
assert rv['t'] == (1, 2, 3)
示例9: test_json_customization
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_json_customization(self):
class X(object):
def __init__(self, val):
self.val = val
class MyEncoder(flak.json.JSONEncoder):
def default(self, o):
if isinstance(o, X):
return "<%d>" % o.val
return flak.json.JSONEncoder.default(self, o)
class MyDecoder(flak.json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs.setdefault("object_hook", self.object_hook)
flak.json.JSONDecoder.__init__(self, *args, **kwargs)
def object_hook(self, obj):
if len(obj) == 1 and "_foo" in obj:
return X(obj["_foo"])
return obj
app = Flak(__name__)
app.json_encoder = MyEncoder
app.json_decoder = MyDecoder
@app.route("/", methods=["POST"])
def index(cx):
return cx.dumps(cx.get_json()["x"])
c = app.test_client()
rv = c.post("/", data=json.dumps({"x": {"_foo": 42}}), content_type="application/json")
assert rv.data == b'"<42>"'
示例10: test_url_processors
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_url_processors():
app = Flak(__name__)
@app.url_defaults
def add_language_code(cx, endpoint, values):
if cx.lang_code is not None and \
app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
values.setdefault('lang_code', cx.lang_code)
@app.url_value_preprocessor
def pull_lang_code(cx, endpoint, values):
cx.lang_code = values.pop('lang_code', None)
@app.route('/<lang_code>/')
def index(cx):
return cx.url_for('about')
@app.route('/<lang_code>/about')
def about(cx):
return cx.url_for('something_else')
@app.route('/foo')
def something_else(cx):
return cx.url_for('about', lang_code='en')
c = app.test_client()
assert c.get('/de/').data == b'/de/about'
assert c.get('/de/about').data == b'/foo'
assert c.get('/foo').data == b'/en/about'
示例11: test_processor_exceptions
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_processor_exceptions(self):
app = Flak(__name__)
app.config["LOGGER_HANDLER_POLICY"] = "never"
@app.before_request
def before_request():
if trigger == "before":
1 // 0
@app.after_request
def after_request(response):
if trigger == "after":
1 // 0
return response
@app.route("/")
def index():
return "Foo"
@app.errorhandler(500)
def internal_server_error(cx, e):
return "Hello Server Error", 500
for trigger in "before", "after":
rv = app.test_client().get("/")
assert rv.status_code == 500
assert rv.data == b"Hello Server Error"
示例12: test_reuse_client
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_reuse_client():
app = Flak(__name__)
c = app.test_client()
with c:
assert c.get('/').status_code == 404
with c:
assert c.get('/').status_code == 404
示例13: test_test_client_context_binding
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_test_client_context_binding():
app = Flak(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.route('/')
def index(cx):
cx.globals.value = 42
return 'Hello World!'
@app.route('/other')
def other(cx):
cx.globals.value = 23
1 // 0
with app.test_client() as c:
resp = c.get('/')
cx = c.captured_context
assert cx.globals.value == 42
assert resp.data == b'Hello World!'
assert resp.status_code == 200
resp = c.get('/other')
assert b'Internal Server Error' in resp.data
assert resp.status_code == 500
assert c.captured_context is not cx
cx = c.captured_context
assert cx.globals.value == 23
示例14: test_redirect_keep_session
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_redirect_keep_session():
app = Flak(__name__)
app.secret_key = 'testing'
@app.route('/', methods=['GET', 'POST'])
def index(cx):
if cx.request.method == 'POST':
return flak.redirect('/getsession')
cx.session['data'] = 'foo'
return 'index'
@app.route('/getsession')
def get_session(cx):
return cx.session.get('data', '<missing>')
with app.test_client() as c:
rv = c.get('/getsession')
assert rv.data == b'<missing>'
rv = c.get('/')
assert rv.data == b'index'
rv = c.post('/', data={}, follow_redirects=True)
assert rv.data == b'foo'
rv = c.get('/getsession')
assert rv.data == b'foo'
示例15: test_http_error_subclass_handling
# 需要导入模块: from flak import Flak [as 别名]
# 或者: from flak.Flak import test_client [as 别名]
def test_http_error_subclass_handling():
class ForbiddenSubclass(Forbidden):
pass
app = Flak(__name__)
@app.errorhandler(ForbiddenSubclass)
def handle_forbidden_subclass(cx, e):
assert isinstance(e, ForbiddenSubclass)
return 'banana'
@app.errorhandler(403)
def handle_forbidden_subclass(cx, e):
assert not isinstance(e, ForbiddenSubclass)
assert isinstance(e, Forbidden)
return 'apple'
@app.route('/1')
def index1(cx):
raise ForbiddenSubclass()
@app.route('/2')
def index2(cx):
flak.abort(403)
@app.route('/3')
def index3(cx):
raise Forbidden()
c = app.test_client()
assert c.get('/1').data == b'banana'
assert c.get('/2').data == b'apple'
assert c.get('/3').data == b'apple'