desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'step should be zero for the first form'
def test_step_starts_at_zero(self):
response = self.client.get('/wizard/') self.assertEqual(0, response.context['step0'])
'step should be incremented when we go to the next page'
def test_step_increments(self):
response = self.client.post('/wizard/', {'0-field': 'test', 'wizard_step': '0'}) self.assertEqual(1, response.context['step0'])
'Form should not advance if the hash is missing or bad'
def test_bad_hash(self):
response = self.client.post('/wizard/', {'0-field': 'test', '1-field': 'test2', 'wizard_step': '1'}) self.assertEqual(0, response.context['step0'])
'Form should advance if the hash is present and good, as calculated using django 1.2 method.'
def test_good_hash_django12(self):
data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '2fdbefd4c0cad51509478fbacddf8b13', 'wizard_step': '1'} response = self.client.post('/wizard/', data) self.assertEqual(2, response.context['step0'])
'The Django 1.2 method of calulating hashes should *not* be used as a fallback if the FormWizard subclass has provided their own method of calculating a hash.'
def test_good_hash_django12_subclass(self):
data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '2fdbefd4c0cad51509478fbacddf8b13', 'wizard_step': '1'} response = self.client.post('/wizard2/', data) self.assertEqual(0, response.context['step0'])
'Form should advance if the hash is present and good, as calculated using current method.'
def test_good_hash_current(self):
data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c', 'wizard_step': '1'} response = self.client.post('/wizard/', data) self.assertEqual(2, response.context['step0'])
'Regression test for ticket #14498. All previous steps\' forms should be validated.'
def test_14498(self):
reached = [False] that = self class WizardWithProcessStep(WizardClass, ): def process_step(self, request, form, step): that.assertTrue(hasattr(form, 'cleaned_data')) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeFor...
'Regression test for ticket #14576. The form of the last step is not passed to the done method.'
def test_14576(self):
reached = [False] that = self class Wizard(WizardClass, ): def done(self, request, form_list): reached[0] = True that.assertTrue((len(form_list) == 2)) wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) data = {'0-field': 'test', '1-field': 'test2', 'hash_0': '7e...
'Regression test for ticket #15075. Allow modifying wizard\'s form_list in process_step.'
def test_15075(self):
reached = [False] that = self class WizardWithProcessStep(WizardClass, ): def process_step(self, request, form, step): if (step == 0): self.form_list[1] = WizardPageTwoAlternativeForm if (step == 1): that.assertTrue(isinstance(form, WizardPageT...
'Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don\'t hit the database.'
def get_for_model(self, model):
opts = model._meta while opts.proxy: model = opts.proxy_for_model opts = model._meta key = (opts.app_label, opts.object_name.lower()) try: ct = self.__class__._cache[self.db][key] except KeyError: (ct, created) = self.get_or_create(app_label=opts.app_label, model=opts...
'Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id).'
def get_for_id(self, id):
try: ct = self.__class__._cache[self.db][id] except KeyError: ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct
'Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.update_contenttypes for where this gets called).'
def clear_cache(self):
self.__class__._cache.clear()
'Insert a ContentType into the cache.'
def _add_to_cache(self, using, ct):
model = ct.model_class() key = (model._meta.app_label, model._meta.object_name.lower()) self.__class__._cache.setdefault(using, {})[key] = ct self.__class__._cache.setdefault(using, {})[ct.id] = ct
'Returns the Python model class for this type of content.'
def model_class(self):
from django.db import models return models.get_model(self.app_label, self.model)
'Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type\'s get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.'
def get_object_for_this_type(self, **kwargs):
return self.model_class()._default_manager.using(self._state.db).get(**kwargs)
'Handles initializing an object with the generic FK instaed of content-type/object-id fields.'
def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs):
if (self.name in kwargs): value = kwargs.pop(self.name) kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val()
'Return an extra filter to the queryset so that the results are filtered on the appropriate content type.'
def extra_filters(self, pieces, pos, negate):
if negate: return [] ContentType = get_model('contenttypes', 'contenttype') content_type = ContentType.objects.get_for_model(self.model) prefix = '__'.join(pieces[:(pos + 1)]) return [(('%s__%s' % (prefix, self.content_type_field_name)), content_type)]
'Return all objects related to ``objs`` via this ``GenericRelation``.'
def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS):
return self.rel.to._base_manager.db_manager(using).filter(**{('%s__pk' % self.content_type_field_name): ContentType.objects.db_manager(using).get_for_model(self.model).pk, ('%s__in' % self.object_id_field_name): [obj.pk for obj in objs]})
'Make sure that the content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model or by ID -- should hit the database only on the first lookup.'
def test_lookup_cache(self):
ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) ct = ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) ContentType.objects.get_for_id(ct.id) self.assertEqual(1, len(db.connection.queries)) ContentType...
'Check that the shortcut view (used for the admin "view on site" functionality) returns a complete URL regardless of whether the sites framework is installed'
def test_shortcut_view(self):
request = HttpRequest() request.META = {'SERVER_NAME': 'Example.com', 'SERVER_PORT': '80'} from django.contrib.auth.models import User user_ct = ContentType.objects.get_for_model(User) obj = User.objects.create(username='john') if Site._meta.installed: current_site = Site.objects.get_cur...
'Returns the storage backend, setting its loaded data to the ``data`` argument. This method avoids the storage ``_get`` method from getting called so that other parts of the storage backend can be tested independent of the message retrieval logic.'
def get_storage(self, data=None):
storage = self.storage_class(self.get_request()) storage._loaded_data = (data or []) return storage
'With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle.'
def test_full_request_response_cycle(self):
settings.MESSAGE_LEVEL = constants.DEBUG data = {'messages': [('Test message %d' % x) for x in xrange(10)]} show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add...
'Tests that messages persist properly when multiple POSTs are made before a GET.'
def test_multiple_posts(self):
settings.MESSAGE_LEVEL = constants.DEBUG data = {'messages': [('Test message %d' % x) for x in xrange(10)]} show_url = reverse('django.contrib.messages.tests.urls.show') messages = [] for level in ('debug', 'info', 'success', 'warning', 'error'): messages.extend([Message(self.levels[le...
'Tests that the messages API successfully falls back to using user.message_set to store messages directly when the middleware is disabled.'
@skipUnlessAuthIsInstalled def test_middleware_disabled_auth_user(self):
settings.MESSAGE_LEVEL = constants.DEBUG user = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_C...
'Tests that, when the middleware is disabled and a user is not logged in, an exception is raised when one attempts to store a message.'
def test_middleware_disabled_anon_user(self):
settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove('django.contrib.messages.middleware.MessageMid...
'Tests that, when the middleware is disabled and a user is not logged in, an exception is not raised if \'fail_silently\' = True'
def test_middleware_disabled_anon_user_fail_silently(self):
settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove('django.contrib.messages') settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove('django.contrib.messages.middleware.MessageMid...
'Returns the number of messages being stored after a ``storage.update()`` call.'
def stored_messages_count(self, storage, response):
raise NotImplementedError('This method must be set by a subclass.')
'Tests that reading the existing storage doesn\'t cause the data to be lost.'
def test_existing_read(self):
storage = self.get_existing_storage() self.assertFalse(storage.used) data = list(storage) self.assertTrue(storage.used) self.assertEqual(data, list(storage))
'Ensure that CookieStorage honors SESSION_COOKIE_DOMAIN. Refs #15618.'
def test_domain(self):
storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, 'test') storage.update(response) self.assertTrue(('test' in response.cookies['messages'].value)) self.assertEqual(response.cookies['messages']['domain'], '.lawrence.com') self.assertEqual(response.cookies...
'Tests that, if the data exceeds what is allowed in a cookie, older messages are removed before saving (and returned by the ``update`` method).'
def test_max_cookie_length(self):
storage = self.get_storage() response = self.get_response() msg_size = int((((CookieStorage.max_cookie_size - 54) / 4.5) - 37)) for i in range(5): storage.add(constants.INFO, (str(i) * msg_size)) unstored_messages = storage.update(response) cookie_storing = self.stored_messages_count(sto...
'Tests that a complex nested data structure containing Message instances is properly encoded/decoded by the custom JSON encoder/decoder classes.'
def test_json_encoder_decoder(self):
messages = [{'message': Message(constants.INFO, 'Test message'), 'message_list': ([Message(constants.INFO, 'message %s') for x in xrange(5)] + [{'another-message': Message(constants.ERROR, 'error')}])}, Message(constants.INFO, 'message %s')] encoder = MessageEncoder(separators=(',', ':')) value = e...
'Return the storage totals from both cookie and session backends.'
def stored_messages_count(self, storage, response):
total = (self.stored_cookie_messages_count(storage, response) + self.stored_session_messages_count(storage, response)) return total
'Confirms that: (1) A short number of messages whose data size doesn\'t exceed what is allowed in a cookie will all be stored in the CookieBackend. (2) If the CookieBackend can store all messages, the SessionBackend won\'t be written to at all.'
def test_no_fallback(self):
storage = self.get_storage() response = self.get_response() self.get_session_storage(storage)._store = None for i in range(5): storage.add(constants.INFO, (str(i) * 100)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(c...
'Confirms that, if the data exceeds what is allowed in a cookie, messages which did not fit are stored in the SessionBackend.'
def test_session_fallback(self):
storage = self.get_storage() response = self.get_response() msg_size = int((((CookieStorage.max_cookie_size - 54) / 4.5) - 37)) for i in range(5): storage.add(constants.INFO, (str(i) * msg_size)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, respons...
'Confirms that large messages, none of which fit in a cookie, are stored in the SessionBackend (and nothing is stored in the CookieBackend).'
def test_session_fallback_only(self):
storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, ('x' * 5000)) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(cookie_storing, 0) session_storing = self.stored_session_messages_count(storag...
'Makes sure that the response middleware is tolerant of messages not existing on request.'
def test_response_without_messages(self):
request = http.HttpRequest() response = http.HttpResponse() self.middleware.process_response(request, response)
'Prepares the message for serialization by forcing the ``message`` and ``extra_tags`` to unicode in case they are lazy translations. Known "safe" types (None, int, etc.) are not converted (see Django\'s ``force_unicode`` implementation for details).'
def _prepare(self):
self.message = force_unicode(self.message, strings_only=True) self.extra_tags = force_unicode(self.extra_tags, strings_only=True)
'Returns a list of loaded messages, retrieving them first if they have not been loaded yet.'
@property def _loaded_messages(self):
if (not hasattr(self, '_loaded_data')): (messages, all_retrieved) = self._get() self._loaded_data = (messages or []) return self._loaded_data
'Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``. **This method must be implemented by a subclass.** If it is possible to t...
def _get(self, *args, **kwargs):
raise NotImplementedError()
'Stores a list of messages, returning a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.**'
def _store(self, messages, response, *args, **kwargs):
raise NotImplementedError()
'Prepares a list of messages for storage.'
def _prepare_messages(self, messages):
for message in messages: message._prepare()
'Stores all unread messages. If the backend has yet to be iterated, previously stored messages will be stored again. Otherwise, only messages added after the last iteration will be stored.'
def update(self, response):
self._prepare_messages(self._queued_messages) if self.used: return self._store(self._queued_messages, response) elif self.added_new: messages = (self._loaded_messages + self._queued_messages) return self._store(messages, response)
'Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``).'
def add(self, level, message, extra_tags=''):
if (not message): return level = int(level) if (level < self.level): return self.added_new = True message = Message(level, message, extra_tags=extra_tags) self._queued_messages.append(message)
'Returns the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used.'
def _get_level(self):
if (not hasattr(self, '_level')): self._level = getattr(settings, 'MESSAGE_LEVEL', constants.INFO) return self._level
'Sets a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method).'
def _set_level(self, value=None):
if ((value is None) and hasattr(self, '_level')): del self._level else: self._level = int(value)
'Retrieves a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage.'
def _get(self, *args, **kwargs):
data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = (not (messages and (messages[(-1)] == self.not_finished))) if (messages and (not all_retrieved)): messages.pop() return (messages, all_retrieved)
'Either sets the cookie with the encoded data if there is any data to store, or deletes the cookie.'
def _update_cookie(self, encoded_data, response):
if encoded_data: response.set_cookie(self.cookie_name, encoded_data, domain=settings.SESSION_COOKIE_DOMAIN) else: response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)
'Stores the messages to a cookie, returning a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, removes messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much.'
def _store(self, messages, response, remove_oldest=True, *args, **kwargs):
unstored_messages = [] encoded_data = self._encode(messages) if self.max_cookie_size: cookie = SimpleCookie() def stored_length(val): return len(cookie.value_encode(val)[1]) while (encoded_data and (stored_length(encoded_data) > self.max_cookie_size)): if remo...
'Creates an HMAC/SHA1 hash based on the value and the project setting\'s SECRET_KEY, modified to make it unique for the present purpose.'
def _hash(self, value):
key_salt = 'django.contrib.messages' return salted_hmac(key_salt, value).hexdigest()
'Returns an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with.'
def _encode(self, messages, encode_empty=False):
if (messages or encode_empty): encoder = MessageEncoder(separators=(',', ':')) value = encoder.encode(messages) return ('%s$%s' % (self._hash(value), value))
'Safely decodes a encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned.'
def _decode(self, data):
if (not data): return None bits = data.split('$', 1) if (len(bits) == 2): (hash, value) = bits if constant_time_compare(hash, self._hash(value)): try: return json.loads(value, cls=MessageDecoder) except ValueError: pass self...
'Returns the QuerySet containing all user messages (or ``None`` if request.user is not a contrib.auth User).'
def _get_messages_queryset(self):
user = getattr(self.request, 'user', None) if isinstance(user, User): return user._message_set.all()
'Retrieves a list of messages assigned to the User. This backend never stores anything, so all_retrieved is assumed to be False.'
def _get(self, *args, **kwargs):
queryset = self._get_messages_queryset() if (queryset is None): return ([], False) messages = [] for user_message in queryset: messages.append(Message(constants.INFO, user_message.message)) return (messages, False)
'Removes any messages assigned to the User and returns the list of messages (since no messages are stored in this read-only storage).'
def _store(self, messages, *args, **kwargs):
queryset = self._get_messages_queryset() if (queryset is not None): queryset.delete() return messages
'Retrieves a list of messages from the request\'s session. This storage always stores everything it is given, so return True for the all_retrieved flag.'
def _get(self, *args, **kwargs):
return (self.request.session.get(self.session_key), True)
'Stores a list of messages to the request\'s session.'
def _store(self, messages, response, *args, **kwargs):
if messages: self.request.session[self.session_key] = messages else: self.request.session.pop(self.session_key, None) return []
'Gets a single list of messages from all storage backends.'
def _get(self, *args, **kwargs):
all_messages = [] for storage in self.storages: (messages, all_retrieved) = storage._get() if (messages is None): break if messages: self._used_storages.add(storage) all_messages.extend(messages) if all_retrieved: break return (all_...
'Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend.'
def _store(self, messages, response, *args, **kwargs):
for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) elif (storage in self._used_storages): storage._store([], response) self._used_storages.remove(storage) return messages
'Updates the storage backend (i.e., saves the messages). If not all messages could not be stored and ``DEBUG`` is ``True``, a ``ValueError`` is raised.'
def process_response(self, request, response):
if hasattr(request, '_messages'): unstored_messages = request._messages.update(response) if (unstored_messages and settings.DEBUG): raise ValueError('Not all temporary messages could be stored.') return response
'Adds an item to the feed. All args are expected to be Python Unicode objects except pubdate, which is a datetime.datetime object, and enclosure, which is an instance of the Enclosure class.'
def add_item(self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None, **kwargs):
to_unicode = (lambda s: force_unicode(s, strings_only=True)) if categories: categories = [to_unicode(c) for c in categories] if (ttl is not None): ttl = force_unicode(ttl) item = {'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'author_email'...
'Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().'
def root_attributes(self):
return {}
'Add elements in the root (i.e. feed/channel) element. Called from write().'
def add_root_elements(self, handler):
pass
'Return extra attributes to place on each item (i.e. item/entry) element.'
def item_attributes(self, item):
return {}
'Add elements on each item (i.e. item/entry) element.'
def add_item_elements(self, handler, item):
pass
'Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.'
def write(self, outfile, encoding):
raise NotImplementedError
'Returns the feed in the given encoding as a string.'
def writeString(self, encoding):
from StringIO import StringIO s = StringIO() self.write(s, encoding) return s.getvalue()
'Returns the latest item\'s pubdate. If none of them have a pubdate, this returns the current date/time.'
def latest_post_date(self):
updates = [i['pubdate'] for i in self.items if (i['pubdate'] is not None)] if (len(updates) > 0): updates.sort() return updates[(-1)] else: return datetime.datetime.now()
'All args are expected to be Python Unicode objects'
def __init__(self, url, length, mime_type):
(self.length, self.mime_type) = (length, mime_type) self.url = iri_to_uri(url)
'Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.'
def __init__(self, methodName='runTest'):
self._testMethodName = methodName self._resultForDoCleanups = None try: testMethod = getattr(self, methodName) except AttributeError: raise ValueError(('no such test method in %s: %s' % (self.__class__, methodName))) self._testMethodDoc = testMethod.__doc__ self...
'Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function...
def addTypeEqualityFunc(self, typeobj, function):
self._type_equality_funcs[typeobj] = function
'Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).'
def addCleanup(self, function, *args, **kwargs):
self._cleanups.append((function, args, kwargs))
'Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method\'s docstring.'
def shortDescription(self):
doc = self._testMethodDoc return ((doc and doc.split('\n')[0].strip()) or None)
'Execute all cleanup functions. Normally called for you after tearDown.'
def doCleanups(self):
result = self._resultForDoCleanups ok = True while self._cleanups: (function, args, kwargs) = self._cleanups.pop((-1)) try: function(*args, **kwargs) except Exception: ok = False result.addError(self, sys.exc_info()) return ok
'Run the test without collecting errors in a TestResult'
def debug(self):
self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: (function, args, kwargs) = self._cleanups.pop((-1)) function(*args, **kwargs)
'Skip this test.'
def skipTest(self, reason):
raise SkipTest(reason)
'Fail immediately, with the given message.'
def fail(self, msg=None):
raise self.failureException(msg)
'Fail the test if the expression is true.'
def assertFalse(self, expr, msg=None):
if expr: msg = self._formatMessage(msg, ('%s is not False' % safe_repr(expr))) raise self.failureException(msg)
'Fail the test unless the expression is true.'
def assertTrue(self, expr, msg=None):
if (not expr): msg = self._formatMessage(msg, ('%s is not True' % safe_repr(expr))) raise self.failureException(msg)
'Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus \' : \' and the expli...
def _formatMessage(self, msg, standardMsg):
if (not self.longMessage): return (msg or standardMsg) if (msg is None): return standardMsg try: return ('%s : %s' % (standardMsg, msg)) except UnicodeDecodeError: return ('%s : %s' % (safe_str(standardMsg), safe_str(msg)))
'Fail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with callab...
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
if (callableObj is None): return _AssertRaisesContext(excClass, self) try: callableObj(*args, **kwargs) except excClass: return if hasattr(excClass, '__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException(('%s ...
'Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types.'
def _getAssertEqualityFunc(self, first, second):
if (type(first) is type(second)): asserter = self._type_equality_funcs.get(type(first)) if (asserter is not None): return asserter return self._baseAssertEqual
'The default assertEqual implementation, not type specific.'
def _baseAssertEqual(self, first, second, msg=None):
if (not (first == second)): standardMsg = ('%s != %s' % (safe_repr(first), safe_repr(second))) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
'Fail if the two objects are unequal as determined by the \'==\' operator.'
def assertEqual(self, first, second, msg=None):
assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg)
'Fail if the two objects are equal as determined by the \'==\' operator.'
def assertNotEqual(self, first, second, msg=None):
if (not (first != second)): msg = self._formatMessage(msg, ('%s == %s' % (safe_repr(first), safe_repr(second)))) raise self.failureException(msg)
'Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (meas...
def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
if (first == second): return if ((delta is not None) and (places is not None)): raise TypeError('specify delta or places not both') if (delta is not None): if (abs((first - second)) <= delta): return standardMsg = ('%s != %s within %s ...
'Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measur...
def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
if ((delta is not None) and (places is not None)): raise TypeError('specify delta or places not both') if (delta is not None): if ((not (first == second)) and (abs((first - second)) > delta)): return standardMsg = ('%s == %s within %s delta' % (s...
'An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype...
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None, max_diff=(80 * 8)):
if (seq_type is not None): seq_type_name = seq_type.__name__ if (not isinstance(seq1, seq_type)): raise self.failureException(('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1)))) if (not isinstance(seq2, seq_type)): raise self.failu...
'A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences.'
def assertListEqual(self, list1, list2, msg=None):
self.assertSequenceEqual(list1, list2, msg, seq_type=list)
'A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences.'
def assertTupleEqual(self, tuple1, tuple2, msg=None):
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
'A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a differ...
def assertSetEqual(self, set1, set2, msg=None):
try: difference1 = set1.difference(set2) except TypeError as e: self.fail(('invalid type when attempting set difference: %s' % e)) except AttributeError as e: self.fail(('first argument does not support set difference: %s' % e)) try: ...
'Just like self.assertTrue(a in b), but with a nicer default message.'
def assertIn(self, member, container, msg=None):
if (member not in container): standardMsg = ('%s not found in %s' % (safe_repr(member), safe_repr(container))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a not in b), but with a nicer default message.'
def assertNotIn(self, member, container, msg=None):
if (member in container): standardMsg = ('%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a is b), but with a nicer default message.'
def assertIs(self, expr1, expr2, msg=None):
if (expr1 is not expr2): standardMsg = ('%s is not %s' % (safe_repr(expr1), safe_repr(expr2))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a is not b), but with a nicer default message.'
def assertIsNot(self, expr1, expr2, msg=None):
if (expr1 is expr2): standardMsg = ('unexpectedly identical: %s' % (safe_repr(expr1),)) self.fail(self._formatMessage(msg, standardMsg))
'Checks whether actual is a superset of expected.'
def assertDictContainsSubset(self, expected, actual, msg=None):
missing = [] mismatched = [] for (key, value) in expected.iteritems(): if (key not in actual): missing.append(key) elif (value != actual[key]): mismatched.append(('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[key]))))...
'An unordered sequence specific comparison. It asserts that expected_seq and actual_seq contain the same elements. It is the equivalent of:: self.assertEqual(sorted(expected_seq), sorted(actual_seq)) Raises with an error message listing which elements of expected_seq are missing from actual_seq and vice versa if any. A...
def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
try: expected = sorted(expected_seq) actual = sorted(actual_seq) except TypeError: expected = list(expected_seq) actual = list(actual_seq) (missing, unexpected) = unorderable_list_difference(expected, actual, ignore_duplicate=False) else: return self.assertSeq...
'Assert that two multi-line strings are equal.'
def assertMultiLineEqual(self, first, second, msg=None):
self.assertTrue(isinstance(first, basestring), 'First argument is not a string') self.assertTrue(isinstance(second, basestring), 'Second argument is not a string') if (first != second): standardMsg = ('%s != %s' % (safe_repr(first, True), safe_repr(second, True)))...
'Just like self.assertTrue(a < b), but with a nicer default message.'
def assertLess(self, a, b, msg=None):
if (not (a < b)): standardMsg = ('%s not less than %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a <= b), but with a nicer default message.'
def assertLessEqual(self, a, b, msg=None):
if (not (a <= b)): standardMsg = ('%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))
'Just like self.assertTrue(a > b), but with a nicer default message.'
def assertGreater(self, a, b, msg=None):
if (not (a > b)): standardMsg = ('%s not greater than %s' % (safe_repr(a), safe_repr(b))) self.fail(self._formatMessage(msg, standardMsg))