예제 #1
0
    def setUp(self):
        # Create books list and save it
        self.books = [
            Book(author='J.R.R. Tolkien', title='The Hobbit'),
            Book(author='Fyodor Dostoevsky', title='Crime and Punishment'),
            Book(author='Richard Phillips Feynman', title="Surely You're Joking, Mr. Feynman"),
            Book(author='Michio Kaku', title='Physics of the Impossible'),
            Book(author='Cixin Liu', title='The Three-Body Problem'),
        ]
        [book.save() for book in self.books]

        # Create a dictionary contain n number of random reviews bound to book
        self.reviews = dict()
        for n, book in enumerate(self.books, start=1):
            self.reviews[str(book)] = {
                'avg': 0,
                'reviews': list(),
                'number_of_reviews': int(),
            }
            self.reviews[str(book)]['number_of_reviews'] = n
            for _ in range(n):
                rate = random.randrange(0, 5)
                review = Review(book=book, review=rate)
                review.save()
                self.reviews[str(book)]['reviews'].append(review)
                self.reviews[str(book)]['avg'] += rate
            self.reviews[str(book)]['avg'] /= n
예제 #2
0
def save_review_from_row(review_row):
    review = Review()
    review.user_id = User.objects.get(id=review_row[0])
    review.user_name = User.objects.get(id=review_row[0])
    review.movie = Movie.objects.get(id=review_row[1])
    review.rating = review_row[2]
    review.pub_date = datetime.datetime.now(tz=timezone.utc)
    review.save()
예제 #3
0
class ReviewModelTestCase(TestCase):
    def setUp(self):
        self.book = Book(author='J.R.R. Tolkien', title='The Hobbit')
        self.book.save()
        self.review = Review(book=self.book, review=5)

    def test_review_creation(self):
        self.review.save()
        self.assertIsNotNone(self.review.id)

    def test_review_low_validation(self):
        with self.assertRaises(ValidationError):
            self.review.review = -1
            self.review.full_clean()

    def test_review_high_validation(self):
        with self.assertRaises(ValidationError):
            self.review.review = 6
            self.review.full_clean()
예제 #4
0
 def post(self, request):
     try:
         product_id = request.data.get("product_id", None)
         product = Product.objects.get(product_id=product_id)
         customer_id = request.user.customer_id
         review = Review()
         for field, value in request.data.items():
             setattr(review, field, value)
         customer_review = Review.objects.filter(customer_id=customer_id,
                                                 product_id=product_id)
         if customer_review:
             return errors.handle(errors.USR_11)
         review.customer_id = customer_id
         review.save()
         serializer_element = ReviewSerializer(instance=review)
         holding_dict = serializer_element.data
         return_dict = {"name": product.name, **holding_dict}
         return Response(return_dict, 201)
     except Product.DoesNotExist:
         return errors.handle(errors.PRO_01)
예제 #5
0
def __handle_create_review_post(request):
    try:
        user_id = request.POST['reviewer']
        reviewer = User.objects.get(pk=user_id)
        book_id = request.POST['book']
        book = Book.objects.get(pk=book_id)
        rating = request.POST['rating']
        content = request.POST['content']
        review = Review(
            reviewer=reviewer,
            book=book,
            rating=rating,
            content=content,
        )
        review.save()
        return generate_response("review saved", True, review)
    except KeyError as e:
        return generate_response("missing %s" % e.args[0].strip("'"), False)
    except Exception as e:
        return generate_response(str(e), False)
예제 #6
0
def add_review(businessId):
    requestData = request.get_json()

    try:
        feedback = check_review(requestData.get('feedback'))
    except Exception as exception:
        return response_message(exception.args, status_code=500)

    auth_token = request.headers.get("Authorization")
    user = get_user(auth_token)
    if not isinstance(user, User):
        return response_message("Please login to review business", 401)

    business = Business.query.filter_by(id=businessId).first()
    if not business:
        return response_message("The business you requested does not exist", status_code=404)

    review = Review(feedback)
    review.user_id = user.id
    review.business_id = business.id
    review.save()
    return response_message("Your review has been added", 201)
