def test_display_2(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/organizations")
     response = display(request, "organizations")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Public Health"), -1)
    def testBeginLoginWithXrdsUrl(self):
        # skip the test if openid is not enabled (as in cms.envs.test):
        if not settings.MITX_FEATURES.get("AUTH_USE_OPENID") or not settings.MITX_FEATURES.get(
            "AUTH_USE_OPENID_PROVIDER"
        ):
            return

        # the provider URL must be converted to an absolute URL in order to be
        # used as an openid provider.
        provider_url = reverse("openid-provider-xrds")
        factory = RequestFactory()
        request = factory.request()
        abs_provider_url = request.build_absolute_uri(location=provider_url)

        # In order for this absolute URL to work (i.e. to get xrds, then authentication)
        # in the test environment, we either need a live server that works with the default
        # fetcher (i.e. urlopen2), or a test server that is reached through a custom fetcher.
        # Here we do the latter:
        fetcher = MyFetcher(self.client)
        openid.fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        # now we can begin the login process by invoking a local openid client,
        # with a pointer to the (also-local) openid provider:
        with self.settings(OPENID_SSO_SERVER_URL=abs_provider_url):
            url = reverse("openid-login")
            resp = self.client.post(url)
            code = 200
            self.assertEqual(
                resp.status_code,
                code,
                "got code {0} for url '{1}'. Expected code {2}".format(resp.status_code, url, code),
            )
Example #3
0
    def test_admin_timeline_prunes_user_output(self):
        """multiple users in timeline is confusing."""
        admin = self.User.objects.create(username="admin", email="admin@example.com")
        admin.is_staff = True
        admin.is_superuser = True
        admin.save()

        # create a drip campaign that will surely give us duplicates.
        model_drip = Drip.objects.create(
            name="A Custom Week Ago", subject_template="HELLO {{ user.username }}", body_html_template="KETTEHS ROCK!"
        )
        QuerySetRule.objects.create(
            drip=model_drip,
            field_name="date_joined",
            lookup_type="gte",
            field_value=(timezone.now() - timedelta(days=1)).isoformat(),
        )

        # then get it's admin view.
        rf = RequestFactory()
        timeline_url = reverse(
            "admin:drip_timeline", kwargs={"drip_id": model_drip.id, "into_past": 3, "into_future": 3}
        )

        request = rf.get(timeline_url)
        request.user = admin

        match = resolve(timeline_url)

        response = match.func(request, *match.args, **match.kwargs)

        # check that our admin (not excluded from test) is shown once.
        self.assertEqual(unicode(response.content).count(admin.email), 1)
Example #4
0
    def test_that_initialize_server_request_when_custom_content_type(self):
        """Chceck if post data is not included in params when constent type
        is not application/x-www-form-urlencoded. It would cause problems only when signature method is
        HMAC-SHA1
         """

        data = json.dumps({"data": {"foo": "bar"}})
        content_type = "application/json"
        querystring = self.__make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        # we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, data, content_type)

        # this is basically a "remake" of the relevant parts of OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter("oauth_consumer_key")
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter("oauth_token")
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        # check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
Example #5
0
    def test_send_mail(self, fake_messages):
        """Test EmailRepsForm email sending functionality."""

        data = {"subject": "Test email subject", "body": "Test email body", "functional_area": self.functional_area.id}

        form = EmailRepsForm(data=data)
        ok_(form.is_valid())

        area = self.functional_area
        UserFactory.create_batch(20, userprofile__functional_areas=[area])

        factory = RequestFactory()
        request = factory.request()
        request.user = UserFactory.create()

        reps = User.objects.filter(userprofile__functional_areas__name=area)

        form.send_email(request, reps)

        eq_(len(mail.outbox), 20)

        address = lambda u: "%s %s <%s>" % (u.first_name, u.last_name, u.email)
        recipients = map(address, reps)

        receivers = []
        for i in range(0, len(mail.outbox)):
            eq_(mail.outbox[i].subject, data["subject"])
            eq_(mail.outbox[i].body, data["body"])
            receivers.append(mail.outbox[i].to[0])

        eq_(set(receivers), set(recipients))
        fake_messages.assert_called_with(ANY, "Email sent successfully.")
Example #6
0
    def test_rollback_commit_publish(self):
        tracker, commit1 = make_commit(self.widgy_site, datetime.timedelta(days=1))

        request_factory = RequestFactory()

        commit2 = tracker.commit(publish_at=timezone.now() - datetime.timedelta(days=1))
        self.assertEqual(tracker.get_published_node(request_factory.get("/")), commit2.root_node)
Example #7
0
class TestAuthentication(unittest.TestCase):
    def setUp(self):
        self.req_factory = RequestFactory()

    @override_settings(API_KEY="test")
    def test_valid_auth(self):
        http_auth = "Basic {0}".format(base64.encodestring(settings.API_KEY))
        request = self.req_factory.post("/api/v1/metric/", {}, HTTP_AUTHORIZATION=http_auth)
        auth = SettingsAuthentication()
        auth_resp = auth.authenticate(request)
        self.assertFalse(auth_resp is None, "Authentication failed")

    @override_settings(API_KEY="test")
    def test_invalid_auth(self):
        http_auth = "Basic {0}".format(base64.encodestring("wrongkey"))
        request = self.req_factory.post("/api/v1/metric/", {}, HTTP_AUTHORIZATION=http_auth)
        auth = SettingsAuthentication()
        self.assertRaises(exceptions.AuthenticationFailed, auth.authenticate, request)

    @override_settings(API_KEY="test")
    def test_no_auth(self):
        request = self.req_factory.post("/api/v1/metric/", {})
        auth = SettingsAuthentication()
        auth_resp = auth.authenticate(request)
        self.assertTrue(auth_resp is None, "Authentication succeeded")
 def test_query_3(self):
     # Test if the given string exists inside the query
     request_factory = RequestFactory()
     request = request_factory.get("/query/?q=7")
     response = query(request)
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Sandy Hook Elementary School Shooting"), -1)
 def test_people2(self):
     # Test if person kind is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/people/brobma")
     response = people(request, "brobma")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("<li>President</li>"), -1)
 def test_display_more_3(self):
     # Test if crisis name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crises/haiear/videos")
     response = display_more(request, "crises", "haiear", "videos")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Haiti Earthquake"), -1)
 def test_query_2(self):
     # Test if the given string exists inside the query
     request_factory = RequestFactory()
     request = request_factory.get("/query/?q=4")
     response = query(request)
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Naoto Kan"), -1)
 def test_display_more_2(self):
     # Test if organization name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/organizations/whorgn/videos")
     response = display_more(request, "organizations", "whorgn", "videos")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("World Health Organization"), -1)
 def test_display_more_1(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/people/brobma/videos")
     response = display_more(request, "people", "brobma", "videos")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Barack Obama"), -1)
 def test_display_3(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crises")
     response = display(request, "crises")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("Natural Disaster"), -1)
Example #15
0
    def test_skip_limit(self, mock_request):
        text = "dummy content"
        thread_id = "test_thread_id"
        response_skip = "45"
        response_limit = "15"
        mock_request.side_effect = make_mock_request_impl(text, thread_id)

        request = RequestFactory().get(
            "dummy_url",
            {"resp_skip": response_skip, "resp_limit": response_limit},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        request.user = self.student
        response = views.single_thread(request, self.course.id, "dummy_discussion_id", "test_thread_id")
        self.assertEquals(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEquals(response_data["content"], make_mock_thread_data(text, thread_id, True))
        mock_request.assert_called_with(
            "get",
            StringEndsWithMatcher(thread_id),  # url
            data=None,
            params=PartialDictMatcher(
                {
                    "mark_as_read": True,
                    "user_id": 1,
                    "recursive": True,
                    "resp_skip": response_skip,
                    "resp_limit": response_limit,
                }
            ),
            headers=ANY,
            timeout=ANY,
        )
 def test_people3(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/people/brobma")
     response = people(request, "brobma")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find('<h1 class="main-focus;">Barack Obama</h1>'), -1)
Example #17
0
class StatusEndpointViewsTestCase(TestCase):
    urls = "healthcheck.contrib.django.status_endpoint.urls"

    def setUp(self):
        self.factory = RequestFactory()

    @override_settings(STATUS_CHECK_DBS=True, STATUS_CHECK_FILES=("/etc/quiesce",))
    def test_default_checks(self):
        request = self.factory.get(reverse(views.status))
        response = views.status(request)
        self.assertEqual(response.status_code, 200)

    @override_settings(STATUS_CHECK_DBS=True, STATUS_CHECK_FILES=())
    def test_dont_check_files(self):
        request = self.factory.get(reverse(views.status))
        response = views.status(request)
        response_json = json.loads(response.content)
        self.assertTrue("quiesce file doesn't exist" not in response_json)
        self.assertTrue("Django Databases Health Check" in response_json)
        db_names = response_json["Django Databases Health Check"]["details"]
        self.assertTrue(all(connection.alias in db_names for connection in connections.all()))
        self.assertEqual(response.status_code, 200)

    @override_settings(STATUS_CHECK_DBS=False, STATUS_CHECK_FILES=())
    def test_no_checks_raises_200(self):
        request = self.factory.get(reverse(views.status))
        response = views.status(request)
        response = {"content": json.loads(response.content), "status": response.status_code}

        expected_response = {"content": "There were no checks.", "status": 200}

        self.assertEqual(response, expected_response)
 def test_organization2(self):
     # Test if person kind is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/organization/whorgn")
     response = organizations(request, "whorgn")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("<li>Public Health</li>"), -1)
Example #19
0
class RedeliverAdminActionTest(TestCase):
    def setUp(self):
        self.site = factories.make_world()
        self.admin_site = AdminSite()
        self.admin = DeferredMessageAdmin(DeferredMessage, self.admin_site)
        self.factory = RequestFactory()
        self.user = User.objects.get(username="sw")
        self.user.is_superuser = True

    def test_redeliver(self):
        foireq = FoiRequest.objects.all()[0]
        dm = factories.DeferredMessageFactory()
        dm.save()
        req = self.factory.post("/", {})
        req.user = self.user

        result = self.admin.redeliver(req, DeferredMessage.objects.filter(id__in=[dm.id]))
        self.assertEqual(result.status_code, 200)

        req = self.factory.post("/", {"req_id": foireq.id})
        req.user = self.user
        req._messages = default_storage(req)

        result = self.admin.redeliver(req, DeferredMessage.objects.filter(id__in=[dm.id]))
        self.assertIsNone(result)

        dm = DeferredMessage.objects.get(id=dm.id)
        self.assertEqual(dm.request, foireq)
 def test_organization3(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/organization/whorgn")
     response = organizations(request, "whorgn")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find('<h1 class="main-focus;">World Health Organization</h1>'), -1)
Example #21
0
    def test_post_using_auth_in_body_content_type_and_application_x_www_form_urlencoded(self):
        """Opposite of test_that_initialize_server_request_when_custom_content_type,
        If content type is application/x-www-form-urlencoded, post data should be added to params,
        and it affects signature
        """
        self._request_token()
        self._authorize_and_access_token_using_form()

        data = {"foo": "bar"}
        content_type = "application/x-www-form-urlencoded"
        querystring = self.__make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        # we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, urllib.urlencode(data), content_type)

        # this is basically a "remake" of the relevant parts of OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter("oauth_consumer_key")
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter("oauth_token")
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        # check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
 def test_crisis2(self):
     # Test if crisis kind is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/crises/haiear")
     response = crises(request, "haiear")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("<li>Natural Disaster</li>"), -1)
Example #23
0
class TestTourView(TestCase):
    def setUp(self):
        self.view = fx_views.TourView.as_view()
        self.rf = RequestFactory(HTTP_USER_AGENT="Firefox")

    @override_settings(DEV=True)
    def test_fx_old_tour_template(self, render_mock):
        """Should use old firstrun template"""
        req = self.rf.get("/en-US/firefox/tour/")
        self.view(req, version="29.0")
        template = render_mock.call_args[0][1]
        eq_(template, ["firefox/australis/firstrun.html"])

    @override_settings(DEV=True)
    def test_fx_dev_browser_35_0_a2(self, render_mock):
        """Should use dev browser firstrun template"""
        req = self.rf.get("/en-US/firefox/tour/")
        self.view(req, version="35.0a2")
        template = render_mock.call_args[0][1]
        eq_(template, ["firefox/dev-firstrun.html"])

    @override_settings(DEV=True)
    def test_fx_firstrun_tour_36_0(self, render_mock):
        """Should use fx36 tour template for 36.0"""
        req = self.rf.get("/en-US/firefox/tour/")
        self.view(req, version="36.0")
        template = render_mock.call_args[0][1]
        eq_(template, ["firefox/australis/fx36/tour.html"])
 def test_crisis3(self):
     # Test if crisis name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/crisix/crises/haiear")
     response = crises(request, "haiear")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find('<h1 class="main-focus;">2010 Haiti Earthquake</h1>'), -1)
    def testBeginLogin(self):
        # skip the test if openid is not enabled (as in cms.envs.test):
        if not settings.MITX_FEATURES.get("AUTH_USE_OPENID") or not settings.MITX_FEATURES.get(
            "AUTH_USE_OPENID_PROVIDER"
        ):
            return

        # the provider URL must be converted to an absolute URL in order to be
        # used as an openid provider.
        provider_url = reverse("openid-provider-xrds")
        factory = RequestFactory()
        request = factory.request()
        abs_provider_url = request.build_absolute_uri(location=provider_url)

        # now we can begin the login process by invoking a local openid client,
        # with a pointer to the (also-local) openid provider:
        with self.settings(OPENID_SSO_SERVER_URL=abs_provider_url):
            url = reverse("openid-login")
            resp = self.client.post(url)
            code = 200
            self.assertEqual(
                resp.status_code,
                code,
                "got code {0} for url '{1}'. Expected code {2}".format(resp.status_code, url, code),
            )
