Example #1
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_car_has_object_permission(self):
     car = Mock()
     user = Mock()
     request = Mock()
     request.user = user
     car.user = user
     permission = CarOwnerPermission()
     self.assertTrue(permission.has_object_permission(request, Mock(), car))
 def test_treatment_has_object_permission(self):
     car = Mock()
     user = Mock()
     request = Mock()
     request.user = user
     car.user = user
     treatment = Mock()
     treatment.car = car
     permission = TreatmentOwnerPermission()
     self.assertTrue(permission.has_object_permission(request, Mock(), treatment))
Example #4
0
 def login(self, adapter, provider_name):
     del adapter, provider_name
     response = Mock()
     response.error = self.error
     if self.error:
         response.user = False
     else:
         user = Mock()
         user.name = self.name
         user.email = self.email
         response.user = user
     return response
Example #5
0
def test_returns_false_if_not_in_its_slideshows():
    team = TeamFactory()
    SlideshowFactory(templates="repo/t,repo1/t", team=team)
    request = Mock()
    request.user = UserFactory()
    permission = IsAllowedToSeeTemplate()
    assert not permission.has_permission(request, Mock())
Example #6
0
    def test_addon_sharing(self):
        addon = Addon.objects.get(id=7172)

        jingo.load_helpers()
        # mock helpers
        locale_url = lambda url: url
        locale_url.__name__ = "locale_url"
        jingo.register.function(locale_url)

        request = Mock()
        request.user = DjangoUser()
        request.APP = amo.FIREFOX
        ctx = {"request": request}

        # disable cake csrf token
        cake_csrf_token = lambda: ""
        cake_csrf_token.__name__ = "cake_csrf_token"
        jingo.register.function(cake_csrf_token)

        doc = pq(addon_sharing(ctx, addon))
        self.assert_(doc.html())
        self.assertEquals(doc("li").length, len(sharing.SERVICES_LIST))

        # Make sure services are in the right order.
        for i in range(len(sharing.SERVICES_LIST)):
            self.assertEquals(doc("li").eq(i).attr("class"), sharing.SERVICES_LIST[i].shortname)
Example #7
0
    def test_tag_list(self):
        addon = Addon.objects.get(id=3615)

        request = Mock()
        request.user = addon.authors.all()[0].create_django_user()
        request.groups = ()

        tags = addon.tags.not_blacklisted()

        ctx = {"APP": amo.FIREFOX, "LANG": "en-us", "request": request, "addon": addon, "tags": tags}

        # initialize jingo
        jingo.load_helpers()
        cake_csrf_token = lambda: ""
        cake_csrf_token.__name__ = "cake_csrf_token"
        jingo.register.function(cake_csrf_token)

        # no tags, no list
        s = render("{{ tag_list(addon) }}", ctx)
        self.assertEqual(s.strip(), "")

        s = render("{{ tag_list(addon, tags=tags) }}", ctx)
        assert s, "Non-empty tags must return tag list."
        doc = pq(s)
        eq_(doc("li").length, len(tags))
Example #8
0
    def test_list_packages_filters(self):
        """
        The package list must be stripped from inherited packages and [*redirected] messages
        """
        devpi_listing = [
            "*redirected: http://localhost:2414/user/index2/delete_me",
            "http://localhost:2414/user/index2/+f/70e/3bc67b3194143/delete_me-0.2-py2.py3-none-any.whl",
            "http://localhost:2414/user/index2/+f/313/8642d2b43a764/delete_me-0.2.tar.gz",
            "http://localhost:2414/other_user/index1/+f/70e/3bc67b3194143/delete_me-0.2-py2.py3-none-any.whl",
            "http://localhost:2414/other_user/index1/+f/313/8642d2b43a764/delete_me-0.2.tar.gz",
        ]
        expected_packages = {"user/index2": {Package(devpi_listing[1])}}

        devpi_client = Mock(spec=DevpiCommandWrapper)
        devpi_client.user = "user"
        devpi_client.url = "http://localhost:2414/user/index2"
        devpi_client.list_indices.return_value = ["user/index2"]
        devpi_client.list.return_value = devpi_listing

        actual_packages = list_packages_by_index(devpi_client, "user", "delete_me", only_dev=False, version_filter=None)
        self.assertDictEqual(expected_packages, actual_packages)

        devpi_client.list.assert_called_once_with(
            "--index", "user/index2", "--all", "delete_me"
        )  # `--all` is important as otherwise not all packages will be returned
