desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Asserts that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The passed-in arguments must be valid HTML.'
| def assertHTMLEqual(self, html1, html2, msg=None):
| dom1 = assert_and_parse_html(self, html1, msg, u'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg, u'Second argument is not valid HTML:')
if (dom1 != dom2):
standardMsg = (u'%s != %s' % (safe_repr(dom1, True), safe_repr(dom2, True)))
diff = (u'\n' + u'\n'.join(difflib.ndiff(six.text_type(dom1).splitlines(), six.text_type(dom2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
|
'Asserts that two HTML snippets are not semantically equivalent.'
| def assertHTMLNotEqual(self, html1, html2, msg=None):
| dom1 = assert_and_parse_html(self, html1, msg, u'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg, u'Second argument is not valid HTML:')
if (dom1 == dom2):
standardMsg = (u'%s == %s' % (safe_repr(dom1, True), safe_repr(dom2, True)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Asserts that two XML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The passed-in arguments must be valid XML.'
| def assertXMLEqual(self, xml1, xml2, msg=None):
| try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = (u'First or second argument is not valid XML\n%s' % e)
self.fail(self._formatMessage(msg, standardMsg))
else:
if (not result):
standardMsg = (u'%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Asserts that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The passed-in arguments must be valid XML.'
| def assertXMLNotEqual(self, xml1, xml2, msg=None):
| try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = (u'First or second argument is not valid XML\n%s' % e)
self.fail(self._formatMessage(msg, standardMsg))
else:
if result:
standardMsg = (u'%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True)))
self.fail(self._formatMessage(msg, standardMsg))
|
'Performs any pre-test setup. This includes:
* Flushing the database.
* If the Test Case class has a \'fixtures\' member, installing the
named fixtures.
* If the Test Case class has a \'urls\' member, replace the
ROOT_URLCONF with it.
* Clearing the mail test outbox.'
| def _pre_setup(self):
| self.client = self.client_class()
self._fixture_setup()
self._urlconf_setup()
mail.outbox = []
|
'Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
* Force closing the connection, so that the next test gets
a clean cursor.'
| def _post_teardown(self):
| self._fixture_teardown()
self._urlconf_teardown()
for conn in connections.all():
conn.close()
|
'Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won\'t work for external links since it uses
TestClient to do a request.'
| def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix=u''):
| if msg_prefix:
msg_prefix += u': '
if hasattr(response, u'redirect_chain'):
self.assertTrue((len(response.redirect_chain) > 0), (msg_prefix + (u"Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code))))
self.assertEqual(response.redirect_chain[0][1], status_code, (msg_prefix + (u"Initial response didn't redirect as expected: Response code was %d (expected %d)" % (response.redirect_chain[0][1], status_code))))
(url, status_code) = response.redirect_chain[(-1)]
self.assertEqual(response.status_code, target_status_code, (msg_prefix + (u"Response didn't redirect as expected: Final Response code was %d (expected %d)" % (response.status_code, target_status_code))))
else:
self.assertEqual(response.status_code, status_code, (msg_prefix + (u"Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code))))
url = response[u'Location']
(scheme, netloc, path, query, fragment) = urlsplit(url)
redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code, (msg_prefix + (u"Couldn't retrieve redirection page '%s': response code was %d (expected %d)" % (path, redirect_response.status_code, target_status_code))))
(e_scheme, e_netloc, e_path, e_query, e_fragment) = urlsplit(expected_url)
if (not (e_scheme or e_netloc)):
expected_url = urlunsplit((u'http', (host or u'testserver'), e_path, e_query, e_fragment))
self.assertEqual(url, expected_url, (msg_prefix + (u"Response redirected to '%s', expected '%s'" % (url, expected_url))))
|
'Asserts that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn\'t matter - the assertion is true
if the text occurs at least once in the response.'
| def assertContains(self, response, text, count=None, status_code=200, msg_prefix=u'', html=False):
| if (hasattr(response, u'render') and callable(response.render) and (not response.is_rendered)):
response.render()
if msg_prefix:
msg_prefix += u': '
self.assertEqual(response.status_code, status_code, (msg_prefix + (u"Couldn't retrieve content: Response code was %d (expected %d)" % (response.status_code, status_code))))
text = force_text(text, encoding=response._charset)
if response.streaming:
content = ''.join(response.streaming_content)
else:
content = response.content
content = content.decode(response._charset)
if html:
content = assert_and_parse_html(self, content, None, u"Response's content is not valid HTML:")
text = assert_and_parse_html(self, text, None, u'Second argument is not valid HTML:')
real_count = content.count(text)
if (count is not None):
self.assertEqual(real_count, count, (msg_prefix + (u"Found %d instances of '%s' in response (expected %d)" % (real_count, text, count))))
else:
self.assertTrue((real_count != 0), (msg_prefix + (u"Couldn't find '%s' in response" % text)))
|
'Asserts that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn\'t occurs in the content of the response.'
| def assertNotContains(self, response, text, status_code=200, msg_prefix=u'', html=False):
| if (hasattr(response, u'render') and callable(response.render) and (not response.is_rendered)):
response.render()
if msg_prefix:
msg_prefix += u': '
self.assertEqual(response.status_code, status_code, (msg_prefix + (u"Couldn't retrieve content: Response code was %d (expected %d)" % (response.status_code, status_code))))
text = force_text(text, encoding=response._charset)
content = response.content.decode(response._charset)
if html:
content = assert_and_parse_html(self, content, None, u"Response's content is not valid HTML:")
text = assert_and_parse_html(self, text, None, u'Second argument is not valid HTML:')
self.assertEqual(content.count(text), 0, (msg_prefix + (u"Response should not contain '%s'" % text)))
|
'Asserts that a form used to render the response has a specific field
error.'
| def assertFormError(self, response, form, field, errors, msg_prefix=u''):
| if msg_prefix:
msg_prefix += u': '
contexts = to_list(response.context)
if (not contexts):
self.fail((msg_prefix + u'Response did not use any contexts to render the response'))
errors = to_list(errors)
found_form = False
for (i, context) in enumerate(contexts):
if (form not in context):
continue
found_form = True
for err in errors:
if field:
if (field in context[form].errors):
field_errors = context[form].errors[field]
self.assertTrue((err in field_errors), (msg_prefix + (u"The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" % (field, form, i, err, repr(field_errors)))))
elif (field in context[form].fields):
self.fail((msg_prefix + (u"The field '%s' on form '%s' in context %d contains no errors" % (field, form, i))))
else:
self.fail((msg_prefix + (u"The form '%s' in context %d does not contain the field '%s'" % (form, i, field))))
else:
non_field_errors = context[form].non_field_errors()
self.assertTrue((err in non_field_errors), (msg_prefix + (u"The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" % (form, i, err, non_field_errors))))
if (not found_form):
self.fail((msg_prefix + (u"The form '%s' was not used to render the response" % form)))
|
'Asserts that the template with the provided name was used in rendering
the response. Also usable as context manager.'
| def assertTemplateUsed(self, response=None, template_name=None, msg_prefix=u''):
| if ((response is None) and (template_name is None)):
raise TypeError(u'response and/or template_name argument must be provided')
if msg_prefix:
msg_prefix += u': '
if ((not hasattr(response, u'templates')) or ((response is None) and template_name)):
if response:
template_name = response
response = None
context = _AssertTemplateUsedContext(self, template_name)
return context
template_names = [t.name for t in response.templates]
if (not template_names):
self.fail((msg_prefix + u'No templates used to render the response'))
self.assertTrue((template_name in template_names), (msg_prefix + (u"Template '%s' was not a template used to render the response. Actual template(s) used: %s" % (template_name, u', '.join(template_names)))))
|
'Asserts that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.'
| def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=u''):
| if ((response is None) and (template_name is None)):
raise TypeError(u'response and/or template_name argument must be provided')
if msg_prefix:
msg_prefix += u': '
if ((not hasattr(response, u'templates')) or ((response is None) and template_name)):
if response:
template_name = response
response = None
context = _AssertTemplateNotUsedContext(self, template_name)
return context
template_names = [t.name for t in response.templates]
self.assertFalse((template_name in template_names), (msg_prefix + (u"Template '%s' was used unexpectedly in rendering the response" % template_name)))
|
'Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds.'
| def serve_forever(self, poll_interval=0.5):
| self.__serving = True
self.__is_shut_down.clear()
while self.__serving:
(r, w, e) = select.select([self], [], [], poll_interval)
if r:
self._handle_request_noblock()
self.__is_shut_down.set()
|
'Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while
serve_forever() is running in another thread, or it will
deadlock.'
| def shutdown(self):
| self.__serving = False
if (not self.__is_shut_down.wait(2)):
raise RuntimeError(u'Failed to shutdown the live test server in 2 seconds. The server might be stuck or generating a slow response.')
|
'Handle one request, possibly blocking.'
| def handle_request(self):
| fd_sets = select.select([self], [], [], None)
if (not fd_sets[0]):
return
self._handle_request_noblock()
|
'Handle one request, without blocking.
I assume that select.select has returned that the socket is
readable before this function was called, so there should be
no risk of blocking in get_request().'
| def _handle_request_noblock(self):
| try:
(request, client_address) = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except Exception:
self.handle_error(request, client_address)
self.close_request(request)
|
'Sets up the live server and databases, and then loops over handling
http requests.'
| def run(self):
| if self.connections_override:
from django.db import connections
for (alias, conn) in self.connections_override.items():
connections[alias] = conn
try:
handler = StaticFilesHandler(_MediaFilesHandler(WSGIHandler()))
for (index, port) in enumerate(self.possible_ports):
try:
self.httpd = StoppableWSGIServer((self.host, port), QuietWSGIRequestHandler)
except WSGIServerException as e:
if (((index + 1) < len(self.possible_ports)) and hasattr(e.args[0], u'errno') and (e.args[0].errno == errno.EADDRINUSE)):
continue
else:
raise
else:
self.port = port
break
self.httpd.set_app(handler)
self.is_ready.set()
self.httpd.serve_forever()
except Exception as e:
self.error = e
self.is_ready.set()
|
'The base environment for a request.'
| def _base_environ(self, **request):
| environ = {u'HTTP_COOKIE': self.cookies.output(header=u'', sep=u'; '), u'PATH_INFO': str(u'/'), u'REMOTE_ADDR': str(u'127.0.0.1'), u'REQUEST_METHOD': str(u'GET'), u'SCRIPT_NAME': str(u''), u'SERVER_NAME': str(u'testserver'), u'SERVER_PORT': str(u'80'), u'SERVER_PROTOCOL': str(u'HTTP/1.1'), u'wsgi.version': (1, 0), u'wsgi.url_scheme': str(u'http'), u'wsgi.input': FakePayload(''), u'wsgi.errors': self.errors, u'wsgi.multiprocess': True, u'wsgi.multithread': False, u'wsgi.run_once': False}
environ.update(self.defaults)
environ.update(request)
return environ
|
'Construct a generic request object.'
| def request(self, **request):
| return WSGIRequest(self._base_environ(**request))
|
'Construct a GET request.'
| def get(self, path, data={}, **extra):
| parsed = urlparse(path)
r = {u'CONTENT_TYPE': str(u'text/html; charset=utf-8'), u'PATH_INFO': self._get_path(parsed), u'QUERY_STRING': (urlencode(data, doseq=True) or force_str(parsed[4])), u'REQUEST_METHOD': str(u'GET')}
r.update(extra)
return self.request(**r)
|
'Construct a POST request.'
| def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
| post_data = self._encode_data(data, content_type)
parsed = urlparse(path)
r = {u'CONTENT_LENGTH': len(post_data), u'CONTENT_TYPE': content_type, u'PATH_INFO': self._get_path(parsed), u'QUERY_STRING': force_str(parsed[4]), u'REQUEST_METHOD': str(u'POST'), u'wsgi.input': FakePayload(post_data)}
r.update(extra)
return self.request(**r)
|
'Construct a HEAD request.'
| def head(self, path, data={}, **extra):
| parsed = urlparse(path)
r = {u'CONTENT_TYPE': str(u'text/html; charset=utf-8'), u'PATH_INFO': self._get_path(parsed), u'QUERY_STRING': (urlencode(data, doseq=True) or force_str(parsed[4])), u'REQUEST_METHOD': str(u'HEAD')}
r.update(extra)
return self.request(**r)
|
'Construct an OPTIONS request.'
| def options(self, path, data=u'', content_type=u'application/octet-stream', **extra):
| return self.generic(u'OPTIONS', path, data, content_type, **extra)
|
'Construct a PUT request.'
| def put(self, path, data=u'', content_type=u'application/octet-stream', **extra):
| return self.generic(u'PUT', path, data, content_type, **extra)
|
'Construct a DELETE request.'
| def delete(self, path, data=u'', content_type=u'application/octet-stream', **extra):
| return self.generic(u'DELETE', path, data, content_type, **extra)
|
'Stores exceptions when they are generated by a view.'
| def store_exc_info(self, **kwargs):
| self.exc_info = sys.exc_info()
|
'Obtains the current session variables.'
| def _session(self):
| if (u'django.contrib.sessions' in settings.INSTALLED_APPS):
engine = import_module(settings.SESSION_ENGINE)
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
if cookie:
return engine.SessionStore(cookie.value)
return {}
|
'The master request method. Composes the environment dictionary
and passes to the handler, returning the result of the handler.
Assumes defaults for the query environment, which can be overridden
using the arguments to the request.'
| def request(self, **request):
| environ = self._base_environ(**request)
data = {}
on_template_render = curry(store_rendered_templates, data)
signals.template_rendered.connect(on_template_render, dispatch_uid=u'template-render')
got_request_exception.connect(self.store_exc_info, dispatch_uid=u'request-exception')
try:
try:
response = self.handler(environ)
except TemplateDoesNotExist as e:
if (e.args != (u'500.html',)):
raise
if self.exc_info:
exc_info = self.exc_info
self.exc_info = None
six.reraise(*exc_info)
response.client = self
response.request = request
response.templates = data.get(u'templates', [])
response.context = data.get(u'context')
if (response.context and (len(response.context) == 1)):
response.context = response.context[0]
if response.cookies:
self.cookies.update(response.cookies)
return response
finally:
signals.template_rendered.disconnect(dispatch_uid=u'template-render')
got_request_exception.disconnect(dispatch_uid=u'request-exception')
|
'Requests a response from the server using GET.'
| def get(self, path, data={}, follow=False, **extra):
| response = super(Client, self).get(path, data=data, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Requests a response from the server using POST.'
| def post(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra):
| response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Request a response from the server using HEAD.'
| def head(self, path, data={}, follow=False, **extra):
| response = super(Client, self).head(path, data=data, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Request a response from the server using OPTIONS.'
| def options(self, path, data=u'', content_type=u'application/octet-stream', follow=False, **extra):
| response = super(Client, self).options(path, data=data, content_type=content_type, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Send a resource to the server using PUT.'
| def put(self, path, data=u'', content_type=u'application/octet-stream', follow=False, **extra):
| response = super(Client, self).put(path, data=data, content_type=content_type, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Send a DELETE request to the server.'
| def delete(self, path, data=u'', content_type=u'application/octet-stream', follow=False, **extra):
| response = super(Client, self).delete(path, data=data, content_type=content_type, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Sets the Factory to appear as if it has successfully logged into a site.
Returns True if login is possible; False if the provided credentials
are incorrect, or the user is inactive, or if the sessions framework is
not available.'
| def login(self, **credentials):
| user = authenticate(**credentials)
if (user and user.is_active and (u'django.contrib.sessions' in settings.INSTALLED_APPS)):
engine = import_module(settings.SESSION_ENGINE)
request = HttpRequest()
if self.session:
request.session = self.session
else:
request.session = engine.SessionStore()
login(request, user)
request.session.save()
session_cookie = settings.SESSION_COOKIE_NAME
self.cookies[session_cookie] = request.session.session_key
cookie_data = {u'max-age': None, u'path': u'/', u'domain': settings.SESSION_COOKIE_DOMAIN, u'secure': (settings.SESSION_COOKIE_SECURE or None), u'expires': None}
self.cookies[session_cookie].update(cookie_data)
return True
else:
return False
|
'Removes the authenticated user\'s cookies and session object.
Causes the authenticated user to be logged out.'
| def logout(self):
| session = import_module(settings.SESSION_ENGINE).SessionStore()
session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
if session_cookie:
session.delete(session_key=session_cookie.value)
self.cookies = SimpleCookie()
|
'Follows any redirects by requesting responses from the server using GET.'
| def _handle_redirects(self, response, **extra):
| response.redirect_chain = []
while (response.status_code in (301, 302, 303, 307)):
url = response[u'Location']
redirect_chain = response.redirect_chain
redirect_chain.append((url, response.status_code))
url = urlsplit(url)
if url.scheme:
extra[u'wsgi.url_scheme'] = url.scheme
if url.hostname:
extra[u'SERVER_NAME'] = url.hostname
if url.port:
extra[u'SERVER_PORT'] = str(url.port)
response = self.get(url.path, QueryDict(url.query), follow=False, **extra)
response.redirect_chain = redirect_chain
if (response.redirect_chain[(-1)] in response.redirect_chain[0:(-1)]):
break
return response
|
'Create a new DocTest containing the given examples. The
DocTest\'s globals are initialized with a copy of `globs`.'
| def __init__(self, examples, globs, name, filename, lineno, docstring):
| assert (not isinstance(examples, six.string_types)), 'DocTest no longer accepts str; use DocTestParser instead'
self.examples = examples
self.docstring = docstring
self.globs = globs.copy()
self.name = name
self.filename = filename
self.lineno = lineno
|
'Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.'
| def parse(self, string, name='<string>'):
| string = string.expandtabs()
min_indent = self._min_indent(string)
if (min_indent > 0):
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
output = []
(charno, lineno) = (0, 0)
for m in self._EXAMPLE_RE.finditer(string):
output.append(string[charno:m.start()])
lineno += string.count('\n', charno, m.start())
(source, options, want, exc_msg) = self._parse_example(m, name, lineno)
if (not self._IS_BLANK_OR_COMMENT(source)):
output.append(Example(source, want, exc_msg, lineno=lineno, indent=(min_indent + len(m.group('indent'))), options=options))
lineno += string.count('\n', m.start(), m.end())
charno = m.end()
output.append(string[charno:])
return output
|
'Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.'
| def get_doctest(self, string, globs, name, filename, lineno):
| return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
|
'Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it\'s most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called "line 1" then.
The optional argument `name` is a name identifying this
string, and is only used for error messages.'
| def get_examples(self, string, name='<string>'):
| return [x for x in self.parse(string, name) if isinstance(x, Example)]
|
'Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example\'s source code (with prompts and indentation stripped);
and `want` is the example\'s expected output (with indentation
stripped).
`name` is the string\'s name, and `lineno` is the line number
where the example starts; both are used for error messages.'
| def _parse_example(self, m, name, lineno):
| indent = len(m.group('indent'))
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno)
source = '\n'.join([sl[(indent + 4):] for sl in source_lines])
want = m.group('want')
want_lines = want.split('\n')
if ((len(want_lines) > 1) and re.match(' *$', want_lines[(-1)])):
del want_lines[(-1)]
self._check_prefix(want_lines, (' ' * indent), name, (lineno + len(source_lines)))
want = '\n'.join([wl[indent:] for wl in want_lines])
m = self._EXCEPTION_RE.match(want)
if m:
exc_msg = m.group('msg')
else:
exc_msg = None
options = self._find_options(source, name, lineno)
return (source, options, want, exc_msg)
|
'Return a dictionary containing option overrides extracted from
option directives in the given source string.
`name` is the string\'s name, and `lineno` is the line number
where the example starts; both are used for error messages.'
| def _find_options(self, source, name, lineno):
| options = {}
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
option_strings = m.group(1).replace(',', ' ').split()
for option in option_strings:
if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)):
raise ValueError(('line %r of the doctest for %s has an invalid option: %r' % ((lineno + 1), name, option)))
flag = OPTIONFLAGS_BY_NAME[option[1:]]
options[flag] = (option[0] == '+')
if (options and self._IS_BLANK_OR_COMMENT(source)):
raise ValueError(('line %r of the doctest for %s has an option directive on a line with no example: %r' % (lineno, name, source)))
return options
|
'Return the minimum indentation of any non-blank line in `s`'
| def _min_indent(self, s):
| indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
if (len(indents) > 0):
return min(indents)
else:
return 0
|
'Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.'
| def _check_prompt_blank(self, lines, indent, name, lineno):
| for (i, line) in enumerate(lines):
if ((len(line) >= (indent + 4)) and (line[(indent + 3)] != ' ')):
raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), name, line[indent:(indent + 3)], line)))
|
'Check that every line in the given list starts with the given
prefix; if any line does not, then raise a ValueError.'
| def _check_prefix(self, lines, prefix, name, lineno):
| for (i, line) in enumerate(lines):
if (line and (not line.startswith(prefix))):
raise ValueError(('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (((lineno + i) + 1), name, line)))
|
'Create a new doctest finder.
The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest). The
signature for this factory function should match the signature
of the DocTest constructor.
If the optional argument `recurse` is false, then `find` will
only examine the given object, and not any contained objects.
If the optional argument `exclude_empty` is false, then `find`
will include tests for objects with empty docstrings.'
| def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True):
| self._parser = parser
self._verbose = verbose
self._recurse = recurse
self._exclude_empty = exclude_empty
|
'Return a list of the DocTests that are defined by the given
object\'s docstring, or by any of its contained objects\'
docstrings.
The optional parameter `module` is the module that contains
the given object. If the module is not specified or is None, then
the test finder will attempt to automatically determine the
correct module. The object\'s module is used:
- As a default namespace, if `globs` is not specified.
- To prevent the DocTestFinder from extracting DocTests
from objects that are imported from other modules.
- To find the name of the file containing the object.
- To help find the line number of the object within its
file.
Contained objects whose module does not match `module` are ignored.
If `module` is False, no attempt to find the module will be made.
This is obscure, of use mostly in tests: if `module` is False, or
is None but cannot be found automatically, then all objects are
considered to belong to the (non-existent) module, so all contained
objects will (recursively) be searched for doctests.
The globals for each DocTest is formed by combining `globs`
and `extraglobs` (bindings in `extraglobs` override bindings
in `globs`). A new copy of the globals dictionary is created
for each DocTest. If `globs` is not specified, then it
defaults to the module\'s `__dict__`, if specified, or {}
otherwise. If `extraglobs` is not specified, then it defaults
to {}.'
| def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
| if (name is None):
name = getattr(obj, '__name__', None)
if (name is None):
raise ValueError(("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),)))
if (module is False):
module = None
elif (module is None):
module = inspect.getmodule(obj)
try:
file = (inspect.getsourcefile(obj) or inspect.getfile(obj))
source_lines = linecache.getlines(file)
if (not source_lines):
source_lines = None
except TypeError:
source_lines = None
if (globs is None):
if (module is None):
globs = {}
else:
globs = module.__dict__.copy()
else:
globs = globs.copy()
if (extraglobs is not None):
globs.update(extraglobs)
tests = []
self._find(tests, obj, name, module, source_lines, globs, {})
return tests
|
'Return true if the given object is defined in the given
module.'
| def _from_module(self, module, object):
| if (module is None):
return True
elif inspect.isfunction(object):
return (module.__dict__ is object.__globals__)
elif inspect.isclass(object):
return (module.__name__ == object.__module__)
elif (inspect.getmodule(object) is not None):
return (module is inspect.getmodule(object))
elif hasattr(object, '__module__'):
return (module.__name__ == object.__module__)
elif isinstance(object, property):
return True
else:
raise ValueError('object must be a class or function')
|
'Find tests for the given object and any contained objects, and
add them to `tests`.'
| def _find(self, tests, obj, name, module, source_lines, globs, seen):
| if self._verbose:
print ('Finding tests in %s' % name)
if (id(obj) in seen):
return
seen[id(obj)] = 1
test = self._get_test(obj, name, module, globs, source_lines)
if (test is not None):
tests.append(test)
if (inspect.ismodule(obj) and self._recurse):
for (valname, val) in obj.__dict__.items():
valname = ('%s.%s' % (name, valname))
if ((inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val)):
self._find(tests, val, valname, module, source_lines, globs, seen)
if (inspect.ismodule(obj) and self._recurse):
for (valname, val) in getattr(obj, '__test__', {}).items():
if (not isinstance(valname, six.string_types)):
raise ValueError(('DocTestFinder.find: __test__ keys must be strings: %r' % (type(valname),)))
if (not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, six.string_types))):
raise ValueError(('DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %r' % (type(val),)))
valname = ('%s.__test__.%s' % (name, valname))
self._find(tests, val, valname, module, source_lines, globs, seen)
if (inspect.isclass(obj) and self._recurse):
for (valname, val) in obj.__dict__.items():
if isinstance(val, staticmethod):
val = getattr(obj, valname)
if isinstance(val, classmethod):
val = getattr(obj, valname).__func__
if ((inspect.isfunction(val) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)):
valname = ('%s.%s' % (name, valname))
self._find(tests, val, valname, module, source_lines, globs, seen)
|
'Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.'
| def _get_test(self, obj, name, module, globs, source_lines):
| if isinstance(obj, six.string_types):
docstring = obj
else:
try:
if (obj.__doc__ is None):
docstring = ''
else:
docstring = obj.__doc__
if (not isinstance(docstring, six.string_types)):
docstring = str(docstring)
except (TypeError, AttributeError):
docstring = ''
lineno = self._find_lineno(obj, source_lines)
if (self._exclude_empty and (not docstring)):
return None
if (module is None):
filename = None
else:
filename = getattr(module, '__file__', module.__name__)
if (filename[(-4):] in ('.pyc', '.pyo')):
filename = filename[:(-1)]
return self._parser.get_doctest(docstring, globs, name, filename, lineno)
|
'Return a line number of the given object\'s docstring. Note:
this method assumes that the object has a docstring.'
| def _find_lineno(self, obj, source_lines):
| lineno = None
if inspect.ismodule(obj):
lineno = 0
if inspect.isclass(obj):
if (source_lines is None):
return None
pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-')))
for (i, line) in enumerate(source_lines):
if pat.match(line):
lineno = i
break
if inspect.ismethod(obj):
obj = obj.__func__
if inspect.isfunction(obj):
obj = obj.__code__
if inspect.istraceback(obj):
obj = obj.tb_frame
if inspect.isframe(obj):
obj = obj.f_code
if inspect.iscode(obj):
lineno = (getattr(obj, 'co_firstlineno', None) - 1)
if (lineno is not None):
if (source_lines is None):
return (lineno + 1)
pat = re.compile('(^|.*:)\\s*\\w*("|\')')
for lineno in range(lineno, len(source_lines)):
if pat.match(source_lines[lineno]):
return lineno
return None
|
'Create a new test runner.
Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
outputs of doctest examples.
Optional keyword arg \'verbose\' prints lots of stuff if true,
only failures if false; by default, it\'s true iff \'-v\' is in
sys.argv.
Optional argument `optionflags` can be used to control how the
test runner compares expected output to actual output, and how
it displays failures. See the documentation for `testmod` for
more information.'
| def __init__(self, checker=None, verbose=None, optionflags=0):
| self._checker = (checker or OutputChecker())
if (verbose is None):
verbose = ('-v' in sys.argv)
self._verbose = verbose
self.optionflags = optionflags
self.original_optionflags = optionflags
self.tries = 0
self.failures = 0
self._name2ft = {}
self._fakeout = _SpoofOut()
|
'Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)'
| def report_start(self, out, test, example):
| if self._verbose:
if example.want:
out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want)))
else:
out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
|
'Report that the given example ran successfully. (Only
displays a message if verbose=True)'
| def report_success(self, out, test, example, got):
| if self._verbose:
out('ok\n')
|
'Report that the given example failed.'
| def report_failure(self, out, test, example, got):
| out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
|
'Report that the given example raised an unexpected exception.'
| def report_unexpected_exception(self, out, test, example, exc_info):
| out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
|
'Run the examples in `test`. Write the outcome of each example
with one of the `DocTestRunner.report_*` methods, using the
writer function `out`. `compileflags` is the set of compiler
flags that should be used to execute examples. Return a tuple
`(f, t)`, where `t` is the number of examples tried, and `f`
is the number of examples that failed. The examples are run
in the namespace `test.globs`.'
| def __run(self, test, compileflags, out):
| failures = tries = 0
original_optionflags = self.optionflags
(SUCCESS, FAILURE, BOOM) = range(3)
check = self._checker.check_output
for (examplenum, example) in enumerate(test.examples):
quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0))
self.optionflags = original_optionflags
if example.options:
for (optionflag, val) in example.options.items():
if val:
self.optionflags |= optionflag
else:
self.optionflags &= (~ optionflag)
if (self.optionflags & SKIP):
continue
tries += 1
if (not quiet):
self.report_start(out, test, example)
filename = ('<doctest %s[%d]>' % (test.name, examplenum))
original_displayhook = sys.displayhook
if six.PY3:
lines = []
def py3_displayhook(value):
if (value is None):
return original_displayhook(value)
s = repr(value)
expected = example.want
expected = expected.strip()
s = s.replace('u', '')
s = s.replace('b', '')
expected = expected.replace('u', '')
expected = expected.replace('b', '')
s = s.replace("'", '"')
expected = expected.replace("'", '"')
lines.append(s)
if (s == expected):
sys.stdout.write(('%s\n' % example.want.strip()))
elif (len(expected.split('\n')) == len(lines)):
if ('\n'.join(lines) == expected):
sys.stdout.write(('%s\n' % example.want.strip()))
else:
sys.stdout.write(('%s\n' % repr(value)))
elif (len(expected.split('\n')) != len(lines)):
pass
else:
sys.stdout.write(('%s\n' % repr(value)))
sys.displayhook = py3_displayhook
try:
six.exec_(compile(example.source, filename, 'single', compileflags, 1), test.globs)
self.debugger.set_continue()
exception = None
except KeyboardInterrupt:
raise
except:
exception = sys.exc_info()
self.debugger.set_continue()
finally:
sys.displayhook = original_displayhook
got = self._fakeout.getvalue()
self._fakeout.truncate(0)
self._fakeout.seek(0)
outcome = FAILURE
if (exception is None):
if check(example.want, got, self.optionflags):
outcome = SUCCESS
else:
exc_msg = traceback.format_exception_only(*exception[:2])[(-1)]
if six.PY3:
m = re.match('(.*)\\.(\\w+:.+\\s)', exc_msg)
if (m != None):
f_name = m.group(1)
if (f_name == exception[0].__module__):
exc_msg = m.group(2)
if (not quiet):
got += _exception_traceback(exception)
if (example.exc_msg is None):
outcome = BOOM
elif check(example.exc_msg, exc_msg, self.optionflags):
outcome = SUCCESS
elif (self.optionflags & IGNORE_EXCEPTION_DETAIL):
m1 = re.match('[^:]*:', example.exc_msg)
m2 = re.match('[^:]*:', exc_msg)
if (m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags)):
outcome = SUCCESS
if (outcome is SUCCESS):
if (not quiet):
self.report_success(out, test, example, got)
elif (outcome is FAILURE):
if (not quiet):
self.report_failure(out, test, example, got)
failures += 1
elif (outcome is BOOM):
if (not quiet):
self.report_unexpected_exception(out, test, example, exception)
failures += 1
else:
assert False, ('unknown outcome', outcome)
self.optionflags = original_optionflags
self.__record_outcome(test, failures, tries)
return (failures, tries)
|
'Record the fact that the given DocTest (`test`) generated `f`
failures out of `t` tried examples.'
| def __record_outcome(self, test, f, t):
| (f2, t2) = self._name2ft.get(test.name, (0, 0))
self._name2ft[test.name] = ((f + f2), (t + t2))
self.failures += f
self.tries += t
|
'Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
`clear_globs` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
the test completes, then use `clear_globs=False`.
`compileflags` gives the set of flags that should be used by
the Python compiler when running the examples. If not
specified, then it will default to the set of future-import
flags that apply to `globs`.
The output of each example is checked using
`DocTestRunner.check_output`, and the results are formatted by
the `DocTestRunner.report_*` methods.'
| def run(self, test, compileflags=None, out=None, clear_globs=True):
| self.test = test
if (compileflags is None):
compileflags = _extract_future_flags(test.globs)
save_stdout = sys.stdout
if (out is None):
out = save_stdout.write
sys.stdout = self._fakeout
save_set_trace = pdb.set_trace
self.debugger = _OutputRedirectingPdb(save_stdout)
self.debugger.reset()
pdb.set_trace = self.debugger.set_trace
self.save_linecache_getlines = linecache.getlines
linecache.getlines = self.__patched_linecache_getlines
try:
return self.__run(test, compileflags, out)
finally:
sys.stdout = save_stdout
pdb.set_trace = save_set_trace
linecache.getlines = self.save_linecache_getlines
if clear_globs:
test.globs.clear()
|
'Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then the
DocTestRunner\'s verbosity is used.'
| def summarize(self, verbose=None):
| if (verbose is None):
verbose = self._verbose
notests = []
passed = []
failed = []
totalt = totalf = 0
for x in self._name2ft.items():
(name, (f, t)) = x
assert (f <= t)
totalt += t
totalf += f
if (t == 0):
notests.append(name)
elif (f == 0):
passed.append((name, t))
else:
failed.append(x)
if verbose:
if notests:
print ('%d items had no tests:' % len(notests))
notests.sort()
for thing in notests:
print (' %s' % thing)
if passed:
print ('%d items passed all tests:' % len(passed))
passed.sort()
for (thing, count) in passed:
print (' %3d tests in %s' % (count, thing))
if failed:
print self.DIVIDER
print ('%d items had failures:' % len(failed))
failed.sort()
for (thing, (f, t)) in failed:
print (' %3d of %3d in %s' % (f, t, thing))
if verbose:
print ('%d tests in % d items' % (len(self._name2ft), totalt))
print ('%d passed and %d failed.' % ((totalt - totalf), totalf))
if totalf:
print ('***Test Failed*** %d failures.' % totalf)
elif verbose:
print 'Test passed.'
return (totalf, totalt)
|
'Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for more information about
option flags.'
| def check_output(self, want, got, optionflags):
| if (got == want):
return True
if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)):
if ((got, want) == ('True\n', '1\n')):
return True
if ((got, want) == ('False\n', '0\n')):
return True
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
want = re.sub(('(?m)^%s\\s*?$' % re.escape(BLANKLINE_MARKER)), '', want)
got = re.sub('(?m)^\\s*?$', '', got)
if (got == want):
return True
if (optionflags & NORMALIZE_WHITESPACE):
got = ' '.join(got.split())
want = ' '.join(want.split())
if (got == want):
return True
if (optionflags & ELLIPSIS):
if _ellipsis_match(want, got):
return True
return False
|
'Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.'
| def output_difference(self, example, got, optionflags):
| want = example.want
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
if self._do_a_fancy_diff(want, got, optionflags):
want_lines = want.splitlines(True)
got_lines = got.splitlines(True)
if (optionflags & REPORT_UDIFF):
diff = difflib.unified_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:]
kind = 'unified diff with -expected +actual'
elif (optionflags & REPORT_CDIFF):
diff = difflib.context_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:]
kind = 'context diff with expected followed by actual'
elif (optionflags & REPORT_NDIFF):
engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = list(engine.compare(want_lines, got_lines))
kind = 'ndiff with -expected +actual'
else:
assert 0, 'Bad diff option'
diff = [(line.rstrip() + '\n') for line in diff]
return (('Differences (%s):\n' % kind) + _indent(''.join(diff)))
if (want and got):
return ('Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)))
elif want:
return ('Expected:\n%sGot nothing\n' % _indent(want))
elif got:
return ('Expected nothing\nGot:\n%s' % _indent(got))
else:
return 'Expected nothing\nGot nothing\n'
|
'Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
The DocTestCase provides a debug method that raises
UnexpectedException errors if there is an unexepcted
exception:
>>> test = DocTestParser().get_doctest(\'>>> raise KeyError\n42\',
... {}, \'foo\', \'foo.py\', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException as e:
... failure = e
The UnexpectedException contains the test, the example, and
the original exception:
>>> failure.test is test
True
>>> failure.example.want
\'42\n\'
>>> exc_info = failure.exc_info
>>> raise exc_info[0], exc_info[1], exc_info[2]
Traceback (most recent call last):
KeyError
If the output doesn\'t match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest(\'\'\'
... >>> x = 1
... >>> x
... 2
... \'\'\', {}, \'foo\', \'foo.py\', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except DocTestFailure as e:
... failure = e
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
\'2\n\'
and the actual output:
>>> failure.got
\'1\n\''
| def debug(self):
| self.setUp()
runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False)
runner.run(self._dt_test)
self.tearDown()
|
'val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
>>> print(t.get())
123'
| def __init__(self, val):
| self.val = val
|
'square() -> square TestClass\'s associated value
>>> _TestClass(13).square().get()
169'
| def square(self):
| self.val = (self.val ** 2)
return self
|
'get() -> return TestClass\'s associated value.
>>> x = _TestClass(-42)
>>> print(x.get())
-42'
| def get(self):
| return self.val
|
'Destroys all the non-mirror databases.'
| def teardown_databases(self, old_config, **kwargs):
| (old_names, mirrors) = old_config
for (connection, old_name, destroy) in old_names:
if destroy:
connection.creation.destroy_test_db(old_name, self.verbosity)
|
'Run the unit tests for all the test labels in the provided list.
Labels must be of the form:
- app.TestClass.test_method
Run a single specific test method
- app.TestClass
Run all the test methods in a given class
- app
Search for doctests and unittests in the named application.
When looking for tests, the test runner will look in the models and
tests modules for the application.
A list of \'extra\' tests may also be provided; these tests
will be added to the test suite.
Returns the number of tests that failed.'
| def run_tests(self, test_labels, extra_tests=None, **kwargs):
| self.setup_test_environment()
suite = self.build_suite(test_labels, extra_tests)
old_config = self.setup_databases()
if (self.verbosity > 0):
logger = logging.getLogger('py.warnings')
handler = logging.StreamHandler()
logger.addHandler(handler)
result = self.run_suite(suite)
if (self.verbosity > 0):
logger.removeHandler(handler)
self.teardown_databases(old_config)
self.teardown_test_environment()
return self.suite_result(suite, result)
|
'Display stage -- can be called many times'
| def render(self, context):
| context.render_context.push()
try:
return self._render(context)
finally:
context.render_context.pop()
|
'Return a list of tokens from a given template_string.'
| def tokenize(self):
| in_tag = False
result = []
for bit in tag_re.split(self.template_string):
if bit:
result.append(self.create_token(bit, in_tag))
in_tag = (not in_tag)
return result
|
'Convert the given token string into a new Token object and return it.
If in_tag is True, we are processing something that matched a tag,
otherwise it should be treated as a literal string.'
| def create_token(self, token_string, in_tag):
| if (in_tag and token_string.startswith(BLOCK_TAG_START)):
block_content = token_string[2:(-2)].strip()
if (self.verbatim and (block_content == self.verbatim)):
self.verbatim = False
if (in_tag and (not self.verbatim)):
if token_string.startswith(VARIABLE_TAG_START):
token = Token(TOKEN_VAR, token_string[2:(-2)].strip())
elif token_string.startswith(BLOCK_TAG_START):
if (block_content[:9] in (u'verbatim', u'verbatim ')):
self.verbatim = (u'end%s' % block_content)
token = Token(TOKEN_BLOCK, block_content)
elif token_string.startswith(COMMENT_TAG_START):
content = u''
if token_string.find(TRANSLATOR_COMMENT_MARK):
content = token_string[2:(-2)].strip()
token = Token(TOKEN_COMMENT, content)
else:
token = Token(TOKEN_TEXT, token_string)
token.lineno = self.lineno
self.lineno += token_string.count(u'\n')
return token
|
'Convenient wrapper for FilterExpression'
| def compile_filter(self, token):
| return FilterExpression(token, self)
|
'Overload this method to do the actual parsing and return the result.'
| def top(self):
| raise NotImplementedError()
|
'Returns True if there is more stuff in the tag.'
| def more(self):
| return (self.pointer < len(self.subject))
|
'Undoes the last microparser. Use this for lookahead and backtracking.'
| def back(self):
| if (not len(self.backout)):
raise TemplateSyntaxError(u'back called without some previous parsing')
self.pointer = self.backout.pop()
|
'A microparser that just returns the next tag from the line.'
| def tag(self):
| subject = self.subject
i = self.pointer
if (i >= len(subject)):
raise TemplateSyntaxError((u'expected another tag, found end of string: %s' % subject))
p = i
while ((i < len(subject)) and (subject[i] not in (u' ', u' DCTB '))):
i += 1
s = subject[p:i]
while ((i < len(subject)) and (subject[i] in (u' ', u' DCTB '))):
i += 1
self.backout.append(self.pointer)
self.pointer = i
return s
|
'A microparser that parses for a value: some string constant or
variable name.'
| def value(self):
| subject = self.subject
i = self.pointer
def next_space_index(subject, i):
u'\n Increment pointer until a real space (i.e. a space not within\n quotes) is encountered\n '
while ((i < len(subject)) and (subject[i] not in (u' ', u' DCTB '))):
if (subject[i] in (u'"', u"'")):
c = subject[i]
i += 1
while ((i < len(subject)) and (subject[i] != c)):
i += 1
if (i >= len(subject)):
raise TemplateSyntaxError((u'Searching for value. Unexpected end of string in column %d: %s' % (i, subject)))
i += 1
return i
if (i >= len(subject)):
raise TemplateSyntaxError((u'Searching for value. Expected another value but found end of string: %s' % subject))
if (subject[i] in (u'"', u"'")):
p = i
i += 1
while ((i < len(subject)) and (subject[i] != subject[p])):
i += 1
if (i >= len(subject)):
raise TemplateSyntaxError((u'Searching for value. Unexpected end of string in column %d: %s' % (i, subject)))
i += 1
i = next_space_index(subject, i)
res = subject[p:i]
while ((i < len(subject)) and (subject[i] in (u' ', u' DCTB '))):
i += 1
self.backout.append(self.pointer)
self.pointer = i
return res
else:
p = i
i = next_space_index(subject, i)
s = subject[p:i]
while ((i < len(subject)) and (subject[i] in (u' ', u' DCTB '))):
i += 1
self.backout.append(self.pointer)
self.pointer = i
return s
|
'Resolve this variable against a given context.'
| def resolve(self, context):
| if (self.lookups is not None):
value = self._resolve_lookup(context)
else:
value = self.literal
if self.translate:
if self.message_context:
return pgettext_lazy(self.message_context, value)
else:
return ugettext_lazy(value)
return value
|
'Performs resolution of a real variable (i.e. not a literal) against the
given context.
As indicated by the method\'s name, this method is an implementation
detail and shouldn\'t be called by external code. Use Variable.resolve()
instead.'
| def _resolve_lookup(self, context):
| current = context
try:
for bit in self.lookups:
try:
current = current[bit]
except (TypeError, AttributeError, KeyError, ValueError):
try:
current = getattr(current, bit)
except (TypeError, AttributeError):
try:
current = current[int(bit)]
except (IndexError, ValueError, KeyError, TypeError):
raise VariableDoesNotExist(u'Failed lookup for key [%s] in %r', (bit, current))
if callable(current):
if getattr(current, u'do_not_call_in_templates', False):
pass
elif getattr(current, u'alters_data', False):
current = settings.TEMPLATE_STRING_IF_INVALID
else:
try:
current = current()
except TypeError:
current = settings.TEMPLATE_STRING_IF_INVALID
except Exception as e:
if getattr(e, u'silent_variable_failure', False):
current = settings.TEMPLATE_STRING_IF_INVALID
else:
raise
return current
|
'Return the node rendered as a string.'
| def render(self, context):
| pass
|
'Return a list of all nodes (within this node and its nodelist)
of the given type'
| def get_nodes_by_type(self, nodetype):
| nodes = []
if isinstance(self, nodetype):
nodes.append(self)
for attr in self.child_nodelists:
nodelist = getattr(self, attr, None)
if nodelist:
nodes.extend(nodelist.get_nodes_by_type(nodetype))
return nodes
|
'Return a list of all nodes of the given type'
| def get_nodes_by_type(self, nodetype):
| nodes = []
for node in self:
nodes.extend(node.get_nodes_by_type(nodetype))
return nodes
|
'Pickling support function.
Ensures that the object can\'t be pickled before it has been
rendered, and that the pickled state only includes rendered
data, not the data used to construct the response.'
| def __getstate__(self):
| obj_dict = super(SimpleTemplateResponse, self).__getstate__()
if (not self._is_rendered):
raise ContentNotRenderedError('The response content must be rendered before it can be pickled.')
for attr in self.rendering_attrs:
if (attr in obj_dict):
del obj_dict[attr]
return obj_dict
|
'Accepts a template object, path-to-template or list of paths'
| def resolve_template(self, template):
| if isinstance(template, (list, tuple)):
return loader.select_template(template)
elif isinstance(template, six.string_types):
return loader.get_template(template)
else:
return template
|
'Converts context data into a full Context object
(assuming it isn\'t already a Context object).'
| def resolve_context(self, context):
| if isinstance(context, Context):
return context
else:
return Context(context)
|
'Returns the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property.'
| @property
def rendered_content(self):
| template = self.resolve_template(self.template_name)
context = self.resolve_context(self.context_data)
content = template.render(context)
return content
|
'Adds a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.'
| def add_post_render_callback(self, callback):
| if self._is_rendered:
callback(self)
else:
self._post_render_callbacks.append(callback)
|
'Renders (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Returns the baked response instance.'
| def render(self):
| retval = self
if (not self._is_rendered):
self.content = self.rendered_content
for post_callback in self._post_render_callbacks:
newretval = post_callback(retval)
if (newretval is not None):
retval = newretval
return retval
|
'Sets the content for the response'
| @content.setter
def content(self, value):
| HttpResponse.content.fset(self, value)
self._is_rendered = True
|
'Convert context data into a full RequestContext object
(assuming it isn\'t already a Context object).'
| def resolve_context(self, context):
| if isinstance(context, Context):
return context
return RequestContext(self._request, context, current_app=self._current_app)
|
'Returns a tuple containing the source and origin for the given template
name.'
| def load_template_source(self, template_name, template_dirs=None):
| raise NotImplementedError
|
'Resets any state maintained by the loader instance (e.g., cached
templates or cached loader modules).'
| def reset(self):
| pass
|
'Empty the template cache.'
| def reset(self):
| self.template_cache.clear()
|
'Loads templates from Python eggs via pkg_resource.resource_string.
For every installed app, it tries to get the resource (app, template_name).'
| def load_template_source(self, template_name, template_dirs=None):
| if (resource_string is not None):
pkg_name = (u'templates/' + template_name)
for app in settings.INSTALLED_APPS:
try:
resource = resource_string(app, pkg_name)
except Exception:
continue
if (not six.PY3):
resource = resource.decode(settings.FILE_CHARSET)
return (resource, (u'egg:%s:%s' % (app, pkg_name)))
raise TemplateDoesNotExist(template_name)
|
'Returns the absolute paths to "template_name", when appended to each
directory in "template_dirs". Any paths that don\'t lie inside one of the
template dirs are excluded from the result set, for security reasons.'
| def get_template_sources(self, template_name, template_dirs=None):
| if (not template_dirs):
template_dirs = settings.TEMPLATE_DIRS
for template_dir in template_dirs:
try:
(yield safe_join(template_dir, template_name))
except UnicodeDecodeError:
raise
except ValueError:
pass
|
'Returns the absolute paths to "template_name", when appended to each
directory in "template_dirs". Any paths that don\'t lie inside one of the
template dirs are excluded from the result set, for security reasons.'
| def get_template_sources(self, template_name, template_dirs=None):
| if (not template_dirs):
template_dirs = app_template_dirs
for template_dir in template_dirs:
try:
(yield safe_join(template_dir, template_name))
except UnicodeDecodeError:
raise
except ValueError:
pass
|
'Returns what to display in error messages for this node'
| def display(self):
| return self.id
|
'Set a variable in the current context'
| def __setitem__(self, key, value):
| self.dicts[(-1)][key] = value
|
'Get a variable\'s value, starting at the current context and going upward'
| def __getitem__(self, key):
| for d in reversed(self.dicts):
if (key in d):
return d[key]
raise KeyError(key)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.