예제 #1
0
파일: tests.py 프로젝트: ericls/niji
 def test_close_open_topic(self):
     lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50))
     d = requests.patch(
         self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
         json.dumps({"closed": True})
     )
     self.assertEqual(d.status_code, 403)
     self.browser.get(self.live_server_url + reverse("niji:index"))
     login(self.browser, 'super', '123')
     cookies = self.browser.get_cookies()
     s = requests.Session()
     s.headers = {'Content-Type': 'application/json'}
     for cookie in cookies:
         if cookie['name'] == 'csrftoken':
             continue
         s.cookies.set(cookie['name'], cookie['value'])
     d = s.patch(
         self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
         json.dumps({"closed": True})
     ).json()
     self.assertEqual(d["closed"], True)
     d = s.patch(
         self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
         json.dumps({"closed": False})
     ).json()
     self.assertEqual(d["closed"], False)
예제 #2
0
 def test_posts(self):
     for model, items in self.post_data.items():
         for item in items:
             # hackpad_id and other null text fields omitted on create
             # for now due to rest_framework bug:
             # https://github.com/tomchristie/django-rest-framework/issues/1879
             # Update: This has been fixed in master:
             # https://github.com/tomchristie/django-rest-framework/pull/1834
             for field in ("hackpad_id", "username", "password"):
                 if field in item:
                     del item[field]
             create_response = self.client.post(
                 api_reverse("{}-list".format(model)), format="json", data=item, HTTP_AUTHORIZATION=self.basic_auth
             )
             self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
             self.assertTrue("id" in create_response.data)
             item["id"] = create_response.data["id"]
             for field in ("hackpad_id", "username", "password"):  # See comment above
                 if field in create_response.data:
                     item[field] = None
             self.assertEqual(self.normalize_dict(create_response.data), item)
             get_response = self.client.get(
                 api_reverse("{}-detail".format(model), args=[item["id"]]),
                 format="json",
                 HTTP_AUTHORIZATION=self.basic_auth,
             )
             self.assertEqual(self.normalize_dict(get_response.data), item)
예제 #3
0
 def get(self, request, format=None):
     data = {
         "categories": {
             "url": api_reverse("category:list_api", request=request),
             "count": Category.objects.all().count()
         },
         "comments": {
             "url": api_reverse("comment:list_api", request=request),
             "count": Comment.objects.all().count()
         }
     }
     return Response(data)
예제 #4
0
 def get(self, request, format=None):
     data = {
         'products': {
             'count': Product.objects.all().count(),
             'url': api_reverse('products_api', request=request),
         },
         'categories': {
             'count': Category.objects.all().count(),
             'url': api_reverse('categories_api', request=request),
         },
     }
     return Response(data)
def api_home(request):
	data = {
		"projects":{
			"count":Category.objects.all().count(),
			"url":api_reverse('category_list_api'),
		},
		"comments":{
			"count":Comment.objects.all().count(),
			"url":api_reverse('comment_list_api'),
		}
	}
	return RestResponse(data)
예제 #6
0
 def test_gets(self):
     for model, items in self.start_data.items():
         response = self.client.get(api_reverse('{}-list'.format(model)),
                                    format='json', HTTP_AUTHORIZATION=self.basic_auth)
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data), len(items))
         for response_item, item in zip(response.data, items):
             self.assertEqual(self.normalize_dict(response_item), item)
         for item in items:
             response = self.client.get(api_reverse('{}-detail'.format(model), args=[item['id']]),
                                        format='json', HTTP_AUTHORIZATION=self.basic_auth)
             self.assertEqual(response.status_code, status.HTTP_200_OK)
             self.assertEqual(self.normalize_dict(response.data), item)
예제 #7
0
 def test_negative_sort(self):
     response = self.client.get(
         "{}?ordering=-name".format(api_reverse("graphitestatuscheck-list")),
         format="json",
         HTTP_AUTHORIZATION=self.basic_auth,
     )
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual([item["name"] for item in response.data], self.expected_sort_names[::-1])
예제 #8
0
 def test_query(self):
     response = self.client.get(
         "{}?debounce=1&importance=CRITICAL".format(api_reverse("jenkinsstatuscheck-list")),
         format="json",
         HTTP_AUTHORIZATION=self.basic_auth,
     )
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(len(response.data), 1)
     self.assertEqual(response.data[0]["id"], self.expected_filter_result.id)
