Example #1
0
def test_get_ip_helper():
    # Given I have a request object with the `HTTP_X_FORWARDED_FOR`
    # variable set with local and remote IP addresses
    request = Mock()
    request.META = {"HTTP_X_FORWARDED_FOR": "127.0.0.1,10.0.0.1,150.164.211.1"}

    # When I call the get_ip helper, it should skip the local addresses
    # and give me the first remote address
    util.get_ip(request).should.equal("150.164.211.1")

    # If the request only contain local addresses, the output should be
    # the default unknown addr
    request.META = {"HTTP_X_FORWARDED_FOR": "127.0.0.1,10.0.0.1,10.1.1.25"}
    util.get_ip(request).should.equal("0.0.0.0")
Example #2
0
    def test_auth_api_meta(self):
        request = Mock()
        request_text = base64.encodestring("test1:123")
        request.META = {"HTTP_AUTHORIZATION": "basic %s" % request_text}
        ok_(basic_auth_api(request))

        request = Mock()
        request_text = base64.encodestring("test1:1234")
        request.META = {"HTTP_AUTHORIZATION": "basic %s" % request_text}
        ok_(not basic_auth_api(request))

        request = Mock()
        request_text = base64.encodestring("test123:1234")
        request.META = {"HTTP_AUTHORIZATION": "basic %s" % request_text}
        ok_(not basic_auth_api(request))
Example #3
0
    def test_datastream_etag(self):
        rqst = Mock()
        rqst.META = {}
        # DC
        etag = datastream_etag(rqst, self.obj.pid, "DC")
        self.assertEqual(self.obj.dc.checksum, etag)

        # bogus dsid should not error
        etag = datastream_etag(rqst, self.obj.pid, "bogus-datastream-id")
        self.assertEqual(None, etag)

        # range request 1 to end should return etag
        rqst.META = {"HTTP_RANGE": "bytes=1-"}
        etag = datastream_etag(rqst, self.obj.pid, "DC")
        self.assertEqual(self.obj.dc.checksum, etag)
    def test_decorator(self):
        request = Mock()
        request.META = {"HTTP_USER_AGENT": "KDDI-SA31 UP.Browser/6.2.0.6.3.129 (GUI) MMP/2.0"}
        request.opensocial_viewer_id = "12345678"

        mw.action_log_decorator_initialized = False

        now = datetime.now()
        id = "id"

        @mw.action_log_decorator
        def logging(request):
            with mw.log().log("log1", x=10, y="str", id=id, time=now):
                pass

        mw.sender = Mock()

        logging(request)

        log1 = {
            "uid": "12345678",
            "ver": 2,
            "time": now,
            "device": DeviceType.FP,
            "id": id,
            "action": "log1",
            "x": 10,
            "y": "str",
        }
        expected = [call.emit(log1)]
        eq_(expected, mw.sender.mock_calls)
 def test_single_ip(self):
     """Test that the correct IP is returned with a single remote IP"""
     mock_request = Mock()
     mock_request.META = {"HTTP_X_FORWARDED_FOR": u"8.8.8.8", "REMOTE_ADDR": u"10.228.26.24"}
     self.middleware.process_request(mock_request)
     self.assertEqual(mock_request.META["REMOTE_ADDR"], u"8.8.8.8")
     self.assertEqual(mock_request.META["HTTP_X_FORWARDED_FOR"], u"8.8.8.8")
 def test_sets_both(self):
     """Test that both REMOTE_ADDR and HTTP_X_FORWARDED_FOR are always set"""
     mock_request = Mock()
     mock_request.META = {"HTTP_X_FORWARDED_FOR": u"8.8.8.8"}
     self.middleware.process_request(mock_request)
     self.assertEqual(mock_request.META["REMOTE_ADDR"], u"8.8.8.8")
     self.assertEqual(mock_request.META["HTTP_X_FORWARDED_FOR"], u"8.8.8.8")
Example #7
0
 def test_random_source(self, authenticate_mock):
     backend = MozilliansAuthBackend()
     request_mock = Mock()
     request_mock.META = {"HTTP_REFERER": settings.SITE_URL + "/?source=foobar"}
     backend.request = request_mock
     backend.authenticate(request=request_mock)
     eq_(backend.referral_source, None)