Example #9
0
 def test_contact_create(self):
     # POST with no existing contact creates a new one
     name = u"A BRAND NEW CONTACT"
     data = {
         u"name": name,
         u"language": u"wxyz",
         u"submit": u"Save Contact",
         u"connection_set-0-id": u"",
         u"connection_set-0-DELETE": u"",
         u"connection_set-0-backend": u"1",
         u"connection_set-0-contact": u"",
         u"connection_set-0-identity": u"4567",
         u"connection_set-1-id": u"",
         u"connection_set-1-contact": u"",
         u"connection_set-1-identity": u"",
         u"connection_set-1-backend": u"",
         u"connection_set-INITIAL_FORMS": u"0",
         u"connection_set-TOTAL_FORMS": u"2",
         u"connection_set-MAX_NUM_FORMS": u"10",
     }
     with patch("rapidsms.contrib.registration.views.render"):
         request = Mock(method="POST", POST=data)
         request.__class__ = HttpRequest
         self.login()
         request.user = self.user
         retval = views.contact(request)
     self.assertTrue(isinstance(retval, HttpResponseRedirect))
     self.assertEqual(302, retval.status_code)
     Contact.objects.get(name=name)
Example #10
0
    def test_contact_delete(self):
        # Submitting with Delete button deletes the contact
        contact = self.contacts[0]
        data = {
            u"name": u"The Contact",
            u"language": u"wxyz",
            u"delete_contact": u"dontcare",
            u"connection_set-0-id": u"2",
            u"connection_set-0-DELETE": u"",
            u"connection_set-0-backend": u"1",
            u"connection_set-0-contact": u"1",
            u"connection_set-0-identity": u"4567",
            u"connection_set-1-id": u"",
            u"connection_set-1-contact": u"1",
            u"connection_set-1-identity": u"987654",
            u"connection_set-1-backend": u"1",
            u"connection_set-INITIAL_FORMS": u"1",
            u"connection_set-TOTAL_FORMS": u"2",
            u"connection_set-MAX_NUM_FORMS": u"10",
        }

        with patch("rapidsms.contrib.registration.views.render"):
            request = Mock(method="POST", POST=data)
            request.__class__ = HttpRequest
            self.login()
            request.user = self.user
            retval = views.contact(request, pk=contact.pk)
        self.assertTrue(isinstance(retval, HttpResponseRedirect))
        self.assertEqual(302, retval.status_code)
        self.assertFalse(Contact.objects.filter(pk=contact.pk).exists())
Example #11
0
 def test_contact_update(self):
     # POST to contact view updates the contact and connections
     contact = self.contacts[0]
     data = {
         u"name": u"The Contact",
         u"language": u"wxyz",
         u"submit": u"Save Contact",
         u"connection_set-0-id": u"2",
         u"connection_set-0-DELETE": u"",
         u"connection_set-0-backend": u"1",
         u"connection_set-0-contact": u"1",
         u"connection_set-0-identity": u"4567",
         u"connection_set-1-id": u"",
         u"connection_set-1-contact": u"1",
         u"connection_set-1-identity": u"",
         u"connection_set-1-backend": u"",
         u"connection_set-INITIAL_FORMS": u"1",
         u"connection_set-TOTAL_FORMS": u"2",
         u"connection_set-MAX_NUM_FORMS": u"10",
     }
     with patch("rapidsms.contrib.registration.views.render"):
         request = Mock(method="POST", POST=data)
         request.__class__ = HttpRequest
         self.login()
         request.user = self.user
         retval = views.contact(request, pk=contact.pk)
     self.assertTrue(isinstance(retval, HttpResponseRedirect))
     self.assertEqual(302, retval.status_code)
     new_contact = Contact.objects.get(pk=contact.pk)
     self.assertEqual(data["name"], new_contact.name)
     self.assertEqual(data["language"], new_contact.language)
     identities = [c.identity for c in contact.connection_set.all()]
     self.assertIn(data["connection_set-0-identity"], identities)
