def skipIfDBEngine(engine, reason=None): """ Decorator to skip tests on a given database engine. Note that you can pass a single engine or an iterable here """ if not reason: reason = "not supported on this database" settings_engine = settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"] if isinstance(engine, basestring): return skipIf(settings_engine == engine, reason) return skipIf(settings_engine in engine, reason)
def skipIfDBEngine(engine, reason=None): """ Decorator to skip tests on a given database engine. Note that you can pass a single engine or an iterable here """ if not reason: reason = "not supported on this database" settings_engine = settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] if isinstance(engine, basestring): return skipIf(settings_engine == engine, reason) return skipIf(settings_engine in engine, reason)
def skipIfCustomUserProfileSerializer(test_func): """ Skip a test if a custom user model is in use. """ return skipIf( _is_custom_userprofileserializer(), 'Custom cosinnus user profile serializer model in use')(test_func)
class MockHandler(urllib2.HTTPHandler): def set_next_response(self, msg): self.next_response = msg def http_open(self, req): response = StringIO(self.next_response) resp = urllib.addinfourl(response, {}, req.get_full_url()) resp.code = 200 resp.msg = 'OK' return resp skipOnSqlite = skipIf(connection.vendor == 'sqlite', "Skipping on SQLite") def test_concurrently(times): """ Add this decorator to small pieces of code that you want to test concurrently to make sure they don't raise exceptions when run at the same time. E.g., some Django views that do a SELECT and then a subsequent INSERT might fail when the INSERT assumes that the data has not changed since the SELECT. """ def test_concurrently_decorator(test_func): def wrapper(*args, **kwargs): exceptions = []
def skipUnlessAuthIsInstalled(func): return skipIf( 'django.contrib.auth' not in settings.INSTALLED_APPS, "django.contrib.auth isn't installed")(func)
alice0 = self.backend.authenticate(username=u'alice', password=u'password') pickled = pickle.dumps(alice0, pickle.HIGHEST_PROTOCOL) alice = pickle.loads(pickled) alice.ldap_user.backend.settings = alice0.ldap_user.backend.settings self.assertTrue(alice is not None) self.assertEqual(self.backend.get_group_permissions(alice), set(["auth.add_user", "auth.change_user"])) self.assertEqual(self.backend.get_all_permissions(alice), set(["auth.add_user", "auth.change_user"])) self.assertTrue(self.backend.has_perm(alice, "auth.add_user")) self.assertTrue(self.backend.has_module_perms(alice, "auth")) def _init_settings(self, **kwargs): self.backend.settings = TestSettings(**kwargs) def _init_groups(self): permissions = [ Permission.objects.get(codename="add_user"), Permission.objects.get(codename="change_user") ] active_gon = Group.objects.create(name='active_gon') active_gon.permissions.add(*permissions) active_px = Group.objects.create(name='active_px') active_px.permissions.add(*permissions) # Python 2.5-compatible class decoration LDAPTest = unittest.skipIf(mockldap is None, "django_auth_ldap tests require the mockldap package.")(LDAPTest)
class TestRunner(DjangoTestSuiteRunner): def setup_test_environment(self, *args, **kw): super(TestRunner, self).setup_test_environment(*args, **kw) self.redis_server = None if settings.USE_REDIS: try: import subprocess self.redis_server = subprocess.Popen(['redis-server', '-'], stdin=subprocess.PIPE) except Exception, e: print e return self.redis_server.stdin.write(""" port 63790 loglevel warning """) settings.REDIS_HOST = 'localhost' settings.REDIS_PORT = 63790 self.redis_server.stdin.close() def teardown_test_environment(self, *args, **kw): super(TestRunner, self).teardown_test_environment(*args, **kw) if self.redis_server: self.redis_server.terminate() integration_test = unittest.skipIf( not settings.INTEGRATION_TESTS, "disabled test which needs internet connection")
Template, TemplateSyntaxError, ) from django.test import TestCase from django.test.client import RequestFactory from django.utils import unittest from endless_pagination.exceptions import PaginationError from endless_pagination.models import PageList from endless_pagination.settings import ( PAGE_LABEL, PER_PAGE, ) from endless_pagination.tests import make_model_instances skip_if_old_etree = unittest.skipIf( sys.version_info < (2, 7), 'XPath not supported by this Python version.') class TemplateTagsTestMixin(object): """Base test mixin for template tags.""" def setUp(self): self.factory = RequestFactory() def render(self, request, contents, **kwargs): """Render *contents* using given *request*. The context data is represented by keyword arguments. Is no keyword arguments are provided, a default context will be used. Return the generated HTML and the modified context. """
if not instance.__class__ in cls._created_models: cls._created_models.append(instance.__class__) from django.test.simple import DjangoTestSuiteRunner class TestRunner(DjangoTestSuiteRunner): def setup_test_environment(self, *args, **kw): super(TestRunner, self).setup_test_environment(*args, **kw) self.redis_server = None if settings.USE_REDIS: try: import subprocess self.redis_server = subprocess.Popen(['redis-server', '-'], stdin=subprocess.PIPE) except Exception, e: print e return self.redis_server.stdin.write(""" port 63790 loglevel warning """) settings.REDIS_HOST = 'localhost' settings.REDIS_PORT = 63790 self.redis_server.stdin.close() def teardown_test_environment(self, *args, **kw): super(TestRunner, self).teardown_test_environment(*args, **kw) if self.redis_server: self.redis_server.terminate() integration_test = unittest.skipIf(not settings.INTEGRATION_TESTS, "disabled test which needs internet connection")
def override_settings(*args, **kwargs): return unittest.skipIf(django.get_version().startswith('1.3'), "Django < 1.4 doesn't have override_settings")
alice.ldap_user.backend.settings = alice0.ldap_user.backend.settings self.assertTrue(alice is not None) self.assertEqual(self.backend.get_group_permissions(alice), set(["auth.add_user", "auth.change_user"])) self.assertEqual(self.backend.get_all_permissions(alice), set(["auth.add_user", "auth.change_user"])) self.assertTrue(self.backend.has_perm(alice, "auth.add_user")) self.assertTrue(self.backend.has_module_perms(alice, "auth")) def _init_settings(self, **kwargs): self.backend.settings = TestSettings(**kwargs) def _init_groups(self): permissions = [ Permission.objects.get(codename="add_user"), Permission.objects.get(codename="change_user") ] active_gon = Group.objects.create(name='active_gon') active_gon.permissions.add(*permissions) active_px = Group.objects.create(name='active_px') active_px.permissions.add(*permissions) # Python 2.5-compatible class decoration LDAPTest = unittest.skipIf( mockldap is None, "django_auth_ldap tests require the mockldap package.")(LDAPTest)
user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) self.assertEqual(user.get_all_permissions('object'), set([])) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.get_all_permissions(), set(['auth.test'])) def test_get_all_superuser_permissions(self): "A superuser has all permissions. Refs #14795" user = User.objects.get(username='******') self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all())) BackendTest = unittest.skipIf(not connection.features.supports_joins, 'Requires JOIN support')(BackendTest) class TestObj(object): pass class SimpleRowlevelBackend(object): supports_inactive_user = False # This class also supports tests for anonymous user permissions, and # inactive user permissions via subclasses which just set the # 'supports_anonymous_user' or 'supports_inactive_user' attribute. def has_perm(self, user, perm, obj=None): if not obj:
import django from django.utils.six import assertRegex from django.utils.six.moves import urllib from django.test.utils import override_settings from django.utils import unittest from speeches.tests import InstanceTestCase, OverrideMediaRootMixin from speeches.models import Speaker, Speech, Section from speeches import models m = Mock() m.return_value = ('speeches/fixtures/test_inputs/Ferdinand_Magellan.jpg', None) skip_old_django = unittest.skipIf( django.VERSION[:2] == (1, 4), "Prior to Django 1.5, override_settings didn't sort out MEDIA_URL properly - " "see https://code.djangoproject.com/ticket/17744", ) @override_settings(MEDIA_URL='/uploads/') class OpenGraphTests(OverrideMediaRootMixin, InstanceTestCase): @patch.object(models, 'urlretrieve', m) def setUp(self): super(OpenGraphTests, self).setUp() self.steve = Speaker.objects.create( name='Steve', instance=self.instance, image='http://example.com/image.jpg', )
def skipIfNotCustomUser(test_func): return unittest.skipIf(settings.AUTH_USER_MODEL == 'auth.User', 'Built-in User model in use')(test_func)
def skipIfOAuth(test_func): """ Skip a test if a custom user model is in use. """ return skipIf(settings.DJANGO_ADMIN_SSO_USE_OAUTH, 'Using OAuth')(test_func)
def skipIfCustomUser(test_func): return skipIf(False)(test_func)
def test_typed_listfield(self): EmbeddedModelFieldModel.objects.create( typed_list=[SetModel(setfield=range(3)), SetModel(setfield=range(9))] ) self.assertIn(5, EmbeddedModelFieldModel.objects.get().typed_list[1].setfield) def test_untyped_listfield(self): EmbeddedModelFieldModel.objects.create(untyped_list=[ EmbeddedModel(someint=7), OrderedListModel(ordered_ints=range(5, 0, -1)), SetModel(setfield=[1, 2, 2, 3]) ]) instances = EmbeddedModelFieldModel.objects.get().untyped_list for instance, cls in zip(instances, [EmbeddedModel, OrderedListModel, SetModel]): self.assertIsInstance(instance, cls) self.assertNotEqual(instances[0].auto_now, None) self.assertEqual(instances[1].ordered_ints, range(1, 6)) def test_untyped_dict(self): EmbeddedModelFieldModel.objects.create(untyped_dict={ 'a' : SetModel(setfield=range(3)), 'b' : DictModel(dictfield={'a' : 1, 'b' : 2}), 'c' : DictModel(dictfield={}, auto_now={'y' : 1}) }) data = EmbeddedModelFieldModel.objects.get().untyped_dict self.assertIsInstance(data['a'], SetModel) self.assertNotEqual(data['c'].auto_now['y'], None) EmbeddedModelFieldTest = unittest.skipIf( not supports_dicts, "Backend doesn't support dicts")( EmbeddedModelFieldTest)
def skipIfCustomUser(test_func): """ Skip a test if a custom user model is in use. """ return skipIf(settings.AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
TemplateSyntaxError, ) from django.test import TestCase from django.test.client import RequestFactory from django.utils import unittest from el_pagination.exceptions import PaginationError from el_pagination.models import PageList from el_pagination.settings import ( PAGE_LABEL, PER_PAGE, ) from el_pagination.tests import make_model_instances skip_if_old_etree = unittest.skipIf( sys.version_info < (2, 7), 'XPath not supported by this Python version.') class TemplateTagsTestMixin(object): """Base test mixin for template tags.""" def setUp(self): self.factory = RequestFactory() def render(self, request, contents, **kwargs): """Render *contents* using given *request*. The context data is represented by keyword arguments. Is no keyword arguments are provided, a default context will be used. Return the generated HTML and the modified context.
data = EmbeddedModelFieldModel.objects.get().untyped_dict self.assertIsInstance(data['a'], SetModel) self.assertNotEqual(data['c'].auto_now['y'], None) def test_foreignkey_in_embedded_object(self): simple = EmbeddedModel(some_relation=DictModel.objects.create()) obj = EmbeddedModelFieldModel.objects.create(simple=simple) simple = EmbeddedModelFieldModel.objects.get().simple self.assertNotIn('some_relation', simple.__dict__) self.assertIsInstance(simple.__dict__['some_relation_id'], type(obj.id)) self.assertIsInstance(simple.some_relation, DictModel) EmbeddedModelFieldTest = unittest.skipIf( not supports_dicts, "Backend doesn't support dicts")(EmbeddedModelFieldTest) class SignalTest(TestCase): def test_post_save(self): created = [] @receiver(post_save, sender=SetModel) def handle(**kwargs): created.append(kwargs['created']) SetModel().save() self.assertEqual(created, [True]) SetModel.objects.get().save() self.assertEqual(created, [True, False])
def skipIfCustomUser(test_func): "Tweaked version of check for replaced auth.User" return skipIf(AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
def skipIfOAuth(test_func): """ Skip a test if a custom user model is in use. """ return skipIf(settings.DJANGO_ADMIN_SSO_USE_OAUTH, "Using OAuth")(test_func)
def skipUnlessAuthIsInstalled(func): return skipIf('django.contrib.auth' not in settings.INSTALLED_APPS, "django.contrib.auth isn't installed")(func)
perm = Permission.objects.create(name="test", content_type=content_type, codename="test") user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm("auth.test", "object"), False) self.assertEqual(user.get_all_permissions("object"), set([])) self.assertEqual(user.has_perm("auth.test"), True) self.assertEqual(user.get_all_permissions(), set(["auth.test"])) def test_get_all_superuser_permissions(self): "A superuser has all permissions. Refs #14795" user = User.objects.get(username="******") self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all())) BackendTest = unittest.skipIf(not connection.features.supports_joins, "Requires JOIN support")(BackendTest) class TestObj(object): pass class SimpleRowlevelBackend(object): supports_object_permissions = True supports_inactive_user = False # This class also supports tests for anonymous user permissions, and # inactive user permissions via subclasses which just set the # 'supports_anonymous_user' or 'supports_inactive_user' attribute. def has_perm(self, user, perm, obj=None):