Example #8
0
    def prepare_request_mock(
        self,
        data,
        referer="http://localhost/user_with_workspaces/Public Workspace",
        user=None,
        extra_headers={},
        GET="",
    ):
        request = Mock()
        request.method = "POST"
        request.get_host.return_value = "localhost"
        GET_PARAMETERS = parse_qsl(GET)
        request.GET = MagicMock()
        request.GET.__len__.side_effect = lambda: len(GET_PARAMETERS)
        request.GET.__getitem__.side_effect = lambda key: GET_PARAMETERS[key]
        request.GET.urlencode.side_effect = lambda: GET
        request.COOKIES = {settings.SESSION_COOKIE_NAME: "test"}
        request.META = {
            "HTTP_ACCEPT": "application/json",
            "SERVER_PROTOCOL": "http",
            "REMOTE_ADDR": "127.0.0.1",
            "content_type": "application/json",
            "content_length": len(data),
            "HTTP_HOST": "localhost",
            "HTTP_REFERER": referer,
            "HTTP_X_FI_WARE_OAUTH_TOKEN": "true",
        }
        request.META.update(extra_headers)
        request.read.return_value = data
        if user is None:
            request.user = self.admin_mock
        else:
            request.user = user

        return request
 def test_process_request_empty_header(self):
     request = Mock(path="/")
     request.method = "OPTIONS"
     request.META = {"HTTP_ACCESS_CONTROL_REQUEST_METHOD": ""}
     with settings_override(CORS_URLS_REGEX="^.*$"):
         response = self.middleware.process_request(request)
     self.assertIsInstance(response, HttpResponse)
Example #10
0
 def test_set_flavour_through_get_parameter(self, set_flavour):
     request = Mock()
     request.META = MagicMock()
     request.GET = {"flavour": "mobile"}
     middleware = SetFlavourMiddleware()
     middleware.process_request(request)
     self.assertEqual(set_flavour.call_args, (("mobile", request), {"permanent": True}))
    def _get_response(
        self,
        is_secure=True,
        csrf_cookie_used=True,
        cross_domain_decorator=True,
        referer=None,
        host=None,
        delete_referer=False,
    ):
        """Process a request using the middleware. """
        request = Mock()
        request.META = {"HTTP_REFERER": (referer if referer is not None else self.REFERER)}
        request.is_secure = lambda: is_secure

        if host is not None:
            request.get_host = lambda: host

        if delete_referer:
            del request.META["HTTP_REFERER"]

        if csrf_cookie_used:
            request.META["CSRF_COOKIE_USED"] = True
            request.META["CSRF_COOKIE"] = self.COOKIE_VALUE

        if cross_domain_decorator:
            request.META["CROSS_DOMAIN_CSRF_COOKIE_USED"] = True

        return self.middleware.process_response(request, HttpResponse())
    def test_process_view_replace_https_referer(self):
        post_middleware = CorsPostCsrfMiddleware()
        request = Mock(path="/")
        request.method = "GET"
        request.is_secure = lambda: True
        request.META = {
            "HTTP_REFERER": "https://foo.google.com/",
            "HTTP_HOST": "foobar.com",
            "HTTP_ORIGIN": "https://foo.google.com",
        }
        with settings_override(
            CORS_URLS_REGEX="^.*$", CORS_ORIGIN_REGEX_WHITELIST=".*google.*", CORS_REPLACE_HTTPS_REFERER=True
        ):
            response = self.middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
        self.assertEquals(request.META["ORIGINAL_HTTP_REFERER"], "https://foo.google.com/")
        self.assertEquals(request.META["HTTP_REFERER"], "https://foobar.com/")

        with settings_override(CORS_URLS_REGEX="^.*$", CORS_REPLACE_HTTPS_REFERER=True):
            post_middleware.process_view(request, None, None, None)
        self.assertTrue("ORIGINAL_HTTP_REFERER" not in request.META)
        self.assertEquals(request.META["HTTP_REFERER"], "https://foo.google.com/")

        with settings_override(CORS_URLS_REGEX="^.*$", CORS_REPLACE_HTTPS_REFERER=True):
            response = post_middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
Example #13
0
 def test_get_involved_source(self, authenticate_mock):
     backend = MozilliansAuthBackend()
     request_mock = Mock()
     request_mock.META = {"HTTP_REFERER": settings.SITE_URL + "/?source=contribute"}
     backend.request = request_mock
     backend.authenticate(request=request_mock)
     eq_(backend.referral_source, "contribute")
Example #14
0
    def test_is_idevice_helper(self):
        """Verify that is_idevice detects iphone/ipad/ipod UAs."""
        request = Mock()
        request.META = {}

        # Detect iPad
        request.META["HTTP_USER_AGENT"] = (
            "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) "
            "AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 "
            "Mobile/7B314 Safari/531.21.10"
        )
        assert is_idevice(request)

        # Detect iPhone
        request.META["HTTP_USER_AGENT"] = (
            "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) "
            "AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 "
            "Safari/528.16"
        )
        assert is_idevice(request)

        # Detect iPod
        request.META["HTTP_USER_AGENT"] = (
            "Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 "
            "(KHTML,like Gecko) Version/3.0 Mobile/3A100a Safari/419.3"
        )
        assert is_idevice(request)

        # Don't detect Firefox OS
        request.META["HTTP_USER_AGENT"] = "Firefox OS UA - Mozilla/5.0 (Mobile; rv:12.0) Gecko/12.0 " "Firefox/12.0"
        assert not is_idevice(request)
 def test_no_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = -1
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.body = "a".encode("ascii") * 1000  # 1000 bytes?
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertTrue(request_model.raw_body)
Example #16
0
    def test_login_redirect_invalid_method(self):

        request = Mock()
        request.META = {}
        request.method = "POST"
        request.session.get.return_value = None
        response = login(request)
        self.assertEqual(response.status_code, 405)