예제 #7
0
 def create(self, validated_data):
     review = Review(**validated_data)
     review.save()
     return review
예제 #8
0
class ReviewModelTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            'user1',
            '*****@*****.**',
            'user1_pwd'
        )

        self.review = Review(
            title='My review',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user,
        )

    def test_save_model(self):
        self.review.save()

        self.assertIsNotNone(self.review.id)
        self.assertEqual(self.review.title, 'My review')
        self.assertEqual(self.review.summary, 'This is my first review.')
        self.assertEqual(self.review.rating, 1)
        self.assertEqual(self.review.ip_address, '127.0.0.1')
        self.assertEqual(self.review.company, 'Some Company')
        self.assertEqual(self.review.reviewer, 'Some Reviewer')
        self.assertEqual(self.review.user.username, 'user1')

        iso_re = re.compile('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{1,6}[+-]{1}\d{2}:\d{2}')

        self.assertIsNotNone(iso_re.match(str(self.review.created_at)))
        self.assertEqual(Review.objects.count(), 1)

    def test_model_str(self):
        self.review.save()
        self.assertEquals(str(self.review), 'My review')

    def test_save_valid_model(self):
        self.review.title = 'This is a very very very very very very very veeeeery long title'
        self.summary = ''.join(['a' for i in range(10000)])
        self.review.save()
        self.assertEqual(Review.objects.count(), 1)

    def test_validate_long_title(self):
        self.review.title = 'This is a very very very very very very very very very long title'
        with self.assertRaises(Exception):
            self.review.save()

    def test_validate_long_summary(self):
        self.review.summary = ''.join(['a' for i in range(10001)])
        with self.assertRaises(Exception):
            self.review.save()

    def test_validate_below_zero_rating(self):
        self.review.rating = -1
        with self.assertRaises(Exception):
            self.review.save()

    def test_validate_invalid_ip_address(self):
        self.review.ip_address='127,0,0,1'
        with self.assertRaises(Exception):
            self.review.save()
예제 #9
0
class ReviewSerializerTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('user1', '*****@*****.**',
                                             'user1_pwd')

        self.review = Review(
            title='My review',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user,
        )

        self.data = {
            'id': 1,
            'title': 'My review',
            'summary': 'This is my first review.',
            'rating': 1,
            'ip_address': '127.0.0.1',
            'company': 'Some Company',
            'reviewer': 'Some Reviewer',
        }

    def test_serialize_model(self):
        self.review.save()
        serializer = ReviewSerializer(self.review)

        self.assertIsInstance(serializer, serializers.ModelSerializer)

        data = serializer.data

        self.assertIsNotNone(data.get('id'))
        self.assertEqual(data.get('title'), 'My review')
        self.assertEqual(data.get('summary'), 'This is my first review.')
        self.assertEqual(data.get('rating'), 1)
        self.assertFalse('ip_address' in data)
        self.assertEqual(data.get('company'), 'Some Company')
        self.assertEqual(data.get('reviewer'), 'Some Reviewer')
        self.assertEqual(data.get('user'), 'user1')

    def test_deserialize_data(self):
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertTrue(serializer.is_valid())

        validated_data = serializer.validated_data

        self.assertEqual(validated_data.get('title'), 'My review')
        self.assertEqual(validated_data.get('summary'),
                         'This is my first review.')
        self.assertEqual(validated_data.get('rating'), 1)
        self.assertEqual(validated_data.get('ip_address'), '127.0.0.1')
        self.assertEqual(validated_data.get('company'), 'Some Company')
        self.assertEqual(validated_data.get('reviewer'), 'Some Reviewer')

    def test_validate_long_title(self):
        self.data[
            'title'] = 'This is a very very very very very very very very very long title'
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('title')), 1)

    def test_validate_long_summary(self):
        self.data['summary'] = ''.join(['a' for i in range(10001)])
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('summary')), 1)

    def test_validate_below_zero_rating(self):
        self.data['rating'] = -1
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('rating')), 1)

    def test_validate_beyond_five_rating(self):
        self.data['rating'] = 6
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('rating')), 1)

    def test_validate_invalid_ip_address(self):
        self.data['ip_address'] = '127,0,0,1'
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('ip_address')), 1)
예제 #10
0
 def create(self, validated_data):
     review = Review(**validated_data)
     review.author = self.context['request'].user
     review.save()
     return review
