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


Python RestClient.rest_post方法代码示例

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


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

示例1: TestRestMergeIntoGroup

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestRestMergeIntoGroup(TestCase):
    def setUp(self):
        self.client = RestClient()
        self.testhelper = TestHelper()
        self.testhelper.add(
            nodes="uni", subjects=["sub"], periods=["p1:begins(-2)"], assignments=["a1:admin(a1admin)"]  # 2 months ago
        )
        self.assignment = self.testhelper.sub_p1_a1
        self.url = "/devilry_subjectadmin/rest/mergeintogroup/{0}".format(self.assignment.id)

    def _postas(self, username, data):
        self.client.login(username=username, password="test")
        return self.client.rest_post(self.url, data)

    def test_post(self):
        self.testhelper.add_to_path("uni;sub.p1.a1.g1:candidate(student1,student2):examiner(examiner1).d1")
        self.testhelper.add_delivery("sub.p1.a1.g1", {"bad.py": ["print ", "bah"]})
        self.testhelper.add_feedback("sub.p1.a1.g1", verdict={"grade": "F", "points": 30, "is_passing_grade": False})
        source = self.testhelper.sub_p1_a1_g1

        self.testhelper.add_to_path("uni;sub.p1.a1.g2:candidate(student1,student3):examiner(examiner2)")
        target = self.testhelper.sub_p1_a1_g2

        self.assertEquals(self.assignment.assignmentgroups.count(), 2)
        content, response = self._postas(
            "a1admin", {"source_group_ids": [{"id": source.id}], "target_group_id": target.id}
        )
        self.assertEquals(response.status_code, 200)
        self.assertEquals(content["success"], True)
        self.assertEquals(content["target_group_id"], target.id)
        self.assertEquals(content["source_group_ids"], [{"id": source.id}])
        self.assertEquals(self.assignment.assignmentgroups.count(), 1)
        merged_target = self.assignment.assignmentgroups.all()[0]
        self.assertEquals(merged_target.candidates.count(), 3)
        self.assertEquals(merged_target.examiners.count(), 2)

    def test_post_multiple(self):
        self.testhelper.add_to_path("uni;sub.p1.a1.source1:candidate(student1,student2):examiner(examiner1).d1")
        self.testhelper.add_to_path("uni;sub.p1.a1.source2:candidate(student1,student2)")
        self.testhelper.add_to_path("uni;sub.p1.a1.source3:candidate(student1)")
        self.testhelper.add_to_path("uni;sub.p1.a1.source4:candidate(student6)")
        source_group_ids = []
        for num in xrange(1, 5):
            group = getattr(self.testhelper, "sub_p1_a1_source{0}".format(num))
            source_group_ids.append({"id": group.id})
        self.assertEquals(len(source_group_ids), 4)

        self.testhelper.add_to_path("uni;sub.p1.a1.g2:candidate(student1,student3):examiner(examiner2)")
        target = self.testhelper.sub_p1_a1_g2

        self.assertEquals(self.assignment.assignmentgroups.count(), 5)
        content, response = self._postas(
            "a1admin", {"source_group_ids": source_group_ids, "target_group_id": target.id}
        )
        self.assertEquals(response.status_code, 200)
        self.assertEquals(content["success"], True)
        self.assertEquals(content["target_group_id"], target.id)
        self.assertEquals(content["source_group_ids"], source_group_ids)
        self.assertEquals(self.assignment.assignmentgroups.count(), 1)
        merged_target = self.assignment.assignmentgroups.all()[0]
        self.assertEquals(merged_target.candidates.count(), 4)
        self.assertEquals(merged_target.examiners.count(), 2)

    def test_post_nobody(self):
        self.testhelper.create_user("nobody")
        content, response = self._postas("nobody", {"source_group_ids": [{"id": 1}], "target_group_id": 1})
        self.assertEquals(response.status_code, 403)

    def test_post_not_found(self):
        content, response = self._postas(
            "a1admin", {"source_group_ids": [{"id": 10000000}], "target_group_id": 1100000}
        )
        self.assertEquals(response.status_code, 404)
开发者ID:espenak,项目名称:devilry-django,代码行数:75,代码来源:mergeintogroup.py