예제 #9
0
파일: tests.py 프로젝트: ericls/niji
    def test_unauthorized_access(self):
        d = requests.get(self.live_server_url+api_reverse('niji:topic-list'))
        self.assertEqual(d.status_code, 403)
        d = requests.get(self.live_server_url+api_reverse('niji:topic-detail', kwargs={"pk": self.t1.pk}))
        self.assertEqual(d.status_code, 403)

        self.browser.get(self.live_server_url+reverse("niji:index"))
        login(self.browser, 'test1', '111')
        cookies = self.browser.get_cookies()
        s = requests.Session()
        s.headers = {'Content-Type': 'application/json'}
        for cookie in cookies:
            if cookie['name'] == 'csrftoken':
                continue
            s.cookies.set(cookie['name'], cookie['value'])
        d = s.get(self.live_server_url + api_reverse('niji:topic-list'))
        self.assertEqual(d.status_code, 403)
        d = s.get(self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": self.t1.pk}))
        self.assertEqual(d.status_code, 403)
예제 #10
0
파일: tests.py 프로젝트: ericls/niji
 def test_hide_post(self):
     lucky_post = random.choice(Post.objects.visible().all())
     d = requests.patch(
         self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}),
         json.dumps({"hidden": True})
     )
     self.assertEqual(d.status_code, 403)
     self.browser.get(self.live_server_url + reverse("niji:index"))
     login(self.browser, 'super', '123')
     self.assertIn("Log out", self.browser.page_source)
     cookies = self.browser.get_cookies()
     s = requests.Session()
     s.headers = {'Content-Type': 'application/json'}
     for cookie in cookies:
         if cookie['name'] == 'csrftoken':
             continue
         s.cookies.set(cookie['name'], cookie['value'])
     d = s.patch(
         self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}),
         json.dumps({"hidden": True})
     ).json()
     self.assertEqual(d["hidden"], True)
예제 #11
0
 def test_positive_sort(self):
     response = self.client.get(
         '{}?ordering=name'.format(
             api_reverse('graphitestatuscheck-list')
         ),
         format='json',
         HTTP_AUTHORIZATION=self.basic_auth
     )
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(
         [item['name'] for item in response.data],
         self.expected_sort_names
     )
예제 #12
0
파일: tests.py 프로젝트: bonniejools/cabot
 def test_query(self):
     response = self.client.get(
         '{}?debounce=1&importance=CRITICAL'.format(
             api_reverse('api:statuscheck-list')
         ),
         format='json',
         HTTP_AUTHORIZATION=self.basic_auth
     )
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(len(response.data), 1)
     self.assertEqual(
         response.data[0]['id'],
         self.expected_filter_result.id
     )
예제 #13
0
	def get(self, request, format=None):
		data = {
			'users': {
				'register_url': api_reverse('users_api:register', request=request),
				'login_token_url': api_reverse('login_token', request=request),
				'verify_token_url': api_reverse('verify_token', request=request),
				'refresh_token_url': api_reverse('refresh_token', request=request),
			},
			'posts': {
				'retrieve_url': api_reverse('posts_api:list', request=request),
				'create_url': api_reverse('posts_api:create', request=request),
			},
			'comments': {
				'retrieve_url': api_reverse('comments_api:list', request=request),
				'create_url': api_reverse('comments_api:create', request=request),
			},
		}
		return Response(data)
예제 #14
0
    def get_personal_workouts(self, obj):
        personal_workouts_qs = obj.workout_set.filter(program__program_type='WP').filter(created__month=today.month)
        data = []
        for workout in personal_workouts_qs:
            workout_dict = {}
            workout_dict['id'] = str(workout.id)
            workout_dict['is_finished'] = workout.is_finished
            workout_dict['number'] = workout.number
            workout_dict['name'] = workout.name
            workout_dict['content'] = workout.content
            workout_dict['sex'] = workout.sex
            workout_dict['training_level'] = workout.training_level
            workout_dict['rest'] = workout.rest
            workout_dict['program_type'] = 'WP'
            workout_dict['url'] = api_reverse('api-accounts:workout_detail_api', kwargs={'pk':workout.id})
            workout_dict['created'] = workout.created
            data.append(workout_dict)

        return data
