コード例 #1
0
class TestUpdateUser(APITestCase):
    def setUp(self):
        if not User.objects.filter(username='******').exists():
            self.admin = User.objects.create_superuser(username="******",
                                                       password="******",
                                                       email="*****@*****.**")
            self.admin_token, _ = Token.objects.get_or_create(user=self.admin)
        if not User.objects.filter(username='******').exists():
            self.normal_user = User.objects.create_user(
                username="******", password="******", email="*****@*****.**")
            self.normal_user_token, _ = Token.objects.get_or_create(
                user=self.normal_user)
        self.client = RequestsClient()
        self.maxDiff = None

    def test_valid(self):
        self.client.headers.update({"Authorization": self.admin_token.key})
        response = self.client.put(f'http://127.0.0.1:8000/users/',
                                   json={
                                       "username": "******",
                                       "password": "******",
                                       "email": "*****@*****.**"
                                   })
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_no_data_sent(self):
        self.client.headers.update({"Authorization": self.admin_token.key})
        response = self.client.put(f'http://127.0.0.1:8000/users/')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_one_attribute_not_sent(self):
        self.client.headers.update({"Authorization": self.admin_token.key})
        response = self.client.put(f'http://127.0.0.1:8000/users/',
                                   json={
                                       "username": "******",
                                       "password": "******"
                                   })
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_user_already_exist(self):
        self.client.headers.update({"Authorization": self.admin_token.key})
        response = self.client.put(f'http://127.0.0.1:8000/users/',
                                   json={
                                       "username": "******",
                                       "password": "******",
                                       "email": "*****@*****.**"
                                   })
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #2
0
 def test_update_actor_avatar_url(self):
     client = RequestsClient()
     for ro in self.test_3:
         row = json.loads(ro)
         res = {}
         if row['request']['method'] == "GET":
             res = client.get('http://localhost:8000' +
                              row['request']['url'] + '/')
         elif row['request']['method'] == "PUT":
             res = client.put(
                 'http://localhost:8000' + row['request']['url'] + '/', json=row['request']['body'])
         elif row['request']['method'] == "POST":
             res = client.post(
                 'http://localhost:8000' + row['request']['url'] + '/', json=row['request']['body'])
         elif row['request']['method'] == "DELETE":
             res = client.delete(
                 'http://localhost:8000' + row['request']['url'] + '/')
         self.assertEqual(res.status_code, row['response']['status_code'])
         if row['response']['headers'] != {}:
             self.assertEqual(
                 res.headers['Content-Type'], row['response']['headers']['Content-Type'])
         if row['response']['body'] != {}:
             response = json.loads(res.text)
             for resp in response:
                 if resp['created_at']:
                     temp = parse(resp['created_at'])
                     temp = temp.replace(tzinfo=None)
                     temp = str(temp)
                     resp['created_at'] = temp
             self.assertEqual(response, row['response']['body'])
コード例 #3
0
ファイル: tests.py プロジェクト: hiancdtrsnm/django-challenge
    def test_put_account(self):

        client = RequestsClient()
        r = client.get('http://localhost:8000/api/v1/accounts/',
                       auth=HTTPBasicAuth('testuser', 'testpassword'))

        assert r.status_code == 200

        r = client.get('http://localhost:8000/api/v1/accounts/1',
                       auth=HTTPBasicAuth('testuser', 'testpassword'))

        assert r.status_code == 200

        data = r.json()

        assert data['billing_city'] == 'ee'

        r = client.put('http://localhost:8000/api/v1/accounts/1/',
                       auth=HTTPBasicAuth('testuser', 'testpassword'),
                       json={'billing_city': 'eeeee'})

        assert r.status_code == 200

        data = r.json()

        assert data['billing_city'] == 'eeeee'
コード例 #4
0
class TestAPIViews(TestCase):

    def test_root(self):
        client = RequestsClient()
        response = client.get('http://127.0.0.1:8000/api/')
        self.assertEqual(response.status_code, 200)

    def gen_token(self):
        user = User.objects.create_user('teste', '*****@*****.**', 'teste')
        data = {'username': '******', 'password': '******'}
        response = self.client.post('http://127.0.0.1:8000/api/api-token-auth/', data=data)
        self.token = response.json()['token']

    def _login(self):
        self.client = RequestsClient()
        self.gen_token()
        self.headers = {'Authorization': f'Token {self.token}'}

    def test_token(self):
        self._login()
        self.assertIsNotNone(self.token)

    def create_todo(self):
        data = {'todo': 'teste'}
        response = self.client.post('http://127.0.0.1:8000/api/todos/', headers=self.headers, data=data)
        return response

    def test_create_todo(self):
        self._login()
        response = self.create_todo()
        self.assertEqual(response.status_code, 201)

    def test_get_todo(self):
        self._login()
        new_todo = self.create_todo()
        pk = new_todo.json()['id']
        response = self.client.get(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers)
        self.assertEqual(response.status_code, 200)

    def test_delete_todo(self):
        self._login()
        new_todo = self.create_todo()
        pk = new_todo.json()['id']
        response = self.client.delete(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers)
        self.assertEqual(response.status_code, 204)

    def test_put_todo(self):
        self._login()
        new_todo = self.create_todo()
        pk = new_todo.json()['id']
        data = {'todo': 'Teste!'}
        response = self.client.put(f'http://127.0.0.1:8000/api/todos/{pk}/', headers=self.headers, data=data)
        self.assertEqual(response.status_code, 200)

    def test_list_todos(self):
        self._login()
        new_todo = self.create_todo()
        response = self.client.get('http://127.0.0.1:8000/api/todos/', headers=self.headers)
        self.assertEqual(response.status_code, 200)
コード例 #5
0
ファイル: tests.py プロジェクト: rzavarce/TangramTest
    def test_put_article(self):

        url = 'http://127.0.0.1:8000/api/v1/articles/1/	'
        data = {
            "id": 1,
            "art_title": "qwqwqwqw111111",
            "art_content": "qwqwqwqwqw",
            "art_status": 1
        }

        client = RequestsClient()
        response = client.put(url, data)
