当前位置: 首页>>代码示例>>Python>>正文


Python TestClient.login_user方法代码示例

本文整理汇总了Python中myjobs.tests.test_views.TestClient.login_user方法的典型用法代码示例。如果您正苦于以下问题:Python TestClient.login_user方法的具体用法?Python TestClient.login_user怎么用?Python TestClient.login_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在myjobs.tests.test_views.TestClient的用法示例。


在下文中一共展示了TestClient.login_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_not_disabled

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
    def test_not_disabled(self):
        """
        An anonymous user who provides the :verify: query string or
        user with is_disabled set to True should be redirected to the home
        page. An anonymous user who does not should see a 404. A user with
        is_active set to False should proceed to their destination.
        """
        client = TestClient()
        user = UserFactory()

        #Anonymous user
        resp = client.get(reverse('view_profile'))
        path = resp.request.get('PATH_INFO')
        self.assertRedirects(resp, reverse('home') + '?next=' + path)

        # This is ugly, but it is an artifact of the way Django redirects
        # users who fail the `user_passes_test` decorator.
        qs = '?verify=%s' % user.user_guid
        next_qs = '?next=' + urlquote('/profile/view/%s' % qs)

        # Anonymous user navigates to url with :verify: in query string
        resp = client.get(reverse('view_profile') + qs)
        # Old path + qs is urlquoted and added to the url as the :next: param
        self.assertRedirects(resp, "http://testserver/" + next_qs)

        # Active user
        client.login_user(user)
        resp = client.get(reverse('view_profile'))
        self.assertTrue(resp.status_code, 200)

        #Disabled user
        user.is_disabled = True
        user.save()
        resp = client.get(reverse('view_profile'))
        self.assertRedirects(resp, "http://testserver/?next=/profile/view/")
开发者ID:wejhink,项目名称:MyJobs,代码行数:37,代码来源:test_models.py

示例2: TestDownloadReport

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestDownloadReport(MyReportsTestCase):
    """Tests that reports can be downloaded."""

    def setUp(self):
        super(TestDownloadReport, self).setUp()
        self.client = TestClient(path=reverse('download_report'))
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(5, partner__owner=self.company)
        ContactRecordFactory.create_batch(
            5, contact_type='job', job_applications=1,
            partner__owner=self.company)
        ContactRecordFactory.create_batch(
            5, contact_type='job',
            job_hires=1, partner__owner=self.company)

    def test_download_csv(self):
        """Test that a report can be downloaded in CSV format."""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(path=reverse('reports', kwargs={
            'app': 'mypartners', 'model': 'contactrecord'}))
        report_name = response.content
        report = Report.objects.get(name=report_name)

        # download the report
        response = self.client.get(data={'id': report.pk})

        self.assertEqual(response['Content-Type'], 'text/csv')
开发者ID:zeus911,项目名称:MyJobs,代码行数:32,代码来源:test_views.py

示例3: TestDownloads

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestDownloads(MyReportsTestCase):
    """Tests the reports view."""

    def setUp(self):
        super(TestDownloads, self).setUp()
        self.client = TestClient(path=reverse('downloads'),
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(10, partner__owner=self.company)

    def test_column_order(self):
        """Tests that column order is preserved"""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(
            path=reverse('reports', kwargs={
                'app': 'mypartners', 'model': 'contactrecord'}),
            data={'values': ['partner', 'contact__name', 'contact_type']})

        report_name = response.content
        report = Report.objects.get(name=report_name)

        response = self.client.get(data={'id': report.id})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['columns'], {
            'Partner': True, 'Contact Name': True, 'Contact Type': True})
开发者ID:zeus911,项目名称:MyJobs,代码行数:30,代码来源:test_views.py