示例2: TestCreateGroupRest

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestCreateGroupRest(TestCase, GroupManagerTestMixin):
    def setUp(self):
        self.testhelper = TestHelper()
        self.testhelper.add(nodes='uni',
                            subjects=['sub'],
                            periods=['p1'],
                            assignments=['a1:admin(a1admin)'])
        self.client = RestClient()
        self.testhelper.create_user('candidate1')
        self.testhelper.create_user('examiner1')
        self.testhelper.create_superuser('grandma')
        self.a1id = self.testhelper.sub_p1_a1.id

    def _geturl(self, assignment_id):
        return '/devilry_subjectadmin/rest/group/{0}/'.format(assignment_id)

    def _postas(self, username, assignment_id, data={}):
        self.client.login(username=username, password='test')
        return self.client.rest_post(self._geturl(assignment_id), data)

    def test_create_minimal(self):
        data = {'name': 'g1',
                'is_open': False}
        content, response = self._postas('a1admin', self.a1id, data)
        self.assertEquals(response.status_code, 201)
        self.assertEquals(set(content.keys()),
                          set(['name', 'id', 'etag', 'is_open', 'parentnode',
                               'feedback', 'deadlines', 'candidates', 'tags',
                               'examiners', 'num_deliveries']))
        self.assertEquals(content['name'], 'g1')
        self.assertEquals(content['is_open'], False)
        self.assertEquals(content['parentnode'], self.a1id)
        self.assertEquals(content['num_deliveries'], 0)
        self.assertEquals(content['feedback'], None)
        self.assertEquals(content['deadlines'], [])
        self.assertEquals(content['candidates'], [])
        self.assertEquals(content['examiners'], [])
        self.assertEquals(content['tags'], [])

        groups = self.testhelper.sub_p1_a1.assignmentgroups.all()
        self.assertEquals(len(groups), 1)
        self.assertEquals(content['id'], groups[0].id)


    def _test_create_as(self, username):
        data = {'name': 'g1',
                'is_open': False,
                'examiners': [self.create_examinerdict(username='examiner1')],
                'candidates': [self.create_candidatedict(username='candidate1')],
                'tags': [self.create_tagdict('mytag')]}
        content, response = self._postas(username, self.a1id, data)
        #from pprint import pprint
        #print 'Response content:'
        #pprint(content)
        self.assertEquals(response.status_code, 201)


        self.assertEquals(content['name'], 'g1')
        self.assertEquals(content['is_open'], False)
        self.assertEquals(content['parentnode'], self.a1id)
        self.assertEquals(content['num_deliveries'], 0)

        # Feedback
        self.assertEquals(content['feedback'], None)

        # Deadlines
        self.assertEquals(content['deadlines'], [])

        # Tags
        self.assertEquals(len(content['tags']), 1)
        tag = content['tags'][0]
        self.assertEquals(tag['tag'], 'mytag')
        self.assertEquals(set(tag.keys()), set(['id', 'tag']))

        # Examiners
        self.assertEquals(len(content['examiners']), 1)
        examiner = content['examiners'][0]
        self.assertEquals(set(examiner.keys()),
                          set(['id', 'user']))
        self.assertEquals(set(examiner['user'].keys()),
                          set(['email', 'full_name', 'id', 'username']))
        self.assertEquals(examiner['user']['id'], self.testhelper.examiner1.id)
        self.assertEquals(examiner['user']['username'], 'examiner1')

        # Candidates
        self.assertEquals(len(content['candidates']), 1)
        candidate = content['candidates'][0]
        self.assertEquals(set(candidate.keys()),
                          set(['id', 'user', 'candidate_id']))
        self.assertEquals(set(candidate['user'].keys()),
                          set(['email', 'full_name', 'id', 'username']))
        self.assertEquals(candidate['user']['id'], self.testhelper.candidate1.id)
        self.assertEquals(candidate['candidate_id'], '')
        self.assertEquals(candidate['user']['username'], 'candidate1')

        # It was actually created?
        groups = self.testhelper.sub_p1_a1.assignmentgroups.all()
        self.assertEquals(len(groups), 1)
        self.assertEquals(content['id'], groups[0].id)

#.........这里部分代码省略.........
开发者ID:TZer0,项目名称:devilry-django,代码行数:103,代码来源:group.py