コード例 #6
0
    def test_put_article(self):

        url = 'http://127.0.0.1:8000/api/v1/authors/1/	'
        data = {
            "id": 1,
            "aut_name": "qqqq",
            "aut_email": "*****@*****.**",
            "aut_status": 1
        }

        client = RequestsClient()
        response = client.put(url, data)
コード例 #7
0
ファイル: views.py プロジェクト: vishal9708/Event-Management
def register_club(request):
	host =  request.META['HTTP_HOST'] 
	url =  'http://'+host+'/api/clubs/create/'
	client = RequestsClient()
	#print request.user
	if request.method=="POST":
		
		club_name = request.POST.get("club_name")
		csrftoken = request.POST.get("csrfmiddlewaretoken")
		city_name = request.POST.get("city");
		locality_name = request.POST.get("locality");
		#print city_name,locality_name
		#client = RequestsClient()

		response = client.post(url, json={
				    'club_name': club_name,
				    'user':request.user.id,
				}, headers={'X-CSRFToken': csrftoken})
		print response.status_code
		js =  response.json()
		#print response.status_code
		u = js['venue']['update']
		if response.status_code == 201:
			c**t = APIRequestFactory()
			nurl = 'http://'+host+u;
			print nurl
			res = client.get(nurl);
			print res
			p =  res.json()
			venue_name = p['venue_name']
			content_type = p['content_type']
			object_id = p['object_id']
			r = client.put(nurl,data={
				'venue_name':venue_name,
				'content_type':content_type,
				'venue_city':city_name,
				'venue_locality':locality_name,
				'object_id':object_id,
				})
			print r
		#token = request.POST.get('csrfmiddlewaretoken')
		#a = factory.post('http://127.0.0.1:8000/api/clubs/create/',{'club_name':club_name},format=json)
		#print response.json()
	cities = City.objects.all();
	locality = client.get("http://127.0.0.1/api/venues/citylocality")
	locality = json.dumps(locality.json())
	#print locality
	context={
	'cities':cities,
	'locality':locality,
	}
	return render(request, "clubs-create.html",context)
コード例 #8
0
 def update_todo(self, api_key, todo_id, task_title, task_description,
                 task_state, task_due_date):
     if api_key == "":
         msg = _('API Key must not be empty.')
         raise ValidationError({'error': msg})
     else:
         client = RequestsClient()
         data = {
             'task_title': task_title,
             'task_description': task_description,
             'task_state': task_state,
             'task_due_date': task_due_date,
         }
         try:
             response = client.put(
                 'http://localhost:8000/todoapp/api/update/%s/' % todo_id,
                 data,
                 headers={'Authorization': 'Api-Key %s' % api_key})
             return response
         except Exception as e:
             raise ValidationError({'error': e.args})
コード例 #9
0
    def test_edit_event_name(self):
        self.organization_new_event(self.organization_tokens['access'],
                                    self.event_dict)
        event = Event.objects.get(title=self.event_dict['title'])
        pre_edit_room = Room.objects.get(event=event)
        pre_edit_members = pre_edit_room.members.all()
        self._assert_event_room_name(pre_edit_room.id, event.title)

        client = RequestsClient()
        client.headers.update(
            {'Authorization': 'Bearer ' + self.organization_tokens['access']})
        path = 'http://testserver/api/organization/updateEvent/'
        updates = copy.deepcopy(self.event_dict)
        updates['title'] = 'New Title Update'
        updates['id'] = 1
        edit_event_response = client.put(path, json=updates)
        self.assertEqual(edit_event_response.status_code,
                         201,
                         msg='Failed to edit event: ' + str(updates))

        after_edit_room = Room.objects.get(event__id=event.id)
        self._assert_event_room_name(after_edit_room.id, updates["title"])
        self.assertEqual(list(after_edit_room.members.all()),
                         list(pre_edit_members))