Example #26
0
 def setUp(self):
     self.middleware = SecurityMiddleware()
     request_factory = RequestFactory()
     self.request = request_factory.get("/some/url")
     self.user = User.objects.create_user("useruser", "u@u.nl", "useruser")
     self.user.save()
     self.user_group = UserGroup(name="user_group")
     self.user_group.save()
     self.user_group.members.add(self.user)
     self.user_group.save()
     self.data_set1 = DataSet(name="data_set10")
     self.data_set1.save()
     self.data_set2 = DataSet(name="data_set20")
     self.data_set2.save()
     self.permission_mapper = PermissionMapper()
     self.permission_mapper.save()
     self.permission_mapper.user_group = self.user_group
     self.permission_mapper.data_set = self.data_set1
     self.permission_mapper.save()
     self.geo_content1 = GeoContent()
     self.geo_content1.save()
     self.geo_content1.data_set = self.data_set1
     self.geo_content1.save()
     self.geo_content2 = GeoContent()
     self.geo_content2.save()
     self.geo_content2.data_set = self.data_set2
     self.geo_content2.save()
     self.geo_content3 = GeoContent()
     self.geo_content3.save()
     self.geo_content3.data_set = None
     self.geo_content3.save()
Example #27
0
class TestContributeSignupSwitcher(TestCase):
    def setUp(self):
        self.rf = RequestFactory()

        patcher = patch("bedrock.mozorg.views.lang_file_has_tag")
        self.lang_file_has_tag = patcher.start()
        self.addCleanup(patcher.stop)

        patcher = patch("bedrock.mozorg.views.ContributeSignup")
        self.ContributeSignup = patcher.start()
        self.addCleanup(patcher.stop)

        patcher = patch("bedrock.mozorg.views.ContributeSignupOldForm")
        self.ContributeSignupOldForm = patcher.start()
        self.addCleanup(patcher.stop)

    def test_uses_new_view(self):
        """Uses new view when lang file has the tag."""
        req = self.rf.get("/")
        self.lang_file_has_tag.return_value = True
        views.contribute_signup(req)
        self.ContributeSignup.as_view.return_value.assert_called_with(req)
        self.assertFalse(self.ContributeSignupOldForm.as_view.return_value.called)

    def test_uses_old_view(self):
        """Uses old view when lang file does not have the tag."""
        req = self.rf.get("/")
        self.lang_file_has_tag.return_value = False
        views.contribute_signup(req)
        self.ContributeSignupOldForm.as_view.return_value.assert_called_with(req)
        self.assertFalse(self.ContributeSignup.as_view.return_value.called)
