Beispiel #1
0
def construct_request_json(request):
    result = {
        "GET": {},
        "POST": {},
        "FILES": {},
        "META": {},
        "COOKIES": {}
    }

    for var in request.GET.items():
        result["GET"][var[0]] = repr(var[1])

    for var in request.POST.items():
        result["POST"][var[0]] = repr(var[1])

    for var in request.FILES.items():
        result["FILES"][var[0]] = repr(var[1])

    whitelisted_cookie = SimpleCookie()
    for name, value in request.COOKIES.items():
        if name in COOKIE_BLACKLIST:
            continue

        whitelisted_cookie[name] = value
        result["COOKIES"][name] = repr(value)

    for meta_name, meta_value in sorted(request.META.items()):
        if meta_name == 'HTTP_COOKIE':
            meta_value = whitelisted_cookie.output(header='', sep='; ')
        result["META"][meta_name] = repr(meta_value)

    return json.dumps(result)
Beispiel #2
0
 def test_encode(self):
     """
     Test that we don't output tricky characters in encoded value
     """
     c = SimpleCookie()
     c["test"] = "An,awkward;value"
     self.assertNotIn(";", c.output().rstrip(";"))  # IE compat
     self.assertNotIn(",", c.output().rstrip(";"))  # Safari compat
Beispiel #3
0
 def test_httponly_after_load(self):
     """
     Test that we can use httponly attribute on cookies that we load
     """
     c = SimpleCookie()
     c.load("name=val")
     c['name']['httponly'] = True
     self.assertTrue(c['name']['httponly'])
Beispiel #4
0
 def test_encode(self):
     """
     Test that we don't output tricky characters in encoded value
     """
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
     self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
Beispiel #5
0
 def test_decode(self):
     """
     Test that we can still preserve semi-colons and commas
     """
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     c2 = SimpleCookie()
     c2.load(c.output())
     self.assertEqual(c['test'].value, c2['test'].value)
Beispiel #6
0
 def test_decode_2(self):
     """
     Test that we haven't broken normal encoding
     """
     c = SimpleCookie()
     c['test'] = b"\xf0"
     c2 = SimpleCookie()
     c2.load(c.output())
     self.assertEqual(c['test'].value, c2['test'].value)
Beispiel #7
0
 def test_encode(self):
     """
     Test that we don't output tricky characters in encoded value
     """
     # Python 2.4 compatibility note: Python 2.4's cookie implementation
     # always returns Set-Cookie headers terminating in semi-colons.
     # That's not the bug this test is looking for, so ignore it.
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
     self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
Beispiel #8
0
    def test_pickle(self):
        rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
        expected_output = 'Set-Cookie: %s' % rawdata

        C = SimpleCookie()
        C.load(rawdata)
        self.assertEqual(C.output(), expected_output)

        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            C1 = pickle.loads(pickle.dumps(C, protocol=proto))
            self.assertEqual(C1.output(), expected_output)
    def test_create_with_cookie(self):
        """
        Test the various cookie states
        :return:
        """

        #######################################
        # Generate the voter_device_id cookie
        response = self.client.get(self.generate_voter_device_id_url)
        json_data = json.loads(response.content)

        # Make sure we got back a voter_device_id we can use
        self.assertEqual('voter_device_id' in json_data, True,
                         "voter_device_id expected in the deviceIdGenerateView json response")

        # Now save the retrieved voter_device_id in a mock cookie
        cookies = SimpleCookie()
        cookies["voter_device_id"] = json_data['voter_device_id']
        self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        #######################################
        # Test for status: VOTER_CREATED
        response2 = self.client.get(self.voter_create_url)
        json_data2 = json.loads(response2.content)

        self.assertEqual('status' in json_data2, True,
                         "status expected in the voterCreateView json response but not found")
        self.assertEqual('voter_device_id' in json_data2, True,
                         "voter_device_id expected in the voterCreateView json response but not found")

        # With a brand new voter_device_id, a new voter record should be created
        self.assertEqual(
            json_data2['status'], 'VOTER_CREATED',
            "status:  {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
                status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))

        #######################################
        # Test for status: VOTER_ALREADY_EXISTS
        response3 = self.client.get(self.voter_create_url)
        json_data3 = json.loads(response3.content)

        self.assertEqual('status' in json_data3, True,
                         "status expected in the voterCreateView json response but not found")
        self.assertEqual('voter_device_id' in json_data3, True,
                         "voter_device_id expected in the voterCreateView json response but not found")

        # Try reusing the same voter_device_id
        self.assertEqual(
            json_data3['status'], 'VOTER_ALREADY_EXISTS',
            "status:  {status} (VOTER_ALREADY_EXISTS expected), voter_device_id: {voter_device_id}".format(
                status=json_data3['status'], voter_device_id=json_data3['voter_device_id']))
    def test_retrieve_with_cookie(self):
        """
        Test the various cookie states
        :return:
        """

        #######################################
        # Generate the voter_device_id cookie
        response = self.client.get(self.generate_voter_device_id_url)
        json_data = json.loads(response.content)

        # Make sure we got back a voter_device_id we can use
        self.assertEqual('voter_device_id' in json_data, True,
                         "voter_device_id expected in the deviceIdGenerateView json response")

        # Now save the retrieved voter_device_id in a mock cookie
        cookies = SimpleCookie()
        cookies["voter_device_id"] = json_data['voter_device_id']
        self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        #######################################
        # Create a voter so we can test retrieve
        response2 = self.client.get(self.voter_create_url)
        json_data2 = json.loads(response2.content)

        self.assertEqual('status' in json_data2, True,
                         "status expected in the voterCreateView json response but not found")
        self.assertEqual('voter_device_id' in json_data2, True,
                         "voter_device_id expected in the voterCreateView json response but not found")

        # With a brand new voter_device_id, a new voter record should be created
        self.assertEqual(
            json_data2['status'], 'VOTER_CREATED',
            "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
                status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))

        #######################################
        # Test for id, first_name, last_name, email
        response3 = self.client.get(self.voter_retrieve_url)
        json_data3 = json.loads(response3.content)

        for one_voter in json_data3:
            self.assertEqual('id' in one_voter, True, "id expected in the voterRetrieveView json response but not found")
            self.assertEqual('first_name' in one_voter, True,
                             "first_name expected in the voterRetrieveView json response but not found")
            self.assertEqual('last_name' in one_voter, True,
                             "last_name expected in the voterRetrieveView json response but not found")
            self.assertEqual('email' in one_voter, True,
                             "email expected in the voterRetrieveView json response but not found")
Beispiel #11
0
def artificial_login(**credentials):
    from django.contrib.auth import authenticate, login

    cookies = SimpleCookie()

    user = authenticate(**credentials)
    engine = import_module(settings.SESSION_ENGINE)

    # Create a fake request that goes through request middleware
    request = WSGIRequest(
        {
            "HTTP_COOKIE": cookies.output(header="", sep=";"),
            "PATH_INFO": str("/"),
            "REMOTE_ADDR": str("127.0.0.1"),
            "REQUEST_METHOD": str("GET"),
            "SCRIPT_NAME": str(""),
            "SERVER_NAME": str("testserver"),
            "SERVER_PORT": str("80"),
            "SERVER_PROTOCOL": str("HTTP/1.1"),
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": str("http"),
            "wsgi.input": BytesIO(),
            "wsgi.errors": BytesIO(),
            "wsgi.multiprocess": True,
            "wsgi.multithread": False,
            "wsgi.run_once": False,
        }
    )
    request.session = engine.SessionStore()
    login(request, user)

    # Save the session values.
    request.session.save()

    # Set the cookie to represent the session.
    session_cookie = settings.SESSION_COOKIE_NAME
    cookies[session_cookie] = request.session.session_key
    cookie_data = {
        "max-age": None,
        "path": "/",
        "domain": settings.SESSION_COOKIE_DOMAIN,
        "secure": settings.SESSION_COOKIE_SECURE or None,
        "expires": None,
    }
    cookies[session_cookie].update(cookie_data)
    return {session_cookie: cookies[session_cookie].value, settings.CSRF_COOKIE_NAME: csrf._get_new_csrf_key()}