コード例 #10
0
class SetSerializerTest(APITestCase):
    """
    Tests the functionality of the SetSerializer.
    """

    fixtures = ['fix.json']

    def setUp(self):
        self.c = RequestsClient()
        self.pre_http = "http://127.0.0.1:8000"
        self.user = UserTrackingProfile.objects.first().user_profile.user
        self.user_profile = UserTrackingProfile.objects.first()
        self.rfid = self.user_profile.user_profile.rfid_tag
        self.exercise_unit = ExerciseUnit.objects.first()
        self.header = {'Authorization': 'Token ' + str(self.user.auth_token)}

    def test_set_retrieval(self):
        response = self.c.get(self.pre_http + reverse('set_list'),
                              headers=self.header).status_code
        self.assertEqual(response, 200)

    def test_set_retrieval_by_exercise_unit(self):
        """
        Tests whether Sets for a specific ExerciseUnit can be retrieved.
        """
        response = self.c.get(
            self.pre_http +
            reverse('set_exerciseunit_list',
                    kwargs={'exercise_unit': self.exercise_unit.id}),
            headers=self.header)
        content = (json.loads(response.content.decode("utf-8")))
        self.assertEqual(response.status_code, 200)

    def test_set_creation(self):
        """
        Using existing trainunit and existing exerciseunit.
        """
        # generate request data
        repetitions = 10
        weight = 60
        train_unit = TrainUnit.objects.filter(
            user=UserTrackingProfile.objects.first())[0]
        exercise_unit = train_unit.exerciseunit_set.first()
        exercise_name = exercise_unit.exercise
        date_time = exercise_unit.time_date
        equipment_id = exercise_unit.equipment.id
        durations = random.sample(range(1, 20), repetitions)
        # make request and test
        data = {
            'exercise_unit': exercise_unit.id,
            'repetitions': repetitions,
            'weight': weight,
            'exercise': exercise_name,
            'rfid': self.rfid,
            'date_time': date_time,
            'equipment_id': equipment_id,
            'active': False,
            'durations': json.dumps(durations)
        }
        response = self.c.post(self.pre_http + reverse('set_list'),
                               data,
                               headers=self.header)
        self.assertEqual(response.status_code, 201)

    def test_active_set_creation(self):
        """
        Using existing trainunit and existing exerciseunit.
        """
        # generate request data
        repetitions = 0
        weight = 60
        train_unit = TrainUnit.objects.filter(
            user=UserTrackingProfile.objects.first())[0]
        exercise_unit = train_unit.exerciseunit_set.first()
        exercise_name = exercise_unit.exercise
        date_time = exercise_unit.time_date
        equipment_id = exercise_unit.equipment.id
        durations = random.sample(range(1, 20), repetitions)
        # make request and test
        data = {
            'exercise_unit': '',
            'repetitions': repetitions,
            'weight': weight,
            'exercise': exercise_name,
            'rfid': self.rfid,
            'date_time': date_time,
            'equipment_id': equipment_id,
            'active': True,
            'durations': json.dumps(durations)
        }
        response = self.c.post(self.pre_http + reverse('set_list'),
                               data,
                               headers=self.header)
        self.assertEqual(response.status_code, 201)
        self.assertTrue(
            json.loads(response.content.decode('utf-8'))['active'] is True)

    def test_train_unit_creation(self):
        """
        Create new trainunit and exerciseunit.
        """
        pass

    @override_settings(DEBUG=True)
    def test_exercise_unit_creation(self):
        """
        Using existing trainunit but create new exerciseunit.
        """
        repetitions = 10
        weight = 60
        date_time = timezone.now()
        equipment_id = Equipment.objects.first().id
        exercise_name = Equipment.objects.first().exercises.first().name
        durations = random.sample(range(1, 20), repetitions)
        data = {
            'exercise_unit': "",
            'repetitions': repetitions,
            'weight': weight,
            'exercise': exercise_name,
            'rfid': self.rfid,
            'date_time': date_time,
            'equipment_id': equipment_id,
            'active': False,
            'durations': json.dumps(durations)
        }
        response = self.c.post(self.pre_http + reverse('set_list'),
                               data,
                               headers=self.header)
        self.assertEqual(response.status_code, 201)

    def test_exercise_equipment_validation(self):
        """
        ExerciseName must fit to the specified equipment.
        """
        # generate request data
        repetitions = 10
        weight = 60
        train_unit = TrainUnit.objects.filter(
            user=UserTrackingProfile.objects.first())[0]
        exercise_unit = train_unit.exerciseunit_set.first()
        date_time = exercise_unit.time_date
        equipment_id = Equipment.objects.first().id
        durations = random.sample(range(1, 20), repetitions)
        # make request where exercise name and equipment do not match
        data = {
            'exercise_unit': exercise_unit.id,
            'repetitions': repetitions,
            'weight': weight,
            'exercise': 'some_name',
            'rfid': self.rfid,
            'date_time': date_time,
            'equipment_id': equipment_id,
            'active': False,
            'durations': json.dumps(durations)
        }
        response = self.c.post(self.pre_http + reverse('set_list'),
                               data,
                               headers=self.header)
        content = response.content

        # check whether error occured
        self.assertEqual(response.status_code, 400)
        self.assertIn("object does not exist.", str(content))

    @override_settings(DEBUG=True)
    def test_update(self):
        """
        Check whether sets are updated correctly. Last_update field must be updated automatically.
        :return:
        """
        # data preparation
        train_set = Set.objects.all()[0]
        exercise_unit = train_set.exercise_unit
        exercise = exercise_unit.exercise
        equipment = exercise.equipment_machine.all()[0]
        train_unit = exercise_unit.train_unit
        user = train_unit.user.user_profile
        durations = random.sample(range(1, 20), int(train_set.repetitions) + 5)
        data = {
            'repetitions': int(train_set.repetitions) + 5,
            'weight': 10,
            'exercise': exercise,
            'equipment_id': str(equipment.id),
            'date_time': train_set.date_time,
            'rfid': str(user.rfid_tag),
            'active': str(False),
            'durations': json.dumps(durations),
            'exercise_unit': exercise_unit.id
        }

        before_time = timezone.now()

        # make update request
        url = self.pre_http + reverse('set_detail',
                                      kwargs={'pk': train_set.id})
        response = self.c.put(url, data, headers=self.header)
        content = (json.loads(response.content.decode("utf-8")))

        # check response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(content['repetitions'],
                         int(train_set.repetitions) + 5)
        self.assertEqual(content['weight'], 10)
        self.assertEqual(parser.parse(content['date_time']),
                         train_set.date_time)
        self.assertEqual(content['exercise_unit'], str(exercise_unit.id))
        self.assertTrue(
            Set.objects.get(id=content['id']).last_update > before_time)

    @override_settings(DEBUG=True)
    def test_update_restrictions(self):
        """
        Tests whether only repetition-values that are greater than the current value are supported.
        Tests whether length of durations-field fits to repetitions.
        """
        # data preparation
        train_set = Set.objects.all()[0]
        exercise_unit = train_set.exercise_unit
        exercise_unit_id = exercise_unit.id
        exercise = exercise_unit.exercise
        equipment = exercise.equipment_machine.all()[0]
        train_unit = exercise_unit.train_unit
        user = train_unit.user.user_profile
        durations = random.sample(range(1, 20), int(train_set.repetitions) - 1)
        data = {
            'repetitions': int(train_set.repetitions) - 1,
            'weight': 10,
            'exercise': exercise,
            'equipment_id': str(equipment.id),
            'date_time': train_set.date_time.strftime("%Y-%m-%dT%H:%M:%SZ"),
            'rfid': str(user.rfid_tag),
            'active': str(False),
            'durations': json.dumps(durations),
            'exercise_unit': exercise_unit_id
        }
        url = self.pre_http + reverse('set_detail',
                                      kwargs={'pk': train_set.id})

        # test correct update request. Repetitions value may not be changed since may not be decreased.
        response = self.c.put(url, data, headers=self.header)
        content = (json.loads(response.content.decode("utf-8")))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(content['repetitions'], int(train_set.repetitions))
        self.assertEqual(content['weight'], 10)
        self.assertEqual(parser.parse(content['date_time']),
                         train_set.date_time)
        self.assertEqual(content['exercise_unit'], str(exercise_unit.id))

        # test update request with length of durations field other than repetitions count. Must throw error.
        data['durations'] = json.dumps(
            random.sample(range(1, 20),
                          int(train_set.repetitions) + 4))
        response = self.c.put(url, data, headers=self.header)
        self.assertEqual(response.status_code, 400)

    @override_settings(DEBUG=True)
    def test_delete_active(self):
        """
        Tests whether a created set can be deleted properly. Non-active as well as active sets are tested.
        """
        def get_new_set_id(active):
            """
            Creates new set.
            :return: id of the new set
            """
            rfid = UserTrackingProfile.objects.first().user_profile.rfid_tag
            train_unit = TrainUnit.objects.filter(
                user=UserTrackingProfile.objects.first())[0]
            exercise_unit = train_unit.exerciseunit_set.first()
            exercise_name = exercise_unit.exercise
            date_time = exercise_unit.time_date
            equipment_id = exercise_unit.equipment.id
            durations = random.sample(range(1, 20), 10)
            data = {
                'exercise_unit': exercise_unit.id,
                'repetitions': 10,
                'weight': 60,
                'exercise': exercise_name,
                'rfid': rfid,
                'date_time': date_time,
                'equipment_id': equipment_id,
                'active': active,
                'durations': json.dumps(durations)
            }
            response = json.loads(
                self.c.post(self.pre_http + reverse('set_list'),
                            data,
                            headers=self.header).content.decode("utf-8"))
            return response['id']

        # try deleting a non-active set
        id_1 = get_new_set_id(active=False)
        response_1 = self.c.delete(self.pre_http +
                                   reverse('set_detail', kwargs={'pk': id_1}),
                                   headers=self.header)
        self.assertEqual(response_1.status_code, 204)

        # try deleting an active set
        id_2 = get_new_set_id(active=True)
        active_before = UserTrackingProfile.objects.first().active_set
        response_2 = self.c.delete(self.pre_http +
                                   reverse('set_detail', kwargs={'pk': id_2}),
                                   headers=self.header)
        self.assertEqual(str(active_before.id), id_2)
        self.assertEqual(UserTrackingProfile.objects.first().active_set, None)
        self.assertEqual(response_2.status_code, 204)

    def test_delete_last(self):
        """
        A set must be properly deleted. If it was the last set in the exercise unit, the exercise unit must be
        deleted. If the exercise unit was the last one in the TrainUnit, the TrainUnit must be deleted.
        """
        # create single set with new train unit and exercise unit
        user = UserTrackingProfile.objects.first()
        train_unit = TrainUnit.objects.create(start_time_date=timezone.now(),
                                              end_time_date=timezone.now(),
                                              date=timezone.now().date(),
                                              user=user)
        exercise_unit = ExerciseUnit.objects.create(
            time_date=timezone.now(),
            train_unit=train_unit,
            exercise=Exercise.objects.first())
        set = Set.objects.create(date_time=timezone.now(),
                                 exercise_unit=exercise_unit,
                                 active=False,
                                 repetitions=1,
                                 weight=10,
                                 durations=json.dumps([0]))

        # make sure that every object was created and is unique
        self.assertEqual(Set.objects.filter(id=set.id).count(), 1)
        self.assertEqual(
            ExerciseUnit.objects.filter(id=exercise_unit.id).count(), 1)
        self.assertEqual(TrainUnit.objects.filter(id=train_unit.id).count(), 1)

        # delete set
        response = self.c.delete(self.pre_http +
                                 reverse('set_detail', kwargs={'pk': set.id}),
                                 headers=self.header)

        # set, exercise unit and train unit must be deleted
        self.assertEqual(Set.objects.filter(id=set.id).count(), 0)
        self.assertEqual(
            ExerciseUnit.objects.filter(id=exercise_unit.id).count(), 0)
        self.assertEqual(TrainUnit.objects.filter(id=train_unit.id).count(), 0)
        self.assertEqual(response.status_code, 204)

    def test_not_authenticated_request_list_api(self):
        """
        Every request has to come from an authenticated user. If user is not authenticated, answer with 401 status.
        """
        # generate request data
        repetitions = 10
        weight = 60
        train_unit = TrainUnit.objects.filter(
            user=UserTrackingProfile.objects.first())[0]
        exercise_unit = train_unit.exerciseunit_set.first()
        exercise_name = exercise_unit.exercise
        date_time = exercise_unit.time_date
        equipment_id = Equipment.objects.first().id
        durations = random.sample(range(1, 20), repetitions)
        # make request and test
        data = {
            'exercise_unit': exercise_unit.id,
            'repetitions': repetitions,
            'weight': weight,
            'exercise_name': exercise_name,
            'rfid': self.rfid,
            'date_time': date_time,
            'equipment_id': equipment_id,
            'active': False,
            'durations': json.dumps(durations)
        }
        new_response = self.c.post(self.pre_http + reverse('set_list'), data)
        self.assertEqual(new_response.status_code, 401)

        list_response = self.c.get(self.pre_http + reverse('set_list'))
        self.assertEqual(list_response.status_code, 401)

        # TODO: Check with authenticated, but wrong user

    def test_not_authenticated_request_detail_api(self):
        sample_set = Set.objects.first()
        url = self.pre_http + reverse('set_detail',
                                      kwargs={'pk': sample_set.id})
        response = self.c.get(url)
        self.assertEqual(response.status_code, 401)