Example #12
0
 def test_bulk_add(self):
     # We can upload a CSV file to create contacts & connections
     backend1 = self.create_backend()
     backend2 = self.create_backend()
     # Include a unicode name to make sure that works
     uname = u"Name 1 ḀḂḈ ᵺ"
     data = [
         (uname, backend1.name, u"11111"),
         (u"Name 2", backend2.name, u"22222"),
         (u"Name 3", backend1.name, u"33333"),
         (u"Name 4", backend2.name, u"44444"),
     ]
     # Create test file
     testfile = u"\n".join([u",".join(parts) for parts in data]) + u"\n"
     testfile_data = testfile.encode("utf-8")
     with patch("rapidsms.contrib.registration.views.render") as render:
         request = Mock(method="POST", FILES={"bulk": StringIO(testfile_data)})
         self.login()
         request.user = self.user
         retval = views.contact_bulk_add(request)
     if not isinstance(retval, HttpResponseRedirect):
         context = render.call_args[0][2]
         self.fail(context["bulk_form"].errors + context["csv_errors"])
     self.assertTrue(isinstance(retval, HttpResponseRedirect))
     self.assertEqual(302, retval.status_code)
     contacts = Contact.objects.all()
     self.assertEqual(4, contacts.count())
     names = [contact.name for contact in contacts]
     self.assertIn(uname, names)
Example #13
0
    def test_add_connection(self):
        # POST can add a new connection
        contact = self.create_contact()
        # Give it ONE connection
        self.create_connection(data={"contact": contact})

        # Submit form filled out to add another connection

        connections = contact.connection_set.all()
        data = {
            u"name": u"Joe User",
            u"language": u"en",
            u"submit": u"Save Contact",
            u"connection_set-0-id": connections[0].pk,
            u"connection_set-0-identity": connections[0].identity,
            u"connection_set-0-backend": connections[0].backend.pk,
            u"connection_set-0-contact": contact.pk,
            u"connection_set-1-id": u"",
            u"connection_set-1-identity": "identity",
            u"connection_set-1-backend": connections[0].backend.pk,
            u"connection_set-1-contact": contact.pk,
            u"connection_set-TOTAL_FORMS": u"2",
            u"connection_set-MAX_NUM_FORMS": u"10",
            u"connection_set-INITIAL_FORMS": u"1",
        }
        with patch("rapidsms.contrib.registration.views.render"):
            request = Mock(method="POST", POST=data)
            self.login()
            request.user = self.user
            retval = views.contact(request, pk=contact.pk)
        self.assertTrue(isinstance(retval, HttpResponseRedirect))
        self.assertEqual(302, retval.status_code)
        self.assertEqual(2, Connection.objects.filter(contact=contact).count())
        conn = Connection.objects.get(identity="identity", contact=contact)
        self.assertEqual(connections[0].backend, conn.backend)
Example #14
0
 def test_dasboard_request_is_successful(self, mock_get_create):
     mock_profile = Mock(spec=Profile)
     mock_user = utils.get_user_mock()
     mock_profile.user = mock_user
     mock_get_create.return_value = [mock_profile, False]
     request = utils.get_request("get", "/dashboard/", user=mock_user)
     response = views.dashboard(request)
     eq_(response.status_code, 200)
     eq_(response.template_name, "people/dashboard.html")
     eq_(
         sorted(response.context_data.keys()),
         sorted(
             [
                 "application_list",
                 "content_list",
                 "featured_resource_list",
                 "hub_event_list",
                 "hub_list",
                 "hub_request_list",
                 "object",
                 "post_list",
                 "similar_applications",
             ]
         ),
     )
     mock_get_create.assert_called_once()
