예제 #1
0
def skipUnlessCustomUserProfileSerializer(test_func):
    """
    Skip a test if a custom user model is in use.
    """
    return skipUnless(
        _is_custom_userprofileserializer(),
        'No custom cosinnus user profile serializer model in use')(test_func)
예제 #2
0
def make_reviewed(fn):
    """
    Just setting the WIDGY_MEZZANINE_SITE is not enough during tests, because
    WidgyPage.root_node has been set to point to VersionTracker.  We have to
    manually point it to ReviewedVersionTracker.  We do this only in tests
    because on a normal run, you are never going to be changing what models a
    ForeignKey points to (I would hope).
    """
    from widgy.contrib.widgy_mezzanine.admin import publish_page_on_approve

    site = reviewed_widgy_site
    rel = WidgyPage._meta.get_field('root_node').rel
    old_to = rel.to
    dispatch_uid = str(uuid.uuid4())

    fn = override_settings(WIDGY_MEZZANINE_SITE=site)(fn)
    fn = skipUnless(REVIEW_QUEUE_INSTALLED,
                    'review_queue is not installed')(fn)

    def up():
        rel.to = site.get_version_tracker_model()
        post_save.connect(publish_page_on_approve,
                          sender=site.get_version_tracker_model().commit_model,
                          dispatch_uid=dispatch_uid)

    def down():
        rel.to = old_to
        post_save.disconnect(dispatch_uid=dispatch_uid)

    if isinstance(fn, type):
        old_pre_setup = fn._pre_setup
        old_post_teardown = fn._post_teardown

        def _pre_setup(self):
            up()
            old_pre_setup(self)

        def _post_teardown(self):
            old_post_teardown(self)
            down()

        fn._pre_setup = _pre_setup
        fn._post_teardown = _post_teardown

        return fn
    else:

        def change_foreign_key(*args, **kwargs):
            up()
            try:
                return fn(*args, **kwargs)
            finally:
                down()

        return change_foreign_key
예제 #3
0
def make_reviewed(fn):
    """
    Just setting the WIDGY_MEZZANINE_SITE is not enough during tests, because
    WidgyPage.root_node has been set to point to VersionTracker.  We have to
    manually point it to ReviewedVersionTracker.  We do this only in tests
    because on a normal run, you are never going to be changing what models a
    ForeignKey points to (I would hope).
    """
    from widgy.contrib.widgy_mezzanine.admin import publish_page_on_approve

    site = reviewed_widgy_site
    rel = WidgyPage._meta.get_field('root_node').rel
    old_to = rel.to
    dispatch_uid = str(uuid.uuid4())

    fn = override_settings(WIDGY_MEZZANINE_SITE=site)(fn)
    fn = skipUnless(REVIEW_QUEUE_INSTALLED, 'review_queue is not installed')(fn)

    def up():
        rel.to = site.get_version_tracker_model()
        post_save.connect(publish_page_on_approve,
                          sender=site.get_version_tracker_model().commit_model,
                          dispatch_uid=dispatch_uid)

    def down():
        rel.to = old_to
        post_save.disconnect(dispatch_uid=dispatch_uid)

    if isinstance(fn, type):
        old_pre_setup = fn._pre_setup
        old_post_teardown = fn._post_teardown

        def _pre_setup(self):
            up()
            old_pre_setup(self)

        def _post_teardown(self):
            old_post_teardown(self)
            down()

        fn._pre_setup = _pre_setup
        fn._post_teardown = _post_teardown

        return fn
    else:
        def change_foreign_key(*args, **kwargs):
            up()
            try:
                return fn(*args, **kwargs)
            finally:
                down()
        return change_foreign_key
예제 #4
0
        with self.assertNumQueries(0):
            user = authenticate(username=self.username, password=self.password)

    ####################################################################
    
    def test_get_user(self):
        """Tests that, with cachetree auth backend enabled, get_user uses the
        cache.
        """
        backend = CachedModelBackend()
        user = backend.get_user(user_id=self.user.id)
        with self.assertNumQueries(0):
            user = backend.get_user(user_id=self.user.id)

