Python django.conf.settings.TESTING Examples

The following are 14 code examples for showing how to use django.conf.settings.TESTING(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: lego   Author: webkom   File: apps.py    License: MIT License 6 votes vote down vote up
def ready(self):
        super().ready()
        """
        This magic executes modules named search_indexes in every installed app. Search indexes
        is registered this way.
        """
        if not settings.TESTING:
            # Simple way to initialize the search backend. We may change this in the future.
            if settings.SEARCH_BACKEND == "elasticsearch":
                search_backed = ElasticsearchBackend()
            elif settings.SEARCH_BACKEND == "postgres":
                search_backed = PostgresBackend()
            else:
                raise ValueError("Invalid search backend")

            search_backed.set_up()
            backend.current_backend = search_backed

            autodiscover_modules("search_indexes")
            from .signals import post_save_callback, post_delete_callback  # noqa 
Example 2
Project: kpi   Author: kobotoolbox   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def save_kobocat_user(sender, instance, created, raw, **kwargs):
    """
    Sync auth_user table between KPI and KC, and, if the user is newly created,
    grant all KoBoCAT model-level permissions for the content types listed in
    `settings.KOBOCAT_DEFAULT_PERMISSION_CONTENT_TYPES`
    """
    if not settings.TESTING:
        KobocatUser.sync(instance)

        if created:
            # FIXME: If this fails, the next attempt results in
            #   IntegrityError: duplicate key value violates unique constraint
            #   "auth_user_username_key"
            # and decorating this function with `transaction.atomic` doesn't
            # seem to help. We should roll back the KC user creation if
            # assigning model-level permissions fails
            grant_kc_model_level_perms(instance) 
Example 3
Project: open-ledger   Author: cc-archive   File: forms.py    License: MIT License 6 votes vote down vote up
def clean_description(self):
        desc = self.cleaned_data['description']
        if settings.TESTING:
            check_spam = False
        else:
            akismet = Akismet(settings.AKISMET_KEY, blog="CC Search")
            check_spam = akismet.check(self.request.get_host(),
                                  user_agent=self.request.META.get('user-agent'),
                                  comment_author=self.request.user.username,
                                  comment_content=desc)
        wordfilter = Wordfilter()
        check_words = wordfilter.blacklisted(desc)
        if check_spam or check_words:
            raise forms.ValidationError("This description failed our spam or profanity check; the description has not been updated.")

        return desc 
Example 4
Project: open-humans   Author: OpenHumans   File: signals.py    License: MIT License 6 votes vote down vote up
def member_post_save_webhook_cb(
    sender, instance, created, raw, update_fields, **kwargs
):
    """
    Send a webhook alert when a user signs up.
    """
    if raw or not created or settings.TESTING or settings.ENV != "production":
        return

    try:
        requests.post(
            settings.ZAPIER_WEBHOOK_URL,
            json={
                "type": "member-created",
                "name": instance.name,
                "username": instance.user.username,
                "email": instance.primary_email.email,
            },
        )
    except:  # pylint: disable=bare-except
        # monitoring should never interfere with the operation of the site
        pass 
Example 5
Project: lego   Author: webkom   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        if not settings.TESTING:
            from lego.apps.events.models import Event
            from lego.apps.events.signals import event_save_callback

            post_save.connect(event_save_callback, sender=Event) 
Example 6
Project: lego   Author: webkom   File: events.py    License: MIT License 5 votes vote down vote up
def disable_on_test(signal_handler):
    """
    Decorator that turns off signal handlers when loading fixture data and running tests.
    """

    @wraps(signal_handler)
    def wrapper(*args, **kwargs):
        if kwargs.get("raw") or settings.TESTING:
            return
        return signal_handler(*args, **kwargs)

    return wrapper 
Example 7
Project: kpi   Author: kobotoolbox   File: signals.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def save_kobocat_token(sender, instance, **kwargs):
    """
    Sync AuthToken table between KPI and KC
    """
    if not settings.TESTING:
        KobocatToken.sync(instance) 
Example 8
Project: kpi   Author: kobotoolbox   File: signals.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_kobocat_token(sender, instance, **kwargs):
    """
    Delete corresponding record from KC AuthToken table
    """
    if not settings.TESTING:
        try:
            KobocatToken.objects.get(pk=instance.pk).delete()
        except KobocatToken.DoesNotExist:
            pass 
Example 9
Project: open-ledger   Author: cc-archive   File: signals.py    License: MIT License 5 votes vote down vote up
def update_search_index(sender, instance, **kwargs):
    """When an Image instance is saved, tell the search engine about it."""
    if not settings.TESTING:
        _update_search_index(instance) 
Example 10
Project: open-humans   Author: OpenHumans   File: views.py    License: MIT License 5 votes vote down vote up
def toggle_data(self, user, source, public):
        if source not in get_source_labels() and not source.startswith(
            "direct-sharing-"
        ):
            error_msg = (
                "Public sharing toggle attempted for "
                'unexpected source "{}"'.format(source)
            )
            django_messages.error(self.request, error_msg)

            if not settings.TESTING:
                raven_client.captureMessage(error_msg)
            return
        project = id_label_to_project(source)
        project_membership = DataRequestProjectMember.objects.get(
            member=user.member, project=project
        )

        participant = user.member.public_data_participant
        access, _ = PublicDataAccess.objects.get_or_create(
            participant=participant, project_membership=project_membership
        )
        access.is_public = False
        if public == "True":
            if not project.no_public_data:
                access.is_public = True
        access.save()

        if (
            project.approved
            and not ActivityFeed.objects.filter(
                member=user.member, project=project, action="publicly-shared"
            ).exists()
        ):
            event = ActivityFeed(
                member=user.member, project=project, action="publicly-shared"
            )
            event.save() 
Example 11
Project: django-uniauth   Author: lgoodridge   File: test_simple.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_settings(self):
        """
        Ensure the test settings module works as expected
        """
        from django.conf import settings
        self.assertTrue(settings.TESTING)
        self.assertEqual(settings.LOGIN_URL, "/simple/login/")
        with self.settings(UNIAUTH_LOGIN_DISPLAY_STANDARD=False):
            self.assertFalse(settings.UNIAUTH_LOGIN_DISPLAY_STANDARD) 
Example 12
Project: astrobin   Author: astrobin   File: image.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        image = self.get_object()
        alias = kwargs.pop('alias')
        r = kwargs.pop('r')
        opts = {
            'revision_label': r,
            'animated': 'animated' in self.request.GET,
            'insecure': 'insecure' in self.request.GET,
        }

        force = request.GET.get('force')
        if force is not None:
            image.thumbnail_invalidate()

        sync = request.GET.get('sync')
        if sync is not None:
            opts['sync'] = True

        if settings.TESTING:
            thumb = image.thumbnail_raw(alias, opts)
            if thumb:
                return redirect(thumb.url)
            return None

        url = image.thumbnail(alias, opts)
        return redirect(smart_unicode(url)) 
Example 13
Project: canvas   Author: canvasnetworks   File: footer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def call_update_in_new_process(self, enabled=not settings.TESTING):
        if enabled and self.comment.reply_content:
            for _ in xrange(knobs.FOOTER_UPDATE_ATTEMPTS):
                try:
                    subprocess.check_call(
                        ["env", "python", "/var/canvas/website/manage.py", "generate_footer", str(self.comment.id)],
                        env={'DISPLAY': ':0'}
                    )
                except subprocess.CalledProcessError:
                    continue
                break 
Example 14
Project: open-humans   Author: OpenHumans   File: signals.py    License: MIT License 4 votes vote down vote up
def member_pre_save_cb(sender, instance, raw, **kwargs):
    """
    Subscribe or unsubscribe a user from Mailchimp.
    """
    if raw or settings.TESTING:
        return

    try:
        member = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        pass
    else:
        if member.newsletter == instance.newsletter:
            return

    if not settings.MAILCHIMP_API_KEY:
        logger.warn(
            "User changed email preference but no Mailchimp API key "
            "has been specified, set MAILCHIMP_API_KEY."
        )

        return

    mc = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY)

    try:
        address = instance.primary_email.email
    except AttributeError:
        # We're not sure why the callback is firing an extra time, before
        # SignupView.create_account runs (when email not yet saved).
        return

    if instance.newsletter:
        try:
            mc.lists.subscribe(
                settings.MAILCHIMP_NEWSLETTER_LIST,
                {"email": address},
                double_optin=False,
                update_existing=True,
            )
        except mailchimp.ListAlreadySubscribedError:
            logger.info('"%s" was already subscribed', address)
        except (mailchimp.Error, ValueError) as e:
            logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e)
    else:
        try:
            mc.lists.unsubscribe(
                settings.MAILCHIMP_NEWSLETTER_LIST,
                {"email": address},
                send_goodbye=False,
                send_notify=False,
            )
        except (mailchimp.ListNotSubscribedError, mailchimp.EmailNotExistsError):
            logger.info('"%s" was already unsubscribed', address)
        except (mailchimp.Error, ValueError) as e:
            logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e)