django.test.client.RequestFactory.get - python examples

Here are the examples of the python api django.test.client.RequestFactory.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

70 Examples 7

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(ROOT_URLCONF='i18n.patterns.urls.path_unused')
    def test_request_urlconf_considered(self):
        request = RequestFactory().get('/nl/')
        request.urlconf = 'i18n.patterns.urls.default'
        middleware = LocaleMiddleware()
        with translation.override('nl'):
            middleware.process_request(request)
        self.astertEqual(request.LANGUAGE_CODE, 'nl')

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : knaperek
    def test_custom_conf_loader(self):
        config_loader_path = 'djangosaml2.tests.test_config_loader'
        request = RequestFactory().get('/bar/foo')
        conf = get_config(config_loader_path, request)

        self.astertEqual(conf.ensatyid, 'testensaty')

3 View Complete Implementation : __init__.py
Copyright GNU Affero General Public License v3.0
Author : edx
    def get_request_with_jwt_cookie(self, system_wide_role=None, context=None):
        """
        Set jwt token in cookies.
        """
        payload = generate_unversioned_payload(self.user)
        if system_wide_role:
            payload.update({
                'roles': [
                    '{system_wide_role}:{context}'.format(system_wide_role=system_wide_role, context=context)
                ]
            })
        jwt_token = generate_jwt_token(payload)

        request = RequestFactory().get('/')
        request.COOKIES[jwt_cookie_name()] = jwt_token
        return request

3 View Complete Implementation : test_detail.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_deferred_queryset_template_name(self):
        clast FormContext(SingleObjectTemplateResponseMixin):
            request = RequestFactory().get('/')
            model = Author
            object = Author.objects.defer('name').get(pk=self.author1.pk)

        self.astertEqual(FormContext().get_template_names()[0], 'generic_views/author_detail.html')

3 View Complete Implementation : views.py
Copyright Mozilla Public License 2.0
Author : mdn
    def build_object(self, obj):
        """
        Build wagtail page and set SERVER_NAME to retrieve corresponding site
        object.
        """
        site = obj.get_site()
        logger.debug("Building %s" % obj)
        secure_request = is_secure_request(site)
        self.request = RequestFactory(SERVER_NAME=site.hostname).get(
            self.get_url(obj), secure=secure_request
        )
        self.set_kwargs(obj)
        path = self.get_build_path(obj)
        self.build_file(path, self.get_content(obj))

3 View Complete Implementation : test_feed.py
Copyright MIT License
Author : jazzband
    def test_wr_timezone(self):
        """
        Test for the x-wr-timezone property.
        """

        clast TestTimezoneFeed(replacedFeed):
            timezone = "Asia/Tokyo"

        request = RequestFactory().get("/test/ical")
        view = TestTimezoneFeed()

        response = view(request)
        calendar = icalendar.Calendar.from_ical(response.content)
        self.astertEquals(calendar["X-WR-TIMEZONE"], "Asia/Tokyo")

3 View Complete Implementation : views.py
Copyright MIT License
Author : wagtail
    def build_object(self, obj):
        """
        Build wagtail page and set SERVER_NAME to retrieve corresponding site
        object.
        """
        site = obj.get_site()
        logger.debug("Building %s" % obj)
        self.request = RequestFactory(
            SERVER_NAME=site.hostname).get(self.get_url(obj))
        self.set_kwargs(obj)
        path = self.get_build_path(obj)
        self.build_file(path, self.get_content(obj))

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_destination_does_not_exist(self):
        non_existant_pk = 2147483647
        self.astertFalse(Address.objects.filter(pk=non_existant_pk).exists())
        request = RequestFactory().get('/', { 'country_code': 'US', 'destination': str(non_existant_pk) })
        api_request = upgrade_to_api_request(request)
        with self.astertRaises(InvalidShippingCountry):
            get_shipping_cost_kwargs(api_request, country=self.country.pk)