示例3: TestRestCreateNewAssignmentIntegration

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestRestCreateNewAssignmentIntegration(TestCase):
    def setUp(self):
        self.testhelper = TestHelper()
        self.testhelper.add(nodes='uni',
                            subjects=['sub'],
                            periods=['p1:admin(p1admin)', 'p2'])
        self.client = RestClient()
        self.url = '/devilry_subjectadmin/rest/createnewassignment/'

    def _login_p1admin(self):
        self.client.login(username='p1admin', password='test')


    def _get_testdata(self):
        publishing_time = self.testhelper.sub_p1.start_time + timedelta(days=1)
        first_deadline = self.testhelper.sub_p1.start_time + timedelta(days=2)
        return dict(period_id=self.testhelper.sub_p1.id,
                    short_name='a', long_name='Aa',
                    first_deadline=isoformat_datetime(first_deadline),
                    publishing_time=isoformat_datetime(publishing_time),
                    delivery_types=ELECTRONIC, anonymous=False,
                    setupstudents_mode='do_not_setup',
                    setupexaminers_mode='do_not_setup')

    def test_create(self):
        self._login_p1admin()
        publishing_time = self.testhelper.sub_p1.start_time + timedelta(days=1)
        first_deadline = self.testhelper.sub_p1.start_time + timedelta(days=2)
        content, response = self.client.rest_post(self.url, self._get_testdata())
        self.assertEquals(response.status_code, 201)
        self.assertEquals(set(content.keys()),
                          set(['id', 'period_id', 'short_name', 'long_name', 'first_deadline', 'anonymous']))

    def test_create_notfound(self):
        self._login_p1admin()
        data = self._get_testdata()
        data['period_id'] = 200000
        content, response = self.client.rest_post(self.url, data)
        self.assertEquals(response.status_code, 403)

    def test_create_permissiondenied(self):
        self.testhelper.create_user('nopermsuser')
        self.client.login(username='nopermsuser', password='test')
        data = self._get_testdata()
        content, response = self.client.rest_post(self.url, data)
        self.assertEquals(response.status_code, 403)

    def test_create_validation(self):
        self._login_p1admin()
        content, response = self.client.rest_post(self.url, {})
        self.assertEquals(response.status_code, 400)
        self.assertEquals(content.keys(), ['field_errors'])
        for fieldname in ['delivery_types', 'long_name', 'publishing_time', 'short_name']:
            self.assertEquals(content['field_errors'][fieldname], [u'This field is required.'])

    def test_create_first_deadline_none(self):
        self._login_p1admin()
        data = self._get_testdata()
        data['first_deadline'] = None
        data['setupstudents_mode'] = 'allrelated'
        content, response = self.client.rest_post(self.url, data)
        self.assertEquals(response.status_code, 400)
        self.assertTrue(content['field_errors']['first_deadline'][0].startswith('Required when adding'))
开发者ID:RobertKolner,项目名称:devilry-django,代码行数:65,代码来源:createnewassignment.py

示例4: TestRestListOrCreatePeriodRest

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestRestListOrCreatePeriodRest(TestCase):
    def setUp(self):
        self.testhelper = TestHelper()
        self.testhelper.add(nodes='uni:admin(uniadmin)',
                            subjects=['duck2000:admin(subadmin)'],
                            periods=['one:admin(adminone)',
                                     'two',
                                     'three:admin(adminone)'])
        self.client = RestClient()
        self.url = '/devilry_subjectadmin/rest/period/'
        self.testhelper.create_user('nobody')

    def _listas(self, username, **data):
        self.client.login(username=username, password='test')
        return self.client.rest_get(self.url, **data)

    def test_list(self):
        content, response = self._listas('adminone')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)
        self.assertEquals(set(content[0].keys()),
                          set(['id', 'parentnode', 'etag', 'short_name', 'long_name',
                               'start_time', 'end_time', 'url']))

    def test_list_nonadmin(self):
        self.testhelper.create_user('otheruser')
        content, response = self._listas('otheruser')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 0)

    def test_list_in_subject(self):
        self.testhelper.add(nodes='uni:admin(uniadmin)',
                            subjects=['duck9000'],
                            periods=['p1', 'p2'])
        content, response = self._listas('uniadmin',
                                         parentnode=self.testhelper.duck9000.id)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)
        shortnames = set([p['short_name'] for p in content])
        self.assertEquals(shortnames, set(['p1', 'p2']))

    def _createas(self, username, data):
        self.client.login(username=username, password='test')
        return self.client.rest_post(self.url, data)

    def test_create(self):
        content, response = self._createas('subadmin',
                                           {'short_name': 'test',
                                            'long_name': 'Test',
                                            'admins': [],
                                            'start_time': isoformat_relativetime(days=-2),
                                            'end_time': isoformat_relativetime(days=2),
                                            'parentnode': self.testhelper.duck2000.id})
        self.assertEquals(response.status_code, 201)
        self.assertEquals(content['long_name'], 'Test')
        self.assertEquals(content['short_name'], 'test')
        self.assertEquals(content['parentnode'], self.testhelper.duck2000.id)
        created = Period.objects.get(id=content['id'])
        self.assertEquals(created.short_name, 'test')
        self.assertEquals(created.long_name, 'Test')
        self.assertEquals(created.parentnode.id, self.testhelper.duck2000.id)
        admins = created.admins.all()
        self.assertEquals(len(admins), 0)

    def test_create_nobody(self):
        content, response = self._createas('nobody',
                                           {'short_name': 'test',
                                            'long_name': 'Test',
                                            'admins': [],
                                            'start_time': isoformat_relativetime(days=-2),
                                            'end_time': isoformat_relativetime(days=2),
                                            'parentnode': self.testhelper.duck2000.id})
        self.assertEquals(response.status_code, 403)
        self.assertEquals(content['detail'], 'Permission denied')

    def test_create_admins(self):
        self.testhelper.create_user('testadmin')
        content, response = self._createas('uniadmin',
                                           {'short_name': 'test',
                                            'long_name': 'Test',
                                            'admins': [{'id': self.testhelper.testadmin.id}],
                                            'start_time': isoformat_relativetime(days=-2),
                                            'end_time': isoformat_relativetime(days=2),
                                            'parentnode': self.testhelper.duck2000.id})
        self.assertEquals(response.status_code, 201)
        created = Period.objects.get(id=content['id'])
        admins = created.admins.all()
        self.assertEquals(len(admins), 1)
        self.assertEquals(admins[0].username, 'testadmin')