Beispiel #12
0
    def logout(self):
        """
        Removes the authenticated user's cookies.

        Causes the authenticated user to be logged out.
        """
        session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore()
        session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value)
        self.cookies = SimpleCookie()
Beispiel #13
0
    def test_bypass_maintenance_by_cookie(self):
        settings_cookie = 'some_cookie_value'
        with self.settings(MIDDLEWARE_CLASSES=self.MIDDLEWARE_CLASSES,
                           INSTALLED_APPS=self.INSTALLED_APPS,
                           MAINTENANCE_BYPASS_COOKIE=settings_cookie):
            self._activate(verbosity=1)
            response = self.client.get('/admin/')
            self.assertEqual(response.status_code, 302)

            self.client.cookies = SimpleCookie(
                {'django_maintenance_bypass_cookie': settings_cookie})
            response = self.client.get('/admin/')
            self.assertEqual(response.status_code, 200)
Beispiel #14
0
    def logout(self):
        """Log out the user by removing the cookies and session object."""
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
Beispiel #15
0
    def process_request(self, request):

        domain = request.META.get('HTTP_HOST', '')
        mobile_domain = settings.OPPS_DOMAIN_MOBILE

        current_cookie = request.COOKIES.get('template_mode', None)
        template_mode = request.GET.get('template_mode', None)
        THREAD_LOCALS.template_dirs = settings.TEMPLATE_DIRS_WEB

        if hasattr(request, "is_mobile"):
            agent_is_mobile = request.is_mobile
        else:
            agent_is_mobile = is_mobile_agent(request)

        domain_is_mobile = domain == mobile_domain

        request_is_mobile = agent_is_mobile and domain_is_mobile

        if not template_mode and not current_cookie:
            if domain_is_mobile:
                template_mode = u'mobile'
            else:
                return

        if request_is_mobile and template_mode == u'desktop':
            prot = settings.OPPS_PROTOCOL_WEB
            web_domain = settings.OPPS_DOMAIN_WEB
            url = u"{}://{}/?template_mode=desktop".format(prot, web_domain)
            return HttpResponseRedirect(url)
        elif not request_is_mobile and template_mode == u'mobile':
            prot = settings.OPPS_PROTOCOL_MOBILE
            url = u"{}://{}/?template_mode=mobile".format(prot, mobile_domain)

            # set cache prefix randon in mobile device
            settings.CACHE_MIDDLEWARE_KEY_PREFIX = u"opps_site-{}-{}".format(
                settings.SITE_ID, random.getrandbits(32))

            return HttpResponseRedirect(url)

        request._resp_cookies = SimpleCookie()
        request.set_cookie = MethodType(_set_cookie, request, HttpRequest)
        request.delete_cookie = MethodType(
            _delete_cookie, request, HttpRequest
        )

        if template_mode:
            request.set_cookie('template_mode', template_mode)
            current_cookie = template_mode

        if current_cookie and current_cookie.strip().lower() == u"mobile":
            THREAD_LOCALS.template_dirs = settings.TEMPLATE_DIRS_MOBILE
Beispiel #16
0
 def test_decode_2(self):
     c = SimpleCookie()
     c['test'] = b"\xf0"
     c2 = SimpleCookie()
     c2.load(c.output()[12:])
     self.assertEqual(c['test'].value, c2['test'].value)
     c3 = parse_cookie(c.output()[12:])
     self.assertEqual(c['test'].value, c3['test'])
Beispiel #17
0
    def test_logout03(self):
        # Iniciar sesión via ajax.
        response = self.client.post('/auth/login',
                                    self.credentials,
                                    follow=True)
        self.assertTrue('sessionid' in response.cookies,
                        "La respuesta no contiene la cookie de sesión.")
        sessionid = response.cookies['sessionid']

        # Cerrar sesión
        response = self.client.get('/auth/logout', follow=True)
        self.assertEqual("", response.cookies['sessionid'].value,
                         "No se eliminó la cookie de sesión.")

        # No debería estar autenticado
        self.client.cookies = SimpleCookie({'sessionid': sessionid})
        response = self.client.get('/buscar')
        self.assertFalse(response.context['user'].is_authenticated)

        # Iniciar sesión en la pagina de ingresar

        data = {
            'usuario': self.credentials['usuario'],
            'contrasenia': self.credentials['password'],
            'accion': 'login'
        }

        response = self.client.post('/ingresar', data, follow=True)

        # Cerrar sesión
        response = self.client.get('/auth/logout', follow=True)
        self.assertEqual("", response.cookies['sessionid'].value,
                         "No se eliminó la cookie de sesión.")

        # No debería estar autenticado
        self.client.cookies = SimpleCookie({'sessionid': sessionid})
        response = self.client.get('/buscar')
        self.assertFalse(response.context['user'].is_authenticated)
Beispiel #18
0
 def test_fetch_demo_manifest_en(self, resource_kind, api_client):
     """测试获取资源列表接口(英文版)"""
     api_client.cookies = SimpleCookie(
         {settings.LANGUAGE_COOKIE_NAME: 'en-US'})
     response = api_client.get(
         f'{self.common_prefix}/manifests/?kind={resource_kind}')
     assert resource_kind == getitems(response.json(), 'data.kind')
     assert response.json()['code'] == 0
     if resource_kind not in [
             K8sResourceKind.HorizontalPodAutoscaler.value,
             K8sResourceKind.CustomObject.value
     ]:
         assert response.json(
         )['data']['items'][0]['alias'] == f'{resource_kind} Simple Demo'
Beispiel #19
0
 def test_decode(self):
     """Semicolons and commas are decoded."""
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     c2 = SimpleCookie()
     c2.load(c.output()[12:])
     self.assertEqual(c['test'].value, c2['test'].value)
     c3 = parse_cookie(c.output()[12:])
     self.assertEqual(c['test'].value, c3['test'])
Beispiel #20
0
    def get_request(self, page, lang):
        """
        Create a GET request for the given page and language

        :param page: current page object
        :param lang: request language
        :return: request
        """
        request = self.request_factory.get(page.get_path(lang))
        request.current_page = page
        request.user = self.user
        request.session = {}
        request.cookies = SimpleCookie()
        request.errors = StringIO()
        return request
Beispiel #21
0
    def test_extension_uninstalled_hook(self):
        cid = "{}.{}".format(mommy.random_gen.gen_integer(0),
                             mommy.random_gen.gen_integer(0))
        cid_cookie_val = "{}.{}".format(CID_COOKIE_PREFIX, cid)
        self.client.cookies = SimpleCookie(
            {ga_cookies.CID_COOKIE: cid_cookie_val})

        mocked_consumer_instance = MagicMock()
        with patch('apps.analytics.views.GAConsumer',
                   return_value=mocked_consumer_instance) as MockGAConsumer:
            response = self.client.get(self.extension_installed_url)
            self.assertEqual(response.status_code, 200)
            MockGAConsumer.assert_called_once_with(cid)
            mocked_consumer_instance.send_event_extension_uninstalled.assert_called_once_with(
            )