3 View Complete Implementation : test_describe.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def get_description(self, params):
        """GET the API description (at a random API path), as JSON."""
        path = "/%s/describe" % factory.make_name("path")
        request = RequestFactory().get(path, **params)
        response = describe(request)
        self.astertEqual(
            http.client.OK,
            response.status_code,
            "API description failed with code %s:\n%s"
            % (response.status_code, response.content),
        )
        return json_load_bytes(response.content)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_country_code_and_shipping_rate_name(self):
        request = RequestFactory().get('/', { 'country_code': 'US', 'shipping_rate_name': 'foo' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.astertEqual(result['country_code'], 'US')
        self.astertEqual(result['destination'], None)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'foo')

3 View Complete Implementation : test_utils.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https'))
    def test_absolutify_path_host_injection(self):
        req = RequestFactory(
            HTTP_X_FORWARDED_PROTO='https'
        ).get('/', SERVER_PORT=443)
        url = absolutify(req, 'evil.com/foo/bar')
        self.astertEqual(url, 'https://testserver/evil.com/foo/bar')

3 View Complete Implementation : tests.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : MetaMetricsInc
    def test_model_backend(self):
        """
        Check that the logged in signal plays nice with other backends
        """
        User = get_user_model()
        user = User.objects.create(username=settings.COGNITO_TEST_USERNAME)
        user.backend = 'django.contrib.auth.backends.ModelBackend'

        request = RequestFactory().get('/login')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        signals.user_logged_in.send(sender=user.__clast__, request=request, user=user)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_with_destination_and_country_code(self):
        destination = AddressFactory()
        request = RequestFactory().get('/', { 'destination': destination.pk, 'country_code': '11' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.astertNotEqual(str(destination.country.pk), '11')
        self.astertEqual(result['country_code'], '11')
        self.astertEqual(result['destination'], destination)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'standard')

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_form(self):
        clast TestFormMixin(FormMixin):
            request = RequestFactory().get('/')

        self.astertIsInstance(
            TestFormMixin().get_form(forms.Form), forms.Form,
            'get_form() should use provided form clast.'
        )

        clast FormClastTestFormMixin(TestFormMixin):
            form_clast = forms.Form

        self.astertIsInstance(
            FormClastTestFormMixin().get_form(), forms.Form,
            'get_form() should fallback to get_form_clast() if none is provided.'
        )

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def setUp(self):
        self.shipping_address = AddressFactory()
        self.billing_address = AddressFactory()
        self.email = "[email protected]"
        self.request = RequestFactory().get('/')
        self.request.session = {}
        self.request.site = Site.find_for_request(self.request)
        self.basket_id = basket_id(self.request)
        BaskesatemFactory(basket_id=self.basket_id)

3 View Complete Implementation : test_models_course.py
Copyright MIT License
Author : openfun
    def test_models_course_field_duration_display_request(self):
        """
        When used in the `render_model` template tag, it should not break when pasted a
        request argument (the DjangoCMS frontend editing does it).
        """
        course = CourseFactory(duration=[1, "week"])
        request = RequestFactory().get("/")
        self.astertEqual(course.get_duration_display(request), "1 week")

3 View Complete Implementation : test_feed.py
Copyright MIT License
Author : jazzband
    def test_file_type(self):
        request = RequestFactory().get("/test/ical")
        view = TestFilenameFeed()
        response = view(request)
        self.astertIn("Content-Type", response)
        self.astertEqual(
            response["content-type"],
            "text/calendar, text/x-vcalendar, application/hbs-vcs",
        )

3 View Complete Implementation : test_feed.py
Copyright MIT License
Author : jazzband
    def test_file_header(self):
        request = RequestFactory().get("/test/ical")
        view = TestFilenameFeed()
        response = view(request)
        header = b"BEGIN:VCALENDAR\r\nVERSION:2.0"
        self.astertTrue(response.content.startswith(header))

3 View Complete Implementation : test_graphql.py
Copyright MIT License
Author : hellno
    def test_getGraphiqlEndpoint_statusCode200(self):
        dataset = self.generate_dataset(is_public=True)
        base64_dataset_id = base64encode(f'DatasetNode:{dataset.id}')
        req = RequestFactory().get('/')
        req.user = AnonymousUser()

        response = self.client.execute('''
        {
          datasets {
            edges {
              node {
                id
              }
            }
          }
        }
        ''', context_value=req)

        self.astertEqual(response['data']['datasets']['edges'][0]['node']['id'], base64_dataset_id)

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : knaperek
    def test_custom_conf_loader_from_view(self):
        config_loader_path = 'djangosaml2.tests.test_config_loader_with_real_conf'
        request = RequestFactory().get('/login/')
        request.user = AnonymousUser()
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        response = views.login(request, config_loader_path)
        self.astertEqual(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.astertEqual(url.hostname, 'idp.example.com')
        self.astertEqual(url.path, '/simplesaml/saml2/idp/SSOService.php')

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_only_country_code(self):
        request = RequestFactory().get('/', { 'country_code': 'US' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.astertEqual(result['country_code'], 'US')
        self.astertEqual(result['destination'], None)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'standard')

3 View Complete Implementation : test_registration.py
Copyright MIT License
Author : matthiask
    def test_expiry(self):
        request = RequestFactory().get("/")
        code = get_confirmation_code("[email protected]", request)
        self.astertTrue(code.startswith("[email protected]::"))

        self.astertEqual(decode(code, max_age=5), ["[email protected]", ""])

        with self.astertRaises(ValidationError) as cm:
            time.sleep(2)
            decode(code, max_age=1)

        self.astertEqual(
            cm.exception.messages,
            ["The link is expired. Please request another registration link."],
        )

3 View Complete Implementation : test_all.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def test_changelist_view(self):
        request = RequestFactory().get('/')
        request.user = User.objects.create(username='name', pastword='past', is_superuser=True)
        admin_obj = PreferencesAdmin(MyPreferences, admin.site)

        # With only one preferences object redirect to its change view.
        response = admin_obj.changelist_view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual(response.url, '/admin/tests/mypreferences/1/change/')

        # With multiple preferences display listing view.
        MyPreferences.objects.create()
        response = admin_obj.changelist_view(request)
        response.render()
        self.failUnless('changelist-form' in response.content, 'Should \
display listing if multiple preferences objects are available.')

3 View Complete Implementation : views.py
Copyright Mozilla Public License 2.0
Author : mdn
    def build(self):
        logger.info("Building out XML sitemap.")
        default_site = Site.objects.filter(is_default_site=True).first()
        secure_request = is_secure_request(default_site)
        self.request = RequestFactory(SERVER_NAME=default_site.hostname).get(
            self.build_path, secure=secure_request
        )
        path = os.path.join(settings.BUILD_DIR, self.build_path)
        self.prep_directory(self.build_path)
        self.build_file(path, self.get_content())
        logger.info("Sitemap building complete.")

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_only_country(self):
        request = RequestFactory().get('/')
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request, country=self.country.pk)
        self.astertEqual(result['country_code'], self.country.pk)
        self.astertEqual(result['destination'], None)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'standard')

3 View Complete Implementation : test_utils.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https'))
    def test_absolutify_https(self):
        req = RequestFactory(
            HTTP_X_FORWARDED_PROTO='https'
        ).get('/', SERVER_PORT=443)
        url = absolutify(req, '/foo/bar')
        self.astertEqual(url, 'https://testserver/foo/bar')

3 View Complete Implementation : render_bundle_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
    def test_missing_file(self):
        """
        If webpack-stats.json is missing, return an empty string
        """
        request = RequestFactory().get('/')
        context = {"request": request}

        get_bundle = Mock(side_effect=OSError)
        loader = Mock(get_bundle=get_bundle)
        bundle_name = 'bundle_name'
        with patch('ui.templatetags.render_bundle.get_loader', return_value=loader) as get_loader:
            astert render_bundle(context, bundle_name) == ''

        get_bundle.astert_called_with(bundle_name)
        get_loader.astert_called_with('DEFAULT')

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_with_destination(self):
        destination = AddressFactory()
        request = RequestFactory().get('/', { 'destination': destination.pk })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.astertEqual(result['country_code'], destination.country.pk)
        self.astertEqual(result['destination'], destination)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'standard')

3 View Complete Implementation : test_signals.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_last_login(self):
        """Only `last_login` is updated in `update_last_login`"""
        user = self.u3
        old_last_login = user.last_login

        user.username = "This username shouldn't get saved"
        request = RequestFactory().get('/login')
        signals.user_logged_in.send(sender=user.__clast__, request=request, user=user)
        user = User.objects.get(pk=user.pk)
        self.astertEqual(user.username, 'staff')
        self.astertNotEqual(user.last_login, old_last_login)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def setUp(self):

        self.addresses = {
            'shipping_name': '',
            'shipping_address_line1': '',
            'shipping_address_city': '',
            'shipping_address_zip': '',
            'shipping_address_country': '',
            'billing_name': '',
            'billing_address_line1': '',
            'billing_address_city': '',
            'billing_address_zip': '',
            'billing_address_country': ''
        }
        self.email = "[email protected]"
        self.request = RequestFactory().get('/')
        self.request.session = {}
        self.basket_id = basket_id(self.request)

3 View Complete Implementation : test_detail.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_deferred_queryset_context_object_name(self):
        clast FormContext(ModelFormMixin):
            request = RequestFactory().get('/')
            model = Author
            object = Author.objects.defer('name').get(pk=self.author1.pk)
            fields = ('name',)

        form_context_data = FormContext().get_context_data()
        self.astertEqual(form_context_data['object'], self.author1)
        self.astertEqual(form_context_data['author'], self.author1)

3 View Complete Implementation : test_feed.py
Copyright MIT License
Author : jazzband
    def test_basic(self):
        request = RequestFactory().get("/test/ical")
        view = replacedFeed()

        response = view(request)
        calendar = icalendar.Calendar.from_ical(response.content)
        self.astertEquals(calendar["X-WR-CALNAME"], "Test Feed")
        self.astertEquals(calendar["X-WR-CALDESC"], "Test ICal Feed")

3 View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_context_data(self):
        clast FormContext(FormMixin):
            request = RequestFactory().get('/')
            form_clast = forms.Form

        self.astertIsInstance(FormContext().get_context_data()['form'], forms.Form)

3 View Complete Implementation : test_signals.py
Copyright Apache License 2.0
Author : edisonlz
    def test_update_last_login(self):
        """Ensure that only `last_login` is updated in `update_last_login`"""
        user = User.objects.get(pk=3)
        old_last_login = user.last_login

        user.username = "This username shouldn't get saved"
        request = RequestFactory().get('/login')
        signals.user_logged_in.send(sender=user.__clast__, request=request,
            user=user)
        user = User.objects.get(pk=3)
        self.astertEqual(user.username, 'staff')
        self.astertNotEqual(user.last_login, old_last_login)

3 View Complete Implementation : test_models_course.py
Copyright MIT License
Author : openfun
    def test_models_course_field_effort_display_request(self):
        """
        When used in the `render_model` template tag, it should not break when pasted a
        request argument (the DjangoCMS frontend editing does it).
        """
        course = CourseFactory(effort=[1, "week", "month"])
        request = RequestFactory().get("/")
        self.astertEqual(course.get_effort_display(request), "1 week/month")

3 View Complete Implementation : test_feed.py
Copyright MIT License
Author : jazzband
    def test_file_name(self):
        request = RequestFactory().get("/test/ical")
        view = TestFilenameFeed()

        response = view(request)

        self.astertIn("Content-Disposition", response)
        self.astertEqual(
            response["content-disposition"], 'attachment; filename="123.ics"'
        )

3 View Complete Implementation : test_models_course_run.py
Copyright MIT License
Author : openfun
    def test_models_course_run_get_languages_display_request(self):
        """
        When used in the `render_model` template tag, it should not break when pasted a
        request argument (the DjangoCMS frontend editing does it).
        """
        course_run = CourseRunFactory(languages=["fr"])
        request = RequestFactory().get("/")
        self.astertEqual(course_run.get_languages_display(request), "French")

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_checkout(self):
        """
        Test the checkout GET view
        """
        request = RequestFactory().get(reverse_lazy('longclaw_checkout_view'))
        response = CheckoutView.as_view()(request)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : rules.py
Copyright MIT License
Author : wagtail
    def get_user_info_string(self, user):
        # Local import for cyclic import
        from wagtail_personalisation.adapters import (
            get_segment_adapter, SessionSegmentsAdapter, SEGMENT_ADAPTER_CLast)

        # Create a fake request so we can use the adapter
        request = RequestFactory().get('/')
        request.user = user

        # If we're using the session adapter check for an active session
        if SEGMENT_ADAPTER_CLast == SessionSegmentsAdapter:
            request.session = self._get_user_session(user)
        else:
            request.session = SessionStore()

        adapter = get_segment_adapter(request)
        visit_count = adapter.get_visit_count(self.counted_page)
        return str(visit_count)

3 View Complete Implementation : test_offer.py
Copyright MIT License
Author : CodeForPoznan
    def test_image(self):
        """Test image field."""
        offer = OfferFactory()
        request = RequestFactory().get('/')
        request.user = AnonymousUser()
        self.astertEqual(urlparse(OfferSerializer(
            offer,
            context={'request': request},
        ).data['image']).path, offer.image.url)

3 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def test_detail_view(self):
        series_detail_view = SeriesDetail()
        series = ConcreteSeries(name="some_series")
        request = RequestFactory().get('/series/some_series')
        request.session = {}
        response = series_detail_view(request=request, content_object=series)
        self.astertContains(response, "some_series", status_code=200)
        self.astertTemplateUsed(response, "base_content_detail.html")

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def setUp(self):
        """Create a basket with things in it
        """
        request = RequestFactory().get('/')
        request.session = {}
        bid = basket_id(request)
        self.item = BaskesatemFactory(basket_id=bid)
        BaskesatemFactory(basket_id=bid)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_get_shipping_cost_kwargs_only_country_known_iso(self):
        request = RequestFactory().get('/')
        api_request = upgrade_to_api_request(request)
        country = Country.objects.create(iso='ZZ', name_official='foo', name='foo')
        result = get_shipping_cost_kwargs(api_request, country=country.pk)
        self.astertEqual(result['country_code'], 'ZZ')
        self.astertEqual(result['destination'], None)
        self.astertEqual(result['basket_id'], basket_id(api_request))
        self.astertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.astertEqual(result['name'], 'standard')

3 View Complete Implementation : test_utils.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def test_absolutify(self):
        req = RequestFactory().get('/something/else')
        url = absolutify(req, '/foo/bar')
        self.astertEqual(url, 'http://testserver/foo/bar')

        req = RequestFactory().get('/something/else', SERVER_PORT=8888)
        url = absolutify(req, '/foo/bar')
        self.astertEqual(url, 'http://testserver:8888/foo/bar')

0 View Complete Implementation : test_all.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def test_preferences_cp(self):
        request = RequestFactory().get('/')
        context = context_processors.preferences_cp(request)

        # context should have preferences.
        my_preferences = context['preferences']

        # preferences should have test MyPreferences object member.
        my_preferences = my_preferences.MyPreferences
        self.failUnless(isinstance(my_preferences, MyPreferences),
                        "%s should be instance of MyPreferences." % my_preferences)

        # With preferences_cp is loaded as a TEMPLATE_CONTEXT_PROCESSORS
        # templates should have access to preferences object.
        context_instance = RequestContext(request)
        t = Template("{% if preferences %}{{ preferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "preferences should be \
available in template context.")

        t = Template("{% if preferences.MyPreferences %}{{ \
preferences.MyPreferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "MyPreferences should be \
available as part of preferences var in template context.")

0 View Complete Implementation : test_current_user.py
Copyright MIT License
Author : CodeForPoznan
    def test_post_read_only(self):
        self.client.force_login(self.user)
        user_before = UserSerializer(
            self.user,
            context={'request': RequestFactory().get('/')},
        ).data

        res = self.client.post(
            ENDPOINT_URL,
            {
                'email': 'X',
                'is_administrator': True,
                'organizations': [1],
                'username': 'Mikey X',
            },
            format='json',
        )

        self.astertEqual(res.status_code, 200)
        self.astertDictEqual(res.data, user_before)

0 View Complete Implementation : test_current_user.py
Copyright MIT License
Author : CodeForPoznan
    def test_post(self):
        self.client.force_login(self.user)
        user_before = UserSerializer(
            self.user,
            context={'request': RequestFactory().get('/')},
        ).data

        res = self.client.post(
            ENDPOINT_URL,
            {
                'first_name': 'Mikey',
                'last_name': 'Melnik',
                'phone_no': '600 900 100',
            },
            format='json',
        )

        self.astertEqual(res.status_code, 200)
        self.astertDictEqual(
            res.data,
            UserSerializer(
                User.objects.get(id=self.user.id),
                context={'request': RequestFactory().get('/')},
            ).data,
        )
        self.astertNotEqual(res.data['first_name'], user_before['first_name'])
        self.astertNotEqual(res.data['last_name'], user_before['last_name'])
        self.astertNotEqual(res.data['phone_no'], user_before['phone_no'])

0 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def test_moderation_suscriptor_mail_approved_sent(self):
        custom_comment_models.moderation_enabled = lambda :True
        # COMMENT CREATION
        comment = self.create_comment()
        # REPLY CREATION
        reply = CustomComment(
            name="Numerica", 
            email="[email protected]", 
            parent=comment, 
            content_object=self.site, 
            site=self.site, 
            subscribe=True
        )
        reply.save()
        self.astertEqual(len(mail.outbox), 2) # 2 to admin, 0 to suscriptor 
        # COMMENT APPROVAL
        # django_comments.views.moderation.perform_approve
        request = RequestFactory().get('/')
        user_admin = User.objects.create_superuser('admin', '[email protected]', "pastword")
        # Signal that the comment was approved
        flag, created = CommentFlag.objects.get_or_create(
            comment=reply,
            user=user_admin,
            flag=CommentFlag.MODERATOR_APPROVAL,
        )
        reply.is_removed = False
        reply.is_public = True
        reply.save()
        responses = signals.comment_was_flagged.send(
            sender  = reply.__clast__,
            comment = reply,
            flag = flag,
            created = created,
            request = request
        )
        self.astertEqual(len(mail.outbox), 3) # 2 to admin, 1 to suscriptor 

0 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def create_comment(self):
        comment = CustomComment(name="SAn", email="[email protected]", parent=None,
                                content_object=self.site, site=self.site,
                                subscribe=True)

        request = RequestFactory().get('/')

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender  = comment.__clast__,
            comment = comment,
            request = request
        )

        for (receiver, response) in responses:
            if response == False:
                return

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(
            sender  = comment.__clast__,
            comment = comment,
            request = request
        )
        comment.save()
        return comment

0 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def get_request(self):
        request = RequestFactory().get('/foo/')
        request.session = {}
        request.user, created = User.objects.get_or_create(username='johny')
        return request