CachetreeAuthTestCase = skipUnless(
    "django.contrib.auth" in django_settings.INSTALLED_APPS, 
    "django.contrib.auth is not in INSTALLED_APPS")(CachetreeAuthTestCase)

########################################################################

class CachetreeInvalidationTestCase(CachetreeBaseTestCase):
    """Test cachetree's invalidation functionality.
    """
    
    ####################################################################
    
    def get_test_settings(self):
        """Returns the cachetree settings to be used for the test.
        """
        test_settings = super(CachetreeInvalidationTestCase, self).get_test_settings()
        test_settings['INVALIDATE'] = True
예제 #5
0
파일: tests.py 프로젝트: ArturFis/cartridge
        # Assertion
        mock_charge.create.assert_called_with(
            amount=2237,
            currency="usd",
            card={'number': "4242424242424242",
                  'exp_month': "06",
                  'exp_year': "14",
                  'address_line1': "123 Evergreen Terrace",
                  'address_city': "Springfield",
                  'address_state': "WA",
                  'address_zip': "01234",
                  'country': "USA"})


StripeTests = skipUnless(stripe_used, "Stripe not used")(StripeTests)
if stripe_used:
    charge = "stripe.Charge"
    StripeTests.test_charge = mock.patch(charge)(StripeTests.test_charge)


class TaxationTests(TestCase):

    def test_default_handler_exists(self):
        '''
        Ensure that the handler specified in default settings exists as well as
        the default setting itself.
        '''
        from mezzanine.utils.importing import import_dotted_path

        settings.use_editable()
예제 #6
0
파일: utils.py 프로젝트: 10sr/hue
        yield calls
    finally:
        setattr(logger, log_level, orig)


class TransRealMixin(object):
    """This is the only way to reset the translation machinery. Otherwise
    the test suite occasionally fails because of global state pollution
    between tests."""
    def flush_caches(self):
        from django.utils.translation import trans_real
        trans_real._translations = {}
        trans_real._active = local()
        trans_real._default = None
        trans_real._accepted = {}
        trans_real._checked_languages = {}

    def tearDown(self):
        self.flush_caches()
        super(TransRealMixin, self).tearDown()


# On OSes that don't provide tzset (Windows), we can't set the timezone
# in which the program runs. As a consequence, we must skip tests that
# don't enforce a specific timezone (with timezone.override or equivalent),
# or attempt to interpret naive datetimes in the default timezone.

requires_tz_support = skipUnless(TZ_SUPPORT,
        "This test relies on the ability to run a program in an arbitrary "
        "time zone, but your operating system isn't able to do that.")
예제 #7
0
        actionChains.move_to_element(
            self.sel_query('.phase-cell[phase-id="{0}"]'.format(phase.pk)))
        actionChains.click(
            self.sel_query('.phase-cell[phase-id="{0}"] .delete_phase'.format(
                phase.pk)))
        actionChains.perform()
        time.sleep(0.2)
        self.sel_query("#confirm-delete-btn").click()
        time.sleep(0.5)

        # delete last story
        actionChains = ActionChains(self.browser)
        actionChains.move_to_element(
            self.sel_query('.story-cell[story-id="{0}"]'.format(story.pk)))
        actionChains.click(
            self.sel_query('.story-cell[story-id="{0}"] .delete_story'.format(
                story.pk)))
        actionChains.perform()
        time.sleep(0.2)
        self.sel_query("#confirm-delete-btn").click()
        time.sleep(0.5)

        # Only one story theme and phase should exists
        self.assertFalse(Story.objects.exists())
        self.assertTrue(Theme.objects.get())
        self.assertTrue(Theme.objects.get())


StoryMapLiveTest = skipUnless('SELENIUM' in os.environ,
                              "SELENIUM not enabled")(StoryMapLiveTest)
예제 #8
0
파일: tests.py 프로젝트: chadcatlett/django
    def test_invalid_keys(self):
        """
        On memcached, we don't introduce a duplicate key validation
        step (for speed reasons), we just let the memcached API
        library raise its own exception on bad keys. Refs #6447.

        In order to be memcached-API-library agnostic, we only assert
        that a generic exception of some kind is raised.

        """
        # memcached does not allow whitespace or control characters in keys
        self.assertRaises(Exception, self.cache.set, 'key with spaces', 'value')
        # memcached limits key length to 250
        self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