Example #17
0
 def _init_request(self):
     request = Mock()
     request.META = {"HTTP_USER_AGENT": "KDDI-SA31 UP.Browser/6.2.0.6.3.129 (GUI) MMP/2.0"}
     request.opensocial_viewer_id = "12345678"
     actlogmw = mw.ActionLogMiddleware()
     mw.sender = Mock()
     actlogmw.process_request(request)
     return (actlogmw, request)
Example #18
0
    def test_call_process_response_without_opensocial_viewer_id(self):
        request = Mock()
        request.META = {"HTTP_USER_AGENT": "KDDI-SA31 UP.Browser/6.2.0.6.3.129 (GUI) MMP/2.0"}
        actlogmw = mw.ActionLogMiddleware()
        actlogmw.process_request(request)

        # Test nothing to raise.
        actlogmw.process_response(request, None)
Example #19
0
 def test_mobile_browser_agent(self, set_flavour):
     request = Mock()
     request.META = {
         'HTTP_USER_AGENT': 'My Mobile Browser',
     }
     middleware = MobileDetectionMiddleware()
     middleware.process_request(request)
     self.assertEqual(set_flavour.call_args, (('mobile', request), {}))
 def get_request(self, is_secure, http_referer):
     """
     Build a test request
     """
     request = Mock()
     request.META = {"HTTP_REFERER": http_referer}
     request.is_secure = lambda: is_secure
     return request
Example #21
0
 def test_set_default_flavour(self):
     request = Mock()
     request.META = MagicMock()
     request.GET = {}
     middleware = SetFlavourMiddleware()
     middleware.process_request(request)
     # default flavour is set
     self.assertEqual(get_flavour(), "full")
Example #22
0
 def create_task_request(self, requester_username):
     """Generate request that can be used for submitting tasks"""
     request = Mock()
     request.user = User.objects.get(username=requester_username)
     request.get_host = Mock(return_value="testhost")
     request.META = {"REMOTE_ADDR": "0:0:0:0", "SERVER_NAME": "testhost"}
     request.is_secure = Mock(return_value=False)
     return request
Example #23
0
 def test_desktop_browser_agent(self, set_flavour):
     request = Mock()
     request.META = {
         'HTTP_USER_AGENT': 'My Desktop Browser',
     }
     middleware = MobileDetectionMiddleware()
     middleware.process_request(request)
     self.assertEqual(set_flavour.call_count, 0)
Example #24
0
    def test_get_default_view_smartphone(self):

        request = Mock()
        request.META = {"HTTP_USER_AGENT": ""}
        request.session = {}
        with patch("wirecloud.platform.views.ua_parse") as ua_parse_mock:
            ua_parse_mock.return_value = Mock(is_mobile=True)
            self.assertEqual(get_default_view(request), "smartphone")
            self.assertEqual(request.session["default_mode"], "smartphone")
Example #25
0
def test_geo_ip_helper_with_an_unknown_ip():
    # Given I have a request object with the `HTTP_X_FORWARDED_FOR`
    # variable set to a false value
    request = Mock()
    request.META = {"HTTP_X_FORWARDED_FOR": ""}

    # When I call the get_ip helper, it should return a default
    # 'unknown' value
    util.get_ip(request).should.equal("0.0.0.0")
Example #26
0
 def test_plain(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "text/plain"}
     mock_request.body = "sdfsdf"
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertFalse(body)
     self.assertEqual(raw_body, mock_request.body)
 def test_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = 10  # 10kb
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.body = "a".encode("ascii") * 1024 * 100  # 100kb
     mock_request.path = reverse("silk:requests")
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertFalse(request_model.raw_body)
Example #28
0
 def test_utf_json_not_encoded(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=UTF-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d)
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(raw_body, mock_request.body)
Example #29
0
 def test_invalid_encoding_json(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=asdas-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d).encode("UTF-8")
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body, encoding="UTF-8"), d)
     self.assertEqual(raw_body, raw_body)
Example #30
0
    def test_datastream_lastmodified(self):
        rqst = Mock()
        rqst.META = {}
        # DC
        lastmod = datastream_lastmodified(rqst, self.obj.pid, "DC")
        self.assertEqual(self.obj.dc.created, lastmod)

        # bogus dsid should not error
        lastmod = datastream_lastmodified(rqst, self.obj.pid, "bogus-datastream-id")
        self.assertEqual(None, lastmod)

        # range request should not affect last modification time
        rqst.META = {"HTTP_RANGE": "bytes=1-"}
        lastmod = datastream_lastmodified(rqst, self.obj.pid, "DC")
        self.assertEqual(self.obj.dc.created, lastmod)

        # any other range request should still return last modification time
        rqst.META = {"HTTP_RANGE": "bytes=300-500"}
        lastmod = datastream_lastmodified(rqst, self.obj.pid, "DC", accept_range_request=True)
        self.assertEqual(self.obj.dc.created, lastmod)