예제 #15
0
    def test_list_filter_with_misspell(self):
        products = Product.objects.all()
        product = random.choice(list(products))
        search_for = str(product.title.split(' ')[0])
        search_for = search_for.replace(
            search_for[math.floor(len(search_for) / 2)], '')
        print(f'product={product}')
        print(f'SearchFor={ search_for }')

        res = Product.objects.filter(title__in=search_for)
        print(f'search output len={ len( list( res ) ) }')

        url = api_reverse('products:product-list')
        response = self.client.get(url,
                                   data={'title': search_for},
                                   format='json')
        for _ in response.json():
            print(f'={ _.get( "id" ) }|{ _.get( "title" ) }')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #16
0
 def test_other_user_permission_api(self):
     data = self.create_item()
     data_id = data.get('id')
     user = User.objects.create(username='******')
     payload = jwt_payload_handler(user)
     print(payload)
     token = jwt_encode_handler(payload)
     print(token)
     self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
     rud_url = api_reverse('api-status:detail', kwargs={'id': data_id})
     rud_data = {
         'content': 'permission test'
     }
     get_ = self.client.get(rud_url, format='json')
     put_ = self.client.put(rud_url, rud_data, format='json')
     delete_ = self.client.delete(rud_url, format='json')
     self.assertEqual(get_.status_code, status.HTTP_200_OK)
     self.assertEqual(put_.status_code, status.HTTP_403_FORBIDDEN)
     self.assertEqual(delete_.status_code, status.HTTP_403_FORBIDDEN)
예제 #17
0
    def setUp(self):
        """
        Setup the user, rating and article for the tests
        """
        super().setUp()
        self.rating = {'rating': {'rating': 4}}

        self.rater = {
            "user": {
                "username": "******",
                "password": "******",
                "email": "*****@*****.**"
            }
        }
        self.author_token = self.create_and_login_user()
        self.article_slug = self.create_article(token=self.author_token)
        self.rater_token = self.create_and_login_user(user=self.rater)
        self.article_rating_url = api_reverse('articles:ratings',
                                              {self.article_slug: 'slug'})
예제 #18
0
 def test_status_create_with_image(self):
     self.status_user_token()
     url = api_reverse('api-status:list')
     # (w, h) = (800, 1200)
     # (255, 255, 255)
     image_item = Image.new('RGB', (800, 1280), (0, 124, 174))
     tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
     image_item.save(tmp_file, format='JPEG')
     with open(tmp_file.name, 'rb') as file_obj:
         data = {'content': "come cool test content", 'image': file_obj}
         response = self.client.post(
             url, data, format='multipart'
         )  # multipart allows you to handle data coming through
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         self.assertEqual(Status.objects.count(), 2)
     temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status',
                                 'testcfeuser')
     if os.path.exists(temp_img_dir):
         shutil.rmtree(temp_img_dir)
예제 #19
0
    def test_photo_title_uniqueness_when_one_gallery_has_multiple_photos_with_the_same_title(
            self):
        gallery = baker.make("core.Gallery", user=self.test_user_1)
        photo = baker.make("core.Photo",
                           gallery=gallery,
                           image=self.test_photo_1.image)

        with open(photo.image.path, "rb") as image_data:
            data = {
                "gallery": gallery.pk,
                "title": photo.
                title,  # <-- will fail,because title already exist in this gallery
                "image": image_data,
            }
            client = APIClient()
            client.force_authenticate(self.test_user_1)
            url = api_reverse("api:photo-list")
            response = client.post(url, data=data, format="multipart")
            self.assertEqual(response.status_code, 400)
예제 #20
0
 def test_gallery_create_method_fails_if_user_not_logged_in(self):
     photo = self.test_photo_1
     with open(photo.image.path, 'rb') as image_data:
         data = {
             "name": "testing_gallery_1",
             "category": "1",
             "user": str(self.test_moderator.pk),
             "public": True,
             "title": photo.title,
             "image": image_data
         }
         client = APIClient()
         #No force log in method here, should throw 403 error
         url = api_reverse('api:gallery-list')
         response = client.post(url,
                                data=data,
                                format="multipart",
                                follow=True)
         self.assertEqual(response.status_code, 403)
