def test_reset_locked_items(item, pair, old_junior_review, new_senior_review): with Session() as session: session.add(item) session.add(old_junior_review) session.add(new_senior_review) session.add(pair) session.commit() rips = session.query(Review).all() assert len(rips) == 2 response = reset_locked_items(None, None) assert response['statusCode'] == 200 assert "1" in response['body'] rips = session.query(Review).all() assert len(rips) == 1 item = item_handler.get_item_by_id(item.id, session) assert item.in_progress_reviews_level_2 == 1 assert item.in_progress_reviews_level_1 == 0 # reload object instead of refreshing the session pair = session.query(ReviewPair).one() assert pair.junior_review_id == None assert pair.senior_review_id == new_senior_review.id
def post_comment_on_item(event, context=None): """ Creates comment on item from archive """ with Session() as session: logger = logging.getLogger() logger.setLevel(logging.INFO) try: body = json.loads(event['body']) if isinstance( event['body'], str) else event['body'] except: return helper.get_text_response( 400, "Malformed request. Please provide a valid request.", event) try: user_id = helper.cognito_id_from_event(event) body = json.loads(event['body']) if isinstance( event['body'], str) else event['body'] except: return helper.get_text_response( 400, "Malformed request. Could not read user_id from context data.", event) if 'item_id' not in body: return helper.get_text_response( 400, "Malformed request. Please provide an item_id.", event) try: item = item_handler.get_item_by_id(body['item_id'], session) except: return helper.get_text_response(404, "Item not found", event) # Save qualitative_comment if 'comment' in body: try: comment = comment_handler.create_comment( session, comment=body['comment'], user_id=user_id, parent_type='item', parent_id=item.id) response = { "statusCode": 201, 'headers': { "content-type": "application/json; charset=utf-8" }, "body": json.dumps(comment.to_dict()) } return helper.set_cors(response, event) except: return helper.get_text_response( 404, "No qualitative comment found.", event)
def delete_old_reviews_in_progress(rips, is_test, session): for rip in rips: item = item_handler.get_item_by_id(rip.item_id, is_test, session) if rip.is_peer_review == True: item.in_progress_reviews_level_2 -= 1 else: item.in_progress_reviews_level_1 -= 1 session.merge(item) session.delete(rip) session.commit()
def handle_item_closed(event, context): try: helper.log_method_initiated("Send notification", event, logger) if "detail" not in event or "item_id" not in event["detail"]: return BadRequest(event, "Event contains no item_id.", add_cors_headers=False).to_json_string() with Session() as session: item_id = event["detail"]["item_id"] item = item_handler.get_item_by_id(item_id, session) if item is None: return BadRequest( event, f"No item was found with the given item_id [{item_id}].", add_cors_headers=False).to_json_string() item = item_handler.update_item_warning_tags(item, session) rating = int(item.result_score * 25) rating_text = get_rating_text(rating) parameters = dict(rating=rating, rating_text=rating_text, item_id=item.id, content=item.content) for submission in item.submissions: if submission.mail is not None: try: mail_sender.send_notification("item_closed", mail=submission.mail, replacements=parameters) except Exception as e: logger.exception(e) if submission.telegram_id is not None: try: mail_sender.send_notification( "item_closed", telegram_id=submission.telegram_id, replacements=parameters) except Exception as e: logger.exception(e) return Success(event, add_cors_headers=False).to_json_string() except Exception as e: return InternalError(event, "Error sending notification", e, add_cors_headers=False).to_json_string()
def handle_item_rejected(event, context): try: helper.log_method_initiated("Handle item rejected", event, logger) if "detail" not in event or "item_id" not in event["detail"]: return BadRequest(event, "Event contains no item_id.", add_cors_headers=False).to_json_string() with Session() as session: item_id = event["detail"]["item_id"] item = item_handler.get_item_by_id(item_id, session) if item is None: return BadRequest( event, f"No item was found with the given item_id [{item_id}].", add_cors_headers=False).to_json_string() parameters = dict(content=item.content) for submission in item.submissions: if submission.mail is not None: try: mail_sender.send_notification("item_rejected", mail=submission.mail, replacements=parameters) except Exception as e: logger.exception(e) if submission.telegram_id is not None: try: mail_sender.send_notification( "item_rejected", telegram_id=submission.telegram_id, replacements=parameters) except Exception as e: logger.exception(e) return Success(event, add_cors_headers=False).to_json_string() except Exception as e: response = InternalError(event, "Error sending notification", e, add_cors_headers=False).to_json_string() logger.error(response) return response
def test_reset_locked_items(session, item, pair, old_junior_review, new_senior_review): rips = session.query(Review).all() assert len(rips) == 2 response = reset_locked_items(None, None, True, session) assert response['statusCode'] == 200 assert "1" in response['body'] rips = session.query(Review).all() assert len(rips) == 1 item = item_handler.get_item_by_id(item.id, True, session) assert item.in_progress_reviews_level_2 == 1 assert item.in_progress_reviews_level_1 == 0 session.refresh(pair) assert pair.junior_review_id == None assert pair.senior_review_id == new_senior_review.id
def get_item(event, context): helper.log_method_initiated("Get closed item", event, logger) with Session() as session: try: # Get item id from path params item_id = event['pathParameters']['item_id'] except KeyError: return helper.get_text_response(400, 'Could not read item id from path params', event) item = item_handler.get_item_by_id(item_id, session) if item is None: return helper.get_text_response(404, 'No item found with the specified id', event) if item.status != 'closed': return helper.get_text_response(403, 'You are not allowed to access an item, that has not been closed', event) response = { "statusCode": 200, 'headers': {"content-type": "application/json; charset=utf-8"}, "body": json.dumps(item.to_dict(True, True, True, True, True, True)) } return helper.set_cors(response, event)
def test_create_review(): with Session() as session: session = setup_scenarios.create_levels_junior_and_senior_detectives( session) junior_detective1 = user_handler.get_user_by_id("1", session) junior_detective2 = user_handler.get_user_by_id("2", session) senior_detective1 = user_handler.get_user_by_id("11", session) users = user_handler.get_all_users(session) assert len(users) == 10 # Creating an item item = Item() item.content = "This item needs to be checked" item = item_handler.create_item(item, session) items = item_handler.get_all_items(session) assert len(items) == 1 reviews = session.query(Review).all() review_pairs = session.query(ReviewPair).all() assert len(reviews) == 0 assert len(review_pairs) == 0 # Junior detectives accepting item event = event_creator.get_create_review_event( junior_detective1.id, item.id) response = create_review(event, None) assert response['statusCode'] == 201 item = item_handler.get_item_by_id(item.id, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 1 reviews = session.query(Review).all() review_pairs = session.query(ReviewPair).all() assert len(reviews) == 1 assert len(review_pairs) == 1 event = event_creator.get_create_review_event( junior_detective2.id, item.id) create_review(event, None) item = item_handler.get_item_by_id(item.id, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 2 reviews = session.query(Review).all() review_pairs = session.query(ReviewPair).all() assert len(reviews) == 2 assert len(review_pairs) == 2 # Senior detective accepting item event = event_creator.get_create_review_event( senior_detective1.id, item.id) create_review(event, None) item = item_handler.get_item_by_id(item.id, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_2 == 1 reviews = session.query(Review).all() review_pairs = session.query(ReviewPair).all() assert len(reviews) == 3 assert len(review_pairs) == 2
def test_verification_process_best_case(monkeypatch): monkeypatch.setenv("STAGE", "dev") monkeypatch.setenv("MOTO", "1") monkeypatch.setenv("CORS_ALLOW_ORIGIN", "http://*****:*****@test.de' submission.status = 'confirmed' session.add(submission) session.commit() items = item_handler.get_all_items(session) assert len(items) == 1 # Junior detectives accepting item jr1 = review_handler.create_review(junior_detective1, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 1 jr2 = review_handler.create_review(junior_detective2, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 2 jr3 = review_handler.create_review(junior_detective3, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 3 jr4 = review_handler.create_review(junior_detective4, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 4 with pytest.raises(Exception): review_handler.create_review(junior_detective5, item, session) # Senior detectives accepting item sr1 = review_handler.create_review(senior_detective1, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 1 sr2 = review_handler.create_review(senior_detective2, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 2 sr3 = review_handler.create_review(senior_detective3, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 3 sr4 = review_handler.create_review(senior_detective4, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 4 with pytest.raises(Exception): review_handler.create_review(senior_detective5, item, session) pairs = review_pair_handler.get_review_pairs_by_item(item.id, session) assert len(pairs) == 4 # Detectives reviewing item reviews = [jr1, jr2, jr3, jr4, sr1, sr2, sr3, sr4] for review in reviews: event = event_creator.get_review_event( review, item.id, "in progress", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event( review, item.id, "closed", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 # reload object instead of refreshing the session item = item_handler.get_item_by_id(item.id, session) item = item_handler.update_item_warning_tags(item, session) assert item.status == 'closed' assert item.in_progress_reviews_level_1 == 0 assert item.in_progress_reviews_level_2 == 0 assert item.open_reviews_level_1 == 0 assert item.open_reviews_level_2 == 0 assert item.open_reviews == 0 assert item.close_timestamp is not None assert item.warning_tags_calculated == True assert item.result_score == 1 item_dict = item.to_dict(with_warnings=True) assert 'warning_tags' in item_dict assert len(item_dict['warning_tags']) > 0 assert 'text' in item_dict['warning_tags'][0] assert 'icon' in item_dict['warning_tags'][0] assert item_dict['result_score'] == 0 session.expire_all()
def test_verification_process_worst_case(monkeypatch): monkeypatch.setenv("CORS_ALLOW_ORIGIN", "http://localhost:4200") with Session() as session: session = setup_scenarios.create_levels_junior_and_senior_detectives( session) session = setup_scenarios.create_questions(session) junior_detective1 = user_handler.get_user_by_id("1", session) junior_detective2 = user_handler.get_user_by_id("2", session) junior_detective3 = user_handler.get_user_by_id("3", session) junior_detective4 = user_handler.get_user_by_id("4", session) junior_detective5 = user_handler.get_user_by_id("5", session) senior_detective1 = user_handler.get_user_by_id("11", session) senior_detective2 = user_handler.get_user_by_id("12", session) senior_detective3 = user_handler.get_user_by_id("13", session) senior_detective4 = user_handler.get_user_by_id("14", session) senior_detective5 = user_handler.get_user_by_id("15", session) users = user_handler.get_all_users(session) assert len(users) == 10 # Creating an item item = Item() item.content = "This item needs to be checked" item.status = 'open' item.item_type_id = "Type1" item = item_handler.create_item(item, session) items = item_handler.get_all_items(session) assert len(items) == 1 # Junior detectives accepting item jr1 = review_handler.create_review(junior_detective1, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 1 jr2 = review_handler.create_review(junior_detective2, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 2 jr3 = review_handler.create_review(junior_detective3, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 3 jr4 = review_handler.create_review(junior_detective4, item, session) assert item.open_reviews_level_1 == 4 assert item.in_progress_reviews_level_1 == 4 with pytest.raises(Exception): review_handler.create_review(junior_detective5, item, session) # Senior detectives accepting item sr1 = review_handler.create_review(senior_detective1, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 1 sr2 = review_handler.create_review(senior_detective2, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 2 sr3 = review_handler.create_review(senior_detective3, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 3 sr4 = review_handler.create_review(senior_detective4, item, session) assert item.open_reviews_level_2 == 4 assert item.in_progress_reviews_level_2 == 4 with pytest.raises(Exception): review_handler.create_review(senior_detective5, item, session) pairs = review_pair_handler.get_review_pairs_by_item(item.id, session) assert len(pairs) == 4 # Detective without review in progress trying to get question junior_reviews = [jr1, jr2, jr3, jr4] senior_reviews = [sr1, sr2, sr3, sr4] for review in junior_reviews: event = event_creator.get_review_event( review, item.id, "in progress", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event( review, item.id, "closed", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 for review in senior_reviews: event = event_creator.get_review_event( review, item.id, "in progress", review.user_id, 4) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event( review, item.id, "closed", review.user_id, 4) response = update_review(event, None) assert response['statusCode'] == 200 # reload object instead of refreshing the session item = item_handler.get_item_by_id(item.id, session) assert item.status == 'open' assert item.in_progress_reviews_level_1 == 0 assert item.in_progress_reviews_level_2 == 0 assert item.open_reviews_level_1 == 4 assert item.open_reviews_level_2 == 4 assert item.open_reviews == 4 session.expire_all()
def update_item(event, context, is_test=False, session=None): """Updates an item. Parameters ---------- event: dict, required API Gateway Lambda Proxy Input Format #api-gateway-simple-proxy-for-lambda-input-format Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ API Gateway Lambda Proxy Output Format: application/json Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html """ helper.log_method_initiated("Update item", event, logger) if session is None: session = get_db_session(is_test, session) item_id = event['pathParameters']['item_id'] item = item_handler.get_item_by_id(item_id, is_test, session) if item is None: response = { "statusCode": 404, "body": "No item found with the specified id." } response_cors = helper.set_cors(response, event, is_test) return response_cors body = event['body'] body = json.loads(body) if isinstance(body, str) else body for key in body: if hasattr(item, key): if not isinstance(body[key], dict) and not isinstance( body[key], list): setattr(item, key, body[key]) else: response = { "statusCode": 400, "body": "Could not update item. Provided input does not match item model." } response_cors = helper.set_cors(response, event, is_test) return response_cors item = update_object(item, is_test, session) if item is None: response = { "statusCode": 500, "body": "Could not write changes to db. Event id: {}".format( event['requestContext']['requestId']) } response_cors = helper.set_cors(response, event, is_test) return response_cors response = {"statusCode": 200, "body": json.dumps(item.to_dict())} response_cors = helper.set_cors(response, event, is_test) return response_cors
def extract_claim(event, context): """extracts claim from item content Parameters ---------- event: dict, required item context: object, required Lambda Context runtime methods and attributes Returns ------ titles: list of url titles, first entry is "" for item content text: list of url paragraphs, first entry is item content concatenation: Text: concatenation of all paragraphs """ logger.info('Calling extract_claim with event') logger.info(event) with Session() as session: # Use UTF-8 encoding for comprehend if 'item' in event: if 'content' in event['item']: item_content = str(event['item']['content']) else: logger.error("The item has no content!") raise Exception('Please provide an item with content!') if 'id' not in event['item']: logger.error("The item has no ID!") raise Exception('Please provide an item with an ID!') else: # extract item item_id = event['item']['id'] item = item_handler.get_item_by_id(item_id, session) if item is None: raise Exception('Couldn\'t load item with id: ' + item_id) else: logger.error("There is no item!") raise Exception('Please provide an item!') # remove urls from item_content for itemUrl in item.urls: item_content = item_content.replace(itemUrl.url.url, '') # titles contains as first entry a placeholder for item_content # titles = ["", ] title = "" # text contains as first entry a placeholder for item_content # text = [item_content, ] allText = item_content # open all urls and extract the paragraphs+ first_title = "" for itemUrl in item.urls: url = itemUrl.url.url # set headers for a web browser headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" } resp = requests.get(url, headers=headers) read_content = resp.content # read_content_hidden = read_content.replace(b'<!--', b'<!') soup = BeautifulSoup(read_content, 'html.parser') # get the title of the web page titles = soup.find_all('title') title = "" if len(titles) > 0: title = '{} '.format(titles[0].text) # get the description of the web page description = soup.find("meta", {"name": "description"}) page_description = "" if description: page_description = description["content"] # get all paragraphs of the web page pAll = soup.find_all('p') paragraphs = '' # concatenate all paragraphs for each url for t in pAll: paragraphs += '{} '.format(t.text) # As more paragraphs are appended as higher is the probability that the paragraphs do not belong to the # main article if len(paragraphs) > 50: break # use the title of the first URL as "title" attribute later if first_title == "": first_title = title # use only title as claim, maybe this enhances the quality of entities and phrases allText += "\n" + title if len(allText) < 50: allText += "\n" + page_description if len(allText) < 50: allText += "\n" + paragraphs if len(allText) >= 4800: allText = allText[:4799] return { "title": first_title, # "text": text, "concatenation": { "Text": allText } }
def get_online_factcheck(event, context): logger = logging.getLogger() logger.setLevel(logging.INFO) helper.log_method_initiated("Get online factchecks by item id", event, logger) with Session() as session: try: # get id (str) from path id = event['pathParameters']['item_id'] try: item = item_handler.get_item_by_id(id, session) if item.language == None: raise Exception("Language of Claim not recognized.") entity_objects = entity_handler.get_entities_by_itemid(id, session) phrase_objects = keyphrase_handler.get_phrases_by_itemid_db(id, session) entities = [] for obj in entity_objects: entities.append(obj.to_dict()['entity']) phrases = [] for obj in phrase_objects: phrases.append(obj.to_dict()['phrase']) sfc_event = { "item": item.to_dict(), "KeyPhrases": phrases, "Entities": entities, } context = "" factcheck = SearchFactChecks.get_FactChecks(sfc_event, context) if 'claimReview' in factcheck[0]: factcheck_dict = { "id": "0", "url": factcheck[0]['claimReview'][0]['url']} if 'title' in factcheck[0]['claimReview'][0]: factcheck_dict["title"] = factcheck[0]['claimReview'][0]['title'] elif 'textualRating' in factcheck[0]['claimReview'][0]: factcheck_dict["title"] = factcheck[0]['claimReview'][0]['textualRating'] response = { "statusCode": 200, 'headers': {"content-type": "application/json; charset=utf-8"}, "body": json.dumps(factcheck_dict) } else: response = { "statusCode": 404, "body": "No factcheck found." } except Exception: response = { "statusCode": 404, "body": "No factcheck found. Stacktrace: {}".format(traceback.format_exc()) } except Exception: response = { "statusCode": 400, "body": "Could not get item ID. Check HTTP POST payload. Stacktrace: {}".format(traceback.format_exc()) } response_cors = helper.set_cors(response, event) return response_cors
def test_get_open_items_for_user(self, monkeypatch): monkeypatch.setenv("DBNAME", "Test") session = get_db_session(True, None) session = setup_scenarios.create_levels_junior_and_senior_detectives( session) session = setup_scenarios.create_questions(session) junior_detective1 = user_handler.get_user_by_id("1", True, session) junior_detective2 = user_handler.get_user_by_id("2", True, session) junior_detective3 = user_handler.get_user_by_id("3", True, session) junior_detective4 = user_handler.get_user_by_id("4", True, session) junior_detective5 = user_handler.get_user_by_id("5", True, session) senior_detective1 = user_handler.get_user_by_id("11", True, session) # Creating 5 items item1 = Item() item1.content = "Item 1" item1.status = "open" item1.item_type_id = "Type1" item1 = item_handler.create_item(item1, True, session) item2 = Item() item2.content = "Item 2" item2.status = "open" item2.item_type_id = "Type1" item2 = item_handler.create_item(item2, True, session) item3 = Item() item3.content = "Item 3" item3.status = "open" item3.item_type_id = "Type1" item3 = item_handler.create_item(item3, True, session) item4 = Item() item4.content = "Item 4" item4.status = "open" item4.item_type_id = "Type1" item4 = item_handler.create_item(item4, True, session) item5 = Item() item5.content = "Item 5" item5.status = "open" item5.item_type_id = "Type1" item5 = item_handler.create_item(item5, True, session) items = item_handler.get_all_items(True, session) assert len(items) == 5 open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_items_for_senior) == 5 open_items_for_junior = item_handler.get_open_items_for_user( junior_detective1, 5, True, session)['items'] assert len(open_items_for_junior) == 5 # JuniorDetective 1 accepting item 1 jr1 = review_handler.create_review(junior_detective1, item1, True, session) open_item_after_accept = item_handler.get_open_items_for_user( junior_detective1, 5, True, session)['items'] assert len(open_item_after_accept) == 1 item1 = item_handler.get_item_by_id(item1.id, True, session) assert item1.in_progress_reviews_level_1 == 1 # Accepting event again should not create a new review review_handler.create_review(junior_detective1, item1, True, session) # app.create_review(accept_event, None, True, session) item1 = item_handler.get_item_by_id(item1.id, True, session) assert item1.in_progress_reviews_level_1 == 1 # JuniorDetective 1 finishing review event = event_creator.get_review_event(jr1, item1.id, "in progress", jr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 event = event_creator.get_review_event(jr1, item1.id, "closed", jr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 # For JuniorDetective1 only 4 cases should be available open_items_after_submission = item_handler.get_open_items_for_user( junior_detective1, 5, True, session)['items'] assert len(open_items_after_submission) == 4 open_items_limit_3 = item_handler.get_open_items_for_user( junior_detective1, 3, True, session)['items'] assert len(open_items_limit_3) == 3 open_items_after_other_review = item_handler.get_open_items_for_user( junior_detective4, 5, True, session)['items'] assert len(open_items_after_other_review) == 5 # 4 Junior Detectives reviewing Item 2 jr1 = review_handler.create_review(junior_detective1, item2, True, session) jr2 = review_handler.create_review(junior_detective2, item2, True, session) jr3 = review_handler.create_review(junior_detective3, item2, True, session) jr4 = review_handler.create_review(junior_detective4, item2, True, session) reviews = [jr1, jr2, jr3, jr4] for review in reviews: event = event_creator.get_review_event(review, item2.id, "in progress", review.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 event = event_creator.get_review_event(review, item2.id, "closed", review.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 # 4 Cases should be available for Detective 5 open_items_after_other_review = item_handler.get_open_items_for_user( junior_detective5, 5, True, session)['items'] assert len(open_items_after_other_review) == 4 # 5 cases should be available for senior open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_items_for_senior) == 5 # Senior detective accepting item 1 sr1 = review_handler.create_review(senior_detective1, item1, True, session) open_item_after_accept = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_item_after_accept) == 1 # Senior detective finishing review event = event_creator.get_review_event(sr1, item1.id, "in progress", sr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 event = event_creator.get_review_event(sr1, item1.id, "closed", sr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 # For SeniorDetective1 only 4 cases should be available open_items_after_submission = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_items_after_submission) == 4 # SeniorDetective 1 accepting item 3 sr1 = review_handler.create_review(senior_detective1, item3, True, session) open_item_after_accept = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_item_after_accept) == 1 item3 = item_handler.get_item_by_id(item3.id, True, session) assert item3.in_progress_reviews_level_2 == 1 # Accepting event again should not create a new review review_handler.create_review(senior_detective1, item3, True, session) item3 = item_handler.get_item_by_id(item3.id, True, session) assert item3.in_progress_reviews_level_2 == 1 # SeniorDetective 1 finishing review event = event_creator.get_review_event(sr1, item3.id, "in progress", sr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 event = event_creator.get_review_event(sr1, item3.id, "closed", sr1.user_id, 1, session) response = update_review(event, None, True, session) assert response['statusCode'] == 200 open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, True, session)['items'] assert len(open_items_for_senior) == 3 event = { "requestContext": { "identity": { "cognitoAuthenticationProvider": "...CognitoSignIn:{}".format(senior_detective1.id) } } } response = get_open_items(event, None, True, session) assert 'is_open_review' in response['headers'] assert response['headers']['is_open_review'] == "False" body = json.loads(response['body']) assert len(body) == 3
def create_review(event, context, is_test=False, session=None): """Creates a new review. Parameters ---------- - user_id is retrieved from the event - item_id is retrieved from query parameters Returns ------ - Status code 201 (Created) - The newly created review """ logger = logging.getLogger() logger.setLevel(logging.INFO) helper.log_method_initiated("Create Review", event, logger) if session == None: session = connection_handler.get_db_session(False, None) try: # get item id from body item_id = json.loads(event['body'])['item_id'] if isinstance( event['body'], str) else event['body']['item_id'] # get cognito id user_id = helper.cognito_id_from_event(event) except Exception: return helper.get_text_response( 400, "Malformed request. Please provide a valid request.", event, is_test) try: # get user and item from the db user = user_handler.get_user_by_id(user_id, is_test, session) except Exception: return helper.get_text_response(404, "No user found.", event, is_test) item = item_handler.get_item_by_id(item_id, is_test, session) if item is None: return helper.get_text_response(404, "No item found.", event, is_test) # Try to accept item try: review = review_handler.create_review(user, item, is_test, session) response = { "statusCode": 201, 'headers': { "content-type": "application/json; charset=utf-8" }, "body": json.dumps(review.to_dict_with_questions_and_answers()) } response_cors = helper.set_cors(response, event, is_test) return response_cors except: return helper.get_text_response( 500, "Internal server error. Stacktrace: {}".format( traceback.format_exc()), event, is_test)
def test_get_open_items_for_user(self, monkeypatch): monkeypatch.setenv("CORS_ALLOW_ORIGIN", "http://localhost:4200") with Session() as session: session = setup_scenarios.create_levels_junior_and_senior_detectives( session) session = setup_scenarios.create_questions(session) junior_detective1 = user_handler.get_user_by_id("1", session) junior_detective2 = user_handler.get_user_by_id("2", session) junior_detective3 = user_handler.get_user_by_id("3", session) junior_detective4 = user_handler.get_user_by_id("4", session) junior_detective5 = user_handler.get_user_by_id("5", session) senior_detective1 = user_handler.get_user_by_id("11", session) # Creating 5 items item1 = Item() item1.content = "Item 1" item1.status = "open" item1.item_type_id = "Type1" item1.open_timestamp = datetime.now() + timedelta(seconds=1) item1 = item_handler.create_item(item1, session) url = URL() url.id = str(uuid4()) url.url = 'www.test.com' item_url = ItemURL() item_url.id = str(uuid4()) item_url.item_id = item1.id item_url.url_id = url.id session.add_all([url, item_url]) item2 = Item() item2.content = "Item 2" item2.status = "open" item2.item_type_id = "Type1" item2.open_timestamp = datetime.now() + timedelta(seconds=2) item2 = item_handler.create_item(item2, session) item3 = Item() item3.content = "Item 3" item3.status = "open" item3.item_type_id = "Type1" item3.open_timestamp = datetime.now() + timedelta(seconds=3) item3 = item_handler.create_item(item3, session) item4 = Item() item4.content = "Item 4" item4.status = "open" item4.item_type_id = "Type1" item4.open_timestamp = datetime.now() + timedelta(seconds=4) item4 = item_handler.create_item(item4, session) item5 = Item() item5.content = "Item 5" item5.status = "open" item5.item_type_id = "Type1" item5.open_timestamp = datetime.now() + timedelta(seconds=5) item5 = item_handler.create_item(item5, session) items = item_handler.get_all_items(session) assert len(items) == 5 open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_items_for_senior) == 5 open_items_for_junior = item_handler.get_open_items_for_user( junior_detective1, 5, session)['items'] assert len(open_items_for_junior) == 5 # JuniorDetective 1 accepting item 1 jr1 = review_handler.create_review(junior_detective1, item1, session) open_item_after_accept = item_handler.get_open_items_for_user( junior_detective1, 5, session)['items'] assert len(open_item_after_accept) == 1 item1 = item_handler.get_item_by_id(item1.id, session) assert item1.in_progress_reviews_level_1 == 1 # Accepting event again should not create a new review review_handler.create_review(junior_detective1, item1, session) # app.create_review(accept_event, None, True, session) item1 = item_handler.get_item_by_id(item1.id, session) assert item1.in_progress_reviews_level_1 == 1 # JuniorDetective 1 finishing review event = event_creator.get_review_event(jr1, item1.id, "in progress", jr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event(jr1, item1.id, "closed", jr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 # For JuniorDetective1 only 4 cases should be available open_items_after_submission = item_handler.get_open_items_for_user( junior_detective1, 5, session)['items'] assert len(open_items_after_submission) == 4 open_items_limit_3 = item_handler.get_open_items_for_user( junior_detective1, 3, session)['items'] assert len(open_items_limit_3) == 3 open_items_after_other_review = item_handler.get_open_items_for_user( junior_detective4, 5, session)['items'] assert len(open_items_after_other_review) == 5 # 4 Junior Detectives reviewing Item 2 item2 = item_handler.get_item_by_id(item2.id, session) jr1 = review_handler.create_review(junior_detective1, item2, session) jr2 = review_handler.create_review(junior_detective2, item2, session) jr3 = review_handler.create_review(junior_detective3, item2, session) jr4 = review_handler.create_review(junior_detective4, item2, session) reviews = [jr1, jr2, jr3, jr4] for review in reviews: event = event_creator.get_review_event(review, item2.id, "in progress", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event(review, item2.id, "closed", review.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 # 4 Cases should be available for Detective 5 open_items_after_other_review = item_handler.get_open_items_for_user( junior_detective5, 5, session)['items'] assert len(open_items_after_other_review) == 4 # 5 cases should be available for senior open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_items_for_senior) == 5 # Senior detective accepting item 1 sr1 = review_handler.create_review(senior_detective1, item1, session) open_item_after_accept = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_item_after_accept) == 1 # Senior detective finishing review event = event_creator.get_review_event(sr1, item1.id, "in progress", sr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event(sr1, item1.id, "closed", sr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 # For SeniorDetective1 only 4 cases should be available open_items_after_submission = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_items_after_submission) == 4 # SeniorDetective 1 accepting item 3 item3 = item_handler.get_item_by_id(item3.id, session) sr1 = review_handler.create_review(senior_detective1, item3, session) open_item_after_accept = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_item_after_accept) == 1 item3 = item_handler.get_item_by_id(item3.id, session) assert item3.in_progress_reviews_level_2 == 1 # Accepting event again should not create a new review review_handler.create_review(senior_detective1, item3, session) item3 = item_handler.get_item_by_id(item3.id, session) assert item3.in_progress_reviews_level_2 == 1 # SeniorDetective 1 finishing review event = event_creator.get_review_event(sr1, item3.id, "in progress", sr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 event = event_creator.get_review_event(sr1, item3.id, "closed", sr1.user_id, 1) response = update_review(event, None) assert response['statusCode'] == 200 # Accepting closed item again should not create a new review event = event_creator.get_create_review_event( senior_detective1.id, item3.id) response = create_review.create_review(event, None) assert response['statusCode'] == 500 open_items_for_senior = item_handler.get_open_items_for_user( senior_detective1, 5, session)['items'] assert len(open_items_for_senior) == 3 event = { "requestContext": { "identity": { "cognitoAuthenticationProvider": "...CognitoSignIn:{}".format(senior_detective1.id) } } } response = get_open_items(event, None) # assert 'is_open_review' in response['headers'] # assert response['headers']['is_open_review'] == "False" body = json.loads(response['body']) assert 'is_open_review' in body assert body['is_open_review'] is False assert len(body['items']) == 3