Beispiel #22
0
def test_cache_headers_with_bad_auth(client, case):
    # visiting homepage when logged out is cached ...
    response = client.get(reverse('home'))
    assert is_cached(response)

    # ... but visiting with a bad Authorization header is not cached
    client.credentials(HTTP_AUTHORIZATION='Token fake')
    response = client.get(reverse('home'))
    assert not is_cached(response)

    # ... and visiting with a bad session cookie is not cached
    client.credentials()
    client.cookies = SimpleCookie({settings.SESSION_COOKIE_NAME: 'fake'})
    response = client.get(reverse('home'))
    assert not is_cached(response)
Beispiel #23
0
    def post_request(self, page, lang, data):
        """
        Create a POST request for the given page and language with CSRF disabled

        :param page: current page object
        :param lang: request language
        :return: request
        """
        request = self.request_factory.post(page.get_path(lang), data)
        request.current_page = page
        request.user = self.user
        request.session = {}
        request.cookies = SimpleCookie()
        request.errors = StringIO()
        request._dont_enforce_csrf_checks = True
        return request
Beispiel #24
0
 def test_decode_2(self):
     """
     Test that we haven't broken normal encoding
     """
     c = SimpleCookie()
     c["test"] = b"\xf0"
     c2 = SimpleCookie()
     c2.load(c.output()[12:])
     self.assertEqual(c["test"].value, c2["test"].value)
     c3 = parse_cookie(c.output()[12:])
     self.assertEqual(c["test"].value, c3["test"])
Beispiel #25
0
 def test_decode(self):
     """
     Test that we can still preserve semi-colons and commas
     """
     c = SimpleCookie()
     c["test"] = "An,awkward;value"
     c2 = SimpleCookie()
     c2.load(c.output()[12:])
     self.assertEqual(c["test"].value, c2["test"].value)
     c3 = parse_cookie(c.output()[12:])
     self.assertEqual(c["test"].value, c3["test"])
Beispiel #26
0
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
Beispiel #27
0
    def test_logout03(self):
        # Iniciar sesión.
        response = self.client.post('/auth/login',
                                    self.credentials,
                                    follow=True)
        self.assertTrue('sessionid' in response.cookies,
                        "La respuesta no contiene la cookie de sesión.")
        sessionid = response.cookies['sessionid']

        # Cerrar sesión
        response = self.client.get('/auth/logout', follow=True)
        self.assertEqual("", response.cookies['sessionid'].value,
                         "No se eliminó la cookie de sesión.")

        # No debería estar autenticado
        self.client.cookies = SimpleCookie({'sessionid': sessionid})
        response = self.client.get('/buscar')
        self.assertFalse(response.context['user'].is_authenticated)
Beispiel #28
0
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        UserModel = get_user_model()
        if self.session:
            request.session = self.session
            uid = self.session.get("_auth_user_id")
            if uid:
                request.user = UserModel._default_manager.get(pk=uid)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
Beispiel #29
0
    def _prepare_request(self,
                         request,
                         page,
                         user,
                         lang,
                         use_middlewares,
                         use_toolbar=False,
                         secure=False):
        from django.contrib.auth.models import AnonymousUser
        from importlib import import_module

        engine = import_module(settings.SESSION_ENGINE)

        request.current_page = SimpleLazyObject(lambda: page)
        if not user:
            if self._login_context:
                user = self._login_context.user
            else:
                user = AnonymousUser()
        if user.is_authenticated:
            session_key = user._meta.pk.value_to_string(user)
        else:
            session_key = 'session_key'

        request.user = user
        request._cached_user = user
        request.session = engine.SessionStore(session_key)
        if secure:
            request.environ['SERVER_PORT'] = str('443')
            request.environ['wsgi.url_scheme'] = str('https')
        request.cookies = SimpleCookie()
        request.errors = StringIO()
        request.LANGUAGE_CODE = lang
        if request.method == 'POST':
            request._dont_enforce_csrf_checks = True
        # Let's use middleware in case requested, otherwise just use CMS toolbar if needed
        if use_middlewares:
            self._apply_middlewares(request)
        elif use_toolbar:
            from cms.middleware.toolbar import ToolbarMiddleware
            mid = ToolbarMiddleware()
            mid.process_request(request)
        return request
Beispiel #30
0
    def _prepare_request(self,
                         request,
                         page,
                         user,
                         lang,
                         use_middlewares,
                         use_toolbar=False,
                         secure=False):
        from django.contrib.auth.models import AnonymousUser

        request.current_page = SimpleLazyObject(lambda: page)
        if not user:
            if self._login_context:
                user = self._login_context.user
            else:
                user = AnonymousUser()
        request.user = user
        request._cached_user = user
        request.session = {}
        if secure:
            request.environ['SERVER_PORT'] = str('443')
            request.environ['wsgi.url_scheme'] = str('https')
        if user.is_authenticated():
            request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
        request.cookies = SimpleCookie()
        request.errors = StringIO()
        request.LANGUAGE_CODE = lang
        if request.method == 'POST':
            request._dont_enforce_csrf_checks = True
        # Let's use middleware in case requested, otherwise just use CMS toolbar if needed
        if use_middlewares:
            handler = BaseHandler()
            handler.load_middleware()
            for middleware_method in handler._request_middleware:
                if middleware_method(request):
                    raise Exception('Couldn\'t create request mock object -'
                                    'request middleware returned a response')
        elif use_toolbar:
            from cms.middleware.toolbar import ToolbarMiddleware
            mid = ToolbarMiddleware()
            mid.process_request(request)
        return request
Beispiel #31
0
    def test_not_refresh_but_success(self):
        class req:
            user = self.user
            client = self.client
            scopes = ['all']

        at = JwtHandler.generate(req)

        response = Client().post(reverse('ridi:token'),
                                 HTTP_HOST=GeneralConfig.get_site_domain(),
                                 HTTP_COOKIE=SimpleCookie({
                                     'ridi-at': at
                                 }).output(header='', sep='; '),
                                 secure=True)

        self.assertEqual(response.status_code, 200)

        data = json.dumps(response.content.decode('utf8'))
        self.assertIn('expires_at', data)
        self.assertIn('expires_in', data)
Beispiel #32
0
    def get_request(self, path, user, lang, secure=False):
        from django.contrib.auth.models import AnonymousUser
        request = self.request_factory.get(path, secure=secure)

        if not user:
            user = AnonymousUser()
        request.user = user
        request._cached_user = user
        request.session = {}
        if secure:
            request.environ['SERVER_PORT'] = str('443')
            request.environ['wsgi.url_scheme'] = str('https')
        if callable_or_bool(user.is_authenticated):
            request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
        request.cookies = SimpleCookie()
        request.errors = StringIO()
        request.LANGUAGE_CODE = lang
        if request.method == 'POST':
            request._dont_enforce_csrf_checks = True
        return request
Beispiel #33
0
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        # Create a fake request that goes through request middleware
        request = self.request().request_instance

        engine = import_module(settings.SESSION_ENGINE)
        UserModel = get_user_model()
        if self.session:
            request.session = self.session
            uid = self.session.get("_auth_user_id")
            if uid:
                request.user = UserModel._default_manager.get(pk=uid)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()
Beispiel #34
0
    def api_call(self, url_name, method, session_id=None, authenticated=False, **data):
        try:
            url = reverse(url_name)
        except NoReverseMatch:
            url = url_name
        method = getattr(self.client, method.lower())
        kwargs = {"content_type": "application/json"}
        if session_id is not None:
            auth_type = "AUTH" if authenticated else "ANON"
            kwargs["HTTP_SESSION_ID"] = "SID:%s:testserver:%s" % (auth_type, session_id)

        response = None
        if data:
            response = method(url, json.dumps(data), **kwargs)
        else:
            response = method(url, **kwargs)
        # throw away cookies when using session_id authentication
        if session_id is not None:
            self.client.cookies = SimpleCookie()

        return response
