desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Media for a multiwidget is the combination of all media of the subwidgets'
def _get_media(self):
media = Media() for w in self.widgets: media = (media + w.media) return media
'Returns a BoundField with the given name.'
def __getitem__(self, name):
try: field = self.fields[name] except KeyError: raise KeyError(('Key %r not found in Form' % name)) return BoundField(self, field, name)
'Returns an ErrorDict for the data provided for the form'
def _get_errors(self):
if (self._errors is None): self.full_clean() return self._errors
'Returns True if the form has no errors. Otherwise, False. If errors are being ignored, returns False.'
def is_valid(self):
return (self.is_bound and (not bool(self.errors)))
'Returns the field name with a prefix appended, if this Form has a prefix set. Subclasses may wish to override.'
def add_prefix(self, field_name):
return ((self.prefix and ('%s-%s' % (self.prefix, field_name))) or field_name)
'Add a \'initial\' prefix for checking dynamic initial values'
def add_initial_prefix(self, field_name):
return (u'initial-%s' % self.add_prefix(field_name))
'Helper function for outputting HTML. Used by as_table(), as_ul(), as_p().'
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
top_errors = self.non_field_errors() (output, hidden_fields) = ([], []) for (name, field) in self.fields.items(): html_class_attr = '' bf = BoundField(self, field, name) bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) if bf.is_hidden: ...
'Returns this form rendered as HTML <tr>s -- excluding the <table></table>.'
def as_table(self):
return self._html_output(normal_row=u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row=u'<tr><td colspan="2">%s</td></tr>', row_ender=u'</td></tr>', help_text_html=u'<br />%s', errors_on_separate_row=False)
'Returns this form rendered as HTML <li>s -- excluding the <ul></ul>.'
def as_ul(self):
return self._html_output(normal_row=u'<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>', error_row=u'<li>%s</li>', row_ender='</li>', help_text_html=u' %s', errors_on_separate_row=False)
'Returns this form rendered as HTML <p>s.'
def as_p(self):
return self._html_output(normal_row=u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>', error_row=u'%s', row_ender='</p>', help_text_html=u' %s', errors_on_separate_row=True)
'Returns an ErrorList of errors that aren\'t associated with a particular field -- i.e., from Form.clean(). Returns an empty ErrorList if there are none.'
def non_field_errors(self):
return self.errors.get(NON_FIELD_ERRORS, self.error_class())
'Returns the raw_value for a particular field name. This is just a convenient wrapper around widget.value_from_datadict.'
def _raw_value(self, fieldname):
field = self.fields[fieldname] prefix = self.add_prefix(fieldname) return field.widget.value_from_datadict(self.data, self.files, prefix)
'Cleans all of self.data and populates self._errors and self.cleaned_data.'
def full_clean(self):
self._errors = ErrorDict() if (not self.is_bound): return self.cleaned_data = {} if (self.empty_permitted and (not self.has_changed())): return self._clean_fields() self._clean_form() self._post_clean() if self._errors: delattr(self, 'cleaned_data')
'An internal hook for performing additional cleaning after form cleaning is complete. Used for model validation in model forms.'
def _post_clean(self):
pass
'Hook for doing any extra form-wide cleaning after Field.clean() been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named \'__all__\'.'
def clean(self):
return self.cleaned_data
'Returns True if data differs from initial.'
def has_changed(self):
return bool(self.changed_data)
'Provide a description of all media required to render the widgets on this form'
def _get_media(self):
media = Media() for field in self.fields.values(): media = (media + field.widget.media) return media
'Returns True if the form needs to be multipart-encrypted, i.e. it has FileInput. Otherwise, False.'
def is_multipart(self):
for field in self.fields.values(): if field.widget.needs_multipart_form: return True return False
'Returns a list of all the BoundField objects that are hidden fields. Useful for manual form layout in templates.'
def hidden_fields(self):
return [field for field in self if field.is_hidden]
'Returns a list of BoundField objects that aren\'t hidden fields. The opposite of the hidden_fields() method.'
def visible_fields(self):
return [field for field in self if (not field.is_hidden)]
'Renders this field as an HTML widget.'
def __unicode__(self):
if self.field.show_hidden_initial: return (self.as_widget() + self.as_hidden(only_initial=True)) return self.as_widget()
'Returns an ErrorList for this field. Returns an empty ErrorList if there are none.'
def _errors(self):
return self.form.errors.get(self.name, self.form.error_class())
'Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field\'s default widget will be used.'
def as_widget(self, widget=None, attrs=None, only_initial=False):
if (not widget): widget = self.field.widget attrs = (attrs or {}) auto_id = self.auto_id if (auto_id and ('id' not in attrs) and ('id' not in widget.attrs)): if (not only_initial): attrs['id'] = auto_id else: attrs['id'] = self.html_initial_id if (not ...
'Returns a string of HTML for representing this as an <input type="text">.'
def as_text(self, attrs=None, **kwargs):
return self.as_widget(TextInput(), attrs, **kwargs)
'Returns a string of HTML for representing this as a <textarea>.'
def as_textarea(self, attrs=None, **kwargs):
return self.as_widget(Textarea(), attrs, **kwargs)
'Returns a string of HTML for representing this as an <input type="hidden">.'
def as_hidden(self, attrs=None, **kwargs):
return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
'Returns the data for this BoundField, or None if it wasn\'t given.'
def _data(self):
return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
'Wraps the given contents in a <label>, if the field has an ID attribute. Does not HTML-escape the contents. If contents aren\'t given, uses the field\'s HTML-escaped label. If attrs are given, they\'re used as HTML attributes on the <label> tag.'
def label_tag(self, contents=None, attrs=None):
contents = (contents or conditional_escape(self.label)) widget = self.field.widget id_ = (widget.attrs.get('id') or self.auto_id) if id_: attrs = ((attrs and flatatt(attrs)) or '') contents = (u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))) ...
'Returns a string of space-separated CSS classes for this field.'
def css_classes(self, extra_classes=None):
if hasattr(extra_classes, 'split'): extra_classes = extra_classes.split() extra_classes = set((extra_classes or [])) if (self.errors and hasattr(self.form, 'error_css_class')): extra_classes.add(self.form.error_css_class) if (self.field.required and hasattr(self.form, 'required_css_class...
'Returns True if this BoundField\'s widget is hidden.'
def _is_hidden(self):
return self.field.widget.is_hidden
'Calculates and returns the ID attribute for this BoundField, if the associated Form has specified auto_id. Returns an empty string otherwise.'
def _auto_id(self):
auto_id = self.form.auto_id if (auto_id and ('%s' in smart_unicode(auto_id))): return (smart_unicode(auto_id) % self.html_name) elif auto_id: return self.html_name return ''
'Wrapper around the field widget\'s `id_for_label` class method. Useful, for example, for focusing on this field regardless of whether it has a single widget or a MutiWidget.'
def _id_for_label(self):
widget = self.field.widget id_ = (widget.attrs.get('id') or self.auto_id) return widget.id_for_label(id_)
'Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handler: An UploadHandler instance that performs operations on the uploaded data. :encoding: The encoding with which to treat the incoming data.'
def __init__(self, META, input_data, upload_handlers, encoding=None):
content_type = META.get('HTTP_CONTENT_TYPE', META.get('CONTENT_TYPE', '')) if (not content_type.startswith('multipart/')): raise MultiPartParserError(('Invalid Content-Type: %s' % content_type)) (ctypes, opts) = parse_header(content_type) boundary = opts.get('boundary') if ((not bounda...
'Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Returns a tuple containing the POST and FILES dictionary, respectively.'
def parse(self):
from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers limited_input_data = LimitBytes(self._input_data, self._content_length) for handler in handlers: result = handler.handle_raw_input(limited_input_data, self._meta, self._content_length, self._boundary...
'Handle all the signalling that takes place when a file is complete.'
def handle_file_complete(self, old_field_name, counters):
for (i, handler) in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: self._files.appendlist(force_unicode(old_field_name, self._encoding, errors='replace'), file_obj) break
'Cleanup filename from Internet Explorer full paths.'
def IE_sanitize(self, filename):
return (filename and filename[(filename.rfind('\\') + 1):].strip())
'Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called.'
def __init__(self, producer, length=None):
self._producer = producer self._empty = False self._leftover = '' self.length = length self.position = 0 self._remaining = length self._unget_history = []
'Used when the exact number of bytes to read is unimportant. This procedure just returns whatever is chunk is conveniently returned from the iterator instead. Useful to avoid unnecessary bookkeeping if performance is an issue.'
def next(self):
if self._leftover: output = self._leftover self._leftover = '' else: output = self._producer.next() self._unget_history = [] self.position += len(output) return output
'Used to invalidate/disable this lazy stream. Replaces the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next().'
def close(self):
self._producer = []
'Places bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound.'
def unget(self, bytes):
if (not bytes): return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = ''.join([bytes, self._leftover])
'Updates the unget history as a sanity check to see if we\'ve pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we\'re mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request.'
def _update_unget_history(self, num_bytes):
self._unget_history = ([num_bytes] + self._unget_history[:49]) number_equal = len([current_number for current_number in self._unget_history if (current_number == num_bytes)]) if (number_equal > 40): raise SuspiciousOperation("The multipart parser got stuck, which shouldn't happe...
'Read data from the underlying file. If you ask for too much or there isn\'t anything left, this will raise an InputStreamExhausted error.'
def read(self, num_bytes=None):
if (self.remaining <= 0): raise InputStreamExhausted() if (num_bytes is None): num_bytes = self.remaining else: num_bytes = min(num_bytes, self.remaining) self.remaining -= num_bytes return self._file.read(num_bytes)
'Finds a multipart boundary in data. Should no boundry exist in the data None is returned instead. Otherwise a tuple containing the indices of the following are returned: * the end of current encapsulation * the start of the next encapsulation'
def _find_boundary(self, data, eof=False):
index = self._fs(data) if (index < 0): return None else: end = index next = (index + len(self._boundary)) if (data[max(0, (end - 1))] == '\n'): end -= 1 if (data[max(0, (end - 1))] == '\r'): end -= 1 return (end, next)
'Returns the HTTP host using the environment or request headers.'
def get_host(self):
if ('HTTP_X_FORWARDED_HOST' in self.META): host = self.META['HTTP_X_FORWARDED_HOST'] elif ('HTTP_HOST' in self.META): host = self.META['HTTP_HOST'] else: host = self.META['SERVER_NAME'] server_port = str(self.META['SERVER_PORT']) if (server_port != ((self.is_secure() ...
'Builds an absolute URI from the location and the variables available in this request. If no location is specified, the absolute URI is built on ``request.get_full_path()``.'
def build_absolute_uri(self, location=None):
if (not location): location = self.get_full_path() if (not absolute_http_url_re.match(location)): current_uri = ('%s://%s%s' % (((self.is_secure() and 'https') or 'http'), self.get_host(), self.path)) location = urljoin(current_uri, location) return iri_to_uri(location)
'Sets the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, it is removed and recreated on the next access (so that it is decoded correctly).'
def _set_encoding(self, val):
self._encoding = val if hasattr(self, '_get'): del self._get if hasattr(self, '_post'): del self._post
'Returns a tuple of (POST QueryDict, FILES MultiValueDict).'
def parse_file_upload(self, META, post_data):
self.upload_handlers = ImmutableList(self.upload_handlers, warning='You cannot alter upload handlers after the upload has been processed.') parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding) return parser.parse()
'Returns a mutable copy of this object.'
def copy(self):
return self.__deepcopy__({})
'Full HTTP message, including headers.'
def __str__(self):
return (('\n'.join([('%s: %s' % (key, value)) for (key, value) in self._headers.values()]) + '\n\n') + self.content)
'Converts all values to ascii strings.'
def _convert_to_ascii(self, *values):
for value in values: if isinstance(value, unicode): try: value = value.encode('us-ascii') except UnicodeError as e: e.reason += ', HTTP response headers must be in US-ASCII format' raise else: ...
'Case-insensitive check for a header.'
def has_header(self, header):
return self._headers.has_key(header.lower())
'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 != None): 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.'
def configured(self):
return bool(self._wrapped)
'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.failUnlessEqual((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: 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...
'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):
self.client = Client() try: self._pre_setup() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return super(TransactionTestCase, self).__call__(result) try: self._post_teardown() e...
'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 connection in connections.all(): connection.close()
'Saves the state of the warnings module'
def save_warnings_state(self):
self._warnings_state = get_warnings_state()
'Restores the sate of the warnings module to the state saved by save_warnings_state()'
def restore_warnings_state(self):
restore_warnings_state(self._warnings_state)
'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 a page 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=''):
if msg_prefix: msg_prefix += ': ' self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve page: Response code was %d (expected %d)" % (response.status_code, status_code)))) text = smart_str(text, response._charset) real_count = response.co...
'Asserts that a response indicates that a page 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=''):
if msg_prefix: msg_prefix += ': ' self.assertEqual(response.status_code, status_code, (msg_prefix + ("Couldn't retrieve page: Response code was %d (expected %d)" % (response.status_code, status_code)))) text = smart_str(text, response._charset) self.assertEqual(respons...
'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.'
def assertTemplateUsed(self, response, template_name, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' template_names = [t.name for t in to_list(response.template)] if (not template_names): self.fail((msg_prefix + 'No templates used to render the response')) self.assertTrue((template_name in template_names), (msg_prefix + ("Template ...
'Asserts that the template with the provided name was NOT used in rendering the response.'
def assertTemplateNotUsed(self, response, template_name, msg_prefix=''):
if msg_prefix: msg_prefix += ': ' template_names = [t.name for t in to_list(response.template)] self.assertFalse((template_name in template_names), (msg_prefix + ("Template '%s' was used unexpectedly in rendering the response" % template_name)))
'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 = {'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'QUERY_STRING': '', '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', 'ws...
'Requests a response from the server using GET.'
def get(self, path, data={}, follow=False, **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', 'wsgi.input': FakePayload('')} r.update(extra) response = self.request(**r) if follow: respons...
'Requests a response from the server using POST.'
def post(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra):
if (content_type is MULTIPART_CONTENT): post_data = encode_multipart(BOUNDARY, data) else: match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET post_data = smart_str(data, encoding=...
'Request a response from the server using HEAD.'
def head(self, path, data={}, follow=False, **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', 'wsgi.input': FakePayload('')} r.update(extra) response = self.request(**r) if follow: respon...
'Request a response from the server using OPTIONS.'
def options(self, path, data={}, follow=False, **extra):
parsed = urlparse(path) r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'OPTIONS', 'wsgi.input': FakePayload('')} r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extr...
'Send a resource to the server using PUT.'
def put(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra):
if (content_type is MULTIPART_CONTENT): post_data = encode_multipart(BOUNDARY, data) else: post_data = data query_string = None if (not isinstance(data, basestring)): query_string = urlencode(data, doseq=True) parsed = urlparse(path) r = {'CONTENT_LENGTH': len(post_data),...
'Send a DELETE request to the server.'
def delete(self, path, data={}, follow=False, **extra):
parsed = urlparse(path) r = {'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': (urlencode(data, doseq=True) or parsed[4]), 'REQUEST_METHOD': 'DELETE', 'wsgi.input': FakePayload('')} r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra...
'Sets the Client 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'] (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) ...