Example #15
0
    def test_group_finder_no_groups(self):
        from pyramid_signup import groupfinder
        from pyramid_signup.models import User
        from pyramid_signup.models import UserGroup
        from pyramid_signup.models import Organization

        group = UserGroup("foo", "bar")
        user1 = User(username="sontek", first_name="john")
        user2 = User(username="sontek2", first_name="john")
        organization = Organization("foo", user1)
        group.users.append(user1)

        self.session.add(organization)
        self.session.add(group)
        self.session.add(user1)
        self.session.add(user2)
        self.session.flush()

        request = Mock()
        request.user = user2

        results = groupfinder(2, request)

        assert len(results) == 1
        assert "user:%s" % (user2.pk) in results
Example #16
0
    def test_create_move_publishes_to_redis(self):
        """
        Tests that we are publishing to redis when we create moves
        """
        request = Mock(name="request")
        request.user = self.player1

        redis = Mock(name="redis")
        redis.publish = Mock()

        self.game.board = pickle.dumps(["X", "", "", "", "X", "", "", "", ""])
        self.game.save()

        with patch("core.views.Redis") as mock_redis:
            mock_redis.return_value = redis

            move = 8
            player = "X"
            response = self.client.post("/create_move/%d/" % self.game.id, {"move": move})

            redis.publish.assert_called_with(self.player2.id, ["game_over", self.game.id, player])

            _pop_last_call(redis.publish)

            redis.publish.assert_called_with(self.player1.id, ["game_over", self.game.id, player])

            _pop_last_call(redis.publish)

            redis.publish.assert_called_with(self.player2.id, ["opponent_moved", self.game.id, player, move])
Example #17
0
    def test_user_logged_in(self, get, now):

        # user requests email change
        user = Mock()
        token_object = Mock()
        token_object.token = "sometokencontent"
        token_object.user = user
        get.return_value = token_object

        # user is logged in
        request = MagicMock(HttpRequest)
        request._messages = Mock()
        request.user = user

        # user clicks link in his email
        result = change_email(request, token_object.token)
        self.assertEquals(result.status_code, 302)
        get.assert_called_once_with(token=token_object.token, valid_until__gte=now())
        # user stays logged in
        self.assertTrue(request.user.is_authenticated())
        # token is deleted
        token_object.delete.assert_called_once_with()
        user.save.assert_called_once_with()
        # user email gets changed
        self.assertEqual(user.email, token_object.email)
Example #18
0
 def has_object_perm(self, auth, user, obj, method="GET"):
     perm = ProjectPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     return perm.has_object_permission(request, None, obj)
Example #19
0
 def test_geo_manager(self):
     request = Mock()
     request.user = self.user
     request.allowed_data_set_ids = set([self.data_set1.id])
     print request.allowed_data_set_ids
     geo_manager.request = request
     self.assertEqual(len(GeoContent.objects.all()), 2)
Example #20
0
 def test_not_staff(self):
     """
     If the user is not staff, raise a PermissionDenied exception.
     """
     request = Mock()
     request.user = UserFactory.create(is_staff=False)
     self.view.dispatch(request)
Example #21
0
 def test_vote_captcha_first_vote_loggedin(self):
     # first vote does not require captcha if user is logged in
     # even if no prior votes have been cast by the logged in user
     mock_request_loggedin = Mock(spec=object)
     mock_request_loggedin.user = Mock()
     mock_request_loggedin.user.is_authenticated = lambda: True
     self.assertFalse(vote_needs_captcha(mock_request_loggedin))