开发者ID:RobertKolner,项目名称:devilry-django,代码行数:91,代码来源:period.py

示例5: TestListOrCreateRelatedUserMixin

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]

#.........这里部分代码省略.........
        self.create_relateduser(
            self.testhelper.sub_p2, index=20, tags=""
        )  # Not on p1, so we shold not get this in the listing!
        content, response = self._listas("p1admin")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 3)  # Since this is 3, we did not get the user registered on p2.
        first, second, last = content
        self.assertEquals(first["user"]["username"], "reluser0")
        self.assertEquals(first["user"]["full_name"], "User 0")
        self.assertEquals(first["tags"], "")
        self.assertEquals(second["tags"], "")
        self.assertEquals(second["user"]["username"], "reluser1")
        self.assertEquals(last["user"]["username"], "reluser5")
        self.assertEquals(last["tags"], "group1,group2")
        return content

    def test_list_none(self):
        content, response = self._listas("p1admin")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 0)

    def test_list_superuser(self):
        self._create_relatedusers(2)
        content, response = self._listas("superuser")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)

    def test_list_not_admin(self):
        self._create_relatedusers(2)
        content, response = self._listas("p2admin")
        self.assertEquals(response.status_code, 403)

    def _listqueryas(self, username, query):
        self.client.login(username=username, password="test")
        return self.client.rest_get(self.get_url(), **{"query": query})

    def test_list_query(self):
        self._create_relatedusers(2)
        self.create_relateduser(self.testhelper.sub_p1, index=5, tags="group1,group2")
        self.create_relateduser(
            self.testhelper.sub_p2, index=20, tags=""
        )  # Not on p1, so we shold not get this in the listing!
        self.testhelper.reluser0.devilryuserprofile.full_name = "Superhero"
        self.testhelper.reluser0.devilryuserprofile.save()
        self.testhelper.reluser1.devilryuserprofile.full_name = "Super Not hero"
        self.testhelper.reluser1.email = "[email protected]"
        self.testhelper.reluser1.devilryuserprofile.save()
        self.testhelper.reluser1.save()

        content, response = self._listqueryas("p1admin", query="5")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 1)

        content, response = self._listqueryas("p1admin", query="HeRo")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)

        content, response = self._listqueryas("p1admin", query="group2")
        self.assertEquals(len(content), 1)

        content, response = self._listqueryas("p1admin", query="[email protected]")
        self.assertEquals(len(content), 1)

    def _createas(self, username, data):
        self.client.login(username=username, password="test")
        return self.client.rest_post(self.get_url(), data)

    def get_valid_createdata(self):
        """
        Overridden in TestListOrCreateRelatedStudentRest.
        """
        return {
            "period": self.testhelper.sub_p1.id,
            "user": self.testhelper.testuser.id,  # TODO: Support username
            "tags": "tag1,tag2",
        }

    def _create_test_helper(self, username):
        self.assertEquals(self.modelcls.objects.all().count(), 0)
        content, response = self._createas(username, self.get_valid_createdata())
        self.assertEquals(response.status_code, 201)
        self.assertEquals(content["user"].keys(), [u"username", u"email", u"full_name", u"id"])
        self.assertEquals(content["user"]["username"], "testuser")
        self.assertEquals(content["user"]["id"], self.testhelper.testuser.id)
        self.assertEquals(content["tags"], "tag1,tag2")
        self.assertEquals(content["period"], self.testhelper.sub_p1.id)
        self.assertEquals(self.modelcls.objects.all().count(), 1)
        created = self.modelcls.objects.all()[0]
        self.assertEquals(created.user.username, "testuser")
        return content, created

    def test_create(self):
        return self._create_test_helper("p1admin")

    def test_create_not_admin(self):
        content, response = self._createas("p2admin", self.get_valid_createdata())
        self.assertEquals(response.status_code, 403)

    def test_create_superuser(self):
        content, response = self._create_test_helper("superuser")
