Python django.test() Examples

The following are 30 code examples for showing how to use django.test(). 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module django , 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: conftest.py    License: GNU General Public License v3.0 6 votes vote down vote up
def client():
    """Django Test Client, with some convenient overriden methods.
    """
    from django.test import Client

    class _Client(Client):
        @property
        def json(self):
            """Add json method on the client for sending json type request.

            Usages:
            >>> import json
            >>> url = reverse("phone-verify")
            >>> client.json.get(url)
            >>> client.json.post(url, data=json.dumps(payload))
            """
            return PartialMethodCaller(
                obj=self, content_type='application/json;charset="utf-8"'
            )

    return _Client() 
Example 3
def test_cookie_samesite_none_force_all(self):
        with self.settings(SESSION_COOKIE_SAMESITE='None', SESSION_COOKIE_SAMESITE_FORCE_ALL=True):
            response = self.client.get('/cookies-test/')
            self.assertEqual(response.cookies['sessionid']['samesite'], 'None')
            self.assertEqual(response.cookies['csrftoken']['samesite'], 'None')
            self.assertEqual(response.cookies['custom_cookie']['samesite'], 'None')
            self.assertEqual(response.cookies['zcustom_cookie']['samesite'], 'None')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('custom_cookie=' in cookies_string[1])
            self.assertTrue('; SameSite=None' in cookies_string[1])
            self.assertTrue('csrftoken=' in cookies_string[0])
            self.assertTrue('; SameSite=None' in cookies_string[0])
            self.assertTrue('sessionid=' in cookies_string[2])
            self.assertTrue('; SameSite=None' in cookies_string[2])
            self.assertTrue('zcustom_cookie=' in cookies_string[3])
            self.assertTrue('; SameSite=None' in cookies_string[3]) 
