Example #1
0
    def test_channel_in_get(self):
        for ch in CHANNELS:
            request = Mock()
            request.path_info = "/"
            request.GET = dict(channel=ch)
            p = urlresolvers.Prefixer(request)
            eq_(p.get_channel(), ch)

        # Invalid channel
        request = Mock()
        request.path_info = "/"
        request.GET = dict(channel="bogus")
        p = urlresolvers.Prefixer(request)
        eq_(p.get_channel(), settings.DEFAULT_CHANNEL)
Example #2
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}))
Example #3
0
 def _test_mobile_persona_ctx(self):
     request = Mock()
     request.APP = amo.FIREFOX
     request.GET = {}
     request.user.is_authenticated.return_value = False
     request.amo_user.mobile_addons = []
     return {"APP": amo.FIREFOX, "LANG": "en-US", "request": request}
def test_get_results(is_valid):
    is_valid.return_value = False
    request = Mock()
    request.GET = {}
    request.default_prod = FIREFOX
    r = views._get_results(request)
    eq_(r[2], request.default_prod)
Example #5
0
    def test_pagesize(self):
        """``pagenumber`` gets the pagenumber from the request."""
        from moztrap.view.lists.templatetags.pagination import pagesize

        request = Mock()
        request.GET = {"pagenumber": 2, "pagesize": 10}
        self.assertEqual(pagesize(request), 10)
Example #6
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 setUp(self):
     request = Mock()
     request.method = "GET"
     request.GET = {"msgid": "the-msgid"}
     get_all_translations = Mock(return_value={"dummy": "json"})
     with patch("livetranslation.views.get_all_translations", get_all_translations):
         self.response = get_translations(request)
Example #8
0
    def test_get_context_data(self):
        user = Mock()
        user.domain = None
        app_id = None
        request = Mock()
        request.GET = {}
        request.openrosa_headers = {}
        timing_context = Mock()
        timing_context.to_list.return_value = []
        with patch("corehq.apps.ota.views.has_privilege", return_value=False), patch(
            "corehq.apps.hqadmin.views.get_restore_response",
            return_value=(HttpResponse("bad response", status=500), timing_context),
        ):

            view = AdminRestoreView(user=user, app_id=app_id, request=request)
            context = view.get_context_data(foo="bar", view="AdminRestoreView")
            self.assertEqual(
                context,
                {
                    "foo": "bar",
                    "view": "AdminRestoreView",
                    "payload": "<error>Unexpected restore response 500: bad response. If you believe this is a bug "
                    "please report an issue.</error>\n",
                    "restore_id": None,
                    "status_code": 500,
                    "timing_data": [],
                    "num_cases": 0,
                },
            )
Example #9
0
 def test_set_default_flavour(self):
     request = Mock()
     request.GET = {}
     middleware = SetFlavourMiddleware()
     middleware.process_request(request)
     # default flavour is set
     self.assertEqual(get_flavour(), "full")
 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)
    def test_get_limit_valid_limit(self, mock_request):
        mock_request = Mock()
        mock_request.GET = {"limit": "80"}

        expected_result = [80, self.base_error]
        actual_result = get_limit(mock_request, self.base_error)

        self.assertEqual(expected_result, actual_result)
Example #12
0
 def test_should_import_data_senders(self):
     file_name = "reporters.csv"
     request = Mock()
     request.GET = {"qqfile": file_name}
     request.raw_post_data = self.csv_data
     error_message, failure_imports, success, success_message = import_data(request=request, manager=self.dbm)
     self.assertTrue(success)
     self.assertEqual(4, get_entity_count_for_type(self.dbm, entity_type="reporter"))
 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 #14
0
    def cls(self, full_path, GET):
        """Construct mock request; instantiate and return Sort object."""
        request = Mock()
        request.GET = GET
        request.get_full_path.return_value = full_path

        from moztrap.view.lists.sort import Sort

        return Sort(request)
Example #15
0
def test_share_view():
    u = u"\u05d0\u05d5\u05e1\u05e3"
    s = encoding.smart_str(u)
    request, obj = Mock(), Mock()
    request.GET = {"service": "twitter"}
    obj.get_url_path.return_value = u
    sharing.views.share(request, obj, u, u)
    obj.get_url_path.return_value = s
    sharing.views.share(request, obj, s, s)
    def test_get_lat_long_prox_valid_lat_long_no_prox(self, mock_request):
        mock_request = Mock()
        mock_request.GET = {"lat": "45.6", "lng": "-123.4"}

        point = fromstr("POINT (-123.4000000000000057 45.6000000000000014)", srid=4326)

        expected_result = [point, 20, None, self.base_error]
        actual_result = get_lat_long_prox(mock_request, self.base_error)

        self.assertEqual(expected_result[1:], actual_result[1:])
        self.assertEqual(expected_result[0].x, actual_result[0].x)
        self.assertEqual(expected_result[0].y, actual_result[0].y)