开发者ID:TZer0,项目名称:devilry-django,代码行数:104,代码来源:relateduser.py

示例6: TestRestPopFromGroup

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestRestPopFromGroup(TestCase):
    def setUp(self):
        self.client = RestClient()
        self.testhelper = TestHelper()
        self.testhelper.add(nodes='uni',
                            subjects=['sub'],
                            periods=['p1:begins(-2)'], # 2 months ago 
                            assignments=['a1:admin(a1admin)'])
        self.assignment = self.testhelper.sub_p1_a1
        self.url = '/devilry_subjectadmin/rest/popfromgroup/{0}'.format(self.assignment.id)

    def _postas(self, username, data):
        self.client.login(username=username, password='test')
        return self.client.rest_post(self.url, data)

    def test_post(self):
        self.testhelper.add_to_path('uni;sub.p1.a1.g1:candidate(student1,student2):examiner(examiner1).d1')
        self.testhelper.add_delivery('sub.p1.a1.g1', {'bad.py': ['print ', 'bah']})
        self.testhelper.add_feedback('sub.p1.a1.g1', verdict={'grade': 'F', 'points': 30, 'is_passing_grade': False})
        source = self.testhelper.sub_p1_a1_g1
        student1cand = source.candidates.get(student=self.testhelper.student1)

        self.assertEquals(self.assignment.assignmentgroups.count(), 1)
        content, response = self._postas('a1admin', {'group_id': source.id,
                                                    'candidate_id': student1cand.id})
        self.assertEquals(response.status_code, 200)
        self.assertEquals(self.assignment.assignmentgroups.count(), 2)
        self.assertEquals(content['success'], True)
        self.assertEquals(content['group_id'], source.id)
        self.assertNotEquals(content['new_group_id'], source.id)
        self.assertEquals(source.candidates.count(), 1)
        self.assertEquals(source.candidates.all()[0].student.username, 'student2')

        newgroup = self.assignment.assignmentgroups.get(~Q(id=source.id))
        self.assertEquals(content['new_group_id'], newgroup.id)
        self.assertEquals(newgroup.candidates.count(), 1)
        self.assertEquals(newgroup.candidates.all()[0].student.username, 'student1')

        # Some sanity tests. Note that all of this is already tested in the tests for AssignmentGroup.pop_candidate
        def get_delivery(group):
            return Delivery.objects.get(deadline__assignment_group=group)
        delivery = get_delivery(source)
        newdelivery = get_delivery(newgroup)
        self.assertEquals(delivery.time_of_delivery, newdelivery.time_of_delivery)
        self.assertEquals(delivery.feedbacks.all()[0].grade,
                          newdelivery.feedbacks.all()[0].grade)
        self.assertEquals(newdelivery.feedbacks.all()[0].grade, 'F')

    def test_post_nobody(self):
        self.testhelper.create_user('nobody')
        content, response = self._postas('nobody', {'group_id': 1,
                                                    'candidate_id': 1})
        self.assertEquals(response.status_code, 403)

    def test_post_to_few_candidates(self):
        self.testhelper.add_to_path('uni;sub.p1.a1.g1:candidate(student1):examiner(examiner1).d1')
        source = self.testhelper.sub_p1_a1_g1
        student1cand = source.candidates.get(student=self.testhelper.student1)
        content, response = self._postas('a1admin', {'group_id': source.id,
                                                     'candidate_id': student1cand.id})
        self.assertEquals(response.status_code, 400)
        self.assertEquals(content['detail'], 'Can not pop candidates on a group with less than 2 candidates.')

    def test_post_not_candidate_on_group(self):
        self.testhelper.add_to_path('uni;sub.p1.a1.g1:candidate(student1, student2)')
        self.testhelper.add_to_path('uni;sub.p1.a1.g2:candidate(notcandong1)')
        source = self.testhelper.sub_p1_a1_g1
        notcandong1Cand = self.testhelper.sub_p1_a1_g2.candidates.get(student=self.testhelper.notcandong1)
        content, response = self._postas('a1admin', {'group_id': source.id,
                                                     'candidate_id': notcandong1Cand.id})
        self.assertEquals(response.status_code, 404)