Example #28
0
 def _fulfill_content_milestones(user, course_key, content_key):
     """
     Internal helper to handle milestone fulfillments for the specified content module
     """
     # Fulfillment Use Case: Entrance Exam
     # If this module is part of an entrance exam, we'll need to see if the student
     # has reached the point at which they can collect the associated milestone
     if milestones_helpers.is_entrance_exams_enabled():
         course = modulestore().get_course(course_key)
         content = modulestore().get_item(content_key)
         entrance_exam_enabled = getattr(course, "entrance_exam_enabled", False)
         in_entrance_exam = getattr(content, "in_entrance_exam", False)
         if entrance_exam_enabled and in_entrance_exam:
             # We don't have access to the true request object in this context, but we can use a mock
             request = RequestFactory().request()
             request.user = user
             exam_pct = get_entrance_exam_score(request, course)
             if exam_pct >= course.entrance_exam_minimum_score_pct:
                 exam_key = UsageKey.from_string(course.entrance_exam_id)
                 relationship_types = milestones_helpers.get_milestone_relationship_types()
                 content_milestones = milestones_helpers.get_course_content_milestones(
                     course_key, exam_key, relationship=relationship_types["FULFILLS"]
                 )
                 # Add each milestone to the user's set...
                 user = {"id": request.user.id}
                 for milestone in content_milestones:
                     milestones_helpers.add_user_milestone(user, milestone)
Example #29
0
    def test_cached_view(self):
        calls = [0]

        @cached_view(timeout=100)
        def get_calls(request):
            calls[0] += 1
            return calls[0]

        factory = RequestFactory()
        r1 = factory.get("/hi")
        r2 = factory.get("/hi")
        r2.META["REMOTE_ADDR"] = "10.10.10.10"
        r3 = factory.get("/bye")

        self.assertEqual(get_calls(r1), 1)  # cache
        self.assertEqual(get_calls(r1), 1)  # hit
        self.assertEqual(get_calls(r2), 1)  # hit, since only url is considered
        self.assertEqual(get_calls(r3), 2)  # miss

        get_calls.invalidate(r1)
        self.assertEqual(get_calls(r1), 3)  # miss

        # Can pass uri to invalidate
        get_calls.invalidate(r1.build_absolute_uri())
        self.assertEqual(get_calls(r1), 4)  # miss
 def test_display_1(self):
     # Test if person name is on page in format designated in template
     request_factory = RequestFactory()
     request = request_factory.get("/people")
     response = display(request, "people")
     htmlstring = response.content
     self.assertNotEqual(htmlstring.find("President"), -1)