Example #17
0
def test_share_view_for_webapp():
    u = u"\u05d0\u05d5\u05e1\u05e3"
    s = encoding.smart_str(u)
    request, obj = Mock(), Mock()
    request.GET = {"service": "twitter"}
    obj.get_url_path.return_value = u
    obj.is_webapp = Mock()
    obj.is_webapp.return_value = True
    sharing.views.share(request, obj, u, u)
    obj.get_url_path.return_value = s
    res = sharing.views.share(request, obj, s, s)
    qs = parse_qs(urlparse(res["Location"]).query)
    assert "Firefox Marketplace" in qs["status"][0], "Unexpected status: %s" % qs["status"][0]
Example #18
0
    def test_paginate_outsize_known_size(self):
        from moztrap.model.tags.models import Tag

        tpl = template.Template(
            "{% load pagination %}{% paginate queryset as pager %}"
            "{% for obj in pager.objects %}{{ obj }} {% endfor %}"
        )

        request = Mock()
        request.GET = {"pagesize": 99, "pagenumber": 1}

        qs = Tag.objects.all()
        self.assertRaises(SuspiciousOperation, tpl.render, template.Context({"request": request, "queryset": qs}))
Example #19
0
    def test_src_retained(self):
        a = Addon.objects.get(pk=4664)
        a.suggested_amount = "12"

        settings = Mock()
        settings.MAX_CONTRIBUTION = 5

        request = Mock()
        request.GET = {"src": "direct"}

        c = {"LANG": "en-us", "APP": amo.FIREFOX, "settings": settings, "request": request}

        s = contribution(c, a)
        doc = PyQuery(s)
        eq_(doc("input[name=source]").attr("value"), "direct")
Example #20
0
    def test_provides_cors_features_false(self):
        url = URL("http://moth/")
        fr = FuzzableRequest(url)

        http_response = HTTPResponse(200, "", Headers(), url, url)

        url_opener_mock = Mock()
        url_opener_mock.GET = MagicMock(return_value=http_response)

        cors = provides_cors_features(fr, url_opener_mock)

        call_header = Headers({"Origin": "www.w3af.org"}.items())
        url_opener_mock.GET.assert_called_with(url, headers=call_header)

        self.assertFalse(cors)
Example #21
0
    def test_fieldmap_and_fields(self):
        request = Mock()
        request.GET = {}
        expected_fieldmap = {
            "source_entity__id": "source_entity_id",
            "source_entity__string": "key",
            "source_entity__context": "context",
            "string": "translation",
        }
        expected_fields = [
            "source_entity__id",
            "source_entity__string",
            "source_entity__context",
            "string",
            "source_entity__pluralized",
            "rule",
        ]
        fieldmap, fields = self.obj._get_fieldmap_and_fields(request)
        self.assertEqual(fieldmap, expected_fieldmap)
        self.assertEqual(fields, expected_fields)

        request.GET["details"] = ""
        expected_fieldmap.update(
            {
                "reviewed": "reviewed",
                "wordcount": "wordcount",
                "last_update": "last_update",
                "user__username": "user",
                "source_entity__position": "position",
                "source_entity__occurrences": "occurrences",
                "source_entity__pluralized": "pluralized",
            }
        )

        expected_fields.extend(
            [
                "reviewed",
                "wordcount",
                "last_update",
                "user__username",
                "source_entity__position",
                "source_entity__occurrences",
            ]
        )

        fieldmap, fields = self.obj._get_fieldmap_and_fields(request)
        self.assertEqual(fieldmap, expected_fieldmap)
        self.assertEqual(fields, expected_fields)
Example #22
0
    def test_provides_cors_features_true(self):
        url = URL("http://moth/")
        fr = FuzzableRequest(url)

        hdrs = {"Access-Control-Allow-Origin": "http://www.w3af.org/"}.items()
        cors_headers = Headers(hdrs)
        http_response = HTTPResponse(200, "", cors_headers, url, url)

        url_opener_mock = Mock()
        url_opener_mock.GET = MagicMock(return_value=http_response)

        cors = provides_cors_features(fr, url_opener_mock)

        url_opener_mock.GET.assert_called_with(url)

        self.assertTrue(cors)