开发者ID:RobertKolner,项目名称:devilry-django,代码行数:73,代码来源:popfromgroup.py

示例7: TestGroupRest

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestGroupRest(TestCase, GroupManagerTestMixin):
    def setUp(self):
        self.testhelper = TestHelper()
        self.testhelper.add(nodes='uni',
                            subjects=['sub'],
                            periods=['p1'],
                            assignments=['a1:admin(a1admin)'])
        self.client = RestClient()
        self.testhelper.create_user('candidate1')
        self.testhelper.create_user('examiner1')
        self.testhelper.create_superuser('grandma')
        self.a1id = self.testhelper.sub_p1_a1.id

    def _geturl(self, assignment_id):
        return '/devilry_subjectadmin/rest/group/{0}/'.format(assignment_id)

    def _postas(self, username, assignment_id, data={}):
        self.client.login(username=username, password='test')
        return self.client.rest_post(self._geturl(assignment_id), data)

    def test_create_minimal(self):
        data = [{'name': 'g1',
                 'is_open': False}]
        content, response = self._postas('a1admin', self.a1id, data)
        self.assertEquals(response.status_code, 201)
        self.assertEquals(len(content), 1)
        first = content[0]
        self.assertEquals(set(first.keys()),
                          set(['name', 'id', 'etag', 'status', 'is_open', 'parentnode',
                               'feedback', 'deadlines', 'candidates', 'tags',
                               'examiners', 'num_deliveries']))
        self.assertEquals(first['name'], 'g1')
        self.assertEquals(first['is_open'], False)
        self.assertEquals(first['parentnode'], self.a1id)
        self.assertEquals(first['num_deliveries'], 0)
        self.assertEquals(first['feedback'], None)
        self.assertEquals(first['deadlines'], [])
        self.assertEquals(first['candidates'], [])
        self.assertEquals(first['examiners'], [])
        self.assertEquals(first['tags'], [])

        groups = self.testhelper.sub_p1_a1.assignmentgroups.all()
        self.assertEquals(len(groups), 1)
        self.assertEquals(first['id'], groups[0].id)


    def _test_create_as(self, username):
        a1 = self.testhelper.sub_p1_a1
        a1.first_deadline = datetime(2005, 1, 1)
        a1.save()
        data = [{'name': 'g1',
                 'is_open': False,
                 'examiners': [self.create_examinerdict(username='examiner1')],
                 'candidates': [self.create_candidatedict(username='candidate1')],
                 'tags': [self.create_tagdict('mytag')]}]
        content, response = self._postas(username, self.a1id, data)
        #from pprint import pprint
        #print 'Response content:'
        #pprint(content)
        self.assertEquals(response.status_code, 201)
        self.assertEquals(len(content), 1)
        first = content[0]

        self.assertEquals(first['name'], 'g1')
        self.assertEquals(first['is_open'], True) # NOTE: Overrides the parameter since first_deadline is set.
        self.assertEquals(first['parentnode'], self.a1id)
        self.assertEquals(first['num_deliveries'], 0)

        # Feedback
        self.assertEquals(first['feedback'], None)

        # Deadlines
        self.assertEquals(len(first['deadlines']), 1)
        self.assertEquals(first['deadlines'][0]['deadline'], '2005-01-01T00:00:00')
        self.assertEquals(set(first['deadlines'][0].keys()), set(['id', 'deadline']))

        # Tags
        self.assertEquals(len(first['tags']), 1)
        tag = first['tags'][0]
        self.assertEquals(tag['tag'], 'mytag')
        self.assertEquals(set(tag.keys()), set(['id', 'tag']))

        # Examiners
        self.assertEquals(len(first['examiners']), 1)
        examiner = first['examiners'][0]
        self.assertEquals(set(examiner.keys()),
                          set(['id', 'user']))
        self.assertEquals(set(examiner['user'].keys()),
                          set(['email', 'full_name', 'id', 'username', 'displayname']))
        self.assertEquals(examiner['user']['id'], self.testhelper.examiner1.id)
        self.assertEquals(examiner['user']['username'], 'examiner1')

        # Candidates
        self.assertEquals(len(first['candidates']), 1)
        candidate = first['candidates'][0]
        self.assertEquals(set(candidate.keys()),
                          set(['id', 'user', 'candidate_id']))
        self.assertEquals(set(candidate['user'].keys()),
                          set(['email', 'full_name', 'id', 'username', 'displayname']))
        self.assertEquals(candidate['user']['id'], self.testhelper.candidate1.id)