Example 4
def test_cookie_samesite_django30(self):
        # Raise DeprecationWarning for newer versions of Django
        with patch('django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
            with self.assertRaises(DeprecationWarning) as exc:
                self.client.get('/cookies-test/')

            self.assertEqual(exc.exception.args[0], (
                'Your version of Django supports SameSite flag in the cookies mechanism. '
                'You should remove django-cookies-samesite from your project.'
            ))

        with patch('django_cookies_samesite.middleware.django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
            with self.assertRaises(DeprecationWarning) as exc:
                self.client.get('/cookies-test/')

            self.assertEqual(exc.exception.args[0], (
                'Your version of Django supports SameSite flag in the cookies mechanism. '
                'You should remove django-cookies-samesite from your project.'
            )) 
Example 5
def test_cookie_names_changed(self):
        session_name = 'sessionid-test'
        csrf_name = 'csrftoken-test'
        with self.settings(
            SESSION_COOKIE_NAME=session_name,
            CSRF_COOKIE_NAME=csrf_name,
            SESSION_COOKIE_SAMESITE='Lax'
        ):
            response = self.client.get('/cookies-test/')

            self.assertEqual(response.cookies[session_name]['samesite'], 'Lax')
            self.assertEqual(response.cookies[csrf_name]['samesite'], 'Lax')
            cookies_string = sorted(response.cookies.output().split('\r\n'))

            self.assertTrue(csrf_name + '=' in cookies_string[0])
            self.assertTrue('; SameSite=Lax' in cookies_string[0])
            self.assertTrue(session_name + '=' in cookies_string[2])
            self.assertTrue('; SameSite=Lax' in cookies_string[2]) 
Example 6
def test_unsupported_browsers(self, ua_string):
        session_name = 'sessionid-test'
        csrf_name = 'csrftoken-test'

        with self.settings(
            SESSION_COOKIE_NAME=session_name,
            CSRF_COOKIE_NAME=csrf_name,
            SESSION_COOKIE_SAMESITE='Lax'
        ):
            response = self.client.get(
                '/cookies-test/',
                HTTP_USER_AGENT=ua_string,
            )
            self.assertEqual(response.cookies[session_name]['samesite'], '')
            self.assertEqual(response.cookies[csrf_name]['samesite'], '')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('; SameSite=Lax' not in cookies_string[0])
            self.assertTrue('; SameSite=Lax' not in cookies_string[1]) 
Example 7
def test_supported_browsers(self, ua_string):
        session_name = 'sessionid-test'
        csrf_name = 'csrftoken-test'

        with self.settings(
            SESSION_COOKIE_NAME=session_name,
            CSRF_COOKIE_NAME=csrf_name,
            SESSION_COOKIE_SAMESITE='Lax'
        ):
            response = self.client.get(
                '/cookies-test/',
                HTTP_USER_AGENT=ua_string,
            )
            self.assertEqual(response.cookies[session_name]['samesite'], 'Lax')
            self.assertEqual(response.cookies[csrf_name]['samesite'], 'Lax')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('; SameSite=Lax' in cookies_string[0])
            self.assertTrue('; SameSite=Lax' in cookies_string[2]) 
Example 8
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_path_conflict(self):
        """ Check the crazy scenario where an existing metadata object has the same path. """
        old_path = self.product_metadata._path
        self.product_metadata._path = '/products/2/'
        self.product_metadata.save()
        self.assertEqual(self.product_metadata._object_id, self.product.pk)

        # Create a new product that will take the same path
        new_product = Product.objects.create()
        Coverage._meta.get_model('modelinstance').objects.filter(_content_type=self.product_content_type,
                                                                 _object_id=new_product.id).update(title="New Title")

        # This test will not work if we have the id wrong
        if new_product.id != 2:
            raise Exception("Test Error: the product ID is not as expected, this test cannot work.")

        # Check that the existing path was corrected
        product_metadata = Coverage._meta.get_model('modelinstance').objects.get(id=self.product_metadata.id)
        self.assertEqual(old_path, product_metadata._path)

        # Check the new data is available under the correct path
        metadata = get_metadata(path="/products/2/")
        self.assertEqual(metadata.title.value, u"New Title") 
Example 9
Project: scale   Author: ngageoint   File: test_error.py    License: Apache License 2.0 6 votes vote down vote up
def test_create_error_model(self):
        """Validate that a complete Error model is created using JobError
        """

        job_type_name = 'test-job'
        name = 'bad-data'
        title = 'Bad Data'
        description = 'Error received when bad data is detected'
        category = 'DATA'

        error = JobError(job_type_name, name, title, description, category)
        model = error.create_model()
        self.assertEqual(model.name, name)
        self.assertEqual(model.title, title)
        self.assertEqual(model.description, description)
        self.assertEqual(model.category, category)
        self.assertEqual(model.job_type_name, job_type_name) 
Example 10
Project: scale   Author: ngageoint   File: test_mapping.py    License: Apache License 2.0 6 votes vote down vote up
def test_save_models(self):
        """Tests calling JobErrorMapping.save_models() successfully"""

        job_type_name = 'test-job'
        mapping = JobErrorMapping(job_type_name)

        error_1 = JobError(job_type_name, 'mapped_error_1', title='Title', description='Description',
                           category='ALGORITHM')
        error_2 = JobError(job_type_name, 'mapped_error_2', category='DATA')
        mapping.add_mapping(1, error_1)
        mapping.add_mapping(2, error_2)

        # Make sure error models are created successfully
        mapping.save_models()
        self.assertEqual(Error.objects.filter(job_type_name=job_type_name).count(), 2)

        # Make some changes
        error_1.description = 'New description'
        error_2.category = 'ALGORITHM'

        # Make sure error models are updated successfully
        mapping.save_models()
        self.assertEqual(Error.objects.get(name='mapped_error_1').description, 'New description')
        self.assertEqual(Error.objects.get(name='mapped_error_2').category, 'ALGORITHM') 
Example 11
Project: scale   Author: ngageoint   File: test_scale_post_steps.py    License: Apache License 2.0 6 votes vote down vote up
def test_scale_post_steps_successful(self, mock_env_vars, mock_job_exe_manager):
        """Tests successfully executing scale_post_steps."""

        # Set up mocks
        def get_env_vars(name, *args, **kwargs):
            return str(self.job.id) if name == 'SCALE_JOB_ID' else str(self.job_exe.exe_num)
        mock_env_vars.side_effect = get_env_vars
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_type.get_job_interface.return_value.perform_post_steps.return_value = RESULTS
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.id = self.job_exe.id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_id = self.job_exe.job_id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_type_id = self.job_exe.job_type_id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.exe_num = self.job_exe.exe_num

        # Call method to test
        cmd = PostCommand()
        cmd.run_from_argv(['manage.py', 'scale_post_steps'])

        # Check results
        job_exe_output = JobExecutionOutput.objects.get(job_exe_id=self.job_exe.id)
        self.assertDictEqual(job_exe_output.get_output().get_dict(), JOB_RESULTS.get_dict()) 
Example 12
Project: scale   Author: ngageoint   File: test_scale_post_steps.py    License: Apache License 2.0 6 votes vote down vote up
def test_scale_post_steps_no_stderr(self, mock_env_vars, mock_job_exe_manager):
        """Tests successfully executing scale_post_steps."""

        # Set up mocks
        def get_env_vars(name, *args, **kwargs):
            return str(self.job.id) if name == 'SCALE_JOB_ID' else str(self.job_exe.exe_num)
        mock_env_vars.side_effect = get_env_vars
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.stdout = 'something'
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.stderr = None
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_type.get_job_interface.return_value.perform_post_steps.return_value = RESULTS
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.id = self.job_exe.id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_id = self.job_exe.job_id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.job_type_id = self.job_exe.job_type_id
        mock_job_exe_manager.get_job_exe_with_job_and_job_type.return_value.exe_num = self.job_exe.exe_num

        # Call method to test
        cmd = PostCommand()
        cmd.run_from_argv(['manage.py', 'scale_post_steps'])

        # Check results
        job_exe_output = JobExecutionOutput.objects.get(job_exe_id= self.job_exe.id)
        self.assertDictEqual(job_exe_output.get_output().get_dict(), JOB_RESULTS.get_dict()) 
Example 13
Project: scale   Author: ngageoint   File: test_job_interface.py    License: Apache License 2.0 6 votes vote down vote up
def test_input_data_names_must_be_unique(self):
        definition = {
            'command': 'test-command',
            'command_arguments': '${param-1}',
            'version': '1.0',
            'input_data': [{
                'name': 'param-1',
                'type': 'file',
            }, {
                'name': 'param-1',
                'type': 'property',
            }]
        }
        try:
            JobInterface(definition)
            self.fail('Expected invalid job definition to throw an exception')
        except InvalidInterfaceDefinition:
            pass 
Example 14
Project: django-river   Author: javrasya   File: test__migrations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        """
            Remove migration file generated by test if there is any missing.
        """
        clean_migrations() 
Example 15
Project: django-river   Author: javrasya   File: test__migrations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        """
            Remove migration file generated by test if there is any missing.
        """
        clean_migrations() 
Example 16
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 17
def test(self):
        self.assertEqual("eventsourcing.infrastructure.django", DjangoConfig.name) 
Example 18
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_logout_manual(monkeypatch, django_user_model):
    session = SessionStore()
    session['fake_session_key'] = 'fake-session_value'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    factory = RequestFactory()
    request = factory.get('/logout')
    request.session = session

    # Create a fake session ticket and make sure it exists in the db
    SessionTicket.objects.create(
        session_key=session.session_key,
        ticket='fake-ticket'
    )

    user = django_user_model.objects.create_user('test@example.com', '')
    assert user is not None
    request.user = user

    callback_values = {}

    @receiver(cas_user_logout)
    def callback(sender, session, **kwargs):
        callback_values.update(kwargs)
        callback_values['session'] = dict(session)

    LogoutView().get(request)
    if django.VERSION[0] < 2:
        assert request.user.is_anonymous() is True
    else:
        assert request.user.is_anonymous is True

    assert 'user' in callback_values
    assert callback_values['user'] == user
    assert 'session' in callback_values
    assert callback_values['session'].get('fake_session_key') == 'fake-session_value'
    assert 'ticket' in callback_values
    assert callback_values['ticket'] == 'fake-ticket' 
Example 19
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_is_created(monkeypatch, django_user_model):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = True`
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None

    callback_values = {}

    @receiver(cas_user_authenticated)
    def callback(sender, **kwargs):
        callback_values.update(kwargs)

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    assert not django_user_model.objects.filter(
        username='test@example.com',
    ).exists()

    backend = CASBackend()
    user = backend.authenticate(
        ticket='fake-ticket', service='fake-service', request=request,
    )

    assert 'user' in callback_values
    assert callback_values.get('user') == user
    assert callback_values.get('created') is True
    assert 'attributes' in callback_values
    assert 'ticket' in callback_values
    assert 'service' in callback_values 
Example 20
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_already_exists(monkeypatch, django_user_model):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = False`
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None

    callback_values = {}

    @receiver(cas_user_authenticated)
    def callback(sender, **kwargs):
        callback_values.update(kwargs)

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    existing_user = django_user_model.objects.create_user(
        'test@example.com', '',
    )

    backend = CASBackend()
    user = backend.authenticate(
        ticket='fake-ticket', service='fake-service', request=request,
    )

    assert 'user' in callback_values
    assert callback_values.get('user') == user == existing_user
    assert callback_values.get('created') is False
    assert 'attributes' in callback_values
    assert 'ticket' in callback_values
    assert 'service' in callback_values 
Example 21
def test_cookie_samesite_Strict(self):
        with self.settings(SESSION_COOKIE_SAMESITE='Strict'):
            response = self.client.get('/cookies-test/')
            self.assertEqual(response.cookies['sessionid']['samesite'], 'Strict')
            self.assertEqual(response.cookies['csrftoken']['samesite'], 'Strict')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('csrftoken=', cookies_string[0])
            self.assertTrue('; SameSite=Strict', cookies_string[0])
            self.assertTrue('sessionid=', cookies_string[2])
            self.assertTrue('; SameSite=Strict', cookies_string[2]) 
Example 22
def test_cookie_samesite_Lax(self):
        with self.settings(SESSION_COOKIE_SAMESITE='Lax'):
            response = self.client.get('/cookies-test/')
            self.assertEqual(response.cookies['sessionid']['samesite'], 'Lax')
            self.assertEqual(response.cookies['csrftoken']['samesite'], 'Lax')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('csrftoken=' in cookies_string[0])
            self.assertTrue('; SameSite=Lax' in cookies_string[0])
            self.assertTrue('sessionid=' in cookies_string[2])
            self.assertTrue('; SameSite=Lax' in cookies_string[2]) 
Example 23
def test_cookie_samesite_none(self):
        with self.settings(SESSION_COOKIE_SAMESITE='None'):
            response = self.client.get('/cookies-test/')

            self.assertEqual(response.cookies['sessionid']['samesite'], 'None')
            self.assertEqual(response.cookies['csrftoken']['samesite'], 'None')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('csrftoken=' in cookies_string[0])
            self.assertTrue('; SameSite=None' in cookies_string[0])
            self.assertTrue('sessionid=' in cookies_string[2])
            self.assertTrue('; SameSite=None' in cookies_string[2]) 
Example 24
def test_cookie_samesite_invalid(self):
        with self.settings(SESSION_COOKIE_SAMESITE='invalid'):
            with self.assertRaises(ValueError) as exc:
                self.client.get('/cookies-test/')

            self.assertEqual(exc.exception.args[0], 'samesite must be "Lax", "None", or "Strict".') 
Example 25
def test_cookie_samesite_unset(self):
        with self.settings(SESSION_COOKIE_SAMESITE=None):
            response = self.client.get('/cookies-test/')
            self.assertEqual(response.cookies['sessionid'].get('samesite'), '')
            self.assertEqual(response.cookies['csrftoken'].get('samesite'), '')

            cookies_string = sorted(response.cookies.output().split('\r\n'))
            self.assertTrue('csrftoken=' in cookies_string[0])
            self.assertTrue('; SameSite=Lax' not in cookies_string[0])
            self.assertTrue('; SameSite=Strict' not in cookies_string[0])
            self.assertTrue('; SameSite=None' not in cookies_string[0])
            self.assertTrue('sessionid=' in cookies_string[2])
            self.assertTrue('; SameSite=Lax' not in cookies_string[2])
            self.assertTrue('; SameSite=None' not in cookies_string[2]) 
Example 26
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_positional_arg(self):
        self.assertEqual(render_to_string(self.template_name, {'obj': 'test'}), 'obj:test') 
Example 27
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_dictionary_kwarg(self):
            self.assertEqual(render_to_string(self.template_name, dictionary={'obj': 'test'}), 'obj:test') 
Example 28
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_context_instance_kwarg(self):
            self.assertEqual(render_to_string(self.template_name, context_instance=Context({'obj': 'test'})), 'obj:test') 
Example 29
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_request_context(self):
            self.assertEqual(render_to_string(self.template_name, context_instance=RequestContext(None, {'obj': 'test'})), 'obj:test') 
Example 30
Project: django-compat   Author: arteria   File: test_compat.py    License: MIT License 5 votes vote down vote up
def test_context_kwarg(self):
        self.assertEqual(render_to_string(self.template_name, context={'obj': 'test'}), 'obj:test')