desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Has this host been excluded from the proxy config'
| def bypass_host(self, hostname):
| if (self.bypass_hosts is AllHosts):
return True
bypass = False
for domain in self.bypass_hosts:
if hostname.endswith(domain):
bypass = True
return bypass
|
'Connect to the host and port specified in __init__.'
| def connect(self):
| if (self.proxy_info and (socks is None)):
raise ProxiesUnavailableError('Proxy support missing but proxy use was requested!')
msg = 'getaddrinfo returns an empty list'
if (self.proxy_info and self.proxy_info.isgood()):
use_proxy = True
(proxy_type, pr... |
'Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.'
| def _GetValidHostsForCert(self, cert):
| if ('subjectAltName' in cert):
return [x[1] for x in cert['subjectAltName'] if (x[0].lower() == 'dns')]
else:
return [x[0][1] for x in cert['subject'] if (x[0][0].lower() == 'commonname')]
|
'Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.'
| def _ValidateCertificateHostname(self, cert, hostname):
| hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\\.').replace('*', '[^.]*')
if re.search(('^%s$' % (host_re,)), hostname, re.I):
return True
return False
|
'Connect to a host on a given (SSL) port.'
| def connect(self):
| msg = 'getaddrinfo returns an empty list'
if (self.proxy_info and self.proxy_info.isgood()):
use_proxy = True
(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass) = self.proxy_info.astuple()
else:
use_proxy = False
if (use_proxy and proxy_rdns):
... |
'If \'cache\' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python\'s default timeout for sockets will be used. See
for example the docs of socket.setdefaultt... | def __init__(self, cache=None, timeout=None, proxy_info=ProxyInfo.from_environment, ca_certs=None, disable_ssl_certificate_validation=False):
| self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.connections = {}
if (cache and isinstance(cache, basestring)):
self.cache = FileCache(cache)
else:
self.cache = cache
self.credentials = Cre... |
'A generator that creates Authorization objects
that can be applied to requests.'
| def _auth_from_challenge(self, host, request_uri, headers, response, content):
| challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
(yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self))
|
'Add a name and password that will be used
any time a request requires authentication.'
| def add_credentials(self, name, password, domain=''):
| self.credentials.add(name, password, domain)
|
'Add a key and cert that will be used
any time a request requires authentication.'
| def add_certificate(self, key, cert, domain):
| self.certificates.add(key, cert, domain)
|
'Remove all the names and passwords
that are used for authentication'
| def clear_credentials(self):
| self.credentials.clear()
self.authorizations = []
|
'Do the actual request using the connection object
and also follow one level of redirects if necessary'
| def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
| auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = ((auths and sorted(auths)[0][1]) or None)
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, header... |
'Performs a single HTTP request.
The \'uri\' is the URI of the HTTP resource and can begin
with either \'http\' or \'https\'. The value of \'uri\' must be an absolute URI.
The \'method\' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The \'body\' is the en... | def request(self, uri, method='GET', body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
| try:
if (headers is None):
headers = {}
else:
headers = self._normalize_headers(headers)
if (not headers.has_key('user-agent')):
headers['user-agent'] = ('Python-httplib2/%s (gzip)' % __version__)
uri = iri2uri(uri)
(scheme, authority, r... |
'Return a ProxyInfo instance (or None) based on the scheme
and authority.'
| def _get_proxy_info(self, scheme, authority):
| (hostname, port) = urllib.splitport(authority)
proxy_info = self.proxy_info
if callable(proxy_info):
proxy_info = proxy_info(scheme)
if (hasattr(proxy_info, 'applies_to') and (not proxy_info.applies_to(hostname))):
proxy_info = None
return proxy_info
|
'__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.'
| def __recvall(self, count):
| data = self.recv(count)
while (len(data) < count):
d = self.recv((count - len(data)))
if (not d):
raise GeneralProxyError((0, 'connection closed unexpectedly'))
data = (data + d)
return data
|
'override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed'
| def sendall(self, content, *args):
| if (not self.__httptunnel):
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args)
|
'rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.'
| def __rewriteproxy(self, header):
| (host, endpt) = (None, None)
hdrs = header.split('\r\n')
for hdr in hdrs:
if hdr.lower().startswith('host:'):
host = hdr
elif (hdr.lower().startswith('get') or hdr.lower().startswith('post')):
endpt = hdr
if (host and endpt):
hdrs.remove(host)
hdrs... |
'setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The po... | def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
| self.__proxy = (proxytype, addr, port, rdns, username, password)
|
'__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.'
| def __negotiatesocks5(self, destaddr, destport):
| if ((self.__proxy[4] != None) and (self.__proxy[5] != None)):
self.sendall(struct.pack('BBBB', 5, 2, 0, 2))
else:
self.sendall(struct.pack('BBB', 5, 1, 0))
chosenauth = self.__recvall(2)
if (chosenauth[0:1] != chr(5).encode()):
self.close()
raise GeneralProxyError((1, _ge... |
'getsockname() -> address info
Returns the bound IP address and port number at the proxy.'
| def getproxysockname(self):
| return self.__proxysockname
|
'getproxypeername() -> address info
Returns the IP and port number of the proxy.'
| def getproxypeername(self):
| return _orgsocket.getpeername(self)
|
'getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)'
| def getpeername(self):
| return self.__proxypeername
|
'__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.'
| def __negotiatesocks4(self, destaddr, destport):
| rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
if self.__proxy[3]:
ipaddr = struct.pack('BBBB', 0, 0, 0, 1)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = (struct.pack('>BBH',... |
'__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.'
| def __negotiatehttp(self, destaddr, destport):
| if (not self.__proxy[3]):
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ['CONNECT ', addr, ':', str(destport), ' HTTP/1.1\r\n']
headers += ['Host: ', destaddr, '\r\n']
if ((self.__proxy[4] != None) and (self.__proxy[5] != None)):
headers += [s... |
'connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket\'s connect).
To select the proxy server use setproxy().'
| def connect(self, destpair):
| if ((not (type(destpair) in (list, tuple))) or (len(destpair) < 2) or (not isinstance(destpair[0], basestring)) or (type(destpair[1]) != int)):
raise GeneralProxyError((5, _generalerrors[5]))
if (self.__proxy[0] == PROXY_TYPE_SOCKS5):
if (self.__proxy[2] != None):
portnum = self.__pr... |
'Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.'
| def serve_forever(self, poll_interval=0.1):
| self.__serving = True
self.__is_shut_down.clear()
while self.__serving:
(r, w, e) = select.select([self.socket], [], [], 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
self.__is_shut_down.wait()
|
'Handle one request, possibly blocking.
Respects self.timeout.'
| def handle_request(self):
| timeout = self.socket.gettimeout()
if (timeout is None):
timeout = self.timeout
elif (self.timeout is not None):
timeout = min(timeout, self.timeout)
fd_sets = select.select([self], [], [], timeout)
if (not fd_sets[0]):
self.handle_timeout()
return
self._handle_re... |
'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:
self.handle_error(request, client_address)
self.clos... |
'If blank, no PendingDeprecationWarning error will be raised, even though it
doesn\'t end in a slash.'
| def test_blank(self):
| self.settings_module.MEDIA_URL = ''
self.assertEqual('', self.settings_module.MEDIA_URL)
|
'MEDIA_URL works if you end in a slash.'
| def test_end_slash(self):
| self.settings_module.MEDIA_URL = '/foo/'
self.assertEqual('/foo/', self.settings_module.MEDIA_URL)
self.settings_module.MEDIA_URL = 'http://media.foo.com/'
self.assertEqual('http://media.foo.com/', self.settings_module.MEDIA_URL)
|
'MEDIA_URL raises an PendingDeprecationWarning error if it doesn\'t end in a
slash.'
| def test_no_end_slash(self):
| import warnings
warnings.filterwarnings('error', 'If set, MEDIA_URL must end with a slash', PendingDeprecationWarning)
def setattr_settings(settings_module, attr, value):
setattr(settings_module, attr, value)
self.assertRaises(PendingDeprecationWarning, setattr_settings, sel... |
'If a MEDIA_URL ends in more than one slash, presume they know what
they\'re doing.'
| def test_double_slash(self):
| self.settings_module.MEDIA_URL = '/stupid//'
self.assertEqual('/stupid//', self.settings_module.MEDIA_URL)
self.settings_module.MEDIA_URL = 'http://media.foo.com/stupid//'
self.assertEqual('http://media.foo.com/stupid//', self.settings_module.MEDIA_URL)
|
'Cookie will expire when an near expiration time is provided'
| def test_near_expiration(self):
| response = HttpResponse()
expires = (datetime.utcnow() + timedelta(seconds=10))
time.sleep(0.001)
response.set_cookie('datetime', expires=expires)
datetime_cookie = response.cookies['datetime']
self.assertEqual(datetime_cookie['max-age'], 10)
|
'Cookie will expire when an distant expiration time is provided'
| def test_far_expiration(self):
| response = HttpResponse()
response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
datetime_cookie = response.cookies['datetime']
self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')
|
'Cookie will expire if max_age is provided'
| def test_max_age_expiration(self):
| response = HttpResponse()
response.set_cookie('max_age', max_age=10)
max_age_cookie = response.cookies['max_age']
self.assertEqual(max_age_cookie['max-age'], 10)
self.assertEqual(max_age_cookie['expires'], cookie_date((time.time() + 10)))
|
'Reading from request is allowed after accessing request contents as
POST or raw_post_data.'
| def test_read_after_value(self):
| request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')})
self.assertEqual(request.POST, {u'name': [u'value']})
self.assertEqual(request.raw_post_data, 'name=value')
self.assertEqual(request.read(), 'name=value')
|
'Construction of POST or raw_post_data is not allowed after reading
from request.'
| def test_value_after_read(self):
| request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')})
self.assertEqual(request.read(2), 'na')
self.assertRaises(Exception, (lambda : request.raw_post_data))
self.assertEqual(request.POST, {})
|
'Reading raw_post_data after parsing multipart is not allowed'
| def test_raw_post_data_after_POST_multipart(self):
| payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--'])
request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)})
self.assertE... |
'Multipart POST requests with Content-Length >= 0 are valid and need to be handled.'
| def test_POST_multipart_with_content_length_zero(self):
| payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--'])
request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': 0, 'wsgi.input': StringIO(payload)})
self.assertEqual(reques... |
'POST should be populated even if raw_post_data is read first'
| def test_POST_after_raw_post_data_read(self):
| request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')})
raw_data = request.raw_post_data
self.assertEqual(request.POST, {u'name': [u'value']})
|
'POST should be populated even if raw_post_data is read first, and then
the stream is read second.'
| def test_POST_after_raw_post_data_read_and_stream_read(self):
| request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')})
raw_data = request.raw_post_data
self.assertEqual(request.read(1), u'n')
self.assertEqual(request.POST, {u'name': [u'value']})
|
'POST should be populated even if raw_post_data is read first, and then
the stream is read second. Using multipart/form-data instead of urlencoded.'
| def test_POST_after_raw_post_data_read_and_stream_read_multipart(self):
| payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--'])
request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)})
raw_data = r... |
'RegexURLResolver should raise an exception when no urlpatterns exist.'
| def test_no_urls_exception(self):
| resolver = RegexURLResolver('^$', self.urls)
self.assertRaisesErrorWithMessage(ImproperlyConfigured, "The included urlconf regressiontests.urlpatterns_reverse.no_urls doesn't have any patterns in it", getattr, resolver, 'url_patterns')
|
'Verifies that we raise a Resolver404 if what we are resolving doesn\'t
meet the basic requirements of a path to match - i.e., at the very
least, it matches the root pattern \'^/\'. We must never return None
from resolve, or we will get a TypeError further down the line.
Regression for #10834.'
| def test_non_regex(self):
| self.assertRaises(Resolver404, resolve, '')
self.assertRaises(Resolver404, resolve, 'a')
self.assertRaises(Resolver404, resolve, '\\')
self.assertRaises(Resolver404, resolve, '.')
|
'Verifies that the list of URLs that come back from a Resolver404
exception contains a list in the right format for printing out in
the DEBUG 404 page with both the patterns and URL names, if available.'
| def test_404_tried_urls_have_names(self):
| urls = 'regressiontests.urlpatterns_reverse.named_urls'
url_types_names = [[{'type': RegexURLPattern, 'name': 'named-url1'}], [{'type': RegexURLPattern, 'name': 'named-url2'}], [{'type': RegexURLPattern, 'name': None}], [{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': 'named-url3'}], [{'type': Reg... |
'Names deployed via dynamic URL objects that require namespaces can\'t be resolved'
| def test_ambiguous_object(self):
| self.assertRaises(NoReverseMatch, reverse, 'urlobject-view')
self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37, 42])
self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
|
'Names deployed via dynamic URL objects that require namespaces can\'t be resolved'
| def test_ambiguous_urlpattern(self):
| self.assertRaises(NoReverseMatch, reverse, 'inner-nothing')
self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37, 42])
self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1': 42, 'arg2': 37})
|
'Non-existent namespaces raise errors'
| def test_non_existent_namespace(self):
| self.assertRaises(NoReverseMatch, reverse, 'blahblah:urlobject-view')
self.assertRaises(NoReverseMatch, reverse, 'test-ns1:blahblah:urlobject-view')
|
'Normal lookups work as expected'
| def test_normal_name(self):
| self.assertEqual('/normal/', reverse('normal-view'))
self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37, 42]))
self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'Normal lookups work on names included from other patterns'
| def test_simple_included_name(self):
| self.assertEqual('/included/normal/', reverse('inc-normal-view'))
self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37, 42]))
self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'Dynamic URL objects can be found using a namespace'
| def test_namespace_object(self):
| self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view'))
self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37, 42]))
self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'Namespaces can be installed anywhere in the URL pattern tree'
| def test_embedded_namespace_object(self):
| self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view'))
self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'Namespaces can be applied to include()\'d urlpatterns'
| def test_namespace_pattern(self):
| self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view'))
self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37, 42]))
self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'Namespaces can be embedded'
| def test_multiple_namespace_pattern(self):
| self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'... |
'Namespaces can be nested'
| def test_nested_namespace_pattern(self):
| self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/ns... |
'A default application namespace can be used for lookup'
| def test_app_lookup_object(self):
| self.assertEqual('/default/inner/', reverse('testapp:urlobject-view'))
self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42]))
self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
|
'A default application namespace is sensitive to the \'current\' app can be used for lookup'
| def test_app_lookup_object_with_default(self):
| self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3'))
self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42], current_app='test-ns3'))
self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', ... |
'An application namespace without a default is sensitive to the \'current\' app can be used for lookup'
| def test_app_lookup_object_without_default(self):
| self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view'))
self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42]))
self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/other1/in... |
'If the urls.py doesn\'t specify handlers, the defaults are used'
| def test_default_handler(self):
| try:
response = self.client.get('/test/')
self.assertEqual(response.status_code, 404)
except AttributeError:
self.fail("Shouldn't get an AttributeError due to undefined 404 handler")
try:
self.assertRaises(ValueError, self.client.get, '/bad_view/')
... |
'Test that ModelMultipleChoiceField does O(1) queries instead of
O(n) (#10156).'
| def test_model_multiple_choice_number_of_queries(self):
| persons = [Person.objects.create(name=('Person %s' % i)) for i in range(30)]
f = forms.ModelMultipleChoiceField(queryset=Person.objects.all())
self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
|
'Test that ModelMultipleChoiceField run given validators (#14144).'
| def test_model_multiple_choice_run_validators(self):
| for i in range(30):
Person.objects.create(name=('Person %s' % i))
self._validator_run = False
def my_validator(value):
self._validator_run = True
f = forms.ModelMultipleChoiceField(queryset=Person.objects.all(), validators=[my_validator])
f.clean([p.pk for p in Person.objects.all(... |
'When the same field is involved in multiple unique_together
constraints, we need to make sure we don\'t remove the data for it
before doing all the validation checking (not just failing after
the first one).'
| def test_multiple_field_unique_together(self):
| Triple.objects.create(left=1, middle=2, right=3)
form = TripleForm({'left': '1', 'middle': '2', 'right': '3'})
self.assertFalse(form.is_valid())
form = TripleForm({'left': '1', 'middle': '3', 'right': '1'})
self.assertTrue(form.is_valid())
|
'Regression for #12596: Calling super from ModelForm.clean() should be
optional.'
| def test_override_clean(self):
| form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1})
self.assertTrue(form.is_valid())
self.assertEqual(form.instance.left, 1)
|
'Regression test for #8842: FilePathField(blank=True)'
| def test_file_path_field_blank(self):
| form = FPForm()
names = [p[1] for p in form['path'].field.choices]
names.sort()
self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py'])
|
'Regression for #10349: A callable can be provided as the initial value for an m2m field'
| def test_callable(self):
| def formfield_for_dbfield(db_field, **kwargs):
if (db_field.name == 'publications'):
kwargs['initial'] = (lambda : Publication.objects.all().order_by('date_published')[:2])
return db_field.formfield(**kwargs)
book1 = Publication.objects.create(title='First Book', date_published=da... |
'Regression for #11149: save_form_data should be called only once'
| def test_save(self):
| form = CFFForm(data={'f': None})
form.save()
|
'Check basic URL field validation on model forms'
| def test_url_on_modelform(self):
| self.assertFalse(HomepageForm({'url': 'foo'}).is_valid())
self.assertFalse(HomepageForm({'url': 'http://'}).is_valid())
self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid())
self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid())
self.assertFalse(HomepageForm({'url': 'ht... |
'If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)'
| def test_http_prefixing(self):
| form = HomepageForm({'url': 'example.com'})
form.is_valid()
form = HomepageForm({'url': 'example.com/test'})
form.is_valid()
|
'Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.'
| def test_baseform_with_widgets_in_meta(self):
| widget = forms.Textarea()
class BaseForm(forms.ModelForm, ):
class Meta:
model = Person
widgets = {'name': widget}
Form = modelform_factory(Person, form=BaseForm)
self.assertTrue((Form.base_fields['name'].widget is widget))
|
'Test that a custom formfield_callback is used if provided'
| def test_custom_callback(self):
| callback_args = []
def callback(db_field, **kwargs):
callback_args.append((db_field, kwargs))
return db_field.formfield(**kwargs)
widget = forms.Textarea()
class BaseForm(forms.ModelForm, ):
class Meta:
model = Person
widgets = {'name': widget}
_ = mod... |
'If the ``clean`` method on a non-required FileField receives False as
the data (meaning clear the field value), it returns False, regardless
of the value of ``initial``.'
| def test_clean_false(self):
| f = forms.FileField(required=False)
self.assertEqual(f.clean(False), False)
self.assertEqual(f.clean(False, 'initial'), False)
|
'If the ``clean`` method on a required FileField receives False as the
data, it has the same effect as None: initial is returned if non-empty,
otherwise the validation catches the lack of a required value.'
| def test_clean_false_required(self):
| f = forms.FileField(required=True)
self.assertEqual(f.clean(False, 'initial'), 'initial')
self.assertRaises(ValidationError, f.clean, False)
|
'Integration happy-path test that a model FileField can actually be set
and cleared via a ModelForm.'
| def test_full_clear(self):
| form = DocumentForm()
self.assertTrue(('name="myfile"' in unicode(form)))
self.assertTrue(('myfile-clear' not in unicode(form)))
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')})
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqu... |
'If the user submits a new file upload AND checks the clear checkbox,
they get a validation error, and the bound redisplay of the form still
includes the current file and the clear checkbox.'
| def test_clear_and_file_contradiction(self):
| form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')})
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
form = DocumentForm(instance=doc, files={'myfile': SimpleUploadedFile('something.txt', 'content')}, data={'myfile-clear': 'true'})
self.assertTrue((not... |
'An argument of fields=() to fields_for_model should return an empty dictionary'
| def test_empty_fields_to_fields_for_model(self):
| field_dict = fields_for_model(Person, fields=())
self.assertEqual(len(field_dict), 0)
|
'No fields on a ModelForm should actually result in no fields'
| def test_empty_fields_on_modelform(self):
| form = self.EmptyPersonForm()
self.assertEqual(len(form.fields), 0)
|
'No fields should be set on a model instance if construct_instance receives fields=()'
| def test_empty_fields_to_construct_instance(self):
| form = modelform_factory(Person)({'name': 'John Doe'})
self.assertTrue(form.is_valid())
instance = construct_instance(form, Person(), fields=())
self.assertEqual(instance.name, '')
|
'Subselects honor any manual ordering'
| def test_ordered_subselect(self):
| try:
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([2, 3]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2])
self.assertEqual(set(query.values_lis... |
'Delete queries can safely contain sliced subqueries'
| def test_sliced_delete(self):
| try:
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1, 2]))
except DatabaseError:
self.assertFalse(connections[DEFAULT_DB_ALIAS].features.allow_sliced_subqueries)
|
'#13227 -- If a queryset is already evaluated, it can still be used as a query arg'
| def test_evaluated_queryset_as_argument(self):
| n = Note(note='Test1', misc='misc')
n.save()
e = ExtraInfo(info='good', note=n)
e.save()
n_list = Note.objects.all()
list(n_list)
try:
self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
except:
self.fail('Query should be clonable')
|
'Test QueryDict with one key/value pair'
| def test_single_key_value(self):
| q = QueryDict('foo=bar')
self.assertEqual(q['foo'], 'bar')
self.assertRaises(KeyError, q.__getitem__, 'bar')
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
self.assertEqual(q.get('foo', 'default'), 'bar')
self.assertEqual(q.get('bar', 'default'), 'default')
self.assertE... |
'A copy of a QueryDict is mutable.'
| def test_mutable_copy(self):
| q = QueryDict('').copy()
self.assertRaises(KeyError, q.__getitem__, 'foo')
q['name'] = 'john'
self.assertEqual(q['name'], 'john')
|
'Test QueryDict with two key/value pairs with same keys.'
| def test_multiple_keys(self):
| q = QueryDict('vote=yes&vote=no')
self.assertEqual(q['vote'], u'no')
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
self.assertEqual(q.get('vote', 'default'), u'no')
self.assertEqual(q.get('foo', 'default'), 'default')
self.assertEqual(q.getlist('vote'), [u'yes', u'no'])
... |
'QueryDicts must be able to handle invalid input encoding (in this
case, bad UTF-8 encoding).'
| def test_invalid_input_encoding(self):
| q = QueryDict('foo=bar&foo=\xff')
self.assertEqual(q['foo'], u'\ufffd')
self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd'])
|
'Regression test for #8278: QueryDict.update(QueryDict)'
| def test_update_from_querydict(self):
| x = QueryDict('a=1&a=2', mutable=True)
y = QueryDict('a=3&a=4')
x.update(y)
self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4'])
|
'#13572 - QueryDict with a non-default encoding'
| def test_non_default_encoding(self):
| q = QueryDict('sbb=one', encoding='rot_13')
self.assertEqual(q.encoding, 'rot_13')
self.assertEqual(q.items(), [(u'foo', u'bar')])
self.assertEqual(q.urlencode(), 'sbb=one')
q = q.copy()
self.assertEqual(q.encoding, 'rot_13')
self.assertEqual(q.items(), [(u'foo', u'bar')])
self.assertEqu... |
'Test that we don\'t output tricky characters in encoded value'
| def test_encode(self):
| c = SimpleCookie()
c['test'] = 'An,awkward;value'
self.assertTrue((';' not in c.output().rstrip(';')))
self.assertTrue((',' not in c.output().rstrip(';')))
|
'Test that we can still preserve semi-colons and commas'
| def test_decode(self):
| c = SimpleCookie()
c['test'] = 'An,awkward;value'
c2 = SimpleCookie()
c2.load(c.output())
self.assertEqual(c['test'].value, c2['test'].value)
|
'Test that we haven\'t broken normal encoding'
| def test_decode_2(self):
| c = SimpleCookie()
c['test'] = '\xf0'
c2 = SimpleCookie()
c2.load(c.output())
self.assertEqual(c['test'].value, c2['test'].value)
|
'Test that a single non-standard cookie name doesn\'t affect all cookies. Ticket #13007.'
| def test_nonstandard_keys(self):
| self.assertTrue(('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys()))
|
'Tests that django decorators set certain attributes of the wrapped
function.'
| def test_attributes(self):
| self.assertEqual(fully_decorated.__name__, 'fully_decorated')
self.assertEqual(fully_decorated.__doc__, 'Expected __doc__')
self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
|
'Test that the user_passes_test decorator can be applied multiple times
(#9474).'
| def test_user_passes_test_composition(self):
| def test1(user):
user.decorators_applied.append('test1')
return True
def test2(user):
user.decorators_applied.append('test2')
return True
def callback(request):
return request.user.decorators_applied
callback = user_passes_test(test1)(callback)
callback = user... |
'Test that we can call cache_page the new way'
| def test_cache_page_new_style(self):
| def my_view(request):
return 'response'
my_view_cached = cache_page(123)(my_view)
self.assertEqual(my_view_cached(HttpRequest()), 'response')
my_view_cached2 = cache_page(123, key_prefix='test')(my_view)
self.assertEqual(my_view_cached2(HttpRequest()), 'response')
|
'Test that we can call cache_page the old way'
| def test_cache_page_old_style(self):
| def my_view(request):
return 'response'
my_view_cached = cache_page(my_view, 123)
self.assertEqual(my_view_cached(HttpRequest()), 'response')
my_view_cached2 = cache_page(my_view, 123, key_prefix='test')
self.assertEqual(my_view_cached2(HttpRequest()), 'response')
my_view_cached3 = cache... |
'Test the custom ``django_date_trunc method``, in particular against
fields which clash with strings passed to it (e.g. \'year\') - see
#12818__.
__: http://code.djangoproject.com/ticket/12818'
| def test_django_date_trunc(self):
| updated = datetime.datetime(2010, 2, 20)
models.SchoolClass.objects.create(year=2009, last_updated=updated)
years = models.SchoolClass.objects.dates('last_updated', 'year')
self.assertEqual(list(years), [datetime.datetime(2010, 1, 1, 0, 0)])
|
'Test the custom ``django_extract method``, in particular against fields
which clash with strings passed to it (e.g. \'day\') - see #12818__.
__: http://code.djangoproject.com/ticket/12818'
| def test_django_extract(self):
| updated = datetime.datetime(2010, 2, 20)
models.SchoolClass.objects.create(year=2009, last_updated=updated)
classes = models.SchoolClass.objects.filter(last_updated__day=20)
self.assertEqual(len(classes), 1)
|
'An executemany call with too many/not enough parameters will raise an exception (Refs #12612)'
| def test_bad_parameter_count(self):
| cursor = connection.cursor()
query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (connection.introspection.table_name_converter('backends_square'), connection.ops.quote_name('root'), connection.ops.quote_name('square')))
self.assertRaises(Exception, cursor.executemany, query, [(1, 2,... |
'Test creation of model with long name and long pk name doesn\'t error. Ref #8901'
| @skipUnlessDBFeature('supports_long_model_names')
def test_sequence_name_length_limits_create(self):
| models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
|
'Test an m2m save of a model with a long name and a long m2m field name doesn\'t error as on Django >=1.2 this now uses object saves. Ref #8901'
| @skipUnlessDBFeature('supports_long_model_names')
def test_sequence_name_length_limits_m2m(self):
| obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')
obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
|
'Test that sequence resetting as part of a flush with model with long name and long pk name doesn\'t error. Ref #8901'
| @skipUnlessDBFeature('supports_long_model_names')
def test_sequence_name_length_limits_flush(self):
| VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
tables = [VLM._meta.db_table, VLM_m2m._meta.db_table]
sequences = [{'column': VLM._meta.pk.column, 'table': VLM._meta.db_table}]
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.