#.........这里部分代码省略.........
开发者ID:espenak,项目名称:devilry-django,代码行数:103,代码来源:group.py

示例8: TestListOrCreateRelatedUserMixin

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]

#.........这里部分代码省略.........
            self.create_relateduser(self.testhelper.sub_p1, index)

    def test_list(self):
        self._create_relatedusers(2)
        self.create_relateduser(self.testhelper.sub_p1, index=5, tags='group1,group2')
        self.create_relateduser(self.testhelper.sub_p2, index=20, tags='') # Not on p1, so we shold not get this in the listing!
        content, response = self._listas('p1admin')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 3) # Since this is 3, we did not get the user registered on p2.
        first, second, last = content
        self.assertEquals(first['user']['username'], 'reluser0')
        self.assertEquals(first['user']['full_name'] , 'User 0')
        self.assertEquals(first['tags'], '')
        self.assertEquals(second['tags'], '')
        self.assertEquals(second['user']['username'], 'reluser1')
        self.assertEquals(last['user']['username'], 'reluser5')
        self.assertEquals(last['tags'], 'group1,group2')
        return content

    def test_list_none(self):
        content, response = self._listas('p1admin')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 0)

    def test_list_superuser(self):
        self._create_relatedusers(2)
        content, response = self._listas('superuser')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)

    def test_list_not_admin(self):
        self._create_relatedusers(2)
        content, response = self._listas('p2admin')
        self.assertEquals(response.status_code, 403)

    def _listqueryas(self, username, query):
        self.client.login(username=username, password='test')
        return self.client.rest_get(self.get_url(), **{'query': query})

    def test_list_query(self):
        self._create_relatedusers(2)
        self.create_relateduser(self.testhelper.sub_p1, index=5, tags='group1,group2')
        self.create_relateduser(self.testhelper.sub_p2, index=20, tags='') # Not on p1, so we shold not get this in the listing!
        self.testhelper.reluser0.devilryuserprofile.full_name = 'Superhero'
        self.testhelper.reluser0.devilryuserprofile.save()
        self.testhelper.reluser1.devilryuserprofile.full_name = 'Super Not hero'
        self.testhelper.reluser1.email = '[email protected]'
        self.testhelper.reluser1.devilryuserprofile.save()
        self.testhelper.reluser1.save()

        content, response = self._listqueryas('p1admin', query='5')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 1)

        content, response = self._listqueryas('p1admin', query='HeRo')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)

        content, response = self._listqueryas('p1admin', query='group2')
        self.assertEquals(len(content), 1)

        content, response = self._listqueryas('p1admin', query='[email protected]')
        self.assertEquals(len(content), 1)

    def _createas(self, username, data):
        self.client.login(username=username, password='test')
        return self.client.rest_post(self.get_url(), data)

    def get_valid_createdata(self):
        """
        Overridden in TestListOrCreateRelatedStudentRest.
        """
        return {'period': self.testhelper.sub_p1.id,
                'user': self.testhelper.testuser.id, # TODO: Support username
                'tags': 'tag1,tag2'}

    def _create_test_helper(self, username):
        self.assertEquals(self.modelcls.objects.all().count(), 0)
        content, response = self._createas(username, self.get_valid_createdata())
        self.assertEquals(response.status_code, 201)
        self.assertEquals(set(content['user'].keys()),
                          set(['username', 'email', 'full_name', 'id', 'displayname']))
        self.assertEquals(content['user']['username'], 'testuser')
        self.assertEquals(content['user']['id'], self.testhelper.testuser.id)
        self.assertEquals(content['tags'], 'tag1,tag2')
        self.assertEquals(content['period'], self.testhelper.sub_p1.id)
        self.assertEquals(self.modelcls.objects.all().count(), 1)
        created = self.modelcls.objects.all()[0]
        self.assertEquals(created.user.username, 'testuser')
        return content, created

    def test_create(self):
        return self._create_test_helper('p1admin')

    def test_create_not_admin(self):
        content, response = self._createas('p2admin', self.get_valid_createdata())
        self.assertEquals(response.status_code, 403)

    def test_create_superuser(self):
        content, response = self._create_test_helper('superuser')
