desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Sets a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.'
| def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False):
| self.cookies[key] = value
if (expires is not None):
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = (expires - expires.utcnow())
delta = (delta + datetime.timedelta(... |
'Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.'
| def _setup(self):
| try:
settings_module = os.environ[ENVIRONMENT_VARIABLE]
if (not settings_module):
raise KeyError
except KeyError:
raise ImportError(('Settings cannot be imported, because environment variable %s is undefined.' % ENVIRONMENT_VARIABLE))
self._wrap... |
'Called to manually configure the settings. The \'default_settings\'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).'
| def configure(self, default_settings=global_settings, **options):
| if (self._wrapped is not empty):
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for (name, value) in options.items():
setattr(holder, name, value)
self._wrapped = holder
|
'Returns True if the settings have already been configured.'
| @property
def configured(self):
| return (self._wrapped is not empty)
|
'Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).'
| def __init__(self, default_settings):
| self.default_settings = default_settings
|
'Tests that 1 + 1 always equals 2.'
| def test_basic_addition(self):
| self.assertEqual((1 + 1), 2)
|
'The entry method for doctest output checking. Defers to a sequence of
child checkers'
| def check_output(self, want, got, optionflags):
| checks = (self.check_output_default, self.check_output_numeric, self.check_output_xml, self.check_output_json)
for check in checks:
if check(want, got, optionflags):
return True
return False
|
'The default comparator provided by doctest - not perfect, but good for
most purposes'
| def check_output_default(self, want, got, optionflags):
| return doctest.OutputChecker.check_output(self, want, got, optionflags)
|
'Doctest does an exact string comparison of output, which means that
some numerically equivalent values aren\'t equal. This check normalizes
* long integers (22L) so that they equal normal integers. (22)
* Decimals so that they are comparable, regardless of the change
made to __repr__ in Python 2.6.'
| def check_output_numeric(self, want, got, optionflags):
| return doctest.OutputChecker.check_output(self, normalize_decimals(normalize_long_ints(want)), normalize_decimals(normalize_long_ints(got)), optionflags)
|
'Tries to do a \'xml-comparision\' of want and got. Plain string
comparision doesn\'t always work because, for example, attribute
ordering should not be important.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py'
| def check_output_xml(self, want, got, optionsflags):
| _norm_whitespace_re = re.compile('[ \\t\\n][ \\t\\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes if (c.nodeType == Node.TEXT_NODE)])
def children(element):
return [c for c i... |
'Tries to compare want and got as if they were JSON-encoded data'
| def check_output_json(self, want, got, optionsflags):
| (want, got) = self._strip_quotes(want, got)
try:
want_json = simplejson.loads(want)
got_json = simplejson.loads(got)
except Exception:
return False
return (want_json == got_json)
|
'Strip quotes of doctests output values:
>>> o = OutputChecker()
>>> o._strip_quotes("\'foo\'")
"foo"
>>> o._strip_quotes(\'"foo"\')
"foo"
>>> o._strip_quotes("u\'foo\'")
"foo"
>>> o._strip_quotes(\'u"foo"\')
"foo"'
| def _strip_quotes(self, want, got):
| def is_quoted_string(s):
s = s.strip()
return ((len(s) >= 2) and (s[0] == s[(-1)]) and (s[0] in ('"', "'")))
def is_quoted_unicode(s):
s = s.strip()
return ((len(s) >= 3) and (s[0] == 'u') and (s[1] == s[(-1)]) and (s[1] in ('"', "'")))
if (is_quoted_string(want) and is_quote... |
'Saves the state of the warnings module'
| def save_warnings_state(self):
| self._warnings_state = get_warnings_state()
|
'Restores the state of the warnings module to the state
saved by save_warnings_state()'
| def restore_warnings_state(self):
| restore_warnings_state(self._warnings_state)
|
'A context manager that temporarily sets a setting and reverts
back to the original value when exiting the context.'
| def settings(self, **kwargs):
| return override_settings(**kwargs)
|
'Asserts that the message in a raised exception matches the passed
value.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.'
| def assertRaisesMessage(self, expected_exception, expected_message, callable_obj=None, *args, **kwargs):
| return self.assertRaisesRegexp(expected_exception, re.escape(expected_message), callable_obj, *args, **kwargs)
|
'Asserts that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiat... | def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u''):
| if (field_args is None):
field_args = []
if (field_kwargs is None):
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
for (input, output) in valid.items():
self.assertEqual(required.cl... |
'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 = ('%s != %s' % (safe_repr(dom1, True), safe_repr(dom2, True))... |
'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 = ('%s == %s' % (safe_repr(dom1, True), safe_repr(dom2, True))... |
'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._fixture_setup()
self._urlconf_setup()
mail.outbox = []
|
'Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren\'t required to
include a call to super().setUp().'
| def __call__(self, result=None):
| testMethod = getattr(self, self._testMethodName)
skipped = (getattr(self.__class__, '__unittest_skip__', False) or getattr(testMethod, '__unittest_skip__', False))
if (not skipped):
self.client = self.client_class()
try:
self._pre_setup()
except (KeyboardInterrupt, System... |
'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=''):
| if msg_prefix:
msg_prefix += ': '
if hasattr(response, 'redirect_chain'):
self.assertTrue((len(response.redirect_chain) > 0), (msg_prefix + ("Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code))))
... |
'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='', html=False):
| if (hasattr(response, 'render') and callable(response.render) and (not response.is_rendered)):
response.render()
if msg_prefix:
msg_prefix += ': '
self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve content: Response code was %d (expe... |
'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='', html=False):
| if (hasattr(response, 'render') and callable(response.render) and (not response.is_rendered)):
response.render()
if msg_prefix:
msg_prefix += ': '
self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve content: Response code was %d (expe... |
'Asserts that a form used to render the response has a specific field
error.'
| def assertFormError(self, response, form, field, errors, msg_prefix=''):
| if msg_prefix:
msg_prefix += ': '
contexts = to_list(response.context)
if (not contexts):
self.fail((msg_prefix + 'Response did not use any contexts to render the response'))
errors = to_list(errors)
found_form = False
for (i, context) in enumerate(c... |
'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=''):
| 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 += ': '
if ((not hasattr(response, 'templates')) or ((response is None) and template_name)):
if response:
... |
'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=''):
| 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 += ': '
if ((not hasattr(response, 'templates')) or ((response is None) and template_name)):
if response:
... |
'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('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)
... |
'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):
... |
'The base environment for a request.'
| def _base_environ(self, **request):
| environ = {'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': FakePaylo... |
'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 = {'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': '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 = {'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data)}
r.update(extra)
return self.r... |
'Construct a HEAD request.'
| def head(self, path, data={}, **extra):
| parsed = urlparse(path)
r = {'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'HEAD'}
r.update(extra)
return self.request(**r)
|
'Constrict an OPTIONS request'
| def options(self, path, data={}, **extra):
| parsed = urlparse(path)
r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'OPTIONS'}
r.update(extra)
return self.request(**r)
|
'Construct a PUT request.'
| def put(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
| put_data = self._encode_data(data, content_type)
parsed = urlparse(path)
r = {'CONTENT_LENGTH': len(put_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'PUT', 'wsgi.input': FakePayload(put_data)}
r.update(extra)
return self.reque... |
'Construct a DELETE request.'
| def delete(self, path, data={}, **extra):
| parsed = urlparse(path)
r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'DELETE'}
r.update(extra)
return self.request(**r)
|
'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 ('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='template-render')
got_request_exception.connect(self.store_exc_info, dispatch_uid='request-exception')
try:
try... |
'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={}, follow=False, **extra):
| response = super(Client, self).options(path, data=data, **extra)
if follow:
response = self._handle_redirects(response, **extra)
return response
|
'Send a resource to the server using PUT.'
| def put(self, path, data={}, content_type=MULTIPART_CONTENT, 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={}, follow=False, **extra):
| response = super(Client, self).delete(path, data=data, **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 ('django.contrib.sessions' in settings.INSTALLED_APPS)):
engine = import_module(settings.SESSION_ENGINE)
request = HttpRequest()
if self.session:
request.session = self.session
else:
reques... |
'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['Location']
redirect_chain = response.redirect_chain
redirect_chain.append((url, response.status_code))
url = urlsplit(url)
if url.scheme:
extra['wsgi.url_scheme'... |
'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, basestring)), '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()])
... |
'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 argumen... | 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 numbe... | 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('w... |
'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... |
'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... | 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
co... | 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)... |
'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.func_globals)
elif inspect.isclass(object):
return (module.__name__ == object.__module__)
elif (inspect.getmodule(object) is not None):
return (module is inspect.getmodule(... |
'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... |
'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, basestring):
docstring = obj
else:
try:
if (obj.__doc__ is None):
docstring = ''
else:
docstring = obj.__doc__
if (not isinstance(docstring, basestring)):
docstring = str(docstring)
... |
'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):
... |
'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 a... | 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 num... | 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 = or... |
'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
t... | 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)
sel... |
'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 th... | 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)
... |
'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 ... | 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)^%... |
'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):... |
'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.
T... | 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 ... | 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()
result = self.run_suite(suite)
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:
if token_string.startswith(VARIABLE_TAG_START):
token = Token(TOKEN_VAR, token_string[2:(-2)].strip())
elif token_string.startswith(BLOCK_TAG_START):
token = Token(TOKEN_BLOCK, token_string[2:(-2)].strip())
elif token_string.startswith(COMMENT_TAG_START):
... |
'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('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(('expected another tag, found end of string: %s' % subject))
p = i
while ((i < len(subject)) and (subject[i] not in (' ', ' DCTB '))):
i += 1
s = subject[p:i]
whi... |
'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):
'\n Increment pointer until a real space (i.e. a space not within\n quotes) is encountered\n ... |
'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):
try:
current = getattr(current, bit)
except (TypeError, AttributeError):
... |
'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 = self.__dict__.copy()
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_di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.