Python django.test.override_settings() Examples

The following are 30 code examples for showing how to use django.test.override_settings(). 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.test , or try the search function .

Example 1
Project: django-hijack-admin   Author: arteria   File: test_checks.py    License: MIT License 6 votes vote down vote up
def test_check_custom_user_model_default_admin(self):
            # Django doesn't re-register admins when using `override_settings`,
            # so we have to do it manually in this test case.
            admin.site.register(get_user_model(), UserAdmin)

            warnings = checks.check_custom_user_model(HijackAdminConfig)
            expected_warnings = [
                Warning(
                    'django-hijack-admin does not work out the box with a custom user model.',
                    hint='Please mix HijackUserAdminMixin into your custom UserAdmin.',
                    obj=settings.AUTH_USER_MODEL,
                    id='hijack_admin.W001',
                )
            ]
            self.assertEqual(warnings, expected_warnings)

            admin.site.unregister(get_user_model()) 
Example 2
Project: django-phone-verify   Author: CuriousLearner   File: test_api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_security_code_session_token_verification_api(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        f.create_verification(
            security_code=SECURITY_CODE,
            phone_number=PHONE_NUMBER,
            session_token=SESSION_TOKEN,
        )
        url = reverse("phone-verify")
        data = {
            "phone_number": PHONE_NUMBER,
            "security_code": SECURITY_CODE,
            "session_token": SESSION_TOKEN,
        }
        response = client.json.post(url, data=data)
        assert response.status_code == 200
        assert response.data["message"] == "Security code is valid." 
Example 3
Project: django-phone-verify   Author: CuriousLearner   File: test_api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_phone_verification_with_incomplete_payload(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        f.create_verification(
            security_code=SECURITY_CODE,
            phone_number=PHONE_NUMBER,
            session_token=SESSION_TOKEN,
        )
        url = reverse("phone-verify")
        data = {"phone_number": PHONE_NUMBER}
        response = client.json.post(url, data=data)
        assert response.status_code == 400
        response_data = json.loads(json.dumps(response.data))
        assert response_data["session_token"][0] == "This field is required."
        assert response_data["security_code"][0] == "This field is required."

        data = {"security_code": SECURITY_CODE}
        response = client.json.post(url, data=data)
        assert response.status_code == 400
        response_data = json.loads(json.dumps(response.data))
        assert response_data["phone_number"][0] == "This field is required." 
Example 4
Project: django-phone-verify   Author: CuriousLearner   File: test_api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_check_security_code_expiry(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        f.create_verification(
            security_code=SECURITY_CODE,
            phone_number=PHONE_NUMBER,
            session_token=SESSION_TOKEN,
        )
        time.sleep(2)
        url = reverse("phone-verify")
        data = {
            "phone_number": PHONE_NUMBER,
            "security_code": SECURITY_CODE,
            "session_token": SESSION_TOKEN,
        }
        response = client.json.post(url, data=data)
        response_data = json.loads(json.dumps(response.data))

        backend_cls = _get_backend_cls(backend)

        if backend_cls in backends:
            assert response.status_code == 400
            assert response_data["non_field_errors"][0] == "Security code has expired"
        elif backend_cls in sandbox_backends:
            # Sandbox Backend returns a 200 status code when verifying security code expiry
            assert response.status_code == 200 
Example 5
Project: django-phone-verify   Author: CuriousLearner   File: test_services.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_exception_is_logged_when_raised(client, mocker, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        mock_send_verification = mocker.patch(
            "phone_verify.services.PhoneVerificationService.send_verification"
        )
        mock_logger = mocker.patch("phone_verify.services.logger")
        backend_cls = _get_backend_cls(backend)
        if (
            backend_cls == "nexmo.NexmoBackend"
            or backend_cls == "nexmo.NexmoSandboxBackend"
        ):
            exc = ClientError()
            mock_send_verification.side_effect = exc
        elif (
            backend_cls == "twilio.TwilioBackend"
            or backend_cls == "twilio.TwilioSandboxBackend"
        ):
            exc = TwilioRestException(status=mocker.Mock(), uri=mocker.Mock())
            mock_send_verification.side_effect = exc
        send_security_code_and_generate_session_token(phone_number="+13478379634")
        mock_logger.error.assert_called_once_with(
            f"Error in sending verification code to +13478379634: {exc}"
        ) 
Example 6
Project: django-phone-verify   Author: CuriousLearner   File: test_backends.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_send_bulk_sms(client, mocker, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        backend_import = settings.PHONE_VERIFICATION["BACKEND"]
        backend_cls = import_string(backend_import)
        cls_obj = backend_cls(**settings.PHONE_VERIFICATION["OPTIONS"])

        mock_send_sms = mocker.patch(f"{backend_import}.send_sms")
        numbers = ["+13478379634", "+13478379633", "+13478379632"]
        message = "Fake message"

        cls_obj.send_bulk_sms(numbers, message)
        assert mock_send_sms.called
        assert mock_send_sms.call_count == 3
        mock_send_sms.assert_has_calls(
            [
                mocker.call(number=numbers[0], message=message),
                mocker.call(number=numbers[1], message=message),
                mocker.call(number=numbers[2], message=message),
            ]
        ) 
Example 7
Project: resolwe   Author: genialis   File: test_runner.py    License: Apache License 2.0 6 votes vote down vote up
def _prepare_settings():
    """Prepare and apply settings overrides needed for testing."""
    # Override container name prefix setting.
    resolwe_settings.FLOW_EXECUTOR_SETTINGS[
        "CONTAINER_NAME_PREFIX"
    ] = "{}_{}_{}".format(
        resolwe_settings.FLOW_EXECUTOR_SETTINGS.get("CONTAINER_NAME_PREFIX", "resolwe"),
        # NOTE: This is necessary to avoid container name clashes when tests are run from
        # different Resolwe code bases on the same system (e.g. on a CI server).
        get_random_string(length=6),
        os.path.basename(resolwe_settings.FLOW_EXECUTOR_SETTINGS["DATA_DIR"]),
    )
    return override_settings(
        CELERY_ALWAYS_EAGER=True,
        FLOW_EXECUTOR=resolwe_settings.FLOW_EXECUTOR_SETTINGS,
        FLOW_MANAGER=resolwe_settings.FLOW_MANAGER_SETTINGS,
    ) 
Example 8
Project: resolwe   Author: genialis   File: test_runner.py    License: Apache License 2.0 6 votes vote down vote up
def run_suite(self, suite, **kwargs):
        """Run the test suite with manager workers in the background."""
        # Due to the way the app modules are imported, there's no way to
        # statically override settings with TEST overrides before e.g.
        # resolwe.flow.managers.manager is loaded somewhere in the code
        # (the most problematic files are signals.py and
        # resolwe.test.testcases.process); the only realistic mechanism
        # is to override later and call some sort of commit method in
        # the manager.

        keep_data_override = override_settings(FLOW_MANAGER_KEEP_DATA=self.keep_data)
        keep_data_override.__enter__()

        if self.parallel > 1:
            return super().run_suite(suite, **kwargs)

        return _run_manager(super().run_suite, suite, **kwargs) 
Example 9
Project: Pytition   Author: pytition   File: tests_PetitionTransfer.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_transfer_view(self):
        self.login("julia")
        org = Organization.objects.get(name="Les Amis de la Terre")
        user = PytitionUser.objects.get(user__username="julia")
        user_petition = Petition.objects.create(title="Petition 1", user=user)
        url = reverse("transfer_petition", args=[user_petition.id])

        response = self.client.post(url, data={"new_owner_type": "org", "new_owner_name": org.slugname}, follow=True)
        self.assertEqual(response.status_code, 200)
        user_petition = Petition.objects.get(id=user_petition.id)
        self.assertEqual(user_petition.org, org)

        response = self.client.post(url, data={"new_owner_type": "user", "new_owner_name": user.user.username}, follow=True)
        self.assertEqual(response.status_code, 200)
        user_petition = Petition.objects.get(id=user_petition.id)
        self.assertEqual(user_petition.user, user)

        with override_settings(DISABLE_USER_PETITION=True):
            user_petition = Petition.objects.create(title="Petition 1", org=org)
            response = self.client.post(url, data={"new_owner_type": "user", "new_owner_name": user.user.username}, follow=True)
            self.assertContains(response, "Users are not allowed to transfer petitions to organizations on this instance.")
            user_petition = Petition.objects.get(id=user_petition.id)
            self.assertIsNone(user_petition.user) 
Example 10
Project: OasisPlatform   Author: OasisLMF   File: test_data_files.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_data_file_is_unknown_format___response_is_200(self):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                cmf = fake_data_file()

                response = self.app.post(
                    cmf.get_absolute_data_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file.tar', b'an-unknown-mime-format'),
                    ),
                )

                self.assertEqual(200, response.status_code) 
Example 11
Project: OasisPlatform   Author: OasisLMF   File: test_data_files.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_data_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                cmf = fake_data_file()

                self.app.post(
                    cmf.get_absolute_data_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
                    ),
                )

                response = self.app.get(
                    cmf.get_absolute_data_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                )

                self.assertEqual(response.body, file_content)
                self.assertEqual(response.content_type, content_type) 
Example 12
Project: OasisPlatform   Author: OasisLMF   File: test_analysis_model.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_state_is_ready___run_is_started(self, status, task_id):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                res_factory = FakeAsyncResultFactory(target_task_id=task_id)
                analysis = fake_analysis(status=status, run_task_id=task_id, input_file=fake_related_file(), settings_file=fake_related_file())
                initiator = fake_user()

                sig_res = Mock()
                sig_res.delay.return_value = res_factory(task_id)

                with patch('src.server.oasisapi.analyses.models.Analysis.run_analysis_signature', PropertyMock(return_value=sig_res)):
                    analysis.run(initiator)

                    sig_res.link.assert_called_once_with(record_run_analysis_result.s(analysis.pk, initiator.pk))
                    sig_res.link_error.assert_called_once_with(
                        signature('on_error', args=('record_run_analysis_failure', analysis.pk, initiator.pk), queue=analysis.model.queue_name)
                    )
                    sig_res.delay.assert_called_once_with() 
Example 13
Project: OasisPlatform   Author: OasisLMF   File: test_analysis_model.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_state_is_running_or_generating_inputs___validation_error_is_raised_revoke_is_not_called(self, status, task_id):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                res_factory = FakeAsyncResultFactory(target_task_id=task_id)
                initiator = fake_user()

                sig_res = Mock()
                with patch('src.server.oasisapi.analyses.models.Analysis.generate_input_signature', PropertyMock(return_value=sig_res)):
                    analysis = fake_analysis(status=status, run_task_id=task_id, portfolio=fake_portfolio(location_file=fake_related_file()))

                    with self.assertRaises(ValidationError) as ex:
                        analysis.generate_inputs(initiator)

                    self.assertEqual({'status': [
                        'Analysis status must be one of [NEW, INPUTS_GENERATION_ERROR, INPUTS_GENERATION_CANCELLED, READY, RUN_COMPLETED, RUN_CANCELLED, RUN_ERROR]'
                    ]}, ex.exception.detail)
                    self.assertEqual(status, analysis.status)
                    self.assertFalse(res_factory.revoke_called) 
Example 14
Project: OasisPlatform   Author: OasisLMF   File: test_analysis_model.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_portfolio_has_no_location_file___validation_error_is_raised_revoke_is_not_called(self, task_id):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                res_factory = FakeAsyncResultFactory(target_task_id=task_id)
                initiator = fake_user()

                sig_res = Mock()
                with patch('src.server.oasisapi.analyses.models.Analysis.generate_input_signature', PropertyMock(return_value=sig_res)):
                    analysis = fake_analysis(status=Analysis.status_choices.NEW, run_task_id=task_id)

                    with self.assertRaises(ValidationError) as ex:
                        analysis.generate_inputs(initiator)

                    self.assertEqual({'portfolio': ['"location_file" must not be null']}, ex.exception.detail)

                    self.assertEqual(Analysis.status_choices.NEW, analysis.status)
                    self.assertFalse(res_factory.revoke_called) 
Example 15
Project: OasisPlatform   Author: OasisLMF   File: test_analysis_api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_settings_file_is_not_a_valid_format___response_is_400(self):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                analysis = fake_analysis()

                response = self.app.post(
                    analysis.get_absolute_settings_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file.tar', b'content'),
                    ),
                    expect_errors=True,
                )

                self.assertEqual(400, response.status_code) 
Example 16
Project: OasisPlatform   Author: OasisLMF   File: test_analysis_api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_run_traceback_file_is_not_valid_format___post_response_is_405(self):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                analysis = fake_analysis()

                response = self.app.post(
                    analysis.get_absolute_run_traceback_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file.csv', b'content'),
                    ),
                    expect_errors=True,
                )

                self.assertEqual(405, response.status_code) 
Example 17
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_accounts_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                self.app.post(
                    portfolio.get_absolute_accounts_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
                    ),
                )

                response = self.app.get(
                    portfolio.get_absolute_accounts_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                )

                self.assertEqual(response.body, file_content)
                self.assertEqual(response.content_type, content_type) 