Beispiel #35
0
    def test_refresh_success_with_auto_login_is_zero(self):
        api = StoreApi()
        with requests_mock.mock() as m:
            m.get(api._make_url(StoreApi.ACCOUNT_INFO),
                  json={'result': {
                      'idx': 1,
                      'id': 'testuser'
                  }})
            response = Client().post(reverse('ridi:token'),
                                     HTTP_HOST=GeneralConfig.get_site_domain(),
                                     HTTP_COOKIE=SimpleCookie({
                                         'ridi-rt':
                                         self.refresh_token.token,
                                         'ridi-al':
                                         '0'
                                     }).output(header='', sep='; '),
                                     secure=True)

        self.assertEqual(response.status_code, 200)

        data = json.dumps(response.content.decode('utf8'))
        self.assertIn('expires_at', data)
        self.assertIn('expires_in', data)

        self.assertIn(ACCESS_TOKEN_COOKIE_KEY, response.cookies)
        self.assertIn(REFRESH_TOKEN_COOKIE_KEY, response.cookies)

        self.assertEqual(response.cookies[ACCESS_TOKEN_COOKIE_KEY]['max-age'],
                         '')
        self.assertEqual(response.cookies[ACCESS_TOKEN_COOKIE_KEY]['expires'],
                         '')

        self.assertEqual(response.cookies[REFRESH_TOKEN_COOKIE_KEY]['max-age'],
                         '')
        self.assertEqual(response.cookies[REFRESH_TOKEN_COOKIE_KEY]['expires'],
                         '')
Beispiel #36
0
 def test_load_dict(self):
     c = SimpleCookie()
     c.load({"name": "val"})
     self.assertEqual(c["name"].value, "val")
Beispiel #37
0
 def test_load_dict(self):
     c = SimpleCookie()
     c.load({'name': 'val'})
     self.assertEqual(c['name'].value, 'val')
Beispiel #38
0
 def test_encode(self):
     """Semicolons and commas are encoded."""
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     self.assertNotIn(";", c.output().rstrip(';'))  # IE compat
     self.assertNotIn(",", c.output().rstrip(';'))  # Safari compat