コード例 #11
0
class RequestTest(TestCase):
    def setUp(self):
        """
        create client_stub and load users and groups from fixtures
        contenttypes, sites, and permissions are already in test db

        so, in order to create users and group, it is sufficient to invoke:
        python project/manage.py dumpdata --natural-foreign \
          --exclude=auth.permission auth \
          --indent=4 > resources/fixtures/setup.json

        :return:
        """
        from django.core.management import call_command
        call_command("loaddata", "setup", verbosity=0)
        self.client_stub = RequestsClient()

    def test_create_seduta(self):
        with open('./resources/fixtures/seduta.json', 'r') as f:
            seduta = json.load(f)

        r = self.client_stub.post('http://localhost:8000/api-token-auth/',
                                  data={
                                      "username": "******",
                                      "password": "******"
                                  }).json()

        response = self.client_stub.post(
            'http://localhost:8000/precipe',
            json=seduta,
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 201)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/Architettura 1 blocco.pdf',
            files={
                'file': open('./resources/fixtures/docs/architettura.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/JWTHandbook.pdf',
            files={
                'file': open('./resources/fixtures/docs/jwt_handbook.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/frugs/JWTHandbook.pdf',
            files={
                'file': open('./resources/fixtures/docs/jwt_handbook.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.get(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 200)

        response = self.client_stub.delete(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

    def test_create_seduta_with_duplicates(self):
        with open('./resources/fixtures/duplicates_1.json', 'r') as f:
            seduta_1 = json.load(f)

        with open('./resources/fixtures/duplicates_2.json', 'r') as f:
            seduta_2 = json.load(f)

        r = self.client_stub.post('http://localhost:8000/api-token-auth/',
                                  data={
                                      "username": "******",
                                      "password": "******"
                                  }).json()

        response = self.client_stub.post(
            'http://localhost:8000/precipe',
            json=seduta_1,
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 201)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/torino.pdf',
            files={'file': open('./resources/fixtures/docs/torino.pdf', 'rb')},
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.post(
            'http://localhost:8000/precipe',
            json=seduta_2,
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 201)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/torino.pdf',
            files={'file': open('./resources/fixtures/docs/torino.pdf', 'rb')},
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

    def test_create_seduta_long_names(self):
        with open('./resources/fixtures/seduta_long_names.json', 'r') as f:
            seduta = json.load(f)

        r = self.client_stub.post('http://localhost:8000/api-token-auth/',
                                  data={
                                      "username": "******",
                                      "password": "******"
                                  }).json()

        response = self.client_stub.post(
            'http://localhost:8000/precipe',
            json=seduta,
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 201)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/Architettura 1 blocco.pdf',
            files={
                'file': open('./resources/fixtures/docs/architettura.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/7185-All-4-Piano-annuale-degli-interventi-di-ricostruzione-del-patrimonio-pubblico-della-citta-di-LAquila-e-dei-comuni-del-Cratere.pdf',
            files={
                'file': open('./resources/fixtures/docs/jwt_handbook.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.get(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 200)

        response = self.client_stub.delete(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

    def test_create_seduta_big_files(self):
        with open('./resources/fixtures/seduta_big_files.json', 'r') as f:
            seduta = json.load(f)

        r = self.client_stub.post('http://localhost:8000/api-token-auth/',
                                  data={
                                      "username": "******",
                                      "password": "******"
                                  }).json()

        response = self.client_stub.post(
            'http://localhost:8000/precipe',
            json=seduta,
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 201)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/Architettura 1 blocco.pdf',
            files={
                'file': open('./resources/fixtures/docs/architettura.pdf',
                             'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.put(
            'http://localhost:8000/upload_file/files/D3JS_4_MAPPING_SECOND_EDITION.pdf',
            files={
                'file':
                open(
                    './resources/fixtures/docs/D3JS_4_MAPPING_SECOND_EDITION.pdf',
                    'rb')
            },
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)

        response = self.client_stub.get(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 200)

        response = self.client_stub.delete(
            'http://localhost:8000/precipe/1',
            headers={'Authorization': 'JWT ' + r['token']})
        self.assertEquals(response.status_code, 204)
コード例 #12
0
class Info(TestCase):
  '''
  Testing the controller functions only
  '''
  @classmethod
  def setUpClass(cls):
    print("\n" + '\x1b[0;34;40m' + 'Starting API tests...' + '\x1b[0m')

  def setUp(self):
    pass
    self.client = Client()

  def tearDown(self):
    pass

  @classmethod
  def tearDownClass(cls):
    print("Finished API tests...\n")

  @patch('infra.utils.default_model_manager.DefaultManager.get_all')
  def test_01_api_users(self,mocked):
      user1 = {"_id":ObjectId("5b689bc92979917d2be6a9ef"),"fname":"mandar","lname":"gondhalekar"}
      user2 = {"_id":ObjectId("5b689bc92979917d2be6a9ee"),"fname":"ankur","lname":"jain"}
      user3 = {"_id":ObjectId("5b689bc92979917d2be6a9ed"),"fname":"priyanshu","lname":"kumar"}

      mocked.side_effect = [[user3,user2,user1], []]

      response = self.client.get('http://*****:*****@patch('infra.utils.default_model_manager.DefaultManager.get_all')
  def test_02_method_getconversationhistory(self,mocked):
      mocked.side_effect = [

          [{"chunks": [ "5b69c081297991682a83e341", "5b69bf6729799167339482e5", "5b69b8a9297991615abe4253" ]},
           {"chunks": [ "5b69b8a9297991615abe4255" ]},
           {"chunks": [ "5b69c081297991682a83e340", "5b69bf6729799167339482e4", "5b69b8a9297991615abe4252", "5b69b8a9297991615abe4254"]}],

          [{'_id': ObjectId('5b69c081297991682a83e340'), 'data': [{'message': 'hi there!', '_cls': 'chats.models.model_info.Data',
               'timestamp': datetime.datetime(2018, 8, 7, 15, 53, 37, 611000), 'author': 'ankur'}], '_cls': 'chats.models.model_info.Chunk'},
           {'_id': ObjectId('5b69c081297991682a83e341'), 'data': [{'message': 'hi there!', '_cls': 'chats.models.model_info.Data',
               'timestamp': datetime.datetime(2018, 8, 7, 15, 53, 37, 617000), 'author': 'ankur'}],'_cls': 'chats.models.model_info.Chunk'}],

          [{'fname': 'priyanshu', '_id': ObjectId('5b689bc92979917d2be6a9ed')},
           {'fname': 'mandar', '_id': ObjectId('5b689bc92979917d2be6a9ef')}]

      ]

      senderID = "5b689bc92979917d2be6a9ee"
      friends = ["5b689bc92979917d2be6a9ed", "5b689bc92979917d2be6a9ef"]

      handler = Handler()
      self.assertDictEqual(handler.getconversationhistory(senderID,friends),{
          'data': [{'id': '5b69c081297991682a83e341', 'message': [{'message': 'hi there!',
                    'timestamp': datetime.datetime(2018, 8, 7, 15, 53, 37, 617000),'author': 'ankur',
                    '_cls': 'chats.models.model_info.Data'}], 'name': 'priyanshu'},
                    {'id': '5b69c081297991682a83e340', 'message': [{'message': 'hi there!',
                    'timestamp': datetime.datetime(2018, 8, 7, 15, 53, 37, 611000),'author': 'ankur',
                    '_cls': 'chats.models.model_info.Data'}], 'name': 'mandar'}]}
      )

  @patch('chats.handlers.handler_info.Handler.getconversationhistory')
  @patch('infra.utils.default_model_manager.DefaultManager.get_one')
  def test_03_api_history(self,mocked,mocked_getconversationhhistory):

      mocked.side_effect = [
          {},

          {'friends': [ObjectId('5b689bc92979917d2be6a9ef'), ObjectId('5b689bc92979917d2be6a9ed'),
                       '5b689bc92979917d2be6a9ed', '5b689bc92979917d2be6a9ef']},
      ]
      headers = {"id":"5b689bc92979917d2be6a9ee"}

      response = self.client.get('http://*****:*****@patch('chats.handlers.handler_info.Handler.send_msg')
  @patch('infra.utils.default_model_manager.DefaultManager.get_one')
  @patch('infra.utils.default_model_manager.DefaultManager.get_all')
  def test_04_api_message(self,mocked_all,mocked_getone,mocked_sendmsg):

      mocked_all.side_effect = [

          [{"_id": ObjectId("5b689bc92979917d2be6a9ed")}, {"_id" : ObjectId("5b689bc92979917d2be6a9ee")},
           {"_id" : ObjectId("5b689bc92979917d2be6a9ef")}],

          #after 404
          [{"_id": ObjectId("5b689bc92979917d2be6a9ed")}, {"_id": ObjectId("5b689bc92979917d2be6a9ee")},
           {"_id": ObjectId("5b689bc92979917d2be6a9ef")}],

          [{"_id": ObjectId("5b689bc92979917d2be6a9ed")}, {"_id": ObjectId("5b689bc92979917d2be6a9ef")}],

          []
      ]

      mocked_getone.return_value = {'fname': 'ankur'}
      mocked_sendmsg.return_value = {}

      headers = {"id":"5b689bc92979917d2be6a9ee", "Content-Type": "application/json"}
      body = {"destination" : ["5b689bc92979917d2be6a9ed","5b689bc92979917d2be6a9eg"],
              "data" : "this code sucks really bad :( ", "broadcast":0}

      response = self.client.put('http://localhost:8000/message',data = json.dumps(body), headers = headers)
      self.assertEqual(response.status_code, 404)

      body = {"destination" : ["5b689bc92979917d2be6a9ed","5b689bc92979917d2be6a9ef"],
              "data": "this code sucks really bad :( ", "broadcast": 1}
      response = self.client.put('http://localhost:8000/message',data = json.dumps(body), headers = headers)
      self.assertEqual(response.status_code, 200)
コード例 #13
0
class RuleTestCase(APITestCase):
    def setUp(self):
        self.client = RequestsClient()

    def test_framework_works(self):
        self.assertEqual(1, 1)

    def test_list_api_needs_userid(self):
        response = self.client.get("http://testserver/api/rules")
        self.assertEqual(response.status_code, 400)

    def test_can_get_after_create(self):
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1000
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 201)

        rule_id = response.json()['id']

        response = self.client.get(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"})
        self.assertEqual(response.status_code, 200)

        res_json = response.json()
        self.assertEqual(res_json["name"], body["name"])
        self.assertEqual(res_json["rrule"], body["rrule"])
        self.assertEqual(res_json["value"], body["value"])

        self.assertEqual(res_json["id"], rule_id)
        self.assertEqual(res_json["userid"], "testuser")

        # Is rule_id in list of rules?
        response = self.client.get("http://testserver/api/rules",
                                   params={"userid": "testuser"})
        res_json = response.json()
        rule_ids = list(map(lambda r: r["id"], res_json["data"]))
        self.assertEqual(response.status_code, 200)
        self.assertIn(rule_id, rule_ids)

    def test_delete(self):
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1000
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 201)

        rule_id = response.json()['id']

        # Ensure it's there
        response = self.client.get(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"})
        self.assertEqual(response.status_code, 200)

        # Remove it
        response = self.client.delete(f"http://testserver/api/rules/{rule_id}",
                                      params={"userid": "testuser"})
        self.assertEqual(response.status_code, 204)

        # Ensure it is removed
        response = self.client.get(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"})
        self.assertEqual(response.status_code, 404)

        # Assert non-existing rules give 404 when delete attempted
        response = self.client.delete(f"http://testserver/api/rules/{rule_id}",
                                      params={"userid": "testuser"})
        self.assertEqual(response.status_code, 404)

    def test_update(self):
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1000
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 201)

        rule_id = response.json()['id']

        # Update the value
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1200
        }
        response = self.client.put(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"},
                                   json=body)
        self.assertEqual(response.status_code, 200)

        # Ensure change is saved
        response = self.client.get(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"})
        self.assertEqual(response.status_code, 200)

        res_json = response.json()
        self.assertEqual(res_json["name"], body["name"])
        self.assertEqual(res_json["rrule"], body["rrule"])
        self.assertEqual(res_json["value"], body["value"])

        self.assertEqual(res_json["userid"], "testuser")

        self.assertIn("id", res_json)

    def test_no_partial_update(self):
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1000
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 201)

        rule_id = response.json()['id']

        body = {"name": "Rent"}
        response = self.client.put(f"http://testserver/api/rules/{rule_id}",
                                   params={"userid": "testuser"},
                                   json=body)
        self.assertEqual(response.status_code, 400)

    def test_400_when_ridiculously_large_value_is_used(self):
        body = {
            "name": "Paycheck",
            "rrule": str(rrule(freq=WEEKLY, byweekday=1)),
            "value": 99999999999999999999999999999999999
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 400)

    def test_400_when_ridiculously_large_name_is_used(self):
        letters = string.ascii_lowercase
        name = ''.join(
            random.choice(letters) for i in range(NAME_MAX_LENGTH + 1))
        body = {
            "name": name,
            "rrule": str(rrule(freq=WEEKLY, byweekday=1)),
            "value": 100
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 400)

    def test_rrule_validation_failure(self):
        body = {"name": "Paycheck", "rrule": 'invalid rrule', "value": 2000}
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 400)

    def test_missing_userid_parm(self):
        now = date.today()
        endDate = now + relativedelta(days=1)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "currentBalance": "0",
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 400)

    def test_valid_start_date(self):
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate": "2020-13-1",
                                       "endDate": "2021-1-1"
                                   })
        self.assertEqual(response.status_code, 400)

    def test_valid_end_date(self):
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate": "2020-1-1",
                                       "endDate": "2021-13-1"
                                   })
        self.assertEqual(response.status_code, 400)

    def test_start_date_preceeds_end_date(self):
        now = date.today()
        endDate = now - relativedelta(days=1)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate": now.strftime("%Y-%m-%d"),
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 400)

    def test_max_span(self):
        now = date.today()
        startDate = now
        endDate = now + relativedelta(years=30, days=2)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate":
                                       startDate.strftime("%Y-%m-%d"),
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 400)

    def test_up_to_max_span(self):
        now = date.today()
        endDate = now + relativedelta(years=30, days=1)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate": now.strftime("%Y-%m-%d"),
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 200)

    def test_no_transactions_when_no_rules_exist_for_user(self):
        now = date.today()
        endDate = now + relativedelta(years=3)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "fakeuser",
                                       "currentBalance": "0",
                                       "startDate": now.strftime("%Y-%m-%d"),
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()["transactions"], [])

    def test_transactions_when_rules_exist(self):
        # Create a rule
        body = {
            "name": "Rent",
            "rrule": str(rrule(freq=MONTHLY, byweekday=1)),
            "value": -1000
        }
        response = self.client.post("http://testserver/api/rules",
                                    params={"userid": "testuser"},
                                    json=body)
        self.assertEqual(response.status_code, 201)

        # Check transactions
        now = date.today()
        endDate = now + relativedelta(years=3)
        response = self.client.get("http://testserver/api/transactions",
                                   params={
                                       "userid": "testuser",
                                       "currentBalance": "0",
                                       "startDate": now.strftime("%Y-%m-%d"),
                                       "endDate": endDate.strftime("%Y-%m-%d")
                                   })
        self.assertEqual(response.status_code, 200)
        self.assertGreater(len(response.json()["transactions"]), 0)
コード例 #14
0
def club_create(request,pk=1):
	k =  str(pk)
	print k
	client = RequestsClient()
	if request.method=="POST":
		if k=="1":
			host =  request.META['HTTP_HOST'] 
			url =  'http://'+host+'/api/clubs/create/'
			club_name = request.POST.get('club-name')
			address = request.POST.get('Add1')
			city_name = request.POST.get("city");
			locality_name = request.POST.get("locality")
			pin = request.POST.get("pin")
			license = request.POST.get("license")
			description = request.POST.get("description")
			csrftoken = request.POST.get("csrfmiddlewaretoken")
			#print description
			response = client.post(url, json={
				    'club_name': club_name,
				    'user':request.user.id,
				    'description':description,
				}, headers={'X-CSRFToken': csrftoken})
			js =  response.json()
			#print response.status_code
			u = js['venue']['update']
			if response.status_code==201:
				nurl = 'http://'+host+u;
				#print nurl
				res = client.get(nurl);
				#print res
				p =  res.json()
				venue_name = p['venue_name']
				content_type = p['content_type']
				object_id = p['object_id']
				#print p
				r = client.put(nurl,data={
					'venue_name':venue_name,
					'content_type':content_type,
					'venue_city':city_name,
					'venue_locality':locality_name,
					'object_id':object_id,
					})
				#print r.json()
				ven_js = r.json()
				if r.status_code==200:
					ven_id = int(ven_js['object_id'])
					h= ven_id
					#print h
					ven_id = Venues.objects.filter(id=ven_js['id']).first()
					address = Address(venue=ven_id,address_line=address,zip_code=pin,lon='0.0',let='0.0')
					address.save()
					return redirect('/corporate/clubcreate/2?q='+str(h))
		elif k=="2":
			n= request.GET.get('q')
			single = request.POST.get('single')
			single_price = 0
			couple_price = 0
			couple = request.POST.get('couple')
			s1 = request.POST.get("s1")
			s2 = request.POST.get("s2")
			s3 = request.POST.get("s3")
			s4 = request.POST.get("s4")
			s5 = request.POST.get("s5")
			print s1,s2,s3,s4,s5
			club = Club.objects.filter(id=n).first()
			#return redirect('/corporate/clubcreate/2?q='+str(39))
			if single != None:
				single_price = request.POST.get('single_fee')
				
				#print club.club_name
				entry_type = Entry_Type.objects.filter(id=1).first()

				entry_type_s = Entry_rate(club_name=club,entry_type_r=entry_type,price=single_price)
				entry_type_s.save()
			if couple!=None:
				couple_price = request.POST.get('couple_fee')
				#single_price = request.POST.get('single_fee')
				#entry_type_s = Entry_rate(club_name=n,entry_type_r=1,price=single_price)
				#club = Club.objects.filter(id=n).first()
				entry_type = Entry_Type.objects.filter(id=4).first()
				entry_type_c = Entry_rate(club_name=club,entry_type_r=entry_type,price=couple_price)
				entry_type_c.save()
			#s1 = re
			if s1!=None:
				service1 = Service(service_name=s1,club_name=club)
				service1.save()
			if s2!=None:
				service2 = Service(service_name=s2,club_name=club)
				service2.save()
			if s3!=None:
				service3 = Service(service_name=s3,club_name=club)
				service3.save()
			if s4!=None:
				service4 = Service(service_name=s4,club_name=club)
				service4.save()
			if s5!=None:
				service5 = Service(service_name=s5,club_name=club)
				service5.save()	
			print n
			return redirect("/corporate/")


	else:
		if k=="1":
			print "hell"
			cities = City.objects.all();
			locality = client.get("http://127.0.0.1/api/venues/citylocality")
			locality = json.dumps(locality.json())
			#print locality
			context={
			'cities':cities,
			'locality':locality,
			}
			return render(request,'reg2c.html',context)
		elif k=="2":
			print request.GET.get('q')
			return render(request,'register3c.html',{})
コード例 #15
0
ファイル: tests.py プロジェクト: andrefpf/desafioleve
class CRUDTests(TestCase):
    def setUp(self):
        self.client = RequestsClient()
    
    def test_user(self):
        INPUT_DATA = [ 
            {
                'name':'André Fernandes', 
                'cpf':'12345678902', 
                'birthday':'2000-01-01'
            },
            {
                'name':'João da Silva', 
                'cpf':'12345678900', 
                'birthday':'1980-08-05'
            },
            {
                'name':'Luke Skywalker', 
                'cpf':'12345678901', 
                'birthday':'1975-05-10',
            },
        ]

        PATCH_DATA = {'name':'João da Silva Sauro'}
        
        PUT_DATA = {
            'name':'Lucas Andarilho do Céu', 
            'cpf':'12345678910', 
            'birthday':'1976-06-11',
        }

        EXPECTED_OUTPUT = [
            {
                'pk':1,
                'name':'João da Silva Sauro',
                'cpf':'12345678900',
                'birthday':'1980-08-05',
                'average_salary':0,
                'average_discounts':0,
                'bigger_salary':0,
                'smaller_salary':0,
            },
            {
                'pk':2,
                'name':'Lucas Andarilho do Céu',
                'cpf':'12345678910',
                'birthday':'1976-06-11',
                'average_salary':0,
                'average_discounts':0,
                'bigger_salary':0,
                'smaller_salary':0,
            },
        ]

        URL = 'http://testserver/'

        for i, data in enumerate(INPUT_DATA):
            self.client.post(URL + f'users/{i}/', data)

        self.client.patch(URL + 'users/1/', PATCH_DATA)
        self.client.put(URL + 'users/2/', PUT_DATA)
        self.client.delete(URL + 'users/0/')

        response = self.client.get(URL + 'users/1/')
        assert response.json() == EXPECTED_OUTPUT[0]

        response = self.client.get(URL + 'users/2/')
        assert response.json() == EXPECTED_OUTPUT[1]

        response = self.client.post(URL + 'users/1/', INPUT_DATA[0])
        assert response.status_code == 409

        response = self.client.get(URL + 'users/0/')
        assert response.status_code == 404

    def test_salary(self):
        INPUT_DATA = [
            {
                'date' : '2020-12-17',
                'cpf' : '12345678900',
                'salary' : '2000.00',
                'discount' : '2.00',
            },
            {
                'date' : '2019-11-01',
                'cpf' : '12345678908',
                'salary' : '509.00',
                'discount' : '4.00',
            },
            {
                'date' : '2020-12-17',
                'cpf' : '98765432100',
                'salary' : '98000.00',
                'discount' : '1.00',
            },
        ]

        PATCH_DATA = {'date':'2020-09-16'}
        
        PUT_DATA = {
            'date' : '2012-11-01',
            'cpf' : '12345678988',
            'salary' : '220.00',
            'discount' : '3.00',
        }

        EXPECTED_OUTPUT = [
            {
                'pk' : 0,
                'date' : '2020-09-16',
                'cpf' : '12345678900',
                'salary' : '2000.00',
                'discount' : '2.00',
            },
            {   
                'pk' : 2,
                'date' : '2012-11-01',
                'cpf' : '12345678988',
                'salary' : '220.00',
                'discount' : '3.00',
            },
        ]

        URL = 'http://testserver/'

        for i, data in enumerate(INPUT_DATA):
            self.client.post(URL + f'salaries/{i}/', data)

        self.client.patch(URL + 'salaries/0/', PATCH_DATA)
        self.client.put(URL + 'salaries/2/', PUT_DATA)
        self.client.delete(URL + 'salaries/1/')

        response = self.client.get(URL + 'salaries/0/')
        assert response.json() == EXPECTED_OUTPUT[0]

        response = self.client.get(URL + 'salaries/2/')
        assert response.json() == EXPECTED_OUTPUT[1]

        response = self.client.post(URL + 'salaries/0/', INPUT_DATA[0])
        assert response.status_code == 409

        response = self.client.get(URL + 'salaries/1/')
        assert response.status_code == 404
コード例 #16
0
class SCTFUserAPITest(TestCase):
    @classmethod
    def setUpClass(self):
        self.client = RequestsClient()

        self.u = SCTFUser.objects.create(username="******")
        self.u.set_password("TestPassword")
        self.u.is_verified = True
        self.u.save()

        resp = self.client.post(baseURL + "auth/login",
                                data={
                                    "username": "******",
                                    "password": "******"
                                })

        if resp.status_code != 200:
            raise Exception('Failed to authenticate user with status: ' +
                            str(resp.status_code))
        data = json.loads(resp.content)
        print(data["token"])
        self.token = f"Token {data['token']}"

    @classmethod
    def tearDownClass(self):
        self.u.delete()

    def test_anonymous_create_user(self):
        resp = self.client.post(apiURL + "users/",
                                data={
                                    "username": "******",
                                    "password": "******"
                                })

        self.assertEqual(resp.status_code, 201)
        data = json.loads(resp.content)
        self.assertTrue(SCTFUser.objects.filter(pk=data["id"]).exists())

    def test_anonymous_endpoint_access_get(self):
        self.assertEqual(self.client.get(apiURL + "users/").status_code, 401)

    def test_anonymous_endpoint_access_put(self):
        self.assertEqual(
            self.client.put(apiURL + f"users/{self.u.id}/",
                            data={
                                "username": "******",
                                "password": "******"
                            }).status_code, 401)

    def test_anonymous_endpoint_access_delete(self):
        self.assertEqual(
            self.client.delete(apiURL + f"users/{self.u.id}/").status_code,
            401)

    def test_anonymous_login(self):
        resp = self.client.post(baseURL + "auth/login",
                                data={
                                    "username": "******",
                                    "password": "******"
                                })
        self.assertEqual(resp.status_code, 200)

    def test_correct_user_get(self):
        self.client.headers.update({'Authorization': self.token})
        resp = self.client.get(apiURL + f"users/{self.u.id}/")
        self.assertEqual(resp.status_code, 200)

        d = json.loads(data.content)
        self.assertEqual(d["username"], u.username)
        self.assertEqual(d["first_name"], u.first_name)
        self.assertEqual(d["last_name"], u.last_name)
        self.assertEqual(d["display_name"], u.display_name)