Example 18
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_location_file_is_not_a_valid_format___response_is_400(self):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                response = self.app.post(
                    portfolio.get_absolute_location_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file.tar', b'content'),
                    ),
                    expect_errors=True,
                )

                self.assertEqual(400, response.status_code) 
Example 19
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_location_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                self.app.post(
                    portfolio.get_absolute_location_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
                    ),
                )

                response = self.app.get(
                    portfolio.get_absolute_location_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                )

                self.assertEqual(response.body, file_content)
                self.assertEqual(response.content_type, content_type) 
Example 20
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_reinsurance_scope_file_is_not_a_valid_format___response_is_400(self):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                response = self.app.post(
                    portfolio.get_absolute_reinsurance_scope_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file.tar', b'content'),
                    ),
                    expect_errors=True,
                )

                self.assertEqual(400, response.status_code) 
Example 21
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_reinsurance_scope_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                self.app.post(
                    portfolio.get_absolute_reinsurance_scope_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
                    ),
                )

                response = self.app.get(
                    portfolio.get_absolute_reinsurance_scope_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                )

                self.assertEqual(response.body, file_content)
                self.assertEqual(response.content_type, content_type) 
Example 22
Project: OasisPlatform   Author: OasisLMF   File: test_portfolio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_reinsurance_info_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
        with TemporaryDirectory() as d:
            with override_settings(MEDIA_ROOT=d):
                user = fake_user()
                portfolio = fake_portfolio()

                self.app.post(
                    portfolio.get_absolute_reinsurance_info_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                    upload_files=(
                        ('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
                    ),
                )

                response = self.app.get(
                    portfolio.get_absolute_reinsurance_info_file_url(),
                    headers={
                        'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
                    },
                )

                self.assertEqual(response.body, file_content)
                self.assertEqual(response.content_type, content_type) 
Example 23
def test_ember_expected_renderer(self):
        """
        The :class:`UserEmber` ViewSet has the ``resource_name`` of 'data'
        so that should be the key in the JSON response.
        """
        url = reverse('user-manual-resource-name', kwargs={'pk': self.miles.pk})

        with override_settings(JSON_API_FORMAT_FIELD_NAMES='dasherize'):
            response = self.client.get(url)
        self.assertEqual(200, response.status_code)

        expected = {
            'data': {
                'type': 'data',
                'id': '2',
                'attributes': {
                    'first-name': 'Miles',
                    'last-name': 'Davis',
                    'email': 'miles@example.com'
                }
            }
        }

        assert expected == response.json() 
Example 24
Project: opencraft   Author: open-craft   File: test_database_server.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test__create_default_exists_settings_differ(self):
        """
        Test that `_create_default` does not create new database server and logs warning
        if database server with same hostname but different username, password, port already exists.
        """
        mysql_hostname = urlparse(settings.DEFAULT_INSTANCE_MYSQL_URL).hostname
        mongodb_hostname = urlparse(settings.DEFAULT_INSTANCE_MONGO_URL).hostname

        MySQLServer.objects._create_default()
        MongoDBServer.objects._create_default()

        # Precondition
        self.assertEqual(MySQLServer.objects.count(), 1)
        self.assertEqual(MongoDBServer.objects.count(), 1)

        with override_settings(
                DEFAULT_INSTANCE_MYSQL_URL='mysql://user:pass@{hostname}'.format(hostname=mysql_hostname),
                DEFAULT_INSTANCE_MONGO_URL='mongodb://user:pass@{hostname}'.format(hostname=mongodb_hostname),
        ):
            MySQLServer.objects._create_default()
            MongoDBServer.objects._create_default()

        # Number of database servers should not have changed
        self.assertEqual(MySQLServer.objects.count(), 1)
        self.assertEqual(MongoDBServer.objects.count(), 1) 
Example 25
Project: django-hijack-admin   Author: arteria   File: test_checks.py    License: MIT License 5 votes vote down vote up
def test_check_custom_user_model(self):
            # Django doesn't re-register admins when using `override_settings`,
            # so we have to do it manually in this test case.
            admin.site.register(get_user_model(), HijackUserAdmin)

            warnings = checks.check_custom_user_model(HijackAdminConfig)
            self.assertFalse(warnings)

            admin.site.unregister(get_user_model()) 
Example 26
Project: django-phone-verify   Author: CuriousLearner   File: test_api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_verified_security_code(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        f.create_verification(
            security_code=SECURITY_CODE,
            phone_number=PHONE_NUMBER,
            session_token=SESSION_TOKEN,
            is_verified=True,
        )
        url = reverse("phone-verify")
        data = {
            "phone_number": PHONE_NUMBER,
            "security_code": SECURITY_CODE,
            "session_token": SESSION_TOKEN,
        }

        backend_cls = _get_backend_cls(backend)

        # Security code verification is restricted to one time
        backend["VERIFY_SECURITY_CODE_ONLY_ONCE"] = True
        response = client.json.post(url, data=data)
        response_data = json.loads(json.dumps(response.data))
        if backend_cls in backends:
            assert response.status_code == 400
            assert (
                response_data["non_field_errors"][0]
                == "Security code is already verified"
            )
        elif backend_cls in sandbox_backends:
            # Sandbox Backend returns a 200 status code when verifying security code
            assert response.status_code == 200

        # Security code verification is not restricted to one time
        backend["VERIFY_SECURITY_CODE_ONLY_ONCE"] = False
        response = client.json.post(url, data=data)
        response_data = json.loads(json.dumps(response.data))
        assert response.status_code == 200
        assert response.data["message"] == "Security code is valid." 
Example 27
Project: django-phone-verify   Author: CuriousLearner   File: test_services.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_exception_is_raised_when_no_settings(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        del settings.PHONE_VERIFICATION
        with pytest.raises(ImproperlyConfigured) as exc:
            importlib.reload(phone_verify.services)
            PhoneVerificationService(phone_number="+13478379634")
            assert exc.info == "Please define PHONE_VERIFICATION in settings" 
Example 28
Project: django-phone-verify   Author: CuriousLearner   File: test_backends.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_error_raised_when_no_backend_specified(client, backend):
    with override_settings(PHONE_VERIFICATION=backend):
        settings.PHONE_VERIFICATION["BACKEND"] = None
        url = reverse("phone-register")
        phone_number = PHONE_NUMBER
        data = {"phone_number": phone_number}
        with pytest.raises(ImproperlyConfigured) as exc:
            client.post(url, data)
            assert (
                exc.info
                == "Please specify BACKEND in PHONE_VERIFICATION within your settings"
            ) 
Example 29
Project: django-mptt-comments   Author: zmrenwu   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_authenticated_user_post_comment(self):
        self.client.login(username='test', password='test')
        response = self.client.post(reverse('mptt-comments-post-comment'), data={})
        self.assertEqual(response.status_code, 400)

    # TODO: override_settings doesn't work as control is module level.
    # see: https://docs.djangoproject.com/en/2.1/topics/testing/tools/#overriding-settings
    # @override_settings(MPTT_COMMENTS_ALLOW_ANONYMOUS=False)
    # def test_doesnt_allow_anonymous_user_post_comment(self):
    #     response = self.client.post(reverse('django_mptt_comments:mptt-comments-post-comment'), data={})
    #     self.assertEqual(response.status_code, 302)
    #     self.assertEqual(response.url, settings.LOGIN_URL + '?next=/post/') 
Example 30
Project: django-herald   Author: worthwhile   File: test_notifications.py    License: MIT License 5 votes vote down vote up
def test_get_sent_from_default(self):
        class TestNotification(EmailNotification):
            from_email = None

        with override_settings(DEFAULT_FROM_EMAIL='default@example.com'):
            self.assertEqual(TestNotification().get_sent_from(), 'default@example.com')