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)...
'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)...
'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_...
'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(x...
'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)))) ...
'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 (e...
'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 (e...
'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...
'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: ...
'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: ...
'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) ...
'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 = {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...
'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(e...
'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: t...
'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: reque...
'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_schem...
'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()]) ...
'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.__globals__) elif inspect.isclass(object): return (module.__name__ == object.__module__) elif (inspect.getmodule(object) is not None): return (module is inspect.getmodule(o...
'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, 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(do...
'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() if (self.verbosity > 0): logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) result = self.run_suite(suite) ...
'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): ...
'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] ...
'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 ...
'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): ...
'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 ob...
'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 = ...
'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)