예제 #11
0
class TestUrls(TestCase):
    def setUp(self):
        self.user_john = User.objects.create_user('john', '*****@*****.**',
                                                  'john_pwd')

        self.review_by_john = Review(
            title='My review',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user_john,
        )
        self.review_by_john.save()

        self.client = Client()

    def test_post_review_url(self):
        data = {
            'title': 'My review',
            'summary': 'This is my first review.',
            'rating': 1,
            'ip_address': '127.0.0.1',
            'company': 'Some Company',
            'reviewer': 'Some Reviewer'
        }

        self.client.login(username='******', password='******')
        response = self.client.post('/api/reviews/',
                                    data,
                                    content_type='application/json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        data = response.json()

        self.assertIsNotNone(data.get('id'))
        self.assertEqual(data.get('user'), 'john')

    def test_post_review_url_anon_user(self):
        data = {
            'title': 'My review',
            'summary': 'This is my first review.',
            'rating': 1,
            'ip_address': '127.0.0.1',
            'company': 'Some Company',
            'reviewer': 'Some Reviewer'
        }

        response = self.client.post('/api/reviews/',
                                    data,
                                    content_type='application/json')

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_get_reviews_url(self):
        self.client.login(username='******', password='******')
        response = self.client.get('/api/reviews/')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertEqual(len(data), 1)

    def test_get_reviews_url_anon_user(self):
        response = self.client.get('/api/reviews/')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_get_review_url(self):
        self.client.login(username='******', password='******')
        response = self.client.get('/api/review/{}/'.format(
            self.review_by_john.id))

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertIsNotNone(data.get('id'))
        self.assertEqual(data.get('user'), 'john')

    def test_get_review_url_anon_user(self):
        response = self.client.get('/api/review/{}/'.format(
            self.review_by_john.id))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
예제 #12
0
class TestReviewListView(TestCase):
    def setUp(self):
        self.user_john = User.objects.create_user('john', '*****@*****.**',
                                                  'john_pwd')

        self.user_fred = User.objects.create_user('fred', '*****@*****.**',
                                                  'fred_pwd')

        self.review_by_john = Review(
            title='My review',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user_john,
        )

        self.review_by_fred = Review(
            title='Review by Fred',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user_fred,
        )

        self.data = {
            'title': 'My review',
            'summary': 'This is my first review.',
            'rating': 1,
            'company': 'Some Company',
            'reviewer': 'Some Reviewer'
        }

        self.view = ReviewListView()

    def _prepare_post_request(self, data, user=None):
        payload_content = '''
        {{
            "title": "{c[title]}",
            "summary": "{c[summary]}",
            "rating": {c[rating]},
            "company": "{c[company]}",
            "reviewer": "{c[reviewer]}"
        }}
        '''.format(c=data)

        payload = FakePayload(payload_content)
        request = WSGIRequest({
            'REQUEST_METHOD': 'POST',
            'REMOTE_ADDR': '127.0.0.1',
            'CONTENT_TYPE': 'application/json',
            'CONTENT_LENGTH': '{}'.format(len(payload)),
            'wsgi.input': payload
        })
        if user:
            request.user = user
        request._dont_enforce_csrf_checks = True
        return request

    def _prepare_get_request(self, user=None):
        payload = FakePayload('')
        request = WSGIRequest({
            'REQUEST_METHOD': 'GET',
            'CONTENT_LENGTH': 0,
            'wsgi.input': payload
        })
        if user:
            request.user = user
        request._dont_enforce_csrf_checks = True
        return request

    def test_post_review(self):
        request = self._prepare_post_request(self.data, self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        data = response.data

        self.assertIsNotNone(data.get('id'))
        self.assertEqual(data.get('title'), 'My review')
        self.assertEqual(data.get('summary'), 'This is my first review.')
        self.assertEqual(data.get('rating'), 1)
        self.assertFalse('ip_address' in data)
        self.assertEqual(data.get('company'), 'Some Company')
        self.assertEqual(data.get('reviewer'), 'Some Reviewer')
        self.assertEqual(data.get('user'), 'john')
        self.assertEqual(Review.objects.count(), 1)

    def test_post_review_long_title(self):
        self.data[
            'title'] = 'This is a very very very very very very very very very long title'
        request = self._prepare_post_request(self.data, self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        errors = response.data

        self.assertEqual(len(errors.get('title')), 1)

    def test_post_review_long_summary(self):
        self.data['summary'] = ''.join(['a' for i in range(10001)])
        request = self._prepare_post_request(self.data, self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        errors = response.data

        self.assertEqual(len(errors.get('summary')), 1)

    def test_post_review_below_zero_rating(self):
        self.data['rating'] = -1
        request = self._prepare_post_request(self.data, self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        errors = response.data

        self.assertEqual(len(errors.get('rating')), 1)

    def test_post_review_beyond_five_rating(self):
        self.data['rating'] = 6
        request = self._prepare_post_request(self.data, self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        errors = response.data

        self.assertEqual(len(errors.get('rating')), 1)

    def test_post_review_anon_user(self):
        request = self._prepare_post_request(self.data)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_get_reviews(self):
        self.review_by_john.save()

        request = self._prepare_get_request(self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.data

        self.assertEqual(len(data), 1)
        self.assertIsNotNone(data[0].get('id'))

    def test_get_zero_reviews(self):
        request = self._prepare_get_request(self.user_john)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.data

        self.assertEqual(len(data), 0)

    def test_get_own_reviews(self):
        self.review_by_john.save()
        self.review_by_fred.save()

        request = self._prepare_get_request(self.user_fred)
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.data

        self.assertEqual(len(data), 1)
        self.assertIsNotNone(data[0].get('id'))
        self.assertEqual(data[0].get('title'), 'Review by Fred')

    def test_get_reviews_anon_user(self):
        self.review_by_john.save()

        request = self._prepare_get_request()
        response = self.view.dispatch(request)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
예제 #13
0
class TestReviewDetailView(TestCase):
    def setUp(self):
        self.user_john = User.objects.create_user(
            'john',
            '*****@*****.**',
            'john_pwd'
        )

        self.user_fred = User.objects.create_user(
            'fred',
            '*****@*****.**',
            'fred_pwd'
        )

        self.review_by_john = Review(
            title='My review',
            summary='This is my first review.',
            rating=1,
            ip_address='127.0.0.1',
            company='Some Company',
            reviewer='Some Reviewer',
            user=self.user_john,
        )

        self.view = ReviewDetailView()

    def _prepare_get_request(self, user=None):
        payload = FakePayload('')
        request = WSGIRequest({
            'REQUEST_METHOD': 'GET',
            'CONTENT_LENGTH': 0,
            'wsgi.input': payload
        })
        if user:
            request.user = user
        request._dont_enforce_csrf_checks = True
        return request

    def test_get_review(self):
        self.review_by_john.save()

        request = self._prepare_get_request(self.user_john)
        response = self.view.dispatch(request, pk=self.review_by_john.id)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.data

        self.assertIsNotNone(data.get('id'))
        self.assertEqual(data.get('title'), 'My review')
        self.assertEqual(data.get('summary'), 'This is my first review.')
        self.assertEqual(data.get('rating'), 1)
        self.assertFalse('ip_address' in data)
        self.assertEqual(data.get('company'), 'Some Company')
        self.assertEqual(data.get('reviewer'), 'Some Reviewer')
        self.assertEqual(data.get('user'), 'john')
        self.assertEqual(Review.objects.count(), 1)

    def test_get_review_not_found(self):
        request = self._prepare_get_request(self.user_john)
        response = self.view.dispatch(request, pk=1)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_get_review_forbidden(self):
        self.review_by_john.save()

        request = self._prepare_get_request(self.user_fred)
        response = self.view.dispatch(request, pk=self.review_by_john.id)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_get_review_anon_user(self):
        self.review_by_john.save()

        request = self._prepare_get_request()
        response = self.view.dispatch(request, pk=self.review_by_john.id)

        self.assertIsInstance(self.view, APIView)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)