示例4: TestDownloadReport

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestDownloadReport(MyReportsTestCase):
    """Tests that reports can be downloaded."""

    def setUp(self):
        super(TestDownloadReport, self).setUp()
        self.client = TestClient(path=reverse("download_report"))
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(5, partner__owner=self.company)
        ContactRecordFactory.create_batch(5, contact_type="job", job_applications=1, partner__owner=self.company)
        ContactRecordFactory.create_batch(5, contact_type="job", job_hires=1, partner__owner=self.company)

    def test_download_csv(self):
        """Test that a report can be downloaded in CSV format."""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(path=reverse("reports", kwargs={"app": "mypartners", "model": "contactrecord"}))
        report_name = response.content
        report = Report.objects.get(name=report_name)
        python = report.python

        # download the report
        response = self.client.get(data={"id": report.pk, "values": ["contact", "contact_email", "contact_phone"]})

        self.assertEqual(response["Content-Type"], "text/csv")

        # specifying export values shouldn't modify the underlying report
        self.assertEqual(len(python[0].keys()), len(report.python[0].keys()))
开发者ID:vfulco,项目名称:MyJobs,代码行数:31,代码来源:test_views.py

示例5: TestReportView

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestReportView(MyReportsTestCase):
    """
    Tests the ReportView class, which is used to create and retrieve
    reports.
    """
    def setUp(self):
        super(TestReportView, self).setUp()
        self.client = TestClient(path=reverse('reports', kwargs={
            'app': 'mypartners', 'model': 'contactrecord'}))
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(5, partner__owner=self.company)
        ContactRecordFactory.create_batch(
            5, contact_type='job', job_applications=1,
            partner__owner=self.company)
        ContactRecordFactory.create_batch(
            5, contact_type='job',
            job_hires=1, partner__owner=self.company)

    def test_create_report(self):
        """Test that a report model instance is properly created."""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post()
        report_name = response.content
        report = Report.objects.get(name=report_name)

        self.assertEqual(len(report.python), 15)

        # we use this in other tests

        return report_name

    def test_get_report(self):
        """Test that chart data is retreived from record results."""

        report_name = self.test_create_report()
        report = Report.objects.get(name=report_name)

        response = self.client.get(data={'id': report.pk})
        data = json.loads(response.content)

        # check contact record stats
        for key in ['applications', 'hires', 'communications', 'emails']:
            self.assertEqual(data[key], 5)

        # check contact stats
        self.assertEqual(data['contacts'][0]['records'], 1)
        self.assertEqual(data['contacts'][0]['referrals'], 10)
开发者ID:abdulfiroz007,项目名称:MyJobs,代码行数:52,代码来源:test_views.py

示例6: MyReportsTestCase

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class MyReportsTestCase(TestCase):
    """
    Base class for all MyReports Tests. Identical to `django.test.TestCase`
    except that it provides a MyJobs TestClient instance and a logged in user.
    """
    def setUp(self):
        self.client = TestClient()
        self.user = UserFactory(email='[email protected]')
        self.company = CompanyFactory(name='Test Company')
        self.partner = PartnerFactory(name='Test Partner', owner=self.company)

        # associate company to user
        CompanyUserFactory(user=self.user, company=self.company)

        self.client.login_user(self.user)
开发者ID:kepinae,项目名称:MyJobs,代码行数:17,代码来源:test_views.py

示例7: TestDownloads

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestDownloads(MyReportsTestCase):
    """Tests the reports view."""

    def setUp(self):
        super(TestDownloads, self).setUp()
        self.client = TestClient(path=reverse('downloads'),
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(10, partner__owner=self.company)

    def test_column_order(self):
        """Tests that column order is preserved"""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(
            path=reverse('reports', kwargs={
                'app': 'mypartners', 'model': 'contactrecord'}))

        report_name = response.content
        report = Report.objects.get(name=report_name)
        report.values = json.dumps(['partner', 'contact name', 'contact_type'])
        report.save()

        response = self.client.get(data={'id': report.id})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['columns'].items()[:3],
                         [('Partner', True), ('Contact Name', True),
                          ('Communication Type', True)])

    def test_blacklisted_columns(self):
        """Test that blacklisted columns aren't visible."""
        blacklist = ['pk', 'approval_status']
        response = self.client.post(
            path=reverse('reports', kwargs={
                'app': 'mypartners', 'model': 'contactrecord'}),
            data={'values': ['partner', 'contact__name', 'contact_type']})

        report_name = response.content
        report = Report.objects.get(name=report_name)

        response = self.client.get(data={'id': report.id})
        self.assertFalse(
            set(response.context['columns']).intersection(blacklist))
