def test_get_popular(self): reviews = db_review.get_popular() self.assertEqual(len(reviews), 0) # popular reviews should not contain reviews saved as drafts review = db_review.create( entity_id="e7aad618-fa86-3983-9e77-405e21796eca", entity_type="release_group", user_id=self.user.id, text="A draft", is_draft=True, license_id=self.license["id"], ) reviews = db_review.get_popular() self.assertEqual(len(reviews), 0) # publishing the drafted review; now it should be in popular reviews db_review.update( review_id=review["id"], drafted=True, text=review["text"], rating=review["rating"], is_draft=False, ) reviews = db_review.get_popular() self.assertEqual(len(reviews), 1) self.assertEqual(reviews[0]["is_draft"], False) # A hidden review should not be in popular reviews db_review.set_hidden_state(review["id"], is_hidden=True) reviews = db_review.get_popular() self.assertEqual(len(reviews), 0)
def test_update(self): """Test if rating and count are updated when review is updated, deleted or hidden""" # Check avg_rating when review is created review = db_review.create( entity_id="e7aad618-fa86-3983-9e77-405e21796eca", entity_type="release_group", text=u"Testing!", rating=5, user_id=self.user.id, is_draft=False, license_id=self.license["id"], ) review_2 = db_review.create( entity_id="e7aad618-fa86-3983-9e77-405e21796eca", entity_type="release_group", text=u"Testing!", rating=4, user_id=self.user_2.id, is_draft=False, license_id=self.license["id"], ) avg_rating = db_avg_rating.get(review["entity_id"], review["entity_type"]) self.assertEqual(avg_rating["entity_id"], review["entity_id"]) self.assertEqual(avg_rating["entity_type"], review["entity_type"]) self.assertEqual(avg_rating["rating"], 4.5) self.assertEqual(avg_rating["count"], 2) # Check if avg_rating is updated after review_2 is hidden db_review.set_hidden_state(review_2["id"], is_hidden=True) avg_rating = db_avg_rating.get(review["entity_id"], review["entity_type"]) self.assertEqual(avg_rating["rating"], 5.0) self.assertEqual(avg_rating["count"], 1) # Check if avg_rating is updated after review_2 is revealed db_review.set_hidden_state(review_2["id"], is_hidden=False) avg_rating = db_avg_rating.get(review["entity_id"], review["entity_type"]) self.assertEqual(avg_rating["rating"], 4.5) self.assertEqual(avg_rating["count"], 2) # Check if avg_rating is updated after change in rating db_review.update( review_id=review_2["id"], drafted=review_2["is_draft"], text=u"Testing rating update", rating=None, ) avg_rating = db_avg_rating.get(review["entity_id"], review["entity_type"]) self.assertEqual(avg_rating["rating"], 5.0) self.assertEqual(avg_rating["count"], 1) # Check if avg_rating is updated after a review with rating is deleted db_review.delete(review["id"]) with self.assertRaises(db_exceptions.NoDataFoundException): db_avg_rating.get(review["entity_id"], review["entity_type"])
def test_entity(self): review = self.create_dummy_review() # test review response = self.client.get("/review/%s" % review["id"]) self.assert200(response) self.assertIn(self.review_text, str(response.data)) old_text = review["text"] # test revisions updated_text = "The text has now been updated" updated_rating = 4 db_review.update( review_id=review["id"], drafted=False, text=updated_text, rating=updated_rating, language=review["language"], is_draft=review["is_draft"], ) # test updated text and rating response = self.client.get("/review/{}/revisions/2".format(review["id"])) self.assert200(response) self.assertIn(updated_text, str(response.data)) review_context = self.get_context_variable('review') self.assertEqual(review_context['rating'], 4) # test text and rating for older revision response = self.client.get("/review/{}/revisions/1".format(review["id"])) self.assert200(response) self.assertIn(old_text, str(response.data)) review_context = self.get_context_variable('review') self.assertEqual(review_context['rating'], 3)
def test_list_reports(self): db_spam_report.create(self.revision_id, self.user2.id, "This is a report") db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Updated Review", ) self.review = db_review.get_by_id(self.review["id"]) db_spam_report.create(self.review["last_revision"]["id"], self.user1.id, "This is again a report on the updated review") # two reports on the old revision and one on the new revision. reports, count = db_spam_report.list_reports( review_id=self.review["id"]) # pylint: disable=unused-variable self.assertEqual(count, 3) # get all reports by a user. reports, count = db_spam_report.list_reports(user_id=self.user2.id) self.assertEqual(count, 1) # archive and include all archived reports. # there must be two reports including the archived one. db_spam_report.archive(self.user1.id, self.review["last_revision"]["id"]) reports, count = db_spam_report.list_reports(inc_archived=True) self.assertEqual(count, 3) # there must be one reports excluding the archived one. reports, count = db_spam_report.list_reports(inc_archived=False) self.assertEqual(count, 2)
def test_review_vote_put(self): review = self.create_dummy_review() resp = self.client.put('/review/%s/vote' % review["id"], headers=self.header(self.user), data=json.dumps({"vote": True})) self.assertEqual(resp.json['description'], 'You cannot rate your own review.') resp = self.client.put('/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": True})) self.assert200(resp) resp = self.client.put('/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": False})) self.assert200(resp) # Update to review to only-rating type db_review.update( review_id=review["id"], drafted=review["is_draft"], rating=5, is_draft=False, ) resp = self.client.put('/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": True})) self.assert400(resp, "Voting on reviews without text is not allowed.")
def edit(id): review = get_review_or_404(id) if review["is_draft"] and current_user != review["user"]: raise NotFound(gettext("Can't find a review with the specified ID.")) if review["user"] != current_user: raise Unauthorized(gettext("Only author can edit this review.")) if review["is_hidden"] and not current_user.is_admin(): raise NotFound(gettext("Review has been hidden.")) form = ReviewEditForm(default_license_id=review["license_id"], default_language=review["language"]) if not review["is_draft"]: # Can't change license if review is published. del form.license_choice if form.validate_on_submit(): if review["is_draft"]: license_choice = form.license_choice.data else: license_choice = None if form.text.data == '': form.text.data = None try: db_review.update( review_id=review["id"], drafted=review["is_draft"], text=form.text.data, rating=form.rating.data, is_draft=(form.state.data == 'draft'), license_id=license_choice, language=form.language.data, ) except db_exceptions.BadDataException: raise BadRequest( lazy_gettext("Changing license of a published review\ or converting a published review back to drafts is not allowed." )) flash.success(gettext("Review has been updated.")) return redirect(url_for('.entity', id=review["id"])) else: form.text.data = review["text"] form.rating.data = review["rating"] if review["entity_type"] == 'release_group': spotify_mappings = mbspotify.mappings(str(review["entity_id"])) soundcloud_url = soundcloud.get_url(str(review["entity_id"])) return render_template('review/modify/edit.html', form=form, review=review, entity_type=review["entity_type"], entity=entity, spotify_mappings=spotify_mappings, soundcloud_url=soundcloud_url) return render_template('review/modify/edit.html', form=form, review=review, entity_type=review["entity_type"])
def test_get_revision_number(self): """Test to get the revision number of a revision of a specified review.""" rev_num = revision.get_revision_number(self.review["id"], self.review["last_revision"]["id"]) self.assertEqual(rev_num, 1) db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Updated this review", ) self.review = db_review.get_by_id(self.review["id"]) rev_num = revision.get_revision_number(self.review["id"], self.review["last_revision"]["id"]) self.assertEqual(rev_num, 2)
def review_modify_handler(review_id, user): """Update review with a specified UUID. **OAuth scope:** review :json string text: Text part of review, min length is 25, max is 5000 **(optional)** :json integer rating: Rating part of review, min is 1, max is 5 **(optional)** **NOTE:** Please provide only those parameters which need to be updated :statuscode 200: success :statuscode 400: invalid request :statuscode 403: access denied :statuscode 404: review not found :resheader Content-Type: *application/json* """ def fetch_params(review): try: text = Parser.string('json', 'text', min=REVIEW_TEXT_MIN_LENGTH, max=REVIEW_TEXT_MAX_LENGTH) except MissingDataError: text = review['text'] try: rating = Parser.int('json', 'rating', min=REVIEW_RATING_MIN, max=REVIEW_RATING_MAX) except MissingDataError: rating = review['rating'] if text is None and rating is None: raise InvalidRequest(desc='Review must have either text or rating') return text, rating review = get_review_or_404(review_id) if review["is_hidden"]: raise NotFound("Review has been hidden.") if str(review["user_id"]) != user.id: raise AccessDenied text, rating = fetch_params(review) if (text == review['text']) and (rating == review['rating']): return jsonify(message='Request processed successfully', review=dict(id=review["id"])) db_review.update(review_id=review_id, drafted=review["is_draft"], text=text, rating=rating) return jsonify(message='Request processed successfully', review=dict(id=review["id"]))
def test_get_revision_number(self): """Test to get the revision number of a revision of a specified review.""" rev_num = revision.get_revision_number( self.review["id"], self.review["last_revision"]["id"]) self.assertEqual(rev_num, 1) db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Updated this review", ) self.review = db_review.get_by_id(self.review["id"]) rev_num = revision.get_revision_number( self.review["id"], self.review["last_revision"]["id"]) self.assertEqual(rev_num, 2)
def test_get_reviews(self): reviews = db_users.get_reviews(self.author.id) self.assertEqual(len(reviews), 1) db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Testing Again", ) reviews = db_users.get_reviews(self.author.id) self.assertEqual(len(reviews), 1) self.assertEqual(reviews[0]['creation_time'], self.review_created) two_days_from_now = date.today() + timedelta(days=2) reviews = db_users.get_reviews(self.author.id, from_date=two_days_from_now) self.assertEqual(len(reviews), 0)
def review_modify_handler(review_id, user): """Update review with a specified UUID. **OAuth scope:** review :json string text: Text part of review, min length is 25, max is 5000 **(optional)** :json integer rating: Rating part of review, min is 1, max is 5 **(optional)** **NOTE:** Please provide only those parameters which need to be updated :statuscode 200: success :statuscode 400: invalid request :statuscode 403: access denied :statuscode 404: review not found :resheader Content-Type: *application/json* """ def fetch_params(review): try: text = Parser.string('json', 'text', min=REVIEW_TEXT_MIN_LENGTH, max=REVIEW_TEXT_MAX_LENGTH) except MissingDataError: text = review['text'] try: rating = Parser.int('json', 'rating', min=REVIEW_RATING_MIN, max=REVIEW_RATING_MAX) except MissingDataError: rating = review['rating'] if text is None and rating is None: raise InvalidRequest(desc='Review must have either text or rating') return text, rating review = get_review_or_404(review_id) if review["is_hidden"]: raise NotFound("Review has been hidden.") if str(review["user_id"]) != user.id: raise AccessDenied text, rating = fetch_params(review) if (text == review['text']) and (rating == review['rating']): return jsonify(message='Request processed successfully', review=dict(id=review["id"])) db_review.update( review_id=review_id, drafted=review["is_draft"], text=text, rating=rating ) return jsonify(message='Request processed successfully', review=dict(id=review["id"]))
def rate(): form = RatingEditForm() if form.validate_on_submit(): if current_user.is_blocked: flash.error( gettext("You are not allowed to rate any entity because your " "account has been blocked by a moderator.")) return redirect( url_for('{}.entity'.format(form.entity_type.data), id=form.entity_id.data)) reviews, review_count = db_review.list_reviews( entity_id=form.entity_id.data, entity_type=form.entity_type.data, user_id=current_user.id, ) review = reviews[0] if review_count else None if not review and form.rating.data is None: raise BadRequest( "Cannot create a review with no rating and no text!") if not review and form.rating.data is not None: db_review.create( user_id=current_user.id, entity_id=form.entity_id.data, entity_type=form.entity_type.data, rating=form.rating.data, is_draft=False, ) elif review and review['text'] is None and form.rating.data is None: db_review.delete(review['id']) elif review and review['rating'] != form.rating.data: db_review.update( review_id=review['id'], drafted=review['is_draft'], text=review['text'], rating=form.rating.data, ) # TODO(code-master5): Make this message specify the entity flash.success("We have updated your rating for this entity!") else: flash.error("Error! Could not update the rating...") return redirect( url_for('{}.entity'.format(form.entity_type.data), id=form.entity_id.data))
def test_list_reviews(self): reviews, count = db_review.list_reviews() self.assertEqual(count, 0) self.assertEqual(len(reviews), 0) review = db_review.create( user_id=self.user.id, entity_id="e7aad618-fa86-3983-9e77-405e21796eca", entity_type="release_group", text="Awesome", rating=5, is_draft=False, license_id=self.license["id"], ) reviews, count = db_review.list_reviews() self.assertEqual(count, 1) self.assertEqual(len(reviews), 1) self.assertEqual(reviews[0]["text"], "Awesome") self.assertEqual(reviews[0]["rating"], 5) db_review.update( review_id=review["id"], drafted=review["is_draft"], text="Beautiful!", rating=4, ) reviews, count = db_review.list_reviews() self.assertEqual(count, 1) self.assertEqual(len(reviews), 1) self.assertEqual(reviews[0]["text"], "Beautiful!") self.assertEqual(reviews[0]["rating"], 4) reviews, count = db_review.list_reviews(sort="popularity") self.assertEqual(count, 1) self.assertEqual(len(reviews), 1) reviews, count = db_review.list_reviews(sort="published_on") self.assertEqual(count, 1) self.assertEqual(len(reviews), 1) reviews, count = db_review.list_reviews(sort="random") self.assertEqual(count, 1) self.assertEqual(len(reviews), 1)
def test_get_and_count(self): """Test the get function that gets revisions for the test review ordered by the timestamp and the count function that returns the total number of revisions of a review""" review_id = self.review["id"] count = revision.get_count(review_id) first_revision = revision.get(review_id)[0] self.assertEqual(count, 1) self.assertEqual(first_revision['text'], "Testing!") self.assertEqual(first_revision['rating'], 5) self.assertEqual(type(first_revision['timestamp']), datetime) self.assertEqual(type(first_revision['id']), int) db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Testing Again!", rating=4, ) second_revision = revision.get(review_id)[0] count = revision.get_count(review_id) self.assertEqual(count, 2) self.assertEqual(second_revision['text'], "Testing Again!") self.assertEqual(second_revision['rating'], 4) self.assertEqual(type(second_revision['timestamp']), datetime) self.assertEqual(type(second_revision['id']), int) db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Testing Once Again!", rating=3, ) # Testing offset and limit first_two_revisions = revision.get(review_id, limit=2, offset=1) count = revision.get_count(review_id) self.assertEqual(count, 3) self.assertEqual(first_two_revisions[1]['text'], "Testing!") self.assertEqual(first_two_revisions[0]['text'], "Testing Again!") self.assertEqual(first_two_revisions[1]['rating'], 5) self.assertEqual(first_two_revisions[0]['rating'], 4)
def rate(): form = RatingEditForm() if form.validate_on_submit(): if current_user.is_blocked: flash.error(gettext("You are not allowed to rate any entity because your " "account has been blocked by a moderator.")) return redirect(url_for('{}.entity'.format(form.entity_type.data), id=form.entity_id.data)) reviews, review_count = db_review.list_reviews( entity_id=form.entity_id.data, entity_type=form.entity_type.data, user_id=current_user.id, ) review = reviews[0] if review_count else None if not review and form.rating.data is None: raise BadRequest("Cannot create a review with no rating and no text!") if not review and form.rating.data is not None: db_review.create( user_id=current_user.id, entity_id=form.entity_id.data, entity_type=form.entity_type.data, rating=form.rating.data, is_draft=False, ) elif review and review['text'] is None and form.rating.data is None: db_review.delete(review['id']) elif review and review['rating'] != form.rating.data: db_review.update( review_id=review['id'], drafted=review['is_draft'], text=review['text'], rating=form.rating.data, ) # TODO(code-master5): Make this message specify the entity flash.success("We have updated your rating for this entity!") else: flash.error("Error! Could not update the rating...") return redirect(url_for('{}.entity'.format(form.entity_type.data), id=form.entity_id.data))
def test_list_reports(self): db_spam_report.create(self.revision_id, self.user2.id, "This is a report") db_review.update( review_id=self.review["id"], drafted=self.review["is_draft"], text="Updated Review", ) self.review = db_review.get_by_id(self.review["id"]) db_spam_report.create(self.review["last_revision"]["id"], self.user1.id, "This is again a report on the updated review") # two reports on the old revision and one on the new revision. reports, count = db_spam_report.list_reports(review_id=self.review["id"]) # pylint: disable=unused-variable self.assertEqual(count, 3) # get all reports by a user. reports, count = db_spam_report.list_reports(user_id=self.user2.id) self.assertEqual(count, 1) # archive and include all archived reports. # there must be two reports including the archived one. db_spam_report.archive(self.user1.id, self.review["last_revision"]["id"]) reports, count = db_spam_report.list_reports(inc_archived=True) self.assertEqual(count, 3) # there must be one reports excluding the archived one. reports, count = db_spam_report.list_reports(inc_archived=False) self.assertEqual(count, 2)
def test_review_vote_put(self): review = self.create_dummy_review() resp = self.client.put( '/review/%s/vote' % review["id"], headers=self.header(self.user), data=json.dumps({"vote": True}) ) self.assertEqual(resp.json['description'], 'You cannot rate your own review.') resp = self.client.put( '/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": True}) ) self.assert200(resp) resp = self.client.put( '/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": False}) ) self.assert200(resp) # Update to review to only-rating type db_review.update( review_id=review["id"], drafted=review["is_draft"], rating=5, is_draft=False, ) resp = self.client.put( '/review/%s/vote' % review["id"], headers=self.header(self.another_user), data=json.dumps({"vote": True}) ) self.assert400(resp, "Voting on reviews without text is not allowed.")
def test_update(self): review = db_review.create( user_id=self.user.id, entity_id="e7aad618-fa86-3983-9e77-405e21796eca", entity_type="release_group", text="Testing", rating=5, is_draft=True, license_id=self.license["id"], ) another_license = db_license.create( id="License-2", full_name="Another License", ) # Update review to only rating db_review.update( review_id=review["id"], drafted=review["is_draft"], rating=4, is_draft=False, license_id=another_license["id"], language="es", ) # Checking if contents are updated retrieved_review = db_review.list_reviews()[0][0] self.assertEqual(retrieved_review["text"], None) self.assertEqual(retrieved_review["rating"], 4) self.assertFalse(retrieved_review["is_draft"]) self.assertEqual(retrieved_review["license_id"], another_license["id"]) self.assertEqual(retrieved_review["language"], "es") # Update review to only text db_review.update( review_id=review["id"], drafted=review["is_draft"], text="Testing update", is_draft=False, license_id=another_license["id"], language="es", ) # Checking if contents are updated retrieved_review = db_review.list_reviews()[0][0] self.assertEqual(retrieved_review["text"], "Testing update") self.assertEqual(retrieved_review["rating"], None) # Updating should create a new revision. revisions = db_revision.get(retrieved_review["id"], limit=None) self.assertEqual(len(revisions), 3) self.assertEqual(revisions[0]["timestamp"], retrieved_review["last_revision"]["timestamp"]) self.assertEqual(revisions[0]["text"], retrieved_review["text"]) self.assertEqual(revisions[0]["rating"], retrieved_review["rating"]) # Checking things that shouldn't be allowed with self.assertRaises(db_exceptions.BadDataException): db_review.update( review_id=retrieved_review["id"], drafted=retrieved_review["is_draft"], text="Sucks!", license_id=self.license["id"], ) review = db_review.get_by_id(review["id"]) with self.assertRaises(db_exceptions.BadDataException): db_review.update( review_id=review["id"], drafted=review["is_draft"], text="Sucks!", is_draft=True, )