def get_mock_review():
    r = Mock()
    r.product = get_product_mock()
    r.user = get_auth_user_mock()
    r.score = 4
    r.date_created = datetime.utcfromtimestamp(100)
    return r
Example #23
0
 def has_perm(self, method, obj, auth=None, user=None):
     perm = TeamPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     return perm.has_object_permission(request, None, obj)
    def test_valid_user_noreverse_charge(self):
        address = Mock()
        address.country = Mock()
        address.country.code = "AT"
        address.line4 = "Vienna"
        address.postcode = "1010"
        address.phone_number = "+43 1 234 5678"
        address.line1 = "hastexo Professional Services GmbH"
        address.vatin = ""

        request = Mock()
        request.user = Mock()
        request.user.addresses = Mock()
        request.user.addresses.order_by = Mock(return_value=[address])
        request.user.is_authenticated = Mock(return_value=True)

        selector = PerUserVATSelector()
        strategy = selector.strategy(request=request)

        result_rate = strategy.get_rate(None, None)
        self.assertEqual(result_rate, D("0.20"))

        address.vatin = "ATU66688202"
        # Valid VATIN, but same country as store: should return normal
        # VAT rate.
        result_rate = strategy.get_rate(None, None)
        self.assertEqual(result_rate, D("0.20"))
Example #25
0
    def test_addon_sharing(self):
        addon = Addon.objects.get(id=7172)

        jingo.load_helpers()

        request = Mock()
        request.user = DjangoUser()
        request.APP = amo.FIREFOX
        ctx = {"request": request, "APP": request.APP, "LANG": translation.get_language()}

        # disable cake csrf token
        cake_csrf_token = lambda: ""
        cake_csrf_token.__name__ = "cake_csrf_token"
        jingo.register.function(cake_csrf_token)

        doc = pq(addon_sharing(ctx, addon))
        self.assert_(doc.html())
        self.assertEquals(doc("li").length, len(sharing.SERVICES_LIST))

        # Make sure services are in the right order.
        for i in range(len(sharing.SERVICES_LIST)):
            self.assertEquals(doc("li").eq(i).attr("class"), sharing.SERVICES_LIST[i].shortname)
            assert doc("li a").eq(i).attr("target") in (
                "_blank",
                "_self",
            ), "Sharing link target must either be blank or self."
Example #26
0
    def test_owner_or_mod_required_passes_url_parameters(self):
        @owner_or_moderator_required
        def mock_view(request, user, context):
            return None

        request = Mock(spec=("path", "REQUEST", "user"))
        request.user = AnonymousUser()
        request.REQUEST = {"abra": "cadabra", "foo": "bar"}
        request.path = "/some/path/"
        user = self.create_user("user")
        response = mock_view(request, user, {})
        self.assertEqual(isinstance(response, HttpResponseRedirect), True)

        url = response["location"]
        parsed_url = urlparse(url)

        self.assertEqual(parsed_url.path, reverse("user_signin"))

        next = dict(parse_qsl(parsed_url.query))["next"]
        next_url = unquote(next)
        parsed_url = urlparse(next_url)

        self.assertEqual(parsed_url.path, request.path)

        query = dict(parse_qsl(parsed_url.query))
        self.assertEqual(set(query.keys()), set(["foo", "abra"]))
        self.assertEqual(set(query.values()), set(["bar", "cadabra"]))
        self.assertEqual(query["abra"], "cadabra")
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
Example #28
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 #29
0
 def has_object_perm(self, method, obj, auth=None, user=None, is_superuser=None):
     perm = TeamPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     request.is_superuser = lambda: is_superuser if is_superuser is not None else user.is_superuser
     return perm.has_object_permission(request, None, obj)
Example #30
0
 def test_non_authenicated_call(self):
     "Non-Authenicated call should yield an unauthorized response."
     request = Mock()
     user = Mock()
     user.is_authenticated = lambda: False
     request.user = user
     response = self.lookup.results(request)
     self.assertEqual(response.status_code, 401)