开发者ID:kepinae,项目名称:MyJobs,代码行数:47,代码来源:test_views.py

示例8: test_inactive_user_sees_message

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
    def test_inactive_user_sees_message(self):
        """
        A user with is_verified or is_active set to False should see an
        activation message instead of the content they were originally meaning
        to see.
        """
        client = TestClient(path=reverse('saved_search_main'))
        user = UserFactory()

        # Active user
        client.login_user(user)
        resp = client.get()
        self.assertIn('Saved Search', resp.content)

        # Inactive user
        user.is_verified= False
        user.save()
        resp = client.get()
        self.assertIn('unavailable', resp.content)
开发者ID:wejhink,项目名称:MyJobs,代码行数:21,代码来源:test_models.py

示例9: TestDownloads

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestDownloads(MyReportsTestCase):
    """Tests the reports view."""

    def setUp(self):
        super(TestDownloads, self).setUp()
        self.client = TestClient(path=reverse("downloads"), HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(10, partner__owner=self.company)

    def test_column_order(self):
        """Tests that column order is preserved"""

        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(path=reverse("reports", kwargs={"app": "mypartners", "model": "contactrecord"}))

        report_name = response.content
        report = Report.objects.get(name=report_name)
        report.values = json.dumps(["partner", "contact name", "contact_type"])
        report.save()

        response = self.client.get(data={"id": report.id})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.context["columns"].items()[:3],
            [("Partner", True), ("Contact Name", True), ("Communication Type", True)],
        )

    def test_blacklisted_columns(self):
        """Test that blacklisted columns aren't visible."""
        blacklist = ["pk", "approval_status"]
        response = self.client.post(
            path=reverse("reports", kwargs={"app": "mypartners", "model": "contactrecord"}),
            data={"values": ["partner", "contact__name", "contact_type"]},
        )

        report_name = response.content
        report = Report.objects.get(name=report_name)

        response = self.client.get(data={"id": report.id})
        self.assertFalse(set(response.context["columns"]).intersection(blacklist))
开发者ID:DirectEmployers,项目名称:MyJobs,代码行数:44,代码来源:test_views.py

示例10: TestRegenerate

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestRegenerate(MyReportsTestCase):
    """Tests the reports can be regenerated."""

    def setUp(self):
        super(TestRegenerate, self).setUp()
        self.client = TestClient(path=reverse('reports', kwargs={
            'app': 'mypartners', 'model': 'contactrecord'}))
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(10, partner__owner=self.company)

    def test_regenerate(self):
        # create a report whose results is for all contact records in the
        # company
        response = self.client.post(
            path=reverse('reports', kwargs={
                'app': 'mypartners', 'model': 'contactrecord'}),
            data={'values': ['partner', 'contact__name', 'contact_type']})

        report_name = response.content
        report = Report.objects.get(name=report_name)
        results = report.results

        response = self.client.get(data={'id': report.id})
        self.assertEqual(response.status_code, 200)

        # remove report results and ensure we can still get a resonable
        # response
        report.results.delete()
        report.save()
        self.assertFalse(report.results)

        response = self.client.get(data={'id': report.id})
        self.assertEqual(response.status_code, 200)

        # regenerate results and ensure they are the same as the original
        response = self.client.get(path=reverse('regenerate'), data={
            'id': report.pk})
        report = Report.objects.get(name=report_name)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(report.results)
开发者ID:zeus911,项目名称:MyJobs,代码行数:43,代码来源:test_views.py