예제 #21
0
    def test_post_item_auth_with_tags(self):
        data = {'category': 'random',
                'value': 144,
                'date': datetime.date(2020, 11, 21),
                'tags': 'the, tags are,   right here                    ',
                'time': '5:00PM'
                }

        user = User.objects.first()
        payload = payload_handler(user)
        token = encode_handler(payload)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)

        url = api_reverse('api:info_post_item')
        response = self.client.post(url, data, format='json')
        info = Info.objects.count()

        self.assertEqual(info,4)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
예제 #22
0
    def test_user_login_and_update(self):
        data = {'username': '******', 'password': '******'}
        url = api_reverse('api-login')
        response = self.client.post(url, data)
        print(response.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        token = response.data.get('token')
        if token is not None:
            blog_post = BlogPost.objects.first()
            url = blog_post.get_api_url()
            data = {
                'title': 'Some rando title',
                'content': 'some more content'
            }
            self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
            response = self.client.put(url, data, format='json')
            print(response.data)
            self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #23
0
 def test_user_login_and_update(self):
     data = {
         'username': '******',
         'password': '******',
     }
     url = api_reverse('api-login')
     response = self.client.post(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     token = response.data.get('token')
     if token is not None:
         game_review = GameReview.objects.first()
         url = game_review.get_api_url()
         data = {
             'title': 'Second updated test title',
             'content': 'Second updated test content'
         }
         self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
         response = self.client.put(url, data, format='json')
         self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #24
0
    def test_user_login_and_update(self):
        data = {"username": "******", "password": "******"}
        url = api_reverse("api-login")
        response = self.client.post(url, data)
        print(response.data)
        print(response.status_code)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        token = response.data.get("token")
        if token is not None:
            blog_post = BlogPost.objects.first()
            url = blog_post.get_api_url()
            data = {"title": "Random title", "content": "Some more content"}
            self.client.credentials(HTTP_AUTHORIZATION='JWT ' +
                                    token)  #"JWT <token>"
            response = self.client.put(url, data, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)


#request.post(url, data, headers={"Authorization": "JWT " + <token>})
예제 #25
0
 def test_gallery_create_method_fails_if_category_does_not_exist(self):
     photo = self.test_photo_1
     with open(photo.image.path, 'rb') as image_data:
         data = {
             "name": "testing_gallery_1",
             "category": "1000000000000",  # selection out_of_range
             "user": str(self.test_moderator.pk),
             "public": True,
             "title": photo.title,
             "image": image_data
         }
         client = APIClient()
         client.force_authenticate(self.test_moderator)
         url = api_reverse('api:gallery-list')
         response = client.post(url,
                                data=data,
                                format="multipart",
                                follow=True)
         self.assertEqual(response.status_code, 400)
예제 #26
0
 def test_create_movie(self):
     """
     Ensure we can create a new movie.
     """
     data = {
         'username': '******',
         'password': '******'
     }
     url = api_reverse("api-login")
     response = self.client.post(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     token = response.data.get("token")
     url = reverse('movie-create')
     data = {"title":"The Matrix","chinesetitle":"hhe","director":"Lana Wachowski, Lilly Wachowski","rated":0,"year":"1999","genres":"Action, Sci-Fi","summary":"A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.","fmt":"2","length":"136 min","rating":"8.7","production":"Warner Bros. Pictures","sn":"sdfs","url":"http://www.whatisthematrix.com","img":"https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg"}
     self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
     response = self.client.post(url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(Movie.objects.count(), 1)
     self.assertEqual(Movie.objects.get().fmt, 'DVD')
예제 #27
0
    def test_view_permission_success(self):
        user = User.objects.get(email='*****@*****.**')
        token = Token.objects.get(user=user)
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

        # grant permission programmatically
        content_type = ContentType.objects.get_for_model(User)
        permission = Permission.objects.get(
            codename='can_view_dummy',
            content_type=content_type,
        )
        user.user_permissions.add(permission)

        url = api_reverse('permissions:view')
        r = self.client.get(url, format='json')
        status_boolean = r.data.get('success')

        self.assertEqual(r.status_code, status.HTTP_200_OK)
        self.assertTrue(status_boolean)
예제 #28
0
    def test_post_item_auth_with_wrong_date(self):
        data = {'category': 'random',
                'value': 144,
                'date': '23-23-200',
                'tags': 'the, tags are',
                'time': '5:00PM'
                }

        user = User.objects.first()
        payload = payload_handler(user)
        token = encode_handler(payload)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)

        url = api_reverse('api:info_post_item')
        response = self.client.post(url, data, format='json')
        info = Info.objects.count()

        self.assertEqual(info, 3)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
예제 #29
0
 def test_user_login_and_update(self):
     data = {'username': '******', 'password': '******'}
     url = api_reverse("api-login")
     response = self.client.post(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     token = response.data.get("token")
     if token is not None:
         blog_post = Post.objects.first()
         # print(blog_post.content)
         url = blog_post.get_api_url()
         data = {
             "title": "Some rando title",
             'post_slug': 'some-rando_title',
             'short_description': 'awesome stuff',
             "body": "some more content"
         }
         self.client.credentials(HTTP_AUTHORIZATION='JWT ' +
                                 token)  # JWT <token>
         response = self.client.put(url, data, format='json')
         self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #30
0
 def test_user_login_update(self):
     data = {'username': '******', 'password': '******'}
     url = api_reverse("api-login")
     response = self.client.post(url, data)
     print(response.data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     token = response.data.get("token")
     if token is not None:
         item = BlogPost.objects.first()
         # print(item.content)
         url = item.get_api_url()
         user_obj = User.objects.get(username='******')
         data = {
             "title": "some random title",
             "content": "some more content",
             "user": user_obj.id
         }
         self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
         response = self.client.put(url, data, format='json')
         self.assertEqual(response.status_code, status.HTTP_200_OK)
    def test_status_create_with_img_and_no_content(self):
        self.status_user_token()
        url = api_reverse('api-status:list')

        image_item = Image.new('RGB', (800, 1280), (0, 124, 174))
        tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False)
        image_item.save(tmp_file, format='JPEG')
        with open(tmp_file.name, 'rb') as file_obj:
            data = {"content": None, "image": file_obj}
            response = self.client.post(url, data, format='multipart')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            print(response.data)

            self.assertEqual(Status.objects.count(), 2)

        # para apagar a image
        temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status',
                                    'adminteste2')
        if os.path.exists(temp_img_dir):
            shutil.rmtree(temp_img_dir)
예제 #32
0
    def test_create_dadis(self):
        url = api_reverse("backend:dadis_link")

        data = {
            "species": {
                "scientific_name": "Bos taurus",
                "common_name": "Cattle"
            },
            "supplied_breed": "Asturiana de los Valles",
            "country": "Spain",
            "iso3": "ESP",
            "dadis_url": (
                "https://dadis-breed-4eff5.firebaseapp.com/?country=ESP"
                "&specie=Cattle&breed=Asturiana%20de%20los%20Valles"
                "&callback=allbreeds")
        }
        response = self.client.post(url, data, format="json")

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(DADISLink.objects.count(), 1)
예제 #33
0
    def test_status_create_with_image(self):
        self.status_user_token()

        #for status object create test
        url = api_reverse('api-status:list')
        #(width, height) = (800,1280)
        image_item = Image.new('RGB', (800, 1280), (0,124,174))
        tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
        image_item.save(tmp_file, format='JPEG')
        with open(tmp_file.name, 'rb') as file_obj:
            data={'content':'some cool test content', 'image':None}
            response=self.client.post(url, data, format='multipart')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            self.assertEqual(Status.objects.count(), 3)
            img_data=response.data.get('image')
            self.assertNotEqual(img_data, None)

        temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status', 'testcfeuser')
        if os.path.exists(temp_img_dir):
            shutil.rmtree(temp_img_dir)
예제 #34
0
    def test_d_order_multiple_dishes_with_one_request(self):
        data = [
            {
                "dish": "Fried Rice",
                "delivery_date": "2020-07-17",
                "address": "Lagos",
                "qty": 3
            },
            {
                "dish": "Pounded Yam and Egusi Soup",
                "delivery_date": "2020-07-18",
                "address": "Abuja",
                "qty": 2
            },
        ]

        cart_url = api_reverse('api-food:addCart')
        cart_response = self.client.post(cart_url, data, format='json')
        self.assertEqual(cart_response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Cart.objects.count(), 2)
예제 #35
0
 def test_create_user_successful(self):
     """Create new user --- successful for admins and managers"""
     data = {
         "email": "*****@*****.**",
         "password1": "testcc123",
         "password2": "testcc123",
         "permission": "USER"
     }
     admin = User.objects.get(email="*****@*****.**")
     token1 = Token.objects.get(user=admin)
     self.client.credentials(HTTP_AUTHORIZATION=f'Token {token1}')
     url = api_reverse("api-users:signup")
     response = self.client.post(url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
     data["email"] = "*****@*****.**"
     manager = User.objects.get(email="*****@*****.**")
     token2 = Token.objects.get(user=manager)
     self.client.credentials(HTTP_AUTHORIZATION=f'Token {token2}')
     response = self.client.post(url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
예제 #36
0
파일: tests.py 프로젝트: altonode/blogapi
 def test_user_login_and_update(self):
     data = {
         "username": '******',
         "password": '******',
     }
     url = api_reverse("api-login")
     response = self.client.post(url, data)
     print(response.data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     token = response.data.get("token")
     if token is not None:
         blog_post = BlogPost.objects.first()
         url = blog_post.get_api_url()
         data = {
             "title": "Some other title",
             "content": "Some other content"
         }
         self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
         response = self.client.put(url, data, format='json')
         self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #37
0
    def get_foodprograms(self, obj):
        foodprograms = obj.foodprogram_set.all()
        data = []
        if obj.program_type == 'FP':
            foodprograms = foodprograms.filter(program__program_type='FP')
        elif obj.program_type == 'FG':
            foodprograms = foodprograms.filter(program__program_type='FG')

        for foodprogram in foodprograms:
            if not foodprogram.food_set.all().count() > 0:
                continue
            foodprogram_dict = {}
            foodprogram_dict['id'] = str(foodprogram.id)
            foodprogram_dict['url'] = api_reverse('api-accounts:foodprogram_detail_api', kwargs={'pk':foodprogram.id})
            foodprogram_dict['number'] = foodprogram.number
            foodprogram_dict['name'] = foodprogram.name
            foodprogram_dict['content'] = foodprogram.content
            data.append(foodprogram_dict)

        return data
예제 #38
0
    def test_patch_item_auth_wrong_tags(self):
        data = {
            'category': 'second',
            'value': 21,
            'date': datetime.date(2000, 1, 1),
            'tags': [
                'random1',
                'random2',
            ],
            'time': '5:30AM'
        }

        user = User.objects.first()
        payload = payload_handler(user)
        token = encode_handler(payload)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)

        url = api_reverse('api:info_rud_item', kwargs={'pk': 1})
        response = self.client.patch(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
예제 #39
0
 def test_create_meal_category_by_user(self):
     data = get_login_data(USER_LOGIN_DATA['email'],
                           USER_LOGIN_DATA['password'])
     login_url = api_reverse("api-login")
     client = APIClient()
     response = client.post(login_url, data, format='json')
     if response.status_code == status.HTTP_200_OK:
         self.access_token = response.data.get('access')
         data = {
             'name': "TestName",
             'description': "Test Description",
             'image_url': "http://image.com/image.jpg"
         }
         url = BASE_URL + dj_reverse("api:categories")
         head = {'Authorization': 'Bearer ' + str(self.access_token)}
         response = requests.post(url, data, headers=head)
         self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
     else:
         self.fail("Unable to login")
     client.logout()
예제 #40
0
    def test_post_user_with_user(self):
        user_obj = User.objects.first()
        payload = payload_handler(user_obj)
        token_rsp = encode_handler(payload)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token_rsp)

        data = {
            'first_name': 'Marwin',
            'last_name': 'Android',
            'email': '*****@*****.**',
            'username': '******',
            'password': '******',
            'permissions': [],
            'profile': {
                'rank': 'Paranoid Android'
            }
        }

        url = api_reverse("accounts:user-list")
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
예제 #41
0
    def test_post_solicitudes_with_user_admin(self):
        self.client.credentials(
            HTTP_AUTHORIZATION="eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg1OWE2NDFhMWI4MmNjM2I1MGE4MDFiZjUwNjQwZjM4MjU3ZDEyOTkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vdHJhYmFqby1kZS1ncmFkby1mOWNiOCIsImF1ZCI6InRyYWJham8tZGUtZ3JhZG8tZjljYjgiLCJhdXRoX3RpbWUiOjE1NDczOTgzMTMsInVzZXJfaWQiOiJEcTJoQUZyamp3VFIwU2VHclRwS204anI5RXExIiwic3ViIjoiRHEyaEFGcmpqd1RSMFNlR3JUcEttOGpyOUVxMSIsImlhdCI6MTU0ODQ1Nzk2NCwiZXhwIjoxNTQ4NDYxNTY0LCJlbWFpbCI6ImFuZHJlc2NoZXNzMjAwOUBob3RtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJhbmRyZXNjaGVzczIwMDlAaG90bWFpbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.v75f3olYx5wtqCCbJjO7rrpAhyrSwxIQUQShc7YYYJjPYkxpScM8Wo9KwJRmhsjhe8I9Y5xe1fKVroJGfo-TbfW4TQ8nXWo9uWLix7D9j6oj32tkz_kwc396kJXifQphRqtK4_8mjbFMP9cNt2pBn81YORY19o8G6rKaC8pOPAwJrsVk2--OcBOCYpQu_OfuCEUippRiGh2piPIkN6kQjeB675UD8xTfjblqKGFwt4vi2MNRurKsnmRdg3hZmvMpRO7q1dk3R2y4NYUoCw37alypnIZnh_LabVjDb6-7iW3g_VqPLUayp8JDHfAzsN6Q7kxzjTLkMSfMNutP1ca07w")

        data = {"usuario": 1,
                "nombre_lugar": "Nombre test",
                "direccion": "Test direccion",
                "telefono": "423423",
                "email": ["*****@*****.**"],
                "informacion": "Info test",
                "aceptado": "t",
                "hora_abierto": "{06:00:00, 06:00:00, 06:00:00, 06:00:00, 06:00:00, 06:00:00, 06:00:00}",
                "hora_cerrado": "{22:00:00, 22:00:00, 22:00:00, 22:00:00, 22:00:00, 22:00:00, 22:00:00}",
                "dias_servicio": "{Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo}",
                "foto": "Foto prueba",
                "latitud": "17890",
                "longitud": "54321"}

        url = api_reverse("api-request:request-create")
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
예제 #42
0
 def test_status_create_with_image(self):
     self.status_user_token()
     # (w, h) = (800, 1200)
     # (255, 255, 255) hex color
     url = api_reverse('api-status:list')
     image_item = Image.new('RGB', (800, 1280), (0, 124, 174))
     tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
     image_item.save(tmp_file, format='JPEG')
     with open(tmp_file.name, 'rb') as file_obj:
         data = {'content': "some cool test content", 'image': file_obj}
         response = self.client.post(url, data, format='multipart')
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         self.assertEqual(Status.objects.count(), 2)
         print(response.data)
         img_data = response.data.get('image')
         self.assertNotEqual(img_data, None)
     temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status',
                                 'testgunuser')
     # remove entire dir made from the test
     if os.path.exists(temp_img_dir):
         shutil.rmtree(temp_img_dir)
예제 #43
0
    def test_post_eventos_with_user_admin(self):
        self.client.credentials(
            HTTP_AUTHORIZATION="eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg1OWE2NDFhMWI4MmNjM2I1MGE4MDFiZjUwNjQwZjM4MjU3ZDEyOTkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vdHJhYmFqby1kZS1ncmFkby1mOWNiOCIsImF1ZCI6InRyYWJham8tZGUtZ3JhZG8tZjljYjgiLCJhdXRoX3RpbWUiOjE1NDczOTgzMTMsInVzZXJfaWQiOiJEcTJoQUZyamp3VFIwU2VHclRwS204anI5RXExIiwic3ViIjoiRHEyaEFGcmpqd1RSMFNlR3JUcEttOGpyOUVxMSIsImlhdCI6MTU0ODQ1Nzk2NCwiZXhwIjoxNTQ4NDYxNTY0LCJlbWFpbCI6ImFuZHJlc2NoZXNzMjAwOUBob3RtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJhbmRyZXNjaGVzczIwMDlAaG90bWFpbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.v75f3olYx5wtqCCbJjO7rrpAhyrSwxIQUQShc7YYYJjPYkxpScM8Wo9KwJRmhsjhe8I9Y5xe1fKVroJGfo-TbfW4TQ8nXWo9uWLix7D9j6oj32tkz_kwc396kJXifQphRqtK4_8mjbFMP9cNt2pBn81YORY19o8G6rKaC8pOPAwJrsVk2--OcBOCYpQu_OfuCEUippRiGh2piPIkN6kQjeB675UD8xTfjblqKGFwt4vi2MNRurKsnmRdg3hZmvMpRO7q1dk3R2y4NYUoCw37alypnIZnh_LabVjDb6-7iW3g_VqPLUayp8JDHfAzsN6Q7kxzjTLkMSfMNutP1ca07w")

        data = {"nombre": "Nombre Test",
                "descripcion": "Descripcion Test",
                "lugar": 1,
                "comentario": [],
                "direccion": "Direccion Test",
                "foto": ["gs:\/\/trabajo-de-grado-f9cb8.appspot.com\/lugares\/1\/slider-logo.png"],
                "calificacion": 2,
                "tipo": "Tipo Test",
                "fecha_inicio": "1996-08-10",
                "fecha_fin": "1996-08-20",
                "hora_inicio": "11:00:00",
                "hora_fin": "23:00:00",
                "finalizado": "t"}

        url = api_reverse("api-eventos:evento-create")
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
예제 #44
0
def tedx_api_home_english(request):
	data = {
		"events" : {
			"count" : Event.objects.all().count(),
			"url" : api_reverse("event_list_api_e"),
			},
		"themes" : {
			"count" : Theme.objects.all().count(),
			"url" : api_reverse("theme_list_api_e")
			},
		"speakers" : {
			"count" : Speaker.objects.all().count(),
			"url" : api_reverse("speaker_list_api_e")
			},
		"news" : {
			"count" : News.objects.all().count(),
			"url" : api_reverse("news_list_api_e")
			},
		"types" : {
			"count" : Type.objects.all().count(),
			"url" : api_reverse("type_list_api_e")
			},
		"partners" : {
			"count" : Partner.objects.all().count(),
			"url" : api_reverse("partner_list_api_e")
			},
		"tedx" : {
			"count" : TEDx.objects.all().count(),
			"url" : api_reverse("tedx_list_api_e")
			},
		"about" : {
			"count" : AboutApp.objects.all().count(),
			"url" : api_reverse("about_list_api_e")
			},
		"menu" : {
			"count" : Menu.objects.all().count(),
			"url" : api_reverse("menu_list_api_e")
		},
		"program" : {
			"count" : Presentation.objects.all().count(),
			"url" : api_reverse("program_list_api_e")
		},
		"slot" : {
			"count" : Slot.objects.all().count(),
			"url" : api_reverse("slot_list_api_e")
		},


	}


	return RestResponse(data)
예제 #45
0
 def test_auth_failure(self):
     response = self.client.get(api_reverse('statuscheck-list'))
     self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
예제 #46
0
	def get(self, request, format=None):
		data = {
			"auth": {
				"login_url":  api_reverse("auth_login_api", request=request),
				"refresh_url":  api_reverse("refresh_token_api", request=request), 
				"user_checkout":  api_reverse("user_checkout_api", request=request), 
			},
			"address": {
				"url": api_reverse("user_address_list_api", request=request),
				"create":   api_reverse("user_address_create_api", request=request),
			},
			"checkout": {
				"cart": api_reverse("cart_api", request=request),
				"checkout": api_reverse("checkout_api", request=request),
				"finalize": api_reverse("checkout_finalize_api", request=request),
			},
			"products": {
				"count": Product.objects.all().count(),
				"url": api_reverse("products_api", request=request)
			},
			"categories": {
				"count": Category.objects.all().count(),
				"url": api_reverse("categories_api", request=request)
			},
			"orders": {
				"url": api_reverse("orders_api", request=request),
			}
		}
		return Response(data)