desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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']
(scheme, netloc, path, query, fragment) = urlsplit(url)
redirect_chain = response.redirect_chain
redirect_chain.append((url, response.status_code))
if 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, _namefilter=None, exclude_empty=True):
| self._parser = parser
self._verbose = verbose
self._recurse = recurse
self._exclude_empty = exclude_empty
self._namefilter = _namefilter
|
'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 should not be examined.'
| def _filter(self, obj, prefix, base):
| return ((self._namefilter is not None) and self._namefilter(prefix, base))
|
'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
|
'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[len(VARIABLE_TAG_START):(- len(VARIABLE_TAG_END))].strip())
elif token_string.startswith(BLOCK_TAG_START):
token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):(- len(BLOC... |
'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):
'Increment pointer until a real space (i.e. a space not within quotes) is encountered'
while ((i < len(subject)) and (subject[i] not in (' ', ' DCTB '))):
if (subje... |
'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:
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.')
del obj_dict['template_name']
del obj_dict['context_data']
del obj_dict['_post_render_callbacks']
ret... |
'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, basestring):
return loader.get_template(template)
else:
return template
|
'Convert 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
|
'Add 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)
|
'Render (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._set_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'
| def _set_content(self, value):
| super(SimpleTemplateResponse, self)._set_content(value)
self._is_rendered = True
|
'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(TemplateResponse, self).__getstate__()
del obj_dict['_request']
del obj_dict['_current_app']
return obj_dict
|
'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
else:
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 = ('templates/' + template_name)
for app in settings.INSTALLED_APPS:
try:
return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), ('egg:%s:%s' % (app, pkg_name)))
except:
pass
raise T... |
'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)
|
'Delete a variable from the current context'
| def __delitem__(self, key):
| del self.dicts[(-1)][key]
|
'Returns a new context with the same properties, but with only the
values given in \'values\' stored.'
| def new(self, values=None):
| new_context = copy(self)
new_context._reset_dicts(values)
return new_context
|
'Pushes other_dict to the stack of dictionaries in the Context'
| def update(self, other_dict):
| if (not hasattr(other_dict, '__getitem__')):
raise TypeError('other_dict must be a mapping (dictionary-like) object.')
self.dicts.append(other_dict)
return other_dict
|
'Return a list of tokens from a given template_string'
| def tokenize(self):
| (result, upto) = ([], 0)
for match in tag_re.finditer(self.template_string):
(start, end) = match.span()
if (start > upto):
result.append(self.create_token(self.template_string[upto:start], (upto, start), False))
upto = start
result.append(self.create_token(self.t... |
'The flatpage admin form validates correctly validates urls'
| def test_flatpage_admin_form_url_validation(self):
| self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid())
self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid())
self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid())
self.a... |
'A flatpage can be served through a view, even when the middleware is in use'
| def test_view_flatpage(self):
| response = self.client.get('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
|
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
| def test_view_non_existent_flatpage(self):
| response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'A flatpage served through a view can require authentication'
| def test_view_authenticated_flatpage(self):
| response = self.client.get('/flatpage_root/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser', password='s3krit')
response = self.client.get('/flatpage_root/... |
'A flatpage can be served by the fallback middlware'
| def test_fallback_flatpage(self):
| response = self.client.get('/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
|
'A non-existent flatpage raises a 404 when served by the fallback middlware'
| def test_fallback_non_existent_flatpage(self):
| response = self.client.get('/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)'
| def test_post_view_flatpage(self):
| response = self.client.post('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 403)
|
'POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)'
| def test_post_fallback_flatpage(self):
| response = self.client.post('/flatpage/')
self.assertEqual(response.status_code, 403)
|
'POSTing to an unknown page isn\'t caught as a 403 CSRF error'
| def test_post_unknown_page(self):
| response = self.client.post('/no_such_page/')
self.assertEqual(response.status_code, 404)
|
'The flatpage template tag retrives unregistered prefixed flatpages by default'
| def test_get_flatpages_tag(self):
| out = Template('{% load flatpages %}{% get_flatpages as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context())
self.assertEqual(out, 'A Flatpage,A Nested Flatpage,')
|
'The flatpage template tag retrives unregistered flatpages for an anonymous user'
| def test_get_flatpages_tag_for_anon_user(self):
| out = Template('{% load flatpages %}{% get_flatpages for anonuser as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context({'anonuser': AnonymousUser()}))
self.assertEqual(out, 'A Flatpage,A Nested Flatpage,')
|
'The flatpage template tag retrives all flatpages for an authenticated user'
| def test_get_flatpages_tag_for_user(self):
| out = Template('{% load flatpages %}{% get_flatpages for me as flatpages %}{% for page in flatpages %}{{ page.title }},{% endfor %}').render(Context({'me': self.me}))
self.assertEqual(out, 'A Flatpage,A Nested Flatpage,Sekrit Nested Flatpage,S... |
'The flatpage template tag retrives unregistered prefixed flatpages by default'
| def test_get_flatpages_with_prefix(self):
| out = Template("{% load flatpages %}{% get_flatpages '/location/' as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context())
self.assertEqual(out, 'A Nested Flatpage,')
|
'The flatpage template tag retrives unregistered prefixed flatpages for an anonymous user'
| def test_get_flatpages_with_prefix_for_anon_user(self):
| out = Template("{% load flatpages %}{% get_flatpages '/location/' for anonuser as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context({'anonuser': AnonymousUser()}))
self.assertEqual(out, 'A Nested ... |
'The flatpage template tag retrive prefixed flatpages for an authenticated user'
| def test_get_flatpages_with_prefix_for_user(self):
| out = Template("{% load flatpages %}{% get_flatpages '/location/' for me as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}").render(Context({'me': self.me}))
self.assertEqual(out, 'A Nested Flatpage,Sekrit ... |
'The prefix for the flatpage template tag can be a template variable'
| def test_get_flatpages_with_variable_prefix(self):
| out = Template('{% load flatpages %}{% get_flatpages location_prefix as location_flatpages %}{% for page in location_flatpages %}{{ page.title }},{% endfor %}').render(Context({'location_prefix': '/location/'}))
self.assertEqual(out, 'A Nested Flatpage,')... |
'There are various ways that the flatpages template tag won\'t parse'
| def test_parsing_errors(self):
| render = (lambda t: Template(t).render(Context()))
self.assertRaises(TemplateSyntaxError, render, '{% load flatpages %}{% get_flatpages %}')
self.assertRaises(TemplateSyntaxError, render, '{% load flatpages %}{% get_flatpages as %}')
self.assertRaises(TemplateSyntaxError... |
'A flatpage can be served through a view'
| def test_view_flatpage(self):
| response = self.client.get('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
|
'A non-existent flatpage raises 404 when served through a view'
| def test_view_non_existent_flatpage(self):
| response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'A flatpage served through a view can require authentication'
| def test_view_authenticated_flatpage(self):
| response = self.client.get('/flatpage_root/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser', password='s3krit')
response = self.client.get('/flatpage_root/... |
'A fallback flatpage won\'t be served if the middleware is disabled'
| def test_fallback_flatpage(self):
| response = self.client.get('/flatpage/')
self.assertEqual(response.status_code, 404)
|
'A non-existent flatpage won\'t be served if the fallback middlware is disabled'
| def test_fallback_non_existent_flatpage(self):
| response = self.client.get('/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'A flatpage with special chars in the URL can be served through a view'
| def test_view_flatpage_special_chars(self):
| fp = FlatPage.objects.create(url='/some.very_special~chars-here/', title='A very special page', content="Isn't it special!", enable_comments=False, registration_required=False)
fp.sites.add(settings.SITE_ID)
response = self.client.get('/flatpage_root/some.very_special~chars-here/')
self.a... |
'A flatpage can be served through a view, even when the middleware is in use'
| def test_view_flatpage(self):
| response = self.client.get('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
|
'A non-existent flatpage raises 404 when served through a view, even when the middleware is in use'
| def test_view_non_existent_flatpage(self):
| response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'A flatpage served through a view can require authentication'
| def test_view_authenticated_flatpage(self):
| response = self.client.get('/flatpage_root/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser', password='s3krit')
response = self.client.get('/flatpage_root/... |
'A flatpage can be served by the fallback middlware'
| def test_fallback_flatpage(self):
| response = self.client.get('/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
|
'A non-existent flatpage raises a 404 when served by the fallback middlware'
| def test_fallback_non_existent_flatpage(self):
| response = self.client.get('/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
|
'A flatpage served by the middleware can require authentication'
| def test_fallback_authenticated_flatpage(self):
| response = self.client.get('/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser', password='s3krit')
response = self.client.get('/sekrit/')
self.assertEqual(response.st... |
'Returns the static files serving handler.'
| def get_handler(self, *args, **options):
| handler = super(Command, self).get_handler(*args, **options)
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if ((settings.DEBUG and use_static_handler) or (use_static_handler and insecure_serving)):
handler = StaticFilesHand... |
'Small log helper'
| def log(self, msg, level=2):
| msg = smart_str(msg)
if (not msg.endswith('\n')):
msg += '\n'
if (self.verbosity >= level):
self.stdout.write(msg)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.