示例11: TestViewRecords

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestViewRecords(MyReportsTestCase):
    """
    Tests the `view_records` view which is used to query various models.
    """

    def setUp(self):
        super(TestViewRecords, self).setUp()
        self.client = TestClient(path="/reports/ajax/mypartners", HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(10, partner=self.partner, contact__name="Joe Shmoe")

    def test_restricted_to_ajax(self):
        """View should only be reachable through AJAX."""

        self.client.path += "/partner"
        self.client.defaults.pop("HTTP_X_REQUESTED_WITH")
        response = self.client.post()

        self.assertEqual(response.status_code, 404)

    def test_restricted_to_get(self):
        """POST requests should raise a 404."""

        self.client.path += "/partner"
        response = self.client.post()

        self.assertEqual(response.status_code, 404)

    def test_json_output(self):
        """Test that filtering contact records through ajax works properly."""

        # records to be filtered out
        ContactRecordFactory.create_batch(10, contact__name="John Doe")

        self.client.path += "/contactrecord"
        response = self.client.get(data={"contact__name": "Joe Shmoe"})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_only_user_results_returned(self):
        """Results should only contain records user has access to."""

        # records not owned by user
        partner = PartnerFactory(name="Wrong Partner")
        ContactRecordFactory.create_batch(10, partner=partner)

        self.client.path += "/contactrecord"
        response = self.client.get()
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_filtering_on_partner(self):
        """Test the ability to filter by partner."""

        # we already have one because of self.partner
        PartnerFactory.create_batch(9, name="Test Partner", owner=self.company)

        self.client.path += "/partner"
        response = self.client.get(data={"name": "Test Partner"})
        output = json.loads(response.content)

        # ContactRecordFactory creates 10 partners in setUp
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_list_query_params(self):
        """Test that query parameters that are lists are parsed correctly."""

        contacts = ContactFactory.create_batch(10, partner__owner=self.company)
        pks = [contact.pk for contact in contacts[:5]]

        self.client.path += "/partner"
        response = self.client.get(data={"contact": pks})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 5)

    def test_filtering_on_contact(self):
        """Test the ability to filter by contact."""

        ContactFactory.create_batch(10, name="Jen Doe", partner=self.partner)

        # contacts with the wrong name
        ContactFactory.create_batch(10, name="Jen Smith", partner=self.partner)

        self.client.path += "/contact"
        response = self.client.get(data={"name": "Jen Doe"})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_filter_by_state(self):
        """Tests that filtering by state works."""
#.........这里部分代码省略.........
开发者ID:vfulco,项目名称:MyJobs,代码行数:103,代码来源:test_views.py

示例12: TestViewRecords

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestViewRecords(MyReportsTestCase):
    """
    Tests the `view_records` view which is used to query various models.
    """

    def setUp(self):
        super(TestViewRecords, self).setUp()
        self.client = TestClient(path='/reports/ajax/mypartners',
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.client.login_user(self.user)

        ContactRecordFactory.create_batch(
            10, partner=self.partner, contact__name='Joe Shmoe')

    def test_restricted_to_ajax(self):
        """View should only be reachable through AJAX."""

        self.client.path += '/partner'
        self.client.defaults.pop('HTTP_X_REQUESTED_WITH')
        response = self.client.post()

        self.assertEqual(response.status_code, 404)

    def test_restricted_to_get(self):
        """POST requests should raise a 404."""

        self.client.path += '/partner'
        response = self.client.post()

        self.assertEqual(response.status_code, 404)

    def test_json_output(self):
        """Test that filtering contact records through ajax works properly."""

        # records to be filtered out
        ContactRecordFactory.create_batch(10, contact__name='John Doe')

        self.client.path += '/contactrecord'
        response = self.client.get(data={'contact__name': 'Joe Shmoe'})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_only_user_results_returned(self):
        """Results should only contain records user has access to."""

        # records not owned by user
        partner = PartnerFactory(name="Wrong Partner")
        ContactRecordFactory.create_batch(10, partner=partner)

        self.client.path += '/contactrecord'
        response = self.client.get()
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_filtering_on_partner(self):
        """Test the ability to filter by partner."""

        # we already have one because of self.partner
        PartnerFactory.create_batch(9, name="Test Partner", owner=self.company)

        self.client.path += '/partner'
        response = self.client.get(data={'name': 'Test Partner'})
        output = json.loads(response.content)

        # ContactRecordFactory creates 10 partners in setUp
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

    def test_list_query_params(self):
        """Test that query parameters that are lists are parsed correctly."""

        contacts = ContactFactory.create_batch(10, partner__owner=self.company)
        pks = [contact.pk for contact in contacts[:5]]

        self.client.path += '/partner'
        response = self.client.get(data={'contact': pks})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 5)

    def test_filtering_on_contact(self):
        """Test the ability to filter by contact."""

        ContactFactory.create_batch(10, name="Jen Doe", partner=self.partner)

        # contacts with the wrong name
        ContactFactory.create_batch(10, name="Jen Smith", partner=self.partner)

        self.client.path += '/contact'
        response = self.client.get(data={'name': 'Jen Doe'})
        output = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(output), 10)

