本文整理汇总了Python中werkzeug.test.EnvironBuilder类的典型用法代码示例。如果您正苦于以下问题:Python EnvironBuilder类的具体用法?Python EnvironBuilder怎么用?Python EnvironBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EnvironBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
self.ctx = app.test_request_context()
self.ctx.push()
init_data()
self.client = app.test_client()
builder = EnvironBuilder(method='POST')
self.post_env = builder.get_environ()
示例2: test_03_no_detail_on_success
def test_03_no_detail_on_success(self):
builder = EnvironBuilder(method='POST',
data={'serial': "HOTP123435"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
req = Request(env)
# The response contains the token type SPASS
res = {"jsonrpc": "2.0",
"result": {"status": True,
"value": True},
"version": "privacyIDEA test",
"id": 1,
"detail": {"message": "matching 1 tokens",
"serial": "HOTP123456",
"type": "hotp"}}
resp = Response(json.dumps(res))
# Set a policy, that does not allow the detail on success
set_policy(name="pol2",
scope=SCOPE.AUTHZ,
action="no_detail_on_success", client="10.0.0.0/8")
g.policy_object = PolicyClass()
new_response = no_detail_on_success(req, resp)
jresult = json.loads(new_response.data)
self.assertTrue("detail" not in jresult, jresult)
delete_policy("pol2")
示例3: test_registering_new_device_view
def test_registering_new_device_view(self):
"""Test that the HTML view works."""
hass = MagicMock()
m = mock_open()
with patch(
'homeassistant.components.notify.html5.open', m, create=True
):
hass.config.path.return_value = 'file.conf'
service = html5.get_service(hass, {})
assert service is not None
# assert hass.called
assert len(hass.mock_calls) == 3
view = hass.mock_calls[1][1][0]
assert view.json_path == hass.config.path.return_value
assert view.registrations == {}
builder = EnvironBuilder(method='POST',
data=json.dumps(SUBSCRIPTION_1))
Request = request_class()
resp = view.post(Request(builder.get_environ()))
expected = {
'unnamed device': SUBSCRIPTION_1,
}
assert resp.status_code == 200, resp.response
assert view.registrations == expected
handle = m()
assert json.loads(handle.write.call_args[0][0]) == expected
示例4: test_10_check_external
def test_10_check_external(self):
g.logged_in_user = {"username": "user1",
"role": "user"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
req = Request(env)
g.policy_object = PolicyClass()
req.all_data = {
"user": "cornelius",
"realm": "home"}
# Check success on no definition
r = check_external(req)
self.assertTrue(r)
# Check success with external function
current_app.config["PI_INIT_CHECK_HOOK"] = \
"privacyidea.api.lib.prepolicy.mock_success"
r = check_external(req)
self.assertTrue(r)
# Check exception with external function
current_app.config["PI_INIT_CHECK_HOOK"] = \
"privacyidea.api.lib.prepolicy.mock_fail"
self.assertRaises(Exception, check_external, req)
示例5: test_14_required_email
def test_14_required_email(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
req = Request(env)
# Set a mangle policy to change the username
# and only use the last 4 characters of the username
set_policy(name="email1",
scope=SCOPE.REGISTER,
action="%s=/.*@mydomain\..*" % ACTION.REQUIREDEMAIL)
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {"email": "[email protected]"}
# This emails is allowed
r = required_email(req)
self.assertTrue(r)
# This email is not allowed
req.all_data = {"email": "[email protected]"}
# This emails is allowed
self.assertRaises(RegistrationError, required_email, req)
delete_policy("email1")
g.policy_object = PolicyClass()
# Without a policy, this email can register
req.all_data = {"email": "[email protected]"}
# This emails is allowed
r = required_email(req)
self.assertTrue(r)
示例6: test_03_check_token_upload
def test_03_check_token_upload(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
req = Request(env)
req.all_data = {"filename": "token.xml"}
# Set a policy, that does allow the action
set_policy(name="pol1",
scope=SCOPE.ADMIN,
action="enrollTOTP, enrollHOTP, %s" % ACTION.IMPORT,
client="10.0.0.0/8")
g.policy_object = PolicyClass()
# Try to import tokens
r = check_token_upload(req)
self.assertTrue(r)
# The admin can not upload from another IP address
# An exception is raised
env["REMOTE_ADDR"] = "192.168.0.1"
req = Request(env)
req.all_data = {"filename": "token.xml"}
self.assertRaises(PolicyError,
check_token_upload, req)
# finally delete policy
delete_policy("pol1")
示例7: test_07_set_random_pin
def test_07_set_random_pin(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
req = Request(env)
# Set a policy that defines the tokenlabel
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action="%s=%s" % (ACTION.OTPPINRANDOM, "12"))
set_policy(name="pinhandling",
scope=SCOPE.ENROLL,
action="%s=privacyidea.lib.pinhandling.base.PinHandler" %
ACTION.PINHANDLING)
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {
"user": "cornelius",
"realm": "home"}
init_random_pin(req)
# Check, if the tokenlabel was added
self.assertEqual(len(req.all_data.get("pin")), 12)
# finally delete policy
delete_policy("pol1")
delete_policy("pinhandling")
示例8: test_send_email
def test_send_email(self):
"""
Tests send_email
send_email returns True when it successfully sends an email to a
default address and errors out when unsuccessful.
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com'})
env = builder.get_environ()
req = Request(env)
# Construct message for assertion
msg = handler.create_msg(req)
msg_send = MIMEText(str(msg))
msg_subj = handler.set_mail_subject(msg)
msg_send['Subject'] = msg_subj
msg_send['To'] = conf.EMAIL['default']
# Mock sendmail function so it doesn't send an actual email
smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')
# Call send_email and assert sendmail was called correctly
handler.create_app()
handler.send_email(msg, msg_subj)
smtplib.SMTP.sendmail.assert_called_with(conf.FROM,
conf.EMAIL['default'],
msg_send.as_string())
示例9: test_format_message
def test_format_message(self):
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'some_field': ("This is multi line and "
"should not be on the "
"same line as the title"),
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
target_message = ("Contact:\n"
"--------\n"
"NAME: Valid Guy\n"
"EMAIL: [email protected]\n\n"
"Information:\n"
"------------\n"
"Some Field:\n\n"
"This is multi line and should not be on the same "
"line as the title\n\n")
message = handler.create_msg(req)
formatted_message = handler.format_message(message)
self.assertEqual(formatted_message, target_message)
示例10: test_redirect_url_error_3
def test_redirect_url_error_3(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'redirect': 'http://www.example.com',
'last_name': '!',
'token': 'wrong token'})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock sendmail function so it doesn't send an actual email
smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=3&message=Improper+Form+Submission',
code=302)
示例11: test_redirect_url_error_4
def test_redirect_url_error_4(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock sendmail function so it doesn't send an actual email
smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')
for i in range(conf.CEILING + 1):
app.on_form_page(req)
# Avoid duplicate form error
builder.form['name'] = str(i) + builder.form['name']
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=4&message=Too+Many+Requests',
code=302)
示例12: test_redirect_url_error_1
def test_redirect_url_error_1(self, mock_validate_email):
"""
Tests the user is redirected to appropriate location
"""
# Build test environment
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN})
env = builder.get_environ()
req = Request(env)
# Mock validate email so returns false in Travis
# Not technically necessary because this will return false in Travis
# regardless since it can't find the SMTP server, but kept here for
# consistency
mock_validate_email.return_value = False
# Create app and mock redirect
app = handler.create_app()
werkzeug.utils.redirect = Mock('werkzeug.utils.redirect')
# Mock sendmail function so it doesn't send an actual email
smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')
app.on_form_page(req)
werkzeug.utils.redirect.assert_called_with(
'http://www.example.com?error=1&message=Invalid+Email',
code=302)
示例13: test_registering_new_device_view
def test_registering_new_device_view(self):
"""Test that the HTML view works."""
hass = MagicMock()
with tempfile.NamedTemporaryFile() as fp:
hass.config.path.return_value = fp.name
fp.close()
service = html5.get_service(hass, {})
assert service is not None
# assert hass.called
assert len(hass.mock_calls) == 3
view = hass.mock_calls[1][1][0]
assert view.json_path == fp.name
assert view.registrations == {}
builder = EnvironBuilder(method='POST',
data=json.dumps(SUBSCRIPTION_1))
Request = request_class()
resp = view.post(Request(builder.get_environ()))
expected = {
'unnamed device': SUBSCRIPTION_1,
}
assert resp.status_code == 200, resp.response
assert view.registrations == expected
with open(fp.name) as fpp:
assert json.load(fpp) == expected
示例14: test_unregistering_device_view_handles_unknown_subscription
def test_unregistering_device_view_handles_unknown_subscription(self):
"""Test that the HTML unregister view handles unknown subscriptions."""
hass = MagicMock()
config = {
'some device': SUBSCRIPTION_1,
'other device': SUBSCRIPTION_2,
}
with tempfile.NamedTemporaryFile() as fp:
hass.config.path.return_value = fp.name
fp.write(json.dumps(config).encode('utf-8'))
fp.flush()
service = html5.get_service(hass, {})
assert service is not None
# assert hass.called
assert len(hass.mock_calls) == 3
view = hass.mock_calls[1][1][0]
assert view.json_path == fp.name
assert view.registrations == config
builder = EnvironBuilder(method='DELETE', data=json.dumps({
'subscription': SUBSCRIPTION_3['subscription']
}))
Request = request_class()
resp = view.delete(Request(builder.get_environ()))
assert resp.status_code == 200, resp.response
assert view.registrations == config
with open(fp.name) as fpp:
assert json.load(fpp) == config
示例15: test_07_sign_response
def test_07_sign_response(self):
builder = EnvironBuilder(method='POST',
data={},
headers={})
env = builder.get_environ()
env["REMOTE_ADDR"] = "192.168.0.1"
req = Request(env)
req.values = {"user": "cornelius",
"pass": "offline287082",
"nonce": "12345678"}
res = {"jsonrpc": "2.0",
"result": {"status": True,
"value": True},
"version": "privacyIDEA test",
"id": 1}
resp = Response(json.dumps(res))
from privacyidea.lib.crypto import Sign
g.sign_object = Sign("tests/testdata/private.pem",
"tests/testdata/public.pem")
new_response = sign_response(req, resp)
jresult = json.loads(new_response.data)
self.assertEqual(jresult.get("nonce"), "12345678")
self.assertEqual(jresult.get("signature"), "7220461805369685253863294214862525311437731987121534735993146952136348520396812489782945679627890785973634896605293523175424850299832912878523161817380029213546063467888018205435416020286712762804412024065559270543774578319469096483246637875013247101135063221604113204491121777932147776087110152414627230087278622508771143940031542890514380486863296102037208395371717795767683973979032142677315402422403254992482761563612174177151960004042109847122772813717599078313600692433727690239340230353616318691769042290314664126975201679642739717702497638318611217001361093950139025744740660953017413716736691777322916588328")