本文整理汇总了Python中six.moves.urllib.error方法的典型用法代码示例。如果您正苦于以下问题:Python urllib.error方法的具体用法?Python urllib.error怎么用?Python urllib.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.urllib
的用法示例。
在下文中一共展示了urllib.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _report_errors
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def _report_errors(self, d):
""" Performs error checking on the result from the execute
call.
Specifically, this method is looking for the <error> tag
returned by MicroStrategy.
Args:
d (pyquery): a pyquery object
Returns:
bool: indicates whether or not there was an error.
If there was an error, an exception should be raised.
Raises:
MstrReportException: if there was an error executing
the report.
"""
error = d('error')
if error:
raise MstrReportException(
"There was an error running the report. Microstrategy error message: " + error[0].text
)
return True
return False
示例2: test_error_execute
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_error_execute(self, mock_mstr_client_request):
""" Test that when an error is returned by MicroStrategy,
execute raises an exception
"""
mock_mstr_client_request.return_value = (
"<taskResponse>"
"<report_data_list><report_data><error>Object executed is in "
"prompt status. Please resolve prompts and use the message ID."
"</error></report_data></report_data_list></taskResponse>"
)
self.assertRaises(MstrReportException, self.report.execute)
mock_mstr_client_request.assert_called_with(self.report_args, None)
self.assertRaises(MstrReportException, self.report.get_values)
mock_mstr_client_request.assert_called_with(self.report_args, None)
self.assertEqual(None, self.report._values)
示例3: _record_error
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def _record_error(self, e, error_type):
"""Emits a value for the URL metric that reports an error.
Status code is set to zero and we included an extra field capturing a portion of the exception's name.
@param e: The exception that caused the problem.
@param error_type: The error type, used to make the fielld name to hold the exception name.
@type e: Exception
@type error_type: str
"""
# Convert the exception to a string, truncated to 20 chars.
e_to_str = six.text_type(e)
if len(e_to_str) > 20:
e_to_str = e_to_str[0:20]
self._logger.emit_value(
"response",
"failed",
extra_fields={
"url": self.url,
"status": 0,
"length": 0,
error_type: e_to_str,
},
)
示例4: gather_sample
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def gather_sample(self):
data = self._get_status()
if data is None:
self._logger.error("No data returned.")
else:
samplesToEmit = [
("busy_workers", "apache.workers.active"),
("idle_workers", "apache.workers.idle"),
("connections_total", "apache.connections.active"),
("async_connections_writing", "apache.connections.writing"),
("async_connections_keep_alive", "apache.connections.idle"),
("async_connections_closing", "apache.connections.closing"),
]
statsEmitted = 0
for key, metric_name in samplesToEmit:
if key in data:
self._logger.emit_value(metric_name, int(data[key]))
statsEmitted += 1
if statsEmitted == 0:
self._logger.error(
"Status page did not match expected format. Check to make sure you included "
'the "?auto" option in the status url'
)
示例5: _record_fetch_result
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def _record_fetch_result(self, container_id, result):
"""Record that the `stats` result for the specified container. If there was an error, result should be
None.
@type container_id: str
@type result: JsonObject
"""
self.__lock.acquire()
try:
self.__container_scoreboard[container_id] = result
self.__remaining_metrics_count -= 1
# Since this is only invoked by a worker once their stats call is done, we know they are now idle.
self.__idle_workers_count += 1
# Wake up any thread that was waiting on this result.
self.__cv.notifyAll()
finally:
self.__lock.release()
示例6: test_prohibited_tools
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_prohibited_tools(self):
self.app.post('/p/_admin/update',
params=dict(name='Projects',
prohibited_tools='wiki, tickets'),
extra_environ=dict(username=str('root')))
r = self.app.get('/p/_admin/overview', extra_environ=dict(username=str('root')))
assert 'wiki, tickets' in r
c.user = M.User.query.get(username='root')
c.project = M.Project.query.get(shortname='test')
data = c.project.nav_data(admin_options=True)
assert 'Wiki' not in data
assert 'Tickets' not in data
r = self.app.post('/p/_admin/update',
params=dict(name='Projects',
prohibited_tools='wiki, test'),
extra_environ=dict(username=str('root')))
assert 'error' in self.webflash(r), self.webflash(r)
示例7: test_check_phone_verification_error
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_check_phone_verification_error(self, phone_service):
with h.push_config(config, **{'project.verify_phone': 'true'}):
phone_service.check.return_value = {'status': 'error'}
req_id = 'request-id'
# make request to verify first to initialize session
phone_service.verify.return_value = {
'request_id': req_id, 'status': 'ok'}
r = self.app.get('/p/verify_phone', {'number': '1234567890'})
r = self.app.get('/p/check_phone_verification', {'pin': '1234'})
assert_equal(r.json, {'status': 'error'})
phone_service.check.assert_called_once_with(req_id, '1234')
user = M.User.by_username('test-admin')
hash = user.get_tool_data('phone_verification', 'number_hash')
assert_equal(hash, None)
示例8: log_output
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def log_output(log):
class Writer(object):
def __init__(self, func):
self.func = func
self.closed = False
def write(self, buf):
self.func(buf)
def flush(self):
pass
_stdout = sys.stdout
_stderr = sys.stderr
sys.stdout = Writer(log.info)
sys.stderr = Writer(log.error)
try:
yield log
finally:
sys.stdout = _stdout
sys.stderr = _stderr
示例9: parse_options
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def parse_options():
optparser = OptionParser(usage=''' %prog <Trac URL>
Export ticket data from a Trac instance''')
optparser.add_option('-o', '--out-file', dest='out_filename',
help='Write to file (default stdout)')
optparser.add_option('--no-attachments', dest='do_attachments',
action='store_false', default=True, help='Export attachment info')
optparser.add_option('--only-tickets', dest='only_tickets',
action='store_true', help='Export only ticket list')
optparser.add_option('--start', dest='start_id', type='int', default=1,
help='Start with given ticket numer (or next accessible)')
optparser.add_option('--limit', dest='limit', type='int',
default=None, help='Limit number of tickets')
optparser.add_option('-v', '--verbose', dest='verbose',
action='store_true', help='Verbose operation')
options, args = optparser.parse_args()
if len(args) != 1:
optparser.error("Wrong number of arguments.")
return options, args
示例10: test_edit_ticket_validation
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_edit_ticket_validation(self):
old_summary = 'edit ticket test'
new_summary = "new summary"
self.new_ticket(summary=old_summary)
response = self.app.get('/bugs/1/')
# check that existing form is valid
assert response.html.find('input', {'name': 'ticket_form.summary'})['value'] == old_summary
assert not response.html.find('div', {'class': 'error'})
form = self._find_update_ticket_form(response)
# try submitting with no summary set and check for error message
form['ticket_form.summary'] = ""
error_form = form.submit()
error_message = error_form.html.find('div', {'class': 'error'})
assert error_message
assert error_message.string == 'You must provide a Title'
assert error_message.findPreviousSibling('input').get('name') == 'ticket_form.summary'
# set a summary, submit, and check for success
form = self._find_update_ticket_form(error_form)
form['ticket_form.summary'] = new_summary
r = form.submit()
assert r.status_int == 302, r.showbrowser()
success = r.follow().html
assert success.findAll('form', {'action': '/p/test/bugs/1/update_ticket_from_widget'}) is not None
assert success.find('input', {'name': 'ticket_form.summary'})['value'] == new_summary
示例11: test_create_permission
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_create_permission(self):
"""Test that user with `create` permission can create ticket,
but can't edit it without `update` permission.
"""
response = self.app.get('/p/test/tracker/',
extra_environ=dict(username=str('test-user-0')))
assert 'Create Ticket' in response
response = self.new_ticket(summary='test create, not update',
mount_point='/tracker/',
extra_environ=dict(username=str('test-user-0')))
ticket_url = response.headers['Location']
response = self.app.get(ticket_url,
extra_environ=dict(username=str('test-user-0')))
assert not response.html.find('div', {'class': 'error'})
assert not response.html.find('a', {'class': 'edit_ticket'})
示例12: test_rate_limit_new
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_rate_limit_new(self):
self.new_ticket(summary='First ticket')
# Set rate limit to unlimit
with h.push_config(config, **{'forgetracker.rate_limits': '{}'}):
r = self.app.get('/bugs/new/')
assert_equal(r.status_int, 200)
# Set rate limit to 1 in first hour of project
with h.push_config(config, **{'forgetracker.rate_limits': '{"3600": 1}'}):
r = self.app.get('/bugs/new/')
assert_equal(r.status_int, 302)
assert_equal(r.location, 'http://localhost/bugs/')
wf = json.loads(self.webflash(r))
assert_equal(wf['status'], 'error')
assert_equal(
wf['message'],
'Ticket creation rate limit exceeded. Please try again later.')
示例13: test_rate_limit_save_ticket
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_rate_limit_save_ticket(self):
# Set rate limit to unlimit
with h.push_config(config, **{'forgetracker.rate_limits': '{}'}):
summary = 'Ticket w/o limit'
post_data = {'ticket_form.summary': summary}
r = self.app.post('/bugs/save_ticket', post_data).follow()
assert_in(summary, r)
t = tm.Ticket.query.get(summary=summary)
assert_not_equal(t, None)
# Set rate limit to 1 in first hour of project
with h.push_config(config, **{'forgetracker.rate_limits': '{"3600": 1}'}):
summary = 'Ticket with limit'
post_data = {'ticket_form.summary': summary}
r = self.app.post('/bugs/save_ticket', post_data)
assert_equal(r.status_int, 302)
assert_equal(r.location, 'http://localhost/bugs/')
wf = json.loads(self.webflash(r))
assert_equal(wf['status'], 'error')
assert_equal(
wf['message'],
'Ticket creation rate limit exceeded. Please try again later.')
assert_not_in(summary, r.follow())
t = tm.Ticket.query.get(summary=summary)
assert_equal(t, None)
示例14: get_prompts
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def get_prompts(self):
""" Returns the prompts associated with this report. If there are
no prompts, this method raises an error.
Returns:
list: a list of Prompt objects
Raises:
MstrReportException: if a msgID could not be retrieved
likely implying there are no prompts for this report.
"""
arguments = {'taskId': 'reportExecute'}
arguments.update(self._args)
response = self._mstr_client._request(arguments)
message = pq(response)('msg')('id')
if not message:
logger.debug("failed retrieval of msgID in response %s" % response)
raise MstrReportException(
"Error retrieving msgID for report. Most likely the report does not have any prompts."
)
return
message_id = message[0].text
arguments = {
'taskId': 'getPrompts',
'objectType': '3',
'msgID': message_id,
'sessionState': self._mstr_client._session
}
response = self._mstr_client._request(arguments)
return self._parse_prompts(response)
示例15: test_no_prompts_gives_error
# 需要导入模块: from six.moves import urllib [as 别名]
# 或者: from six.moves.urllib import error [as 别名]
def test_no_prompts_gives_error(self, mock_mstr_client_request):
""" Test that if a user tries to retrieve prompts for a report
and the report has no prompts, that the actual report is returned,
and subsequently an error is raised.
"""
args = {'reportID': 'report_id', 'sessionState': 'session', 'taskId': 'reportExecute'}
mock_mstr_client_request.return_value = self.report_response
self.assertRaises(MstrReportException, self.report.get_prompts)
mock_mstr_client_request.assert_called_with(args)