#.........这里部分代码省略.........
开发者ID:abdulfiroz007,项目名称:MyJobs,代码行数:103,代码来源:test_views.py

示例13: MyProfileViewsTests

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class MyProfileViewsTests(MyJobsBase):
    def setUp(self):
        super(MyProfileViewsTests, self).setUp()
        self.client = TestClient()
        self.client.login_user(self.user)
        self.name = PrimaryNameFactory(user=self.user)

    def test_edit_profile(self):
        """
        Going to the edit_profile view generates a list of existing profile
        items in the main content section and a list of profile sections that
        don't have data filled out in the sidebar.
        """
        resp = self.client.get(reverse('view_profile'))
        soup = BeautifulSoup(resp.content)
        item_id = self.name.id

        # The existing name object should be rendered on the main content
        # section
        self.assertIsNotNone(soup.find('div',
                                       id='name-' + str(item_id) + '-item'))
        # profile-section contains the name of a profile section that has no
        # information filled out yet and shows up in the sidebar
        self.assertTrue(soup.findAll('tr', {'class': 'profile-section'}))

    def test_edit_summary(self):
        """
        See test_edit_profile
        """
        summary = SummaryFactory(user=self.user)
        resp = self.client.get(reverse('view_profile'))
        soup = BeautifulSoup(resp.content)

        item = soup.find('div', id='summary-' + str(summary.id) + '-item')
        self.assertIsNotNone(item)

        link = item.find('a').attrs['href']
        resp = self.client.get(link)
        self.assertEqual(resp.status_code, 200)

    def test_handle_form_get_new(self):
        """
        Invoking the handle_form view without an id parameter returns an
        empty form with the correct form id
        """

        resp = self.client.get(reverse('handle_form'),
                               data={'module': 'Name'})
        self.assertTemplateUsed(resp, 'myprofile/profile_form.html')
        soup = BeautifulSoup(resp.content)
        self.assertEquals(soup.form.attrs['id'], 'profile-unit-form')
        with self.assertRaises(KeyError):
            soup.find('input', id='id_name-given_name').attrs['value']

    def test_handle_form_get_existing(self):
        """
        Invoking the handle_form view with and id paraemeter returns
        a form filled out with the corresponding profile/ID combination
        """

        resp = self.client.get(reverse('handle_form'),
                               data={'module': 'Name', 'id': self.name.id})
        self.assertTemplateUsed(resp, 'myprofile/profile_form.html')
        soup = BeautifulSoup(resp.content)
        self.assertEquals(soup.form.attrs['id'], 'profile-unit-form')
        self.assertEquals(soup.find('input', id='id_name-given_name')
                          .attrs['value'], 'Alice')
        self.assertEquals(soup.find('input', id='id_name-family_name')
                          .attrs['value'], 'Smith')
        self.assertEquals(soup.find('input', id='id_name-primary')
                          .attrs['checked'], 'checked')

    def test_handle_form_post_new_valid(self):
        """
        Invoking the handle_form view as a POST request for a new item
        creates that object in the database and returns the item snippet
        to be rendered on the page.
        """

        resp = self.client.post(reverse('handle_form'),
                                data={'module': 'Name', 'id': 'new',
                                      'given_name': 'Susy',
                                      'family_name': 'Smith'})
        self.assertRedirects(resp, reverse('view_profile'))
        self.assertEqual(Name.objects.filter(given_name='Susy',
                                             family_name='Smith').count(), 1)

    def test_handle_form_post_invalid(self):
        """
        Invoking the handle_form view as a POST request with an invalid
        form returns the list of form errors.
        """
        resp = self.client.post(reverse('handle_form'),
                                data={'module': 'Name', 'id': 'new',
                                      'given_name': 'Susy'},
                                HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.assertEqual(json.loads(resp.content),
                         {u'family_name': [u'This field is required.']})

#.........这里部分代码省略.........
开发者ID:kepinq,项目名称:MyJobs,代码行数:103,代码来源:test_views.py

示例14: MySignOn

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class MySignOn(MyJobsBase):
    def setUp(self):
        super(MySignOn, self).setUp()
        self.user = UserFactory()
        self.auth_callback_url = 'https://secure.my.jobs/account'
        self.auth_callback = '?auth_callback=%s' % self.auth_callback_url
        self.key_qs = '%s&key=%s'

        self.client = TestClient()
        self.client.login_user(self.user)

    def test_anonymous_auth(self):
        """
        Anonymous users must first login before being redirected.

        This redirection happens automatically if JavaScript is disabled. JSON
        is returned and the redirect takes place via JavaScript otherwise.
        """
        login_data = {'username': self.user.email,
                      'password': '[email protected]',
                      'auth_callback': self.auth_callback_url,
                      'action': 'login'}

        self.client.logout()
        self.assertEqual(AuthorizedClient.objects.count(), 0)
        self.assertTrue(self.client.session.get('key') is None)

        response = self.client.post(reverse('sso_authorize'),
                                    login_data)

        self.assertEqual(AuthorizedClient.objects.count(), 1)
        self.assertTrue(self.client.session.get('key') is not None)
        self.assertEqual(response.get('Location'),
                         self.auth_callback_url + '?key=%s' %
                         self.client.session.get('key'))

        self.client.logout()
        response = self.client.post(reverse('sso_authorize'),
                                    login_data,
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        content = json.loads(response.content)
        self.assertEqual(content['url'], self.auth_callback_url +
                         '?key=%s' % self.client.session['key'])

    def test_authenticated_auth(self):
        """
        Users who are already logged in can simply click a button to authorize
        a given site and are then redirected to the given callback url.

        If a given user has already authorized a given site and that site
        provides the key that it was given, this redirect is automatic.
        """
        self.assertEqual(AuthorizedClient.objects.count(), 0)
        self.assertTrue(self.client.session.get('key') is None)

        response = self.client.post(reverse('sso_authorize'),
                                    {'auth_callback': self.auth_callback_url,
                                     'action': 'authorize'})

        self.assertEqual(self.user.authorizedclient_set.count(), 1)
        self.assertTrue(self.client.session.get('key') is not None)
        self.assertEqual(response.get('Location'),
                         self.auth_callback_url + '?key=%s' %
                         self.client.session.get('key'))

        good_qs = self.key_qs % (self.auth_callback,
                                 self.client.session.get('key'))
        response = self.client.get(reverse('sso_authorize') + good_qs)
        self.assertEqual(response.get('Location'),
                         self.auth_callback_url + '?key=%s' %
                         self.client.session.get('key'))

    def test_bad_key(self):
        """
        Providing a bad key will always cause the user to have to
        log back into their account.

        Bad keys are defined as providing a key that doesn't match the
        user's current key or providing a key when the user doesn't currently
        have a key defined.
        """
        # no key
        no_key = self.key_qs % (self.auth_callback,
                                AuthorizedClient.create_key(self.user))
        response = self.client.get(reverse('sso_authorize') + no_key)
        self.assertEqual(AuthorizedClient.objects.count(), 0)

        # Ensure that user was logged out
        response = self.client.get(reverse('view_profile'))
        path = response.request.get('PATH_INFO')
        self.assertRedirects(response, reverse('home')+'?next='+path)

        # wrong key
        self.client.login_user(self.user)
        session = self.client.session
        session['key'] = AuthorizedClient.create_key(self.user)
        session.save()

        # key is a hex string; we can invalidate it by taking a substring
#.........这里部分代码省略.........
开发者ID:AstroMatchDynamics,项目名称:MyJobs,代码行数:103,代码来源:test_views.py

示例15: TestSecureBlocks

# 需要导入模块: from myjobs.tests.test_views import TestClient [as 别名]
# 或者: from myjobs.tests.test_views.TestClient import login_user [as 别名]
class TestSecureBlocks(DirectSEOBase):
    """
    Tests that the secure blocks api view in various circumstances.
    """
    fixtures = ['login_page.json']

    def setUp(self):
        super(TestSecureBlocks, self).setUp()
        self.staff_user = UserFactory(is_staff=True)
        self.client = TestClient()
        self.client.login_user(self.staff_user)
        self.sb_url = reverse('secure_blocks')
        SeoSiteFactory(domain='jobs.example.com')

    def test_secure_blocks_empty(self):
        """Browser asks for no blocks."""
        resp = make_cors_request(self.client, self.sb_url, '{"blocks": {}}')
        self.assertEqual(200, resp.status_code)
        result = json.loads(resp.content)
        self.assertEqual({u'errors':{}}, result,
                         msg="got %s! secure block returned block when none was"
                             " requested" % result)

    def test_secure_blocks_bad_parse(self):
        """Handle unparseable JSON."""
        resp = make_cors_request(self.client, self.sb_url, '@@@@@@@@@')
        self.assertEqual(400, resp.status_code,
                         msg="got %s! block request allowed unparseable json, check"
                             " secure block json parser" % resp.status_code)

    def test_secure_blocks_render(self):
        """Ask for a real block."""
        body = '{"blocks": {"my-jobs-logo-1": {}}}'
        resp = make_cors_request(self.client, self.sb_url, body)
        result = json.loads(resp.content)
        self.assertTrue('my-jobs-logo-1' in result,
                        msg="block request not found in response. check fixture, "
                            "secure blocks logic")

    def test_secure_blocks_bad_origin(self):
        """Check that secure blocks do not load from invalid origins"""
        body = '{"blocks": {"my-jobs-logo-1": {}}}'
        resp = make_cors_request(self.client, self.sb_url, body,
                               http_origin='http://notparent.com/')
        self.assertEqual(resp.status_code, 404,
                         msg="got %s! secure block call responded despite bad origin."
                             " check cross site verify logic" % resp.status_code)

    def test_saved_search_includes_required_js(self):
        """
        Ensure requests for saved search widget includes required js

        """
        savedsearch = (SavedSearchWidgetBlock
                       .objects
                       .get(element_id='test_saved_search'))
        body = '{"blocks": {"test_saved_search": {}}}'
        resp = make_cors_request(self.client, self.sb_url, body)
        self.assertEqual(resp.status_code, 200,
                         msg="Expected 200, got %s. User was not able to "
                             "retrieve blocks for test" % resp.status_code)
        for js in savedsearch.required_js():
            self.assertContains(resp, js,
                                msg_prefix="Did not find %s in response,"
                                           "missing required js" % js)

    def test_topbar_includes_cookies(self):
        body = '{"blocks": {"test_tools_widget": {}}}'
        resp = make_cors_request(self.client, self.sb_url, body)
        self.assertEqual(resp.status_code, 200,
                         msg="Expected 200, got %s. User was not able to "
                             "retrieve blocks for test" % resp.status_code)
        self.assertEqual(resp.cookies['lastmicrosite'].value,
                         'http://jobs.example.com')
开发者ID:DirectEmployers,项目名称:MyJobs,代码行数:76,代码来源:test_secure_blocks.py


注:本文中的myjobs.tests.test_views.TestClient.login_user方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。