Пример #1
0
    def test_get_activity_list(self):
        tester_create_activity('First Salon',
                               now() - timedelta(weeks=1), 'MS Shanghai',
                               [self.ids[0]])
        tester_create_activity('Second Salon',
                               now() - timedelta(days=1), 'MS Beijing',
                               [self.ids[2]])
        tester_create_activity('Third Salon',
                               now() - timedelta(hours=2), 'MS Suzhou',
                               [self.ids[3]])
        tester_create_activity('Fourth Salon', now(), 'MS Seattle',
                               self.ids[0:3])

        client = Client()
        response = client.get(activity_list_url)
        self.assertEqual(response.status_code, 200)  # 未登录,get 返回 200

        tester_login(client=client)
        response = client.get(activity_list_url)
        self.assertEqual(response.status_code, 200)
        json_content = response.json()
        self.assertEqual(json_content['count'], 4)  # 总数正确
        results = json_content['results']
        self.check_order(results)  # 检查是否按日期降序排序

        for activity_dict in results:  # 检查每一个活动
            activity = Activity.objects.get(id=activity_dict['id'])
            self.assertActivityDetailEqual(activity_dict, activity)
Пример #2
0
 def test_reset_password_with_invalid_field(self):
     tester_signup("*****@*****.**", "anotheruser", "another",
                   "20201231")
     # 没上线
     client = Client()
     response = client.patch(change_password_url(self.user.id), {
         "old_password": self.password,
         "new_password": "******"
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 401)
     response = tester_login("*****@*****.**", "anotheruser", client)
     self.assertEqual(response.status_code, 200)
     # 少字段
     response = tester_login(self.email, self.password, client)
     self.assertEqual(response.status_code, 200)
     response = client.patch(change_password_url(self.user.id),
                             {"new_password": "******"},
                             content_type='application/json')
     self.assertEqual(response.status_code, 403)
     response = client.patch(change_password_url(self.user.id), {
         "password": "******",
         "new_password": "******"
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 403)
     # 旧密码错误
     response = client.patch(change_password_url(self.user.id), {
         "old_password": "******",
         "new_email": '*****@*****.**',
         "new_password": "******",
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 403)
     response = tester_login("*****@*****.**", "anotheruser", client)
     self.assertEqual(response.status_code, 200)  # 邮箱没有被修改
     # 新密码强度不够
     response = client.patch(change_password_url(self.user.id), {
         "old_password": "******",
         "new_password": "******"
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 400)
     # 邮箱不合法
     response = client.patch(change_password_url(self.user.id), {
         "old_password": "******",
         "new_email": "qwerty"
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 400)
     # 邮箱已被占用
     response = client.patch(change_password_url(self.user.id), {
         "old_password": "******",
         "new_email": '*****@*****.**',
         'new_password': "******"
     },
                             content_type='application/json')
     self.assertEqual(response.status_code, 400)
     response = tester_login("*****@*****.**", "anotheruser", client)
     self.assertEqual(response.status_code, 200)  # 密码没有被修改
Пример #3
0
 def test_get_whoami(self):
     c = Client()
     tester_login(client=c)
     r1 = c.get(whoami_url)
     self.assertEqual(r1.status_code, 200)
     r2 = c.get(user_detail_url(self.admin.id))
     self.assertEqual(r1.content, r2.content)
Пример #4
0
    def test_get_user_list(self):
        tester_signup('*****@*****.**', 'qwerty', 'account', '1234567')
        user = User.objects.filter(username='******')[0]
        user.userprofile.experience = 1
        user.userprofile.save()
        tester_signup('*****@*****.**', 'qwerty', 'account1', '12345678')
        user = User.objects.create(username="******",
                                   first_name="user")
        UserProfile.objects.create(user=user,
                                   student_id='233',
                                   about="你好,世界!",
                                   experience="5")
        self.assertEqual(User.objects.count(), 4)

        client = Client()
        response = client.get(user_list_url)
        self.assertEqual(response.status_code, 200)  # 未登录,get 返回 200

        tester_login(client=client)
        response = client.get(user_list_url)
        self.assertEqual(response.status_code, 200)
        json_content = response.json()
        results = json_content['results']
        self.check_order(results)
        self.assertEqual([5, 1, 0, 0],
                         list(map(lambda u: u['experience'],
                                  results)))  # 可见结果经过排序
Пример #5
0
    def test_search(self):
        # 定义验证返回结果的函数
        def check_search_queryset(_results: List[Dict], keywords: str):
            self.check_order(_results)
            results_id = list(map(lambda a: str(a['id']), _results))
            for a in Activity.objects.all():  # 检查 user 是否应当出现在搜索结果中,结果是否和预期相同
                presenter_names = a.presenter.all().values_list(
                    'first_name')[0]
                dt = a.datetime.isoformat()
                self.assertEqual(
                    str(a.id) in results_id, keywords in
                    f"{a.title} {dt} {a.location} {''.join(presenter_names)}",
                    "keywords=%s\t"
                    "title=%s\t"
                    "datetime=%s\t"
                    "locations=%s\t"
                    "presenters=%s" % (keywords, a.title, dt, a.location,
                                       ''.join(presenter_names)))

        for i in range(0, 40):
            u = User(username="******" % (i + 1),
                     first_name="user%d" % (i + 78))
            up = UserProfile(user=u,
                             student_id=str(i + 37),
                             about="你好,世界!",
                             experience=randrange(1, 1000))
            u.save()
            up.save()
        self.assertEqual(User.objects.count(), 44)  # 最开始创建了 4 个用户
        for i in range(0, 40):
            a = Activity.objects.create(title=str(i + 55),
                                        location=str(i),
                                        datetime=now())
            a.presenter.add(User.objects.all()[i])
            a.save()

        client = Client()
        tester_login(client=client)
        test_keywords = range(10, 30)  # 测试的关键字
        for keyword in test_keywords:
            keyword = str(keyword)
            response = client.get(
                "%s?search=%s&page_size=100" %
                (activity_list_url, keyword))  # page_size = 0 表示不分页
            self.assertEqual(response.status_code, 200)
            json_content = response.json()
            results = json_content['results']
            check_search_queryset(results, keyword)

        r1 = client.get("%s?search=&page_size=100" % activity_list_url)
        r2 = client.get("%s?page_size=100" % activity_list_url)
        self.assertEqual(json.loads(r1.content),
                         json.loads(r2.content))  # search=<null> 应当不进行搜索

        r1 = client.get("%s?search=qwertyuiop&page_size=100" %
                        activity_list_url)
        self.assertEqual(r1.status_code, 200)  # 搜索无结果,返回 200
        self.assertEqual(json.loads(r1.content)["results"],
                         [])  # 搜索无结果,返回 results=[]
Пример #6
0
    def test_get(self):
        client = Client()
        first_id = Activity.objects.first().id
        response = client.get(activity_detail_url(first_id))
        self.assertEqual(response.status_code, 200)  # 未登录用户访问,返回 200

        tester_login(client=client)
        for a in Activity.objects.all():
            response = client.get(activity_detail_url(a.id))
            self.assertActivityDetailEqual(response.content, a)
Пример #7
0
    def test_get(self):
        client = Client()
        first_id = User.objects.first().id
        response = client.get(user_detail_url(first_id))
        self.assertEqual(response.status_code, 200)  # 未登录用户访问,返回 200

        tester_login(client=client)
        for u in User.objects.all():
            response = client.get(user_detail_url(u.id))
            self.assertUserDetailEqual(response.content, u)
Пример #8
0
    def test_search(self):
        # 定义验证返回结果的函数
        def check_search_queryset(_results: List[Dict], keywords: str):
            self.check_order(_results)
            results_id = list(map(lambda _u: str(_u['id']), _results))
            for u in User.objects.all():  # 检查 user 是否应当出现在搜索结果中,结果是否和预期相同
                self.assertEqual(
                    str(u.id) in results_id, keywords
                    in (u.username + u.first_name + u.userprofile.student_id),
                    "keywords=%s\t"
                    "username=%s\t"
                    "first_name=%s\t"
                    "student_id=%s" % (keywords, u.username, u.first_name,
                                       u.userprofile.student_id))

        for i in range(1, 40):
            user = User.objects.create(username="******" % i,
                                       first_name="user%d" % (i + 78))
            UserProfile.objects.create(user=user,
                                       student_id=str(i + 55),
                                       about="你好,世界!",
                                       experience=randrange(1, 1000))
        self.assertEqual(User.objects.count(), 40)

        client = Client()
        tester_login(client=client)
        test_keywords = list('1234567890') + [
            'hello', 'user', '1@example', '@', '12', '23'
        ]  # 测试的关键字
        for keyword in test_keywords:
            response = client.get(
                "%s?search=%s&page_size=100" %
                (user_list_url, keyword))  # page_size = 0 表示不分页
            self.assertEqual(response.status_code, 200)
            json_content = response.json()
            results = json_content['results']
            check_search_queryset(results, keyword)

        r1 = client.get("%s?search=&page_size=100" % user_list_url)
        r2 = client.get("%s?page_size=100" % user_list_url)
        self.assertEqual(json.loads(r1.content),
                         json.loads(r2.content))  # search=<null> 应当不进行搜索

        r1 = client.get("%s?search=qwertyuiop&page_size=100" % user_list_url)
        self.assertEqual(r1.status_code, 200)  # 搜索无结果,返回 200
        self.assertEqual(json.loads(r1.content)["results"],
                         [])  # 搜索无结果,返回 results=[]
Пример #9
0
    def test_pagination(self):
        total_activities = 56
        for i in range(0, total_activities):
            Activity.objects.create(title=str(i + 55),
                                    location=str(i),
                                    datetime=now())
        self.assertEqual(Activity.objects.count(), total_activities)

        client = Client()
        tester_login(client=client)
        for page_size in [1, 2, 3, 5, 8, 13, 21, 34]:  # 计算这样分页的总页数和页大小
            total_pages = ceil(total_activities / page_size)
            for page in range(1, total_pages):
                r1 = client.get("%s?search=&page_size=%s&page=%s" %
                                (activity_list_url, page_size, page))
                results1 = json.loads(r1.content)['results']
                count = json.loads(r1.content)['count']
                self.assertEqual(len(results1), page_size)  # 页大小正确
                self.assertEqual(count, total_activities)  # 页数正确
                self.check_order(results1)  # 结果顺序正确
                r2 = client.get("%s?page=%s&page_size=%s" %
                                (activity_list_url, page, page_size))
                results2 = json.loads(r2.content)['results']
                self.assertEqual(results1, results2)  # 请求参数顺序不同,但结果相同
                # 判定 page_size 不合法时结果是否和默认 page_size 相同
                if page_size == Pagination.page_size:
                    for invalid_page_size in [
                            -1, total_activities, 0, 'qwerty'
                    ]:
                        r3 = client.get("%s?&page_size=%s&" %
                                        (activity_list_url, invalid_page_size))
                        self.assertEqual(r1.status_code, 200)
                        self.assertEqual(json.loads(r1.content),
                                         json.loads(r3.content))
            # 判定最后一页的正确性
            r1 = client.get("%s?&page_size=%s&=%s" %
                            (activity_list_url, page_size, total_pages))
            results1 = json.loads(r1.content)['results']
            self.assertEqual(len(results1), page_size)  # 页大小正确
            self.check_order(results1)  # 结果顺序正确
            # 判定 page 不合法时结果的正确性
            for page in [-1, total_pages + 1, 0, 'qwerty']:
                r1 = client.get("%s?&page_size=%s&page=%s" %
                                (activity_list_url, page_size, page))
                self.assertEqual(r1.status_code, 404,
                                 f"page={page}, page_size={page_size}")
Пример #10
0
    def test_change_email_and_password(self):
        c1 = Client()
        response = tester_login(self.email, self.password, c1)
        self.assertEqual(response.wsgi_request.user, self.user)
        response = c1.patch(change_password_url(self.user.id), {
            "old_password": self.password,
            "new_password": "******",
            "new_email": "*****@*****.**"
        },
                            content_type='application/json')
        self.assertEqual(response.status_code, 204)

        response = tester_login(self.email, self.password)
        self.assertEqual(response.status_code, 401)  # 旧账号无法登陆

        response = tester_login("*****@*****.**", "ADMINADMIN")
        self.assertEqual(response.status_code, 200)  # 新账号可以登陆
Пример #11
0
    def test_pagination(self):
        total_users = 56
        for i in range(1, total_users):
            user = User.objects.create(username="******" % i,
                                       first_name="user")
            UserProfile.objects.create(user=user,
                                       student_id=str(i),
                                       experience=randrange(0, 1000))
        self.assertEqual(User.objects.count(), total_users)

        client = Client()
        tester_login(client=client)
        for page_size in [1, 2, 3, 5, 8, 13, 21, 34]:  # 计算这样分页的总页数和页大小
            total_pages = ceil(total_users / page_size)
            for page in range(1, total_pages):
                r1 = client.get("%s?search=&page_size=%s&page=%s" %
                                (user_list_url, page_size, page))
                results1 = json.loads(r1.content)['results']
                count = json.loads(r1.content)['count']
                self.assertEqual(len(results1), page_size)  # 页大小正确
                self.assertEqual(count, total_users)  # 页数正确
                self.check_order(results1)  # 结果顺序正确
                r2 = client.get("%s?page=%s&page_size=%s" %
                                (user_list_url, page, page_size))
                results2 = json.loads(r2.content)['results']
                self.assertEqual(results1, results2)  # 请求参数顺序不同,但结果相同
                # 判定 page_size 不合法时结果是否和默认 page_size 相同
                if page_size == Pagination.page_size:
                    for invalid_page_size in [-1, total_users, 0, 'qwerty']:
                        r3 = client.get("%s?&page_size=%s&" %
                                        (user_list_url, invalid_page_size))
                        self.assertEqual(r1.status_code, 200)
                        self.assertEqual(json.loads(r1.content),
                                         json.loads(r3.content))
            # 判定最后一页的正确性
            r1 = client.get("%s?&page_size=%s&=%s" %
                            (user_list_url, page_size, total_pages))
            results1 = json.loads(r1.content)['results']
            self.assertEqual(len(results1), page_size)  # 页大小正确
            self.check_order(results1)  # 结果顺序正确
            # 判定 page 不合法时结果的正确性
            for page in [-1, total_pages + 1, 0, 'qwerty']:
                r1 = client.get("%s?&page_size=%s&page=%s" %
                                (user_list_url, page_size, page))
                self.assertEqual(r1.status_code, 404,
                                 f"page={page}, page_size={page_size}")
Пример #12
0
    def test_get_patch_user_with_no_userprofile(self):
        u = User(id=23333)
        u.save()
        self.assertEqual(hasattr(u, 'userprofile'), False)

        client = Client()
        tester_login(client=client)
        response = client.get(user_detail_url(23333))
        self.assertEqual(response.status_code, 200)  # 能够正确访问

        response = client.patch(user_detail_url(23333),
                                data={"about": "I'm 23333"},
                                content_type='application/json')
        self.assertEqual(response.status_code, 200)

        u = User.objects.get(id=23333)
        self.assertEqual(hasattr(u, 'userprofile'),
                         True)  # Patch 操作创建了 userProfile
        self.assertEqual(u.userprofile.about, "I'm 23333")
Пример #13
0
    def test_create_activity(self):
        client = Client()
        tester_login(client=client)
        date_time = now()
        response = tester_create_activity("First Activity",
                                          date_time,
                                          "MSFT",
                                          self.ids[0:2],
                                          client=client)
        self.assertEqual(response.status_code, 201, response.data)

        self.assertEqual(Activity.objects.count(), 1)  # 活动成功写入数据库
        # 比较 POST 值和数据库中的值
        activity = Activity.objects.first()
        self.assertEqual(activity.title, "First Activity")
        self.assertDatetimeEqual(activity.datetime, date_time)
        self.assertEqual(activity.location, "MSFT")
        presenter_ids = set(map(lambda u: u.id, activity.presenter.all()))
        self.assertSetEqual(presenter_ids, set(self.ids[0:2]))
        self.assertEqual(activity.check_in_open, True)
        self.assertEqual(bool(activity.check_in_code), True)
        self.assertEqual(activity.attender.count(), 0)
        # 比较数据库中的值和返回值
        self.assertActivityDetailEqual(response.content, activity)
Пример #14
0
    def test_create_activity_with_invalid_field(self):
        correct_example = {
            'title': "Third Activity",
            'datetime': now(),
            'location': "MSRA",
            'presenter': [{
                "id": 1
            }]
        }

        field_and_invalid_example = [
            ['title', ''],
            ['datetime', ''],
            ['datetime', '2020-01-01'],
            ['datetime', '20:00'],
            ['datetime', '2021-02-29 20:00'],
            ['datetime', '2020-01-01 20:00+25:00'],
            ['datetime', '2020-01-01 20:00Y'],
            ['location', ''],
            ['presenter', [{}]],
            ['presenter', 'id:1'],
            ['presenter', [{
                "id": 233
            }]],
        ]
        self.assertEqual(Activity.objects.count(), 0)  # 没有创建活动
        client = Client()
        tester_login(client=client)
        for field, example in field_and_invalid_example:
            incorrect_example = correct_example.copy()
            incorrect_example[field] = example
            response = client.post(activity_list_url,
                                   data=incorrect_example,
                                   content_type='application/json')
            self.assertEqual(response.status_code, 400)  # 返回 400
            self.assertEqual(Activity.objects.count(), 0)  # 没有创建活动
Пример #15
0
    def test_create_activity_with_empty_field(self):
        client = Client()
        tester_login(client=client)
        complete_data = {
            'title': "Second Activity",
            'datetime': now(),
            'location': "MSRA",
            'presenter': [{
                "id": User.objects.first().id
            }]
        }
        for missing_field in complete_data.keys():  # 四种数据各缺一遍。都不能成功创建
            incomplete_data = complete_data.copy()
            incomplete_data.pop(missing_field)
            response = client.post(activity_list_url,
                                   incomplete_data,
                                   content_type='application/json')
            self.assertEqual(response.status_code, 400)
            self.assertEqual(response.json().keys(), {missing_field})

        response = client.post(activity_list_url,
                               complete_data,
                               content_type='application/json')
        self.assertEqual(response.status_code, 201)  # 而正确数据是可以注册的
Пример #16
0
    def test_change_password(self):
        c1 = Client()
        response = tester_login(self.email, self.password, c1)
        self.assertEqual(response.wsgi_request.user, self.user)
        response = c1.get('/')
        self.assertEqual(response.wsgi_request.user, self.user)

        c2 = Client()
        tester_login(self.email, self.password, c2)
        r2 = c2.patch(change_password_url(self.user.id), {
            "old_password": self.password,
            "new_password": "******"
        },
                      content_type='application/json')

        self.assertEqual(r2.status_code, 204)
        response = c1.get('/')
        self.assertEqual(response.wsgi_request.user.is_authenticated,
                         False)  # 此时第一个 Client 理应被下线
        response = c2.get('/')
        self.assertEqual(response.wsgi_request.user.is_authenticated,
                         False)  # 此时第二个 Client 理应被下线

        response = tester_login(self.email, self.password, c1)
        self.assertEqual(response.status_code, 401)  # 尝试用旧密码登录
        response = tester_login(self.email, 'ADMINADMIN', c1)
        self.assertEqual(response.status_code, 200)  # 尝试用新密码登录
        r2 = tester_login(self.email, self.password, c2)
        self.assertEqual(r2.status_code, 401)  # 尝试用旧密码登录

        response = c1.patch(change_password_url(self.user.id), {
            "old_password": "******",
            "new_password": self.password
        },
                            content_type='application/json')
        self.assertEqual(response.status_code, 204)  # 将密码改回来
        response = tester_login(self.email, self.password, c1)
        self.assertEqual(response.status_code, 200)