Beispiel #39
0
 def test_samesite(self):
     c = SimpleCookie('name=value; samesite=lax; httponly')
     self.assertEqual(c['name']['samesite'], 'lax')
     self.assertIn('SameSite=lax', c.output())
    def test_follow_with_cookie(self):
        #######################################
        # Generate the voter_device_id cookie
        response10 = self.client.get(self.generate_voter_device_id_url)
        json_data10 = json.loads(response10.content.decode())

        # Make sure we got back a voter_device_id we can use
        self.assertEqual('voter_device_id' in json_data10, True,
                         "voter_device_id expected in the deviceIdGenerateView json response")

        # Now save the retrieved voter_device_id in a mock cookie
        cookies = SimpleCookie()
        cookies["voter_device_id"] = json_data10['voter_device_id']
        self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        #######################################
        # Create a voter so we can test retrieve
        response11 = self.client.get(self.voter_create_url)
        json_data11 = json.loads(response11.content.decode())

        self.assertEqual('status' in json_data11, True,
                         "status expected in the voterOrganizationFollowView json response but not found")
        self.assertEqual('voter_device_id' in json_data11, True,
                         "voter_device_id expected in the voterOrganizationFollowView json response but not found")

        # With a brand new voter_device_id, a new voter record should be created
        self.assertEqual(
            json_data11['status'], 'VOTER_CREATED',
            "status: {status} (VOTER_CREATED expected in voterOrganizationFollowView), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data11['status'], voter_device_id=json_data11['voter_device_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id isn't passed in
        response12 = self.client.get(self.organization_follow_url)
        json_data12 = json.loads(response12.content.decode())

        self.assertEqual('status' in json_data12, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data12, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data12, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data12['status'], 'VALID_ORGANIZATION_ID_MISSING',
            "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data12['status'], voter_device_id=json_data12['voter_device_id']))
        self.assertEqual(json_data12['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data12['organization_id'], 0,
                         "organization_id == 0 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data12['organization_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id isn't passed in
        response13 = self.client.get(self.organization_follow_ignore_url)
        json_data13 = json.loads(response13.content.decode())

        self.assertEqual('status' in json_data13, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data13, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data13, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data13, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data13['status'], 'VALID_ORGANIZATION_ID_MISSING',
            "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
                status=json_data13['status'], voter_device_id=json_data13['voter_device_id']))
        self.assertEqual(json_data13['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data13['organization_id'], 0,
                         "organization_id == 0 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data13['organization_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id isn't passed in
        response14 = self.client.get(self.organization_stop_following_url)
        json_data14 = json.loads(response14.content.decode())

        self.assertEqual('status' in json_data14, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data14, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data14, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data14, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data14['status'], 'VALID_ORGANIZATION_ID_MISSING',
            "status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
                status=json_data14['status'], voter_device_id=json_data14['voter_device_id']))
        self.assertEqual(json_data14['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data14['organization_id'], 0,
                         "organization_id == 0 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data14['organization_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
        response15 = self.client.get(self.organization_follow_url, {'organization_id': 1})
        json_data15 = json.loads(response15.content.decode())

        self.assertEqual('status' in json_data15, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data15, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data15, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data15, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data15['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING',
            "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data15['status'], voter_device_id=json_data15['voter_device_id']))
        self.assertEqual(json_data15['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data15['organization_id'], 1,
                         "organization_id == 1 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data15['organization_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
        response16 = self.client.get(self.organization_follow_ignore_url, {'organization_id': 1})
        json_data16 = json.loads(response16.content.decode())

        self.assertEqual('status' in json_data16, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data16, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data16, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data16, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data16['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE',
            "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data16['status'], voter_device_id=json_data16['voter_device_id']))
        self.assertEqual(json_data16['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data16['organization_id'], 1,
                         "organization_id == 1 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data16['organization_id']))

        #######################################
        # Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
        response17 = self.client.get(self.organization_stop_following_url, {'organization_id': 1})
        json_data17 = json.loads(response17.content.decode())

        self.assertEqual('status' in json_data17, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data17, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data17, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data17, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data17['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING',
            "status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data17['status'], voter_device_id=json_data17['voter_device_id']))
        self.assertEqual(json_data17['success'], False, "success 'False' expected, True returned")
        self.assertEqual(json_data17['organization_id'], 1,
                         "organization_id == 1 expected, organization_id: {organization_id} returned".format(
                             organization_id=json_data17['organization_id']))

        #######################################
        # Add an organization so we can test all of the 'follow' states
        organization1 = Organization.objects.create_organization_simple(
            organization_name="Org1",
            organization_website="www.org1.org",
            organization_twitter_handle="org1",
        )

        #######################################
        # Make sure the correct results are given when saved successfully
        response18 = self.client.get(self.organization_follow_url, {'organization_id': organization1.id})
        json_data18 = json.loads(response18.content.decode())

        self.assertEqual('status' in json_data18, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data18, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data18, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data18, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data18['status'], 'FOLLOWING',
            "status: {status} (FOLLOWING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data18['status'], voter_device_id=json_data18['voter_device_id']))
        self.assertEqual(json_data18['success'], True, "success 'True' expected, False returned")
        self.assertEqual(json_data18['organization_id'], organization1.id,
                         "organization_id returned (organization_id: {organization_id}) didn't match"
                         "original passed in".format(
                             organization_id=json_data18['organization_id']))

        #######################################
        # Make sure the correct results are given when saved successfully
        response19 = self.client.get(self.organization_follow_ignore_url, {'organization_id': organization1.id})
        json_data19 = json.loads(response19.content.decode())

        self.assertEqual('status' in json_data19, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data19, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data19, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data19, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data19['status'], 'IGNORING',
            "status: {status} (IGNORING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data19['status'], voter_device_id=json_data19['voter_device_id']))
        self.assertEqual(json_data19['success'], True, "success 'True' expected, False returned")
        self.assertEqual(json_data19['organization_id'], organization1.id,
                         "organization_id returned (organization_id: {organization_id}) didn't match"
                         "original passed in".format(
                             organization_id=json_data19['organization_id']))

        #######################################
        # Make sure the correct results are given when saved successfully
        response20 = self.client.get(self.organization_stop_following_url, {'organization_id': organization1.id})
        json_data20 = json.loads(response20.content.decode())

        self.assertEqual('status' in json_data20, True, "'status' expected in the json response, and not found")
        self.assertEqual('success' in json_data20, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_id' in json_data20, True,
                         "'organization_id' expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data20, True,
                         "'voter_device_id' expected in the json response, and not found")
        self.assertEqual(
            json_data20['status'], 'STOPPED_FOLLOWING',
            "status: {status} (STOPPED_FOLLOWING expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data20['status'], voter_device_id=json_data20['voter_device_id']))
        self.assertEqual(json_data20['success'], True, "success 'True' expected, False returned")
        self.assertEqual(json_data20['organization_id'], organization1.id,
                         "organization_id returned (organization_id: {organization_id}) didn't match"
                         "original passed in".format(
                             organization_id=json_data20['organization_id']))
    def test_retrieve_with_cookie(self):
        """
        Test the various cookie states
        :return:
        """

        #######################################
        # Generate the voter_device_id cookie
        response01 = self.client.get(self.generate_voter_device_id_url)
        json_data01 = json.loads(response01.content)

        # Make sure we got back a voter_device_id we can use
        self.assertEqual('voter_device_id' in json_data01, True,
                         "voter_device_id expected in the deviceIdGenerateView json response")

        # Now save the retrieved voter_device_id in a mock cookie
        cookies = SimpleCookie()
        cookies["voter_device_id"] = json_data01['voter_device_id']
        self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        #######################################
        # With a cookie, but without a voter_id in the database, we don't expect valid response
        response02 = self.client.get(self.voter_guides_to_follow_retrieve_url)
        json_data02 = json.loads(response02.content)

        self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found")
        self.assertEqual('voter_device_id' in json_data02, True,
                         "voter_device_id expected in the voterGuidesToFollowRetrieveView json response, and not found")

        self.assertEqual(
            json_data02['status'], 'ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID',
            "status: {status} (ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID expected), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data02['status'], voter_device_id=json_data02['voter_device_id']))

        #######################################
        # Create a voter so we can test retrieve
        response03 = self.client.get(self.voter_create_url)
        json_data03 = json.loads(response03.content)

        self.assertEqual('status' in json_data03, True,
                         "status expected in the voterCreateView json response but not found")
        self.assertEqual('voter_device_id' in json_data03, True,
                         "voter_device_id expected in the voterCreateView json response but not found")

        # With a brand new voter_device_id, a new voter record should be created
        self.assertEqual(
            json_data03['status'], 'VOTER_CREATED',
            "status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
                status=json_data03['status'], voter_device_id=json_data03['voter_device_id']))

        #######################################
        # Test the response before any voter guides exist
        response04 = self.client.get(self.voter_guides_to_follow_retrieve_url)
        json_data04 = json.loads(response04.content)

        self.assertEqual('status' in json_data04, True,
                         "status expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('success' in json_data04, True,
                         "success expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('voter_device_id' in json_data04, True,
                         "voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('voter_guides' in json_data04, True,
                         "voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual(
            json_data04['status'], 'NO_VOTER_GUIDES_FOUND',
            "status: {status} (NO_VOTER_GUIDES_FOUND expected), voter_device_id: {voter_device_id}".format(
                status=json_data04['status'], voter_device_id=json_data04['voter_device_id']))


        #######################################
        # Create organization
        organization1 = Organization.objects.create_organization(
            organization_name="Org1",
            organization_website="www.org1.org",
            organization_twitter="org1",
        )

        #######################################
        # Check to make sure there is 1 organization
        response10 = self.client.get(self.organization_count_url)
        json_data10 = json.loads(response10.content)

        self.assertEqual('success' in json_data10, True, "'success' expected in the json response, and not found")
        self.assertEqual('organization_count' in json_data10, True,
                         "'organization_count' expected in the organizationRetrieve json response")
        self.assertEqual(
            json_data10['organization_count'], 1,
            "success: {success} (organization_count '1' expected), organization_count: {organization_count}".format(
                success=json_data10['success'], organization_count=json_data10['organization_count']))

        #######################################
        # Create candidate_campaign


        #######################################
        # Create position where organization is supporting candidate


        #######################################
        # Test the response with one voter guide
        response40 = self.client.get(self.voter_guides_to_follow_retrieve_url)
        json_data40 = json.loads(response40.content)

        self.assertEqual('status' in json_data40, True,
                         "status expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('success' in json_data40, True,
                         "success expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('voter_device_id' in json_data40, True,
                         "voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found")
        self.assertEqual('voter_guides' in json_data40, True,
                         "voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found")
        # Make sure all voter guides returned have the expected array keys
        for one_voter_guide in json_data40['voter_guides']:
            self.assertEqual('google_civic_election_id' in one_voter_guide, True,
                             "google_civic_election_id expected in voterGuidesToFollowRetrieveView json but not found")
            self.assertEqual('voter_guide_owner_type' in one_voter_guide, True,
                             "voter_guide_owner_type expected in voterGuidesToFollowRetrieveView json but not found")
            self.assertEqual('organization_we_vote_id' in one_voter_guide, True,
                             "organization_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found")
            self.assertEqual('public_figure_we_vote_id' in one_voter_guide, True,
                             "public_figure_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found")
            self.assertEqual('owner_voter_id' in one_voter_guide, True,
                             "owner_voter_id expected in voterGuidesToFollowRetrieveView json but not found")
            self.assertEqual('last_updated' in one_voter_guide, True,
                             "last_updated expected in voterGuidesToFollowRetrieveView json but not found")
Beispiel #42
0
class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """

    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables
        environ = {
            "HTTP_COOKIE": self.cookies.output(header="", sep="; "),
            "PATH_INFO": str("/"),
            "REMOTE_ADDR": str("127.0.0.1"),
            "REQUEST_METHOD": str("GET"),
            "SCRIPT_NAME": str(""),
            "SERVER_NAME": str("testserver"),
            "SERVER_PORT": str("80"),
            "SERVER_PROTOCOL": str("HTTP/1.1"),
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": str("http"),
            "wsgi.input": FakePayload(b""),
            "wsgi.errors": self.errors,
            "wsgi.multiprocess": True,
            "wsgi.multithread": False,
            "wsgi.run_once": False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _encode_data(self, data, content_type):
        if content_type is MULTIPART_CONTENT:
            return encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            return force_bytes(data, encoding=charset)

    def _get_path(self, parsed):
        path = force_str(parsed[2])
        # If there are parameters, add them
        if parsed[3]:
            path += str(";") + force_str(parsed[3])
        path = unquote(path)
        # WSGI requires latin-1 encoded strings. See get_path_info().
        if six.PY3:
            path = path.encode("utf-8").decode("iso-8859-1")
        return path

    def get(self, path, data={}, **extra):
        "Construct a GET request."

        parsed = urlparse(path)
        query_string = urlencode(data, doseq=True) or force_str(parsed[4])
        if six.PY3:
            query_string = query_string.encode("utf-8").decode("iso-8859-1")

        r = {"PATH_INFO": self._get_path(parsed), "QUERY_STRING": query_string, "REQUEST_METHOD": str("GET")}
        r.update(extra)
        return self.request(**r)

    def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
        "Construct a POST request."

        post_data = self._encode_data(data, content_type)

        parsed = urlparse(path)
        query_string = force_str(parsed[4])
        if six.PY3:
            query_string = query_string.encode("utf-8").decode("iso-8859-1")

        r = {
            "CONTENT_LENGTH": len(post_data),
            "CONTENT_TYPE": content_type,
            "PATH_INFO": self._get_path(parsed),
            "QUERY_STRING": query_string,
            "REQUEST_METHOD": str("POST"),
            "wsgi.input": FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        query_string = urlencode(data, doseq=True) or force_str(parsed[4])
        if six.PY3:
            query_string = query_string.encode("utf-8").decode("iso-8859-1")

        r = {"PATH_INFO": self._get_path(parsed), "QUERY_STRING": query_string, "REQUEST_METHOD": str("HEAD")}
        r.update(extra)
        return self.request(**r)

    def options(self, path, data="", content_type="application/octet-stream", **extra):
        "Construct an OPTIONS request."
        return self.generic("OPTIONS", path, data, content_type, **extra)

    def put(self, path, data="", content_type="application/octet-stream", **extra):
        "Construct a PUT request."
        return self.generic("PUT", path, data, content_type, **extra)

    def patch(self, path, data="", content_type="application/octet-stream", **extra):
        "Construct a PATCH request."
        return self.generic("PATCH", path, data, content_type, **extra)

    def delete(self, path, data="", content_type="application/octet-stream", **extra):
        "Construct a DELETE request."
        return self.generic("DELETE", path, data, content_type, **extra)

    def generic(self, method, path, data="", content_type="application/octet-stream", **extra):
        parsed = urlparse(path)
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {"PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": str(method)}
        if data:
            r.update({"CONTENT_LENGTH": len(data), "CONTENT_TYPE": str(content_type), "wsgi.input": FakePayload(data)})
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get("QUERY_STRING"):
            query_string = force_bytes(parsed[4])
            # WSGI requires latin-1 encoded strings. See get_path_info().
            if six.PY3:
                query_string = query_string.decode("iso-8859-1")
            r["QUERY_STRING"] = query_string
        return self.request(**r)
Beispiel #43
0
 def test_httponly_after_load(self):
     c = SimpleCookie()
     c.load("name=val")
     c['name']['httponly'] = True
     self.assertTrue(c['name']['httponly'])
Beispiel #44
0
 def test_samesite(self):
     c = SimpleCookie('name=value; samesite=lax; httponly')
     self.assertEqual(c['name']['samesite'], 'lax')
     self.assertIn('SameSite=lax', c.output())
Beispiel #45
0
 def test_encode(self):
     """Semicolons and commas are encoded."""
     c = SimpleCookie()
     c['test'] = "An,awkward;value"
     self.assertNotIn(";", c.output().rstrip(';'))  # IE compat
     self.assertNotIn(",", c.output().rstrip(';'))  # Safari compat
Beispiel #46
0
class RequestFactory:
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
        self.json_encoder = json_encoder
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See https://www.python.org/dev/peps/pep-3333/#environ-variables
        return {
            'HTTP_COOKIE': '; '.join(sorted(
                '%s=%s' % (morsel.key, morsel.coded_value)
                for morsel in self.cookies.values()
            )),
            'PATH_INFO': '/',
            'REMOTE_ADDR': '127.0.0.1',
            'REQUEST_METHOD': 'GET',
            'SCRIPT_NAME': '',
            'SERVER_NAME': 'testserver',
            'SERVER_PORT': '80',
            'SERVER_PROTOCOL': 'HTTP/1.1',
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': 'http',
            'wsgi.input': FakePayload(b''),
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': False,
            'wsgi.run_once': False,
            **self.defaults,
            **request,
        }

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _encode_data(self, data, content_type):
        if content_type is MULTIPART_CONTENT:
            return encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match[1]
            else:
                charset = settings.DEFAULT_CHARSET
            return force_bytes(data, encoding=charset)

    def _encode_json(self, data, content_type):
        """
        Return encoded JSON if data is a dict, list, or tuple and content_type
        is application/json.
        """
        should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, (dict, list, tuple))
        return json.dumps(data, cls=self.json_encoder) if should_encode else data

    def _get_path(self, parsed):
        path = parsed.path
        # If there are parameters, add them
        if parsed.params:
            path += ";" + parsed.params
        path = unquote_to_bytes(path)
        # Replace the behavior where non-ASCII values in the WSGI environ are
        # arbitrarily decoded with ISO-8859-1.
        # Refs comment in `get_bytes_from_wsgi()`.
        return path.decode('iso-8859-1')

    def get(self, path, data=None, secure=False, **extra):
        """Construct a GET request."""
        data = {} if data is None else data
        return self.generic('GET', path, secure=secure, **{
            'QUERY_STRING': urlencode(data, doseq=True),
            **extra,
        })

    def post(self, path, data=None, content_type=MULTIPART_CONTENT,
             secure=False, **extra):
        """Construct a POST request."""
        data = self._encode_json({} if data is None else data, content_type)
        post_data = self._encode_data(data, content_type)

        return self.generic('POST', path, post_data, content_type,
                            secure=secure, **extra)

    def head(self, path, data=None, secure=False, **extra):
        """Construct a HEAD request."""
        data = {} if data is None else data
        return self.generic('HEAD', path, secure=secure, **{
            'QUERY_STRING': urlencode(data, doseq=True),
            **extra,
        })

    def trace(self, path, secure=False, **extra):
        """Construct a TRACE request."""
        return self.generic('TRACE', path, secure=secure, **extra)

    def options(self, path, data='', content_type='application/octet-stream',
                secure=False, **extra):
        "Construct an OPTIONS request."
        return self.generic('OPTIONS', path, data, content_type,
                            secure=secure, **extra)

    def put(self, path, data='', content_type='application/octet-stream',
            secure=False, **extra):
        """Construct a PUT request."""
        data = self._encode_json(data, content_type)
        return self.generic('PUT', path, data, content_type,
                            secure=secure, **extra)

    def patch(self, path, data='', content_type='application/octet-stream',
              secure=False, **extra):
        """Construct a PATCH request."""
        data = self._encode_json(data, content_type)
        return self.generic('PATCH', path, data, content_type,
                            secure=secure, **extra)

    def delete(self, path, data='', content_type='application/octet-stream',
               secure=False, **extra):
        """Construct a DELETE request."""
        data = self._encode_json(data, content_type)
        return self.generic('DELETE', path, data, content_type,
                            secure=secure, **extra)

    def generic(self, method, path, data='',
                content_type='application/octet-stream', secure=False,
                **extra):
        """Construct an arbitrary HTTP request."""
        parsed = urlparse(str(path))  # path can be lazy
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO': self._get_path(parsed),
            'REQUEST_METHOD': method,
            'SERVER_PORT': '443' if secure else '80',
            'wsgi.url_scheme': 'https' if secure else 'http',
        }
        if data:
            r.update({
                'CONTENT_LENGTH': str(len(data)),
                'CONTENT_TYPE': content_type,
                'wsgi.input': FakePayload(data),
            })
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get('QUERY_STRING'):
            # WSGI requires latin-1 encoded strings. See get_path_info().
            query_string = parsed[4].encode().decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        return self.request(**r)
Beispiel #47
0
 def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
     self.json_encoder = json_encoder
     self.defaults = defaults
     self.cookies = SimpleCookie()
     self.errors = BytesIO()
Beispiel #48
0
 def test_load_dict(self):
     c = SimpleCookie()
     c.load({'name': 'val'})
     self.assertEqual(c['name'].value, 'val')
Beispiel #49
0
class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables
        environ = {
            'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
            'PATH_INFO': str('/'),
            'REMOTE_ADDR': str('127.0.0.1'),
            'REQUEST_METHOD': str('GET'),
            'SCRIPT_NAME': str(''),
            'SERVER_NAME': str('testserver'),
            'SERVER_PORT': str('80'),
            'SERVER_PROTOCOL': str('HTTP/1.1'),
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': str('http'),
            'wsgi.input': FakePayload(b''),
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': False,
            'wsgi.run_once': False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _encode_data(self, data, content_type):
        if content_type is MULTIPART_CONTENT:
            return encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            return force_bytes(data, encoding=charset)

    def _get_path(self, parsed):
        path = force_str(parsed[2])
        # If there are parameters, add them
        if parsed[3]:
            path += str(";") + force_str(parsed[3])
        path = uri_to_iri(path).encode(UTF_8)
        # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
        # decoded with ISO-8859-1. We replicate this behavior here.
        # Refs comment in `get_bytes_from_wsgi()`.
        return path.decode(ISO_8859_1) if six.PY3 else path

    def get(self, path, data=None, secure=False, **extra):
        "Construct a GET request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('GET', path, secure=secure, **r)

    def post(self, path, data=None, content_type=MULTIPART_CONTENT,
             secure=False, **extra):
        "Construct a POST request."

        data = {} if data is None else data
        post_data = self._encode_data(data, content_type)

        return self.generic('POST', path, post_data, content_type,
                            secure=secure, **extra)

    def head(self, path, data=None, secure=False, **extra):
        "Construct a HEAD request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('HEAD', path, secure=secure, **r)

    def trace(self, path, secure=False, **extra):
        "Construct a TRACE request."
        return self.generic('TRACE', path, secure=secure, **extra)

    def options(self, path, data='', content_type='application/octet-stream',
                secure=False, **extra):
        "Construct an OPTIONS request."
        return self.generic('OPTIONS', path, data, content_type,
                            secure=secure, **extra)

    def put(self, path, data='', content_type='application/octet-stream',
            secure=False, **extra):
        "Construct a PUT request."
        return self.generic('PUT', path, data, content_type,
                            secure=secure, **extra)

    def patch(self, path, data='', content_type='application/octet-stream',
              secure=False, **extra):
        "Construct a PATCH request."
        return self.generic('PATCH', path, data, content_type,
                            secure=secure, **extra)

    def delete(self, path, data='', content_type='application/octet-stream',
               secure=False, **extra):
        "Construct a DELETE request."
        return self.generic('DELETE', path, data, content_type,
                            secure=secure, **extra)

    def generic(self, method, path, data='',
                content_type='application/octet-stream', secure=False,
                **extra):
        """Constructs an arbitrary HTTP request."""
        parsed = urlparse(force_str(path))
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO': self._get_path(parsed),
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        }
        if data:
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get('QUERY_STRING'):
            query_string = force_bytes(parsed[4])
            # WSGI requires latin-1 encoded strings. See get_path_info().
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        return self.request(**r)
Beispiel #50
0
class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables
        environ = {
            'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
            'PATH_INFO': str('/'),
            'REMOTE_ADDR': str('127.0.0.1'),
            'REQUEST_METHOD': str('GET'),
            'SCRIPT_NAME': str(''),
            'SERVER_NAME': str('testserver'),
            'SERVER_PORT': str('80'),
            'SERVER_PROTOCOL': str('HTTP/1.1'),
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': str('http'),
            'wsgi.input': FakePayload(b''),
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': False,
            'wsgi.run_once': False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _encode_data(self, data, content_type):
        if content_type is MULTIPART_CONTENT:
            return encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            return force_bytes(data, encoding=charset)

    def _get_path(self, parsed):
        path = force_str(parsed[2])
        # If there are parameters, add them
        if parsed[3]:
            path += str(";") + force_str(parsed[3])
        path = uri_to_iri(path).encode(UTF_8)
        # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
        # decoded with ISO-8859-1. We replicate this behavior here.
        # Refs comment in `get_bytes_from_wsgi()`.
        return path.decode(ISO_8859_1) if six.PY3 else path

    def get(self, path, data=None, secure=False, **extra):
        "Construct a GET request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('GET', path, secure=secure, **r)

    def post(self,
             path,
             data=None,
             content_type=MULTIPART_CONTENT,
             secure=False,
             **extra):
        "Construct a POST request."

        data = {} if data is None else data
        post_data = self._encode_data(data, content_type)

        return self.generic('POST',
                            path,
                            post_data,
                            content_type,
                            secure=secure,
                            **extra)

    def head(self, path, data=None, secure=False, **extra):
        "Construct a HEAD request."

        data = {} if data is None else data
        r = {
            'QUERY_STRING': urlencode(data, doseq=True),
        }
        r.update(extra)
        return self.generic('HEAD', path, secure=secure, **r)

    def trace(self, path, secure=False, **extra):
        "Construct a TRACE request."
        return self.generic('TRACE', path, secure=secure, **extra)

    def options(self,
                path,
                data='',
                content_type='application/octet-stream',
                secure=False,
                **extra):
        "Construct an OPTIONS request."
        return self.generic('OPTIONS',
                            path,
                            data,
                            content_type,
                            secure=secure,
                            **extra)

    def put(self,
            path,
            data='',
            content_type='application/octet-stream',
            secure=False,
            **extra):
        "Construct a PUT request."
        return self.generic('PUT',
                            path,
                            data,
                            content_type,
                            secure=secure,
                            **extra)

    def patch(self,
              path,
              data='',
              content_type='application/octet-stream',
              secure=False,
              **extra):
        "Construct a PATCH request."
        return self.generic('PATCH',
                            path,
                            data,
                            content_type,
                            secure=secure,
                            **extra)

    def delete(self,
               path,
               data='',
               content_type='application/octet-stream',
               secure=False,
               **extra):
        "Construct a DELETE request."
        return self.generic('DELETE',
                            path,
                            data,
                            content_type,
                            secure=secure,
                            **extra)

    def generic(self,
                method,
                path,
                data='',
                content_type='application/octet-stream',
                secure=False,
                **extra):
        """Constructs an arbitrary HTTP request."""
        parsed = urlparse(force_str(path))
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO': self._get_path(parsed),
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        }
        if data:
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        r.update(extra)
        # If QUERY_STRING is absent or empty, we want to extract it from the URL.
        if not r.get('QUERY_STRING'):
            query_string = force_bytes(parsed[4])
            # WSGI requires latin-1 encoded strings. See get_path_info().
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        return self.request(**r)
Beispiel #51
0
 def test_httponly_after_load(self):
     c = SimpleCookie()
     c.load("name=val")
     c['name']['httponly'] = True
     self.assertTrue(c['name']['httponly'])
Beispiel #52
0
class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        # This is a minimal valid WSGI environ dictionary, plus:
        # - HTTP_COOKIE: for cookie support,
        # - REMOTE_ADDR: often useful, see #8551.
        # See http://www.python.org/dev/peps/pep-3333/#environ-variables
        environ = {
            'HTTP_COOKIE':       self.cookies.output(header='', sep='; '),
            'PATH_INFO':         '/',
            'REMOTE_ADDR':       '127.0.0.1',
            'REQUEST_METHOD':    'GET',
            'SCRIPT_NAME':       '',
            'SERVER_NAME':       'testserver',
            'SERVER_PORT':       '80',
            'SERVER_PROTOCOL':   'HTTP/1.1',
            'wsgi.version':      (1, 0),
            'wsgi.url_scheme':   'http',
            'wsgi.input':        FakePayload(b''),
            'wsgi.errors':       self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread':  False,
            'wsgi.run_once':     False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _encode_data(self, data, content_type, ):
        if content_type is MULTIPART_CONTENT:
            return encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            return force_bytes(data, encoding=charset)

    def _get_path(self, parsed):
        # If there are parameters, add them
        if parsed[3]:
            return unquote(parsed[2] + ";" + parsed[3])
        else:
            return unquote(parsed[2])

    def get(self, path, data={}, **extra):
        "Construct a GET request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'GET',
        }
        r.update(extra)
        return self.request(**r)

    def post(self, path, data={}, content_type=MULTIPART_CONTENT,
             **extra):
        "Construct a POST request."

        post_data = self._encode_data(data, content_type)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   parsed[4],
            'REQUEST_METHOD': 'POST',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'HEAD',
        }
        r.update(extra)
        return self.request(**r)

    def options(self, path, data='', content_type='application/octet-stream',
            **extra):
        "Construct an OPTIONS request."
        return self.generic('OPTIONS', path, data, content_type, **extra)

    def put(self, path, data='', content_type='application/octet-stream',
            **extra):
        "Construct a PUT request."
        return self.generic('PUT', path, data, content_type, **extra)

    def delete(self, path, data='', content_type='application/octet-stream',
            **extra):
        "Construct a DELETE request."
        return self.generic('DELETE', path, data, content_type, **extra)

    def generic(self, method, path,
                data='', content_type='application/octet-stream', **extra):
        parsed = urlparse(path)
        data = force_bytes(data, settings.DEFAULT_CHARSET)
        r = {
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   parsed[4],
            'REQUEST_METHOD': method,
        }
        if data:
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE':   content_type,
                'wsgi.input':     FakePayload(data),
            })
        r.update(extra)
        return self.request(**r)
Beispiel #53
0
 def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
     self.json_encoder = json_encoder
     self.defaults = defaults
     self.cookies = SimpleCookie()
     self.errors = BytesIO()
Beispiel #54
0
 def reset(self):
     self.cookies = SimpleCookie()
     if hasattr(self, 'user'):
         self.user = User()
Beispiel #55
0
 def __init__(self, **defaults):
     self.defaults = defaults
     self.cookies = SimpleCookie()
     self.errors = BytesIO()
Beispiel #56
0
Datei: tests.py Projekt: g10f/sso
 def logout(self):
     self.client.logout()
     self.client.cookies = SimpleCookie()
Beispiel #57
0
 def __init__(self, **defaults):
     self.defaults = defaults
     self.cookies = SimpleCookie()
     self.errors = BytesIO()
    def test_saves_with_cookie(self):
        """
        Test the various cookie states
        :return:
        """

        #######################################
        # Generate the voter_device_id cookie
        response = self.client.get(self.generate_voter_device_id_url)
        json_data = json.loads(response.content)

        # Make sure we got back a voter_device_id we can use
        self.assertEqual('voter_device_id' in json_data, True,
                         "voter_device_id expected in the deviceIdGenerateView json response")

        # Now save the retrieved voter_device_id in a mock cookie
        cookies = SimpleCookie()
        cookies["voter_device_id"] = json_data['voter_device_id']
        self.client = Client(HTTP_COOKIE=cookies.output(header='', sep='; '))

        #######################################
        # Create a voter so we can test retrieve
        response2 = self.client.get(self.voter_create_url)
        json_data2 = json.loads(response2.content)

        self.assertEqual('status' in json_data2, True,
                         "status expected in the voterAddressSaveView json response but not found")
        self.assertEqual('voter_device_id' in json_data2, True,
                         "voter_device_id expected in the voterAddressSaveView json response but not found")

        # With a brand new voter_device_id, a new voter record should be created
        self.assertEqual(
            json_data2['status'], 'VOTER_CREATED',
            "status:  {status} (VOTER_CREATED expected in voterAddressSaveView), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))

        #######################################
        # Create a voter address so we can test retrieve
        response2 = self.client.post(self.voter_address_save_url, {'address': '123 Main Street, Oakland CA 94602'})
        json_data2 = json.loads(response2.content)

        self.assertEqual('status' in json_data2, True,
                         "status expected in the voterAddressSaveView json response but not found")
        self.assertEqual('voter_device_id' in json_data2, True,
                         "voter_device_id expected in the voterAddressSaveView json response but not found")
        self.assertEqual('success' in json_data2, True,
                         "success expected in the voterAddressSaveView json response but not found")
        self.assertEqual('address' in json_data2, True,
                         "address expected in the voterAddressSaveView json response but not found")

        # First address save
        self.assertEqual(
            json_data2['status'], 'VOTER_ADDRESS_SAVED',
            "status:  {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))

        #######################################
        # Try and save the voter address again
        response3 = self.client.post(self.voter_address_save_url, {'address': '321 Main Street, Oakland CA 94602'})
        json_data3 = json.loads(response3.content)

        # First address update
        self.assertEqual(
            json_data3['status'], 'VOTER_ADDRESS_SAVED',
            "status:  {status} (VOTER_ADDRESS_SAVED expected in voterAddressSaveView), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data3['status'], voter_device_id=json_data3['voter_device_id']))

        #######################################
        # Try and save the voter address without a post variable
        response4 = self.client.get(self.voter_address_save_url)
        json_data4 = json.loads(response4.content)

        self.assertEqual('status' in json_data4, True,
                         "status expected in the voterAddressSaveView json response but not found (no POST var)")
        self.assertEqual('voter_device_id' in json_data4, True,
                         "voter_device_id expected in the voterAddressSaveView json response but not found"
                         " (no POST var)")

        # Test error condition, missing address POST variable
        self.assertEqual(
            json_data4['status'], 'MISSING_POST_VARIABLE-ADDRESS',
            "status:  {status} (MISSING_POST_VARIABLE-ADDRESS expected in voterAddressSaveView), "
            "voter_device_id: {voter_device_id}".format(
                status=json_data4['status'], voter_device_id=json_data4['voter_device_id']))

        #######################################
        # Test to make sure the address has been saved in the database
        response4 = self.client.get(self.voter_address_retrieve_url)
        json_data4 = json.loads(response4.content)

        # Are any expected fields missing?
        self.assertEqual('success' in json_data4, True,
                         "success expected in the voterAddressSaveView json response but not found")
        self.assertEqual('address' in json_data4, True,
                         "address expected in the voterAddressSaveView json response but not found")
        # A more thorough testing of expected variables is done in test_views_voter_address_retrieve.py

        # Does address match the value inserted last?
        self.assertEqual(
            json_data4['address'], '321 Main Street, Oakland CA 94602',
            "address:  {address} ('321 Main Street, Oakland CA 94602' expected in voterAddressSaveView), "
            "voter_device_id: {voter_device_id}".format(
                address=json_data4['address'], voter_device_id=json_data4['voter_device_id']))
Beispiel #59
0
from __future__ import unicode_literals
Beispiel #60
0
 def setUp(self):
     super(TestSafeSessionMiddleware, self).setUp()
     self.user = UserFactory.create()
     self.request = get_mock_request()
     self.client.response = HttpResponse()
     self.client.response.cookies = SimpleCookie()