Example #23
0
    def test_contribution_box(self):
        a = Addon.objects.get(pk=7661)
        a.suggested_amount = "12"

        settings = Mock()
        settings.MAX_CONTRIBUTION = 5

        request = Mock()
        request.GET = {"src": "direct"}

        c = {"LANG": "en-us", "APP": amo.FIREFOX, "settings": settings, "request": request}

        s = contribution(c, a)
        doc = PyQuery(s)
        # make sure input boxes are rendered correctly (bug 555867)
        assert doc("input[name=onetime-amount]").length == 1
    def test_get_lat_long_prox_valid_lat_bad_long(self, mock_request):
        mock_request = Mock()
        mock_request.GET = {"lat": "45.6", "lng": "kittens"}

        expected_error = {
            "level": "Warning",
            "status": True,
            "name": "Bad location",
            "text": "There was an error with the given " "coordinates 45.6, kittens",
            "debug": "ValueError: String or unicode input unrecognized " "as WKT EWKT, and HEXEWKB.",
        }

        expected_result = [None, 20, None, expected_error]
        actual_result = get_lat_long_prox(mock_request, self.base_error)

        self.assertEqual(expected_result, actual_result)
    def test_get_limit_invalid_limit(self, mock_request):
        mock_request = Mock()
        mock_request.GET = {"limit": "I like Pi"}

        expected_error = {
            "debug": "ValueError: invalid literal for int() " "with base 10: 'I like Pi'",
            "status": True,
            "level": "Warning",
            "text": "Invalid limit. Returning all results.",
            "name": "Bad Limit",
        }

        expected_result = [None, expected_error]
        actual_result = get_limit(mock_request, self.base_error)

        self.assertEqual(expected_result, actual_result)
Example #26
0
 def test_default(self):
     request = Mock(spec_set=["GET"])
     request.GET = {}
     context = RootView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": RootView.default_show,
             "order_by": RootView.defualt_order_by,
             "options_show": RootView.show,
             "options_order_by": RootView.order_by,
             "options_paths": RootView()._get_paths(),
         },
         context,
     )
     self.assertNotIn("path", context)
     self.assertIn("results", context)
Example #27
0
    def prepare_request_mock(
        self,
        data=None,
        referer="http://localhost/user_with_workspaces/Public Workspace",
        user=None,
        extra_headers={},
        GET="",
        use_deprecated_code=False,
    ):

        request = Mock()
        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",
            "HTTP_HOST": "localhost",
            "HTTP_REFERER": referer,
        }
        if data is not None:
            request.method = "POST"
            data = data.encode("utf-8")
            request.META["content_type"] = "application/json"
            request.META["content_length"] = len(data)
            request.read.return_value = data
        else:
            request.method = "GET"

        if use_deprecated_code:
            request.META["HTTP_X_FI_WARE_OAUTH_TOKEN"] = "true"
            extra_headers = {self.deprecation_mapping[key]: value for key, value in six.iteritems(extra_headers)}
        else:
            request.META["HTTP_FIWARE_OAUTH_TOKEN"] = "true"

        request.META.update(extra_headers)
        if user is None:
            request.user = self.admin_mock
        else:
            request.user = user

        return request
    def test_get_lat_long_prox_valid_lat_no_long(self, mock_request):
        mock_request = Mock()
        mock_request.GET = {"lat": "45.6"}

        expected_error = {
            "level": "Warning",
            "status": True,
            "name": "Bad location",
            "text": "There was an error with the given " "coordinates 45.6, None",
            "debug": "GEOSException: Error encountered checking Geometry "
            'returned from GEOS C function "GEOSWKTReader_read_r".',
        }

        expected_result = [None, 20, None, expected_error]
        actual_result = get_lat_long_prox(mock_request, self.base_error)

        self.assertEqual(expected_result, actual_result)
Example #29
0
 def test_default(self):
     request = Mock(spec_set=["GET", "session"])
     request.GET = {}
     request.session = {}
     context = ProfilingView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": ProfilingView.default_show,
             "order_by": ProfilingView.defualt_order_by,
             "options_show": ProfilingView.show,
             "options_order_by": ProfilingView.order_by,
             "options_func_names": ProfilingView()._get_function_names(),
         },
         context,
     )
     self.assertNotIn("path", context)
     self.assertIn("results", context)
Example #30
0
    def setUp(self):
        from mock import Mock

        mock_request = Mock()
        mock_request.GET = {}
        mock_request.session = {"twitter_request_token_key": "key", "twitter_request_token_secret": "secret"}
        self.request = mock_request
        self.request.route_url.return_value = "/"
        # Setup mock oauth handler and tweepy client.
        self.mock_handler_factory = Mock()
        self.mock_handler = Mock()
        self.mock_handler.access_token.key = "key"
        self.mock_handler.access_token.secret = "secret"
        self.mock_handler_factory.return_value = self.mock_handler
        self.mock_api_factory = Mock()
        self.mock_client = Mock()
        self.mock_client.last_response.getheader.return_value = "read"
        self.mock_api_factory.return_value = self.mock_client