MemcachedCacheTests = unittest.skipUnless(settings.CACHE_BACKEND.startswith('memcached://'), "memcached not available")(MemcachedCacheTests)

class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
    """
    Specific test cases for the file-based cache.
    """
    def setUp(self):
        self.dirname = tempfile.mkdtemp()
        self.cache = get_cache('file://%s?max_entries=30' % self.dirname)

    def test_hashing(self):
        """Test that keys are hashed into subdirectories correctly"""
        self.cache.set("foo", "bar")
        keyhash = md5_constructor("foo").hexdigest()
        keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
        self.assert_(os.path.exists(keypath))
예제 #9
0
        step (for speed reasons), we just let the memcached API
        library raise its own exception on bad keys. Refs #6447.

        In order to be memcached-API-library agnostic, we only assert
        that a generic exception of some kind is raised.

        """
        # memcached does not allow whitespace or control characters in keys
        self.assertRaises(Exception, self.cache.set, 'key with spaces',
                          'value')
        # memcached limits key length to 250
        self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')


MemcachedCacheTests = unittest.skipUnless(
    settings.CACHE_BACKEND.startswith('memcached://'),
    "memcached not available")(MemcachedCacheTests)


class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
    """
    Specific test cases for the file-based cache.
    """
    def setUp(self):
        self.dirname = tempfile.mkdtemp()
        self.cache = get_cache('file://%s?max_entries=30' % self.dirname)

    def test_hashing(self):
        """Test that keys are hashed into subdirectories correctly"""
        self.cache.set("foo", "bar")
        keyhash = md5_constructor("foo").hexdigest()
예제 #10
0
파일: base2.py 프로젝트: 593in/transifex
 def decorator(func):
     msg = "%s skipped. Please implement it in your project path."%func_name
     if settings.TX_ROOT != settings.PROJECT_PATH:
         logger.debug(msg)
     return unittest.skipUnless(settings.TX_ROOT == settings.PROJECT_PATH, msg)
예제 #11
0
파일: tests.py 프로젝트: mrefish/cartridge
        # Assertion
        mock_charge.create.assert_called_with(
            amount=2237,
            currency="usd",
            card={'number': "4242424242424242",
                  'exp_month': "06",
                  'exp_year': "14",
                  'address_line1': "123 Evergreen Terrace",
                  'address_city': "Springfield",
                  'address_state': "WA",
                  'address_zip': "01234",
                  'country': "USA"})


StripeTests = skipUnless(stripe_used, "Stripe not used")(StripeTests)
if stripe_used:
    charge = "stripe.Charge"
    StripeTests.test_charge = mock.patch(charge)(StripeTests.test_charge)


class TaxationTests(TestCase):

    def test_default_handler_exists(self):
        '''
        Ensure that the handler specified in default settings exists as well as
        the default setting itself.
        '''
        from mezzanine.utils.importing import import_dotted_path

        settings.use_editable()
예제 #12
0
        phase = Phase.objects.get(name="Phase 0")
        actionChains = ActionChains(self.browser)
        actionChains.move_to_element(self.sel_query(
            '.phase-cell[phase-id="{0}"]'.format(phase.pk)))
        actionChains.click(self.sel_query(
            '.phase-cell[phase-id="{0}"] .delete_phase'.format(phase.pk)))
        actionChains.perform()
        time.sleep(0.2)
        self.sel_query("#confirm-delete-btn").click()
        time.sleep(0.5)

        # delete last story
        actionChains = ActionChains(self.browser)
        actionChains.move_to_element(self.sel_query(
            '.story-cell[story-id="{0}"]'.format(story.pk)))
        actionChains.click(self.sel_query(
            '.story-cell[story-id="{0}"] .delete_story'.format(story.pk)))
        actionChains.perform()
        time.sleep(0.2)
        self.sel_query("#confirm-delete-btn").click()
        time.sleep(0.5)

        # Only one story theme and phase should exists
        self.assertFalse(Story.objects.exists())
        self.assertTrue(Theme.objects.get())
        self.assertTrue(Theme.objects.get())


StoryMapLiveTest = skipUnless(
    'SELENIUM' in os.environ, "SELENIUM not enabled")(StoryMapLiveTest)
예제 #13
0
            os.path.abspath(os.path.join(settings.HERE, "..", "screenshots")),
        )
        # add some value to context
        result = Popen([args], shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
        stdout, stderr = result.communicate()
        print stdout
        if result.returncode > 0:
            # some error here, display the reason
            self.fail(stderr if stderr else stdout)

    def test_screenshots(self):
        user = UserFactory.create(email="*****@*****.**", password="******", full_name="Test user")
        project = create_sample_project(user)
        org = create_sample_organization(user)
        project_org = create_sample_project(user, project_kwargs={"org": org})
        org_bl = create_org_sample_backlog(user, backlog_kwargs={"org": org})
        project_bl = create_org_sample_backlog(user, backlog_kwargs={"project": project})
        project_org_bl = create_org_sample_backlog(user, backlog_kwargs={"project": project_org})
        for s in range(2):
            create_sample_story(user, story_kwargs={"backlog": project_bl, "project": project}, backlog=project_bl)
        for s in range(2):
            create_org_sample_story(
                user, story_kwargs={"backlog": project_org_bl, "project": project_org}, backlog=project_org_bl
            )
        for s in range(2):
            create_sample_story(user, story_kwargs={"backlog": org_bl, "project": project_org}, backlog=org_bl)
        self.take_screenshot(reverse("home"))


ScreenshotsTest = skipUnless("SCREENSHOTS" in os.environ, "SCREENSHOTS not enabled")(ScreenshotsTest)
예제 #14
0
        project_bl = create_org_sample_backlog(
            user, backlog_kwargs={'project': project})
        project_org_bl = create_org_sample_backlog(
            user, backlog_kwargs={'project': project_org})
        for s in range(2):
            create_sample_story(user,
                                story_kwargs={
                                    'backlog': project_bl,
                                    'project': project
                                },
                                backlog=project_bl)
        for s in range(2):
            create_org_sample_story(user,
                                    story_kwargs={
                                        'backlog': project_org_bl,
                                        'project': project_org
                                    },
                                    backlog=project_org_bl)
        for s in range(2):
            create_sample_story(user,
                                story_kwargs={
                                    'backlog': org_bl,
                                    'project': project_org
                                },
                                backlog=org_bl)
        self.take_screenshot(reverse("home"))


ScreenshotsTest = skipUnless('SCREENSHOTS' in os.environ,
                             "SCREENSHOTS not enabled")(ScreenshotsTest)
예제 #15
0
            user = authenticate(username=self.username, password=self.password)

    ####################################################################

    def test_get_user(self):
        """Tests that, with cachetree auth backend enabled, get_user uses the
        cache.
        """
        backend = CachedModelBackend()
        user = backend.get_user(user_id=self.user.id)
        with self.assertNumQueries(0):
            user = backend.get_user(user_id=self.user.id)


CachetreeAuthTestCase = skipUnless(
    "django.contrib.auth" in django_settings.INSTALLED_APPS,
    "django.contrib.auth is not in INSTALLED_APPS")(CachetreeAuthTestCase)

########################################################################


class CachetreeInvalidationTestCase(CachetreeBaseTestCase):
    """Test cachetree's invalidation functionality.
    """

    ####################################################################

    def get_test_settings(self):
        """Returns the cachetree settings to be used for the test.
        """
        test_settings = super(CachetreeInvalidationTestCase,
예제 #16
0
 def decorator(func):
     msg = "%s skipped. Please implement it in your project path." % func_name
     if settings.TX_ROOT != settings.PROJECT_PATH:
         logger.debug(msg)
     return unittest.skipUnless(settings.TX_ROOT == settings.PROJECT_PATH,
                                msg)
예제 #17
0
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from django.utils.unittest import skipUnless

from .models import Book, BookSigning

TZ_SUPPORT = hasattr(time, 'tzset')

# On OSes that don't provide tzset (Windows), we can't set the timezone
# in which the program runs. As a consequence, we must skip tests that
# don't enforce a specific timezone (with timezone.override or equivalent),
# or attempt to interpret naive datetimes in the default timezone.

requires_tz_support = skipUnless(
    TZ_SUPPORT,
    "This test relies on the ability to run a program in an arbitrary "
    "time zone, but your operating system isn't able to do that.")


def _make_books(n, base_date):
    for i in range(n):
        b = Book.objects.create(name='Book %d' % i,
                                slug='book-%d' % i,
                                pages=100 + i,
                                pubdate=base_date - datetime.timedelta(days=i))


class ArchiveIndexViewTests(TestCase):
    fixtures = ['generic-views-test-data.json']
    urls = 'regressiontests.generic_views.urls'
예제 #18
0
                asset = StaticAsset(path)
                try:
                    default_asset_cache.get_name(asset)
                except:
                    continue
                else:
                    yield asset


def get_test_asset(*valid_extensions):
    for asset in iter_test_assets(valid_extensions):
        return asset
    return None


skipUnlessTestAsset = skipUnless(get_test_asset(), "No static assets could be found in the static files storage.")


get_test_javascript_asset = partial(get_test_asset, ".js")
skipUnlessTestJavascriptAsset = skipUnless(get_test_javascript_asset(), "No static javascript assets could be found in the static files storage.")


get_test_stylesheet_asset = partial(get_test_asset, ".css")
skipUnlessTestStylesheetAsset = skipUnless(get_test_stylesheet_asset(), "No static stylesheet assets could be found in the static files storage.")


def get_test_thumbnail_asset():
    for asset in iter_test_assets((".jpg", ".jpeg", ".png")):
        try:
            image_size = open_image(asset).size
        except:
예제 #19
0
파일: tests.py 프로젝트: igloosec/hue
from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
from django.test import (TransactionTestCase, skipIfDBFeature,
    skipUnlessDBFeature)
from django.utils import unittest

from multiple_database.tests import TestRouter

from .models import Person

# Some tests require threading, which might not be available. So create a
# skip-test decorator for those test functions.
try:
    import threading
except ImportError:
    threading = None
requires_threading = unittest.skipUnless(threading, 'requires threading')


class SelectForUpdateTests(TransactionTestCase):

    available_apps = ['select_for_update']

    def setUp(self):
        transaction.enter_transaction_management()
        self.person = Person.objects.create(name='Reinhardt')

        # We have to commit here so that code in run_select_for_update can
        # see this data.
        transaction.commit()

        # We need another database connection to test that one connection
예제 #20
0
파일: tests.py 프로젝트: graingert/django
        transaction.managed(True)
        self.assertEqual(connection.isolation_level, self._read_committed)

        transaction.enter_transaction_management()
        self.assertEqual(connection.isolation_level, self._read_committed)

        transaction.leave_transaction_management()
        self.assertEqual(connection.isolation_level, self._read_committed)

        transaction.leave_transaction_management()
        self.assertEqual(connection.isolation_level, self._autocommit)

    def tearDown(self):
        connections[DEFAULT_DB_ALIAS] = self._old_backend

TestPostgresAutocommit = skipUnless(connection.vendor == 'postgresql',
    "This test only valid for PostgreSQL")(TestPostgresAutocommit)
TestPostgresAutoCommit = skipUnlessDBFeature('supports_transactions')(
    TestPostgresAutocommit)


class TestManyToManyAddTransaction(TransactionTestCase):
    def test_manyrelated_add_commit(self):
        "Test for https://code.djangoproject.com/ticket/16818"
        a = M2mA.objects.create()
        b = M2mB.objects.create(fld=10)
        a.others.add(b)

        # We're in a TransactionTestCase and have not changed transaction
        # behavior from default of "autocommit", so this rollback should not
        # actually do anything. If it does in fact undo our add, that's a bug
        # that the bulk insert was not auto-committed.