开发者ID:RobertKolner,项目名称:devilry-django,代码行数:104,代码来源:relateduser.py

示例9: TestRestListOrCreateSubjectRest

# 需要导入模块: from devilry.utils.rest_testclient import RestClient [as 别名]
# 或者: from devilry.utils.rest_testclient.RestClient import rest_post [as 别名]
class TestRestListOrCreateSubjectRest(TestCase):
    def setUp(self):
        self.testhelper = TestHelper()
        self.testhelper.add(
            nodes="uni:admin(uniadmin)",
            subjects=[
                "duck2000:admin(adminone,admintwo):ln(Something fancy)",
                "duck3000",
                "duck1000:admin(adminone)",
                "duck4000:admin(adminone,admintwo,singleadmin)",
            ],
        )
        self.client = RestClient()
        self.url = "/devilry_subjectadmin/rest/subject/"
        self.testhelper.create_user("nobody")

    def _listas(self, username, **data):
        self.client.login(username=username, password="test")
        return self.client.rest_get(self.url, **data)

    def test_list(self):
        content, response = self._listas("adminone")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 3)
        self.assertEquals(content[0]["short_name"], "duck1000")
        self.assertEquals(content[1]["short_name"], "duck2000")
        self.assertEquals(content[1]["long_name"], "Something fancy")
        self.assertEquals(content[2]["short_name"], "duck4000")
        self.assertEquals(set(content[0].keys()), set(["id", "parentnode", "etag", "short_name", "long_name"]))

    def test_list_singleadmin(self):
        content, response = self._listas("singleadmin")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 1)
        self.assertEquals(content[0]["short_name"], "duck4000")

    def test_list_nonadmin(self):
        self.testhelper.create_user("otheruser")
        content, response = self._listas("otheruser")
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 0)

    def test_list_in_node(self):
        self.testhelper.add(nodes="othernode:admin(otheradmin)", subjects=["s1", "s2"])
        content, response = self._listas("otheradmin", parentnode=self.testhelper.othernode.id)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(len(content), 2)
        shortnames = set([p["short_name"] for p in content])
        self.assertEquals(shortnames, set(["s1", "s2"]))

    def _createas(self, username, data):
        self.client.login(username=username, password="test")
        return self.client.rest_post(self.url, data)

    def test_create(self):
        content, response = self._createas(
            "uniadmin", {"short_name": "test", "long_name": "Test", "admins": [], "parentnode": self.testhelper.uni.id}
        )
        self.assertEquals(response.status_code, 201)
        self.assertEquals(content["long_name"], "Test")
        self.assertEquals(content["short_name"], "test")
        self.assertEquals(content["parentnode"], self.testhelper.uni.id)
        created = Subject.objects.get(id=content["id"])
        self.assertEquals(created.short_name, "test")
        self.assertEquals(created.long_name, "Test")
        self.assertEquals(created.parentnode.id, self.testhelper.uni.id)
        admins = created.admins.all()
        self.assertEquals(len(admins), 0)

    def test_create_nobody(self):
        content, response = self._createas(
            "nobody", {"short_name": "test", "long_name": "Test", "admins": [], "parentnode": self.testhelper.uni.id}
        )
        self.assertEquals(response.status_code, 403)
        self.assertEquals(content["detail"], "Permission denied")

    def test_create_admins(self):
        self.testhelper.create_user("testadmin")
        content, response = self._createas(
            "uniadmin",
            {
                "short_name": "test",
                "long_name": "Test",
                "admins": [{"id": self.testhelper.testadmin.id}],
                "parentnode": self.testhelper.uni.id,
            },
        )
        self.assertEquals(response.status_code, 201)
        created = Subject.objects.get(id=content["id"])
        admins = created.admins.all()
        self.assertEquals(len(admins), 1)
        self.assertEquals(admins[0].username, "testadmin")
开发者ID:espenak,项目名称:devilry-django,代码行数:94,代码来源:subject.py


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