def test_change_password(_nondemo_client): new_password = "******" old_password = "******" response = _nondemo_client.post( "/user/change-password", json={ "current_password": "******", "new_password": new_password }, content_type="application/json", ) assert response.status_code == 401 assert response.json.get( "error" ) == "Username and current password incorrect. Please try again." # verifies old password is what it should with session_scope() as db_session: observed_user = db_session.query(User).filter( User.user == NONDEMO_USER).first() assert argon2.verify(old_password, observed_user.argon_password) # changes the password response = _nondemo_client.post( "/user/change-password", json={ "current_password": old_password, "new_password": new_password }, content_type="application/json", ) assert response.status_code == 200 with session_scope() as db_session: # checks that the password is changed observed_user = db_session.query(User).filter( User.user == NONDEMO_USER).first() assert argon2.verify(new_password, observed_user.argon_password) # revert passward for future tests response = _nondemo_client.post( "/user/change-password", json={ "current_password": new_password, "new_password": old_password }, content_type="application/json", ) assert response.status_code == 200 with session_scope() as db_session: # checks that the old_password is back observed_user = db_session.query(User).filter( User.user == NONDEMO_USER).first() assert argon2.verify(old_password, observed_user.argon_password)
def get_all_hpos(): with session_scope() as db_session: individuals = _get_authorized_individuals(db_session) sqlq_all_hpos = sql.SQL(""" select distinct t.hpo_id, t."name" from phenopolis.individual_feature ife join hpo.term t on t.id = ife.feature_id where ife.individual_id = any(%s) and ife.type in ('observed') """) try: limit, offset = _get_pagination_parameters() if limit > MAX_PAGE_SIZE: return ( jsonify(message="The maximum page size for variants is {}". format(MAX_PAGE_SIZE)), 400, ) sqlq = sqlq_all_hpos + sql.SQL("limit {} offset {}".format( limit, offset)) with get_db() as conn: with conn.cursor() as cur: cur.execute(sqlq, [[x.id for x in individuals]]) hpos = cursor2dict(cur) process_for_display(db_session, hpos) except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(hpos), 200
def get_all_genes(): with session_scope() as db_session: try: limit, offset = _get_pagination_parameters() if limit > MAX_PAGE_SIZE: return ( jsonify(message="The maximum page size for genes is {}". format(MAX_PAGE_SIZE)), 400, ) sqlq_end = sql.SQL(""" and exists ( select 1 from public.users_individuals ui join phenopolis.individual i on i.phenopolis_id = ui.internal_id join phenopolis.individual_gene ig on i.id = ig.individual_id and ig.gene_id = g.identifier where ui."user" = %(user)s) """) sqlq = sqlq_main + sqlq_end + sql.SQL("limit {} offset {}".format( limit, offset)) with get_db() as conn: with conn.cursor() as cur: cur.execute(sqlq, { "user": session[USER], "hga": HG_ASSEMBLY }) genes = cursor2dict(cur) process_for_display(db_session, genes) except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(genes), 200
def test_create_user(_not_logged_in_client): payload = {"confirmation_url": "http://phenopolis.org/confirm/"} response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing user name" payload["user"] = "******" response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing password" payload["argon_password"] = "******" response = _not_logged_in_client.post("/user", json=payload, content_type="application/json") assert response.status_code == 400 assert response.json.get("error") == "Missing email" user_name = "test_register1" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" _assert_create_user(db_session, _not_logged_in_client, user) finally: # cleans the database _clean_test_users(db_session, user_name)
def change_password(): try: username = session[USER] data = _get_json_payload() password = data.get("current_password") new_password = data.get("new_password") if is_demo_user(): return ( jsonify( error= "You do not have permission to change the password for username 'demo'." ), 403, ) if not check_auth(username, password): application.logger.info("Change password:- Login Failed") return ( jsonify( error= "Username and current password incorrect. Please try again." ), 401, ) application.logger.info("Login success, changing password") with session_scope() as db_session: user = db_session.query(User).filter(User.user == username).first() user.argon_password = argon2.hash(new_password) msg = "Password for username '" + username + "' changed. You are logged in as '" + username + "'." except PhenopolisException as e: application.logger.error(str(e)) return jsonify(success=False, error=str(e)), e.http_status return jsonify(success=msg), 200
def test_delete_individual_for_user(_nondemo_client): # creates an individual individual = Individual() test_external_id = "for_test_Sample" individual.external_id = test_external_id individual.sex = "M" response = _nondemo_client.post("/individual", json=[individual.as_dict()], content_type="application/json") assert response.status_code == 200 # confirms existence of new individual with session_scope() as db_session: observed_individual = db_session.query(Individual).filter(Individual.external_id == test_external_id).first() assert observed_individual is not None, "Empty newly created individual" # deletes individual response = _nondemo_client.delete( f"/individual/{observed_individual.phenopolis_id}", content_type="application/json" ) assert response.status_code == 200 # confirms it does not exist observed_individual = db_session.query(Individual).filter(Individual.external_id == test_external_id).first() assert observed_individual is None, "Deletion was not successful" # try to delete non-existent individual response = _nondemo_client.delete("/individual/PH00000000", content_type="application/json") assert response.status_code == 404 # try to delete a non-authorised patient for a given user response = _nondemo_client.delete("/individual/PH00008258", content_type="application/json") assert response.status_code == 404, "PH00008258 exists but access not authorised"
def update_patient_data(phenopolis_id): if is_demo_user(): return jsonify(error="Demo user not authorised"), 405 with session_scope() as db_session: individual = _fetch_authorized_individual(db_session, phenopolis_id) # unauthorized access to individual if not individual: response = jsonify( message= "Sorry, either the patient does not exist or you are not permitted to see this patient" ) response.status_code = 404 return response application.logger.debug(request.form) consanguinity = request.form.get("consanguinity_edit[]", "unknown") gender = request.form.get("gender_edit[]", "unknown") genes = request.form.getlist("genes[]") features = request.form.getlist("feature[]") if not len(features): features = ["All"] # TODO: simplify this gender translation unk_obj = MAPPING_SEX_REPRESENTATIONS.get("unknown") gender = MAPPING_SEX_REPRESENTATIONS.get(gender, unk_obj) hpos = _get_hpos(features) _update_individual(consanguinity, gender, genes, hpos, individual) return jsonify({"success": True}), 200
def test_create_and_confirm_user(_not_logged_in_client): user_name = "test_register2" email = "*****@*****.**" with session_scope() as db_session: try: # creates a user user = User() user.user = user_name user.argon_password = "******" user.email = email _assert_create_user(db_session, _not_logged_in_client, user) # confirms the user confirmation_token = generate_confirmation_token(user.email) response = _not_logged_in_client.get( f"/user/confirm/{confirmation_token}") assert response.status_code == 200 observed_user = db_session.query(User).filter( User.user == user.user).first() assert observed_user.user == user.user assert observed_user.enabled, "Enabled field is not true" assert observed_user.confirmed, "Confirmed field is not true" assert observed_user.confirmed_on is not None finally: # cleans the database _clean_test_users(db_session, user_name)
def test_delete_user_itself(_not_logged_in_client): user_name = "temp_user" with session_scope() as db_session: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" _assert_create_user(db_session, _not_logged_in_client, user) confirmation_token = generate_confirmation_token(user.email) response = _not_logged_in_client.get( f"/user/confirm/{confirmation_token}") assert response.status_code == 200 # login with new user resp = _not_logged_in_client.post("/login", json={ "user": f"{user.user}", "password": f"{user.argon_password}" }) assert resp.status_code == 200 assert resp.json == { "success": "Authenticated", "username": f"{user.user}" } # # try to delete another user response = _not_logged_in_client.delete( "/user/demo", content_type="application/json") assert response.status_code == 403 # user deletes itself response = _not_logged_in_client.delete( f"/user/{user_name}", content_type="application/json") assert response.status_code == 200
def test_create_multiple_individuals(_admin_client): individual = Individual() test_external_id = "for_test_Sample" individual.external_id = test_external_id individual.sex = "M" individual.genes = "DRAM2" individual.observed_features = "HP:0000001" individual2 = Individual() test_external_id2 = "for_test_Sample2" individual2.external_id = test_external_id2 individual2.sex = "F" response = _admin_client.post( "/individual", json=[individual.as_dict(), individual2.as_dict()], content_type="application/json" ) assert response.status_code == 200 with session_scope() as db_session: observed_individual = db_session.query(Individual).filter(Individual.external_id == test_external_id).first() assert observed_individual is not None, "Empty newly created individual" assert observed_individual.sex.name == individual.sex observed_individual2 = db_session.query(Individual).filter(Individual.external_id == test_external_id2).first() assert observed_individual2 is not None, "Empty newly created individual" assert observed_individual2.sex.name == individual2.sex # cleans the database _clean_test_individuals(_admin_client, db_session, test_external_id) _clean_test_individuals(_admin_client, db_session, test_external_id2)
def phenopolis_statistics(): with session_scope() as db_session: # counts individuals total_patients = _count_all_individuals() male_patients = _count_all_individuals_by_sex(Sex.M) female_patients = _count_all_individuals_by_sex(Sex.F) unknown_patients = _count_all_individuals_by_sex(Sex.U) # counts variants total_variants = count_variants() # counts HPOs individuals = _get_authorized_individuals(db_session) count_observed_features, count_unobserved_features = count_hpos( individuals) # counts genes total_genes = count_genes(individuals) return jsonify( exomes=total_patients, males=male_patients, females=female_patients, unknowns=unknown_patients, total_variants=total_variants, observed_features=count_observed_features, unobserved_features=count_unobserved_features, total_genes=total_genes, version_number=VERSION, )
def create_user_individual(): try: new_user_individuals = _get_json_payload(UserIndividual) for u in new_user_individuals: _check_user_individual_valid(u) except PhenopolisException as e: application.logger.error(str(e)) return jsonify(success=False, error=str(e)), e.http_status with session_scope() as db_session: request_ok = True message = "User individuals were created" try: # insert user individuals for u in new_user_individuals: # TODO: should not all these checks happen at the DB? _check_db_integrity_user_individual(db_session, u) db_session.add(u) except Exception as e: application.logger.exception(e) request_ok = False message = str(e) if not request_ok: return jsonify(success=False, message=message), 500 else: return jsonify(success=True, message=message), 200
def create_classification(): with session_scope() as db_session: try: classifications = _get_json_payload( IndividualVariantClassification) for c in classifications: _check_classification_valid(db_session, c) except PhenopolisException as e: application.logger.error(str(e)) response = jsonify(success=False, error=str(e)) response.status_code = e.http_status return response request_ok = True http_status = 200 message = "Variant classifications were created" try: # generate a new unique id for the individual for c in classifications: # insert individual c.user_id = session[ USER] # whatever value comes here we ensure the actual user is stored c.id = None # this one should be set by the database c.classified_on = None # this one should be set by the database db_session.add(c) except PhenopolisException as e: application.logger.exception(e) request_ok = False message = str(e) http_status = e.http_status return jsonify(success=request_ok, message=message), http_status
def create_individual(): if is_demo_user(): return jsonify(error="Demo user not authorised"), 405 # checks individuals validity with session_scope() as db_session: try: dlist = _get_json_payload() new_individuals = [] for d in dlist: genes = [] if d.get("observed_features"): feats = d.pop("observed_features").split(",") else: feats = [] if d.get("genes") or d.get("genes") == "": genes = d.pop("genes").split(",") i = Individual(**d) _check_individual_valid(db_session, i) new_individuals.append((i, genes, feats)) except PhenopolisException as e: application.logger.error(str(e)) return jsonify(success=False, error=str(e)), e.http_status request_ok = True http_status = 200 message = "Individuals were created" ids_new_individuals = [] try: # generate a new unique id for the individual for trio in new_individuals: i, g, f = trio # insert individual db_session.add(i) # to refresh i and with new id and phenopolis_id, both lines below needed (black magic) db_session.query(Individual).count() db_session.refresh(i) # add entry to user_individual # TODO: enable access to more users than the creator db_session.add( UserIndividual(user=session[USER], internal_id=i.phenopolis_id)) if session[USER] != ADMIN_USER: db_session.add( UserIndividual(user=ADMIN_USER, internal_id=i.phenopolis_id)) db_session.commit() _insert_genes(i, g) _insert_feats(i, f) ids_new_individuals.append(i.phenopolis_id) except PhenopolisException as e: application.logger.exception(e) request_ok = False message = str(e) http_status = e.http_status return jsonify(success=request_ok, message=message, id=",".join(ids_new_individuals)), http_status
def test_update_individual_with_admin_user(_admin_client): # fetch current sex individual_id = "PH00008267" with session_scope() as db_session: individual = db_session.query(Individual).filter(Individual.phenopolis_id == individual_id).first() sex1 = individual.sex # update sex new_sex_for_api = "unknown" response = _admin_client.post( f"/update_patient_data/{individual_id}", data=f"gender_edit[]={new_sex_for_api}&feature[]=Abnormality of body height" "&feature[]=Multicystic kidney dysplasia" "&feature[]=Mode of inheritance&genes[]=TTLL5&genes[]=GAST", content_type="application/x-www-form-urlencoded", ) assert response.status_code == 200 # confirm observed data db_session.refresh(individual) observed_sex = individual.sex assert observed_sex == MAPPING_SEX_REPRESENTATIONS.get(new_sex_for_api), "Update sex did not work" observed_hpo_names = [x[1] for x in vi._get_feature_for_individual(individual, atype="observed")] assert len(observed_hpo_names) == 3, "Update HPOs did not work" unobserved_hpo_names = [x[1] for x in vi._get_feature_for_individual(individual, atype="unobserved")] assert len(unobserved_hpo_names) == 17, "Do not touch unobserved" assert "Abnormality of body height" in observed_hpo_names, "Update HPOs did not work" assert "Multicystic kidney dysplasia" in observed_hpo_names, "Update HPOs did not work" assert "Mode of inheritance" in observed_hpo_names, "Update HPOs did not work" observed_hpos = [x[0] for x in vi._get_feature_for_individual(individual, atype="observed")] assert len(observed_hpos) == 3, "Update HPOs did not work" assert "HP:0000002" in observed_hpos, "Update HPOs did not work" assert "HP:0000003" in observed_hpos, "Update HPOs did not work" assert "HP:0000005" in observed_hpos, "Update HPOs did not work" sex_org = MAPPING_SEX_REPRESENTATIONS.inverse.get(sex1) response = _admin_client.post( f"/update_patient_data/{individual_id}", data=f"gender_edit[]={sex_org}&feature[]=Abnormality of body height" "&feature[]=Multicystic kidney dysplasia" "&feature[]=Mode of inheritance&genes[]=TTLL5&genes[]=GAST", content_type="application/x-www-form-urlencoded", ) assert response.status_code == 200 db_session.refresh(individual) observed_sex = individual.sex assert observed_sex == sex1, "Update sex did not work" individual_id = "PH00009999" response = _admin_client.post( f"/update_patient_data/{individual_id}", data="genes[]=DRAM2", content_type="application/x-www-form-urlencoded", ) assert response.status_code == 404, "Patient does not exist"
def autocomplete(query): arguments = request.args.to_dict() query_type = arguments.get("query_type") try: limit = int(arguments.get("limit", DEFAULT_SEARCH_RESULTS_LIMIT)) except ValueError: return ( jsonify( success=False, message= f"Please, specify a numeric limit value, {arguments.get('limit')}" ), 400, ) if limit > MAXIMUM_SEARCH_RESULTS_LIMIT: return ( jsonify( success=False, message= f"Please, specify a limit lower than {MAXIMUM_SEARCH_RESULTS_LIMIT}" ), 400, ) application.logger.debug("Autocomplete query '%s' and query type '%s'", query, query_type) with session_scope() as db_session: if query_type == "gene": suggestions = _search_genes(db_session, query, limit) elif query_type == "phenotype": suggestions = _search_phenotypes(db_session, query, limit) elif query_type == "patient": suggestions = _search_patients(db_session, query, limit) elif query_type == "variant": suggestions = _search_variants(db_session, query, limit) elif query_type is None or query_type == "": suggestions = (_search_genes(db_session, query, limit) + _search_phenotypes(db_session, query, limit) + _search_patients(db_session, query, limit) + _search_variants(db_session, query, limit)) else: message = f"Autocomplete request with unsupported query type '{query_type}'" application.logger.error(message) # raise PhenopolisException(message) return ( jsonify(success=False, message=message), 400, ) return jsonify(suggestions), 200
def test_create_user_without_email(_not_logged_in_client): user_name = "test_register4" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" response = _not_logged_in_client.post( "/user", json=user.as_dict(), content_type="application/json") assert response.status_code == 400 finally: # cleans the database _clean_test_users(db_session, user_name)
def enable_user(user_id, status): with session_scope() as db_session: try: if user_id == ADMIN_USER: raise PhenopolisException( "Cannot change the status of Admin user!", 400) user = _get_user_by_id(db_session, user_id) if not user: return jsonify(message="User not found"), 404 user.enabled = _parse_boolean_parameter(status) enabled_flag = user.enabled except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(success=True, message=f"User enabled flag set to {enabled_flag}"), 200
def test_create_user_with_explicit_enabled_and_confirmed_flags( _not_logged_in_client): user_name = "test_register3" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" user.enabled = True user.confirmed = True _assert_create_user(db_session, _not_logged_in_client, user) finally: # cleans the database _clean_test_users(db_session, user_name)
def test_create_user_with_used_email(_not_logged_in_client): user_name = "test_register5" with session_scope() as db_session: try: user = User() user.user = user_name user.argon_password = "******" user.email = "*****@*****.**" payload = user.as_dict() payload["confirmation_url"] = "http://phenopolis.org/confirm/" response = _not_logged_in_client.post( "/user", json=payload, content_type="application/json") assert response.status_code == 500 finally: # cleans the database _clean_test_users(db_session, user_name)
def get_user(user_id): try: with session_scope() as db_session: user = _get_user_by_id(db_session, user_id) if not user: return jsonify(message="User not found"), 404 user_individuals = db_session.query(UserIndividual).filter( UserIndividual.user == user.user).all() user_dict = user.as_dict() # removes the password hash from the endpoint we don't want/need this around del user_dict["argon_password"] user_dict["individuals"] = [ ui.internal_id for ui in user_individuals ] except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(user_dict), 200
def get_individual_by_id(phenopolis_id, subset="all", language="en"): with session_scope() as db_session: config = query_user_config(db_session=db_session, language=language, entity="individual") individual = _fetch_authorized_individual(db_session, phenopolis_id) # unauthorized access to individual if not individual: response = jsonify(message="Patient not found") response.status_code = 404 return response if subset == "preview": individual_view = _individual_preview(config, individual) else: individual_view = _individual_complete_view( db_session, config, individual, subset) return jsonify(individual_view)
def get_all_individuals(): with session_scope() as db_session: try: limit, offset = _get_pagination_parameters() if limit > MAX_PAGE_SIZE: return ( jsonify( message="The maximum page size for individuals is {}". format(MAX_PAGE_SIZE)), 400, ) individuals = _fetch_all_individuals(db_session=db_session, offset=offset, limit=limit) for ind in individuals: a1, a2 = zip(*[ x.split("@") for x in sorted(ind["ancestor_observed_features"]) ]) o1, o2 = zip( *[x.split("@") for x in sorted(ind["observed_features"])]) # NOTE: casting list in strings just for frotend, but list is better, I guess (Alan) ind["ancestor_observed_features"] = ",".join(a1) ind["ancestor_observed_features_names"] = ",".join(a2) ind["observed_features"] = ",".join(o1) ind["observed_features_names"] = ",".join(o2) ind["simplified_observed_features"] = "" ind["simplified_observed_features_names"] = "" ind["phenopolis_id"] = ind["internal_id"] if ind["unobserved_features"]: ind["unobserved_features"] = ",".join( ind["unobserved_features"]) else: ind["unobserved_features"] = "" if ind["genes"]: ind["genes"] = ",".join(ind["genes"]) else: ind["genes"] = "" except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(individuals), 200
def get_all_variants(): with session_scope() as db_session: try: limit, offset = _get_pagination_parameters() if limit > MAX_PAGE_SIZE: return ( jsonify(message="The maximum page size for variants is {}". format(MAX_PAGE_SIZE)), 400, ) sqlq = sqlq_all_variants + sql.SQL("limit {} offset {}".format( limit, offset)) with get_db() as conn: with conn.cursor() as cur: cur.execute(sqlq, [session[USER]]) variants = cursor2dict(cur) process_for_display(db_session, variants) except PhenopolisException as e: return jsonify(success=False, message=str(e)), e.http_status return jsonify(variants), 200
def _assert_variant_classification(client, classification, user_id): response = client.post("/variant-classification", json=classification.as_dict(), content_type="application/json") assert response.status_code == 200 with session_scope() as db_session: observed_classification = ( db_session.query(IndividualVariantClassification).filter( IndividualVariantClassification.individual_id == classification.individual_id).order_by( IndividualVariantClassification.classified_on.desc( )).first()) assert observed_classification is not None assert observed_classification.id is not None assert observed_classification.classified_on is not None assert observed_classification.classification == classification.classification assert observed_classification.variant_id == classification.variant_id assert observed_classification.user_id == user_id assert observed_classification.notes == classification.notes assert observed_classification.pubmed_id == classification.pubmed_id
def _config_variant(variants, language): with session_scope() as db_session: # get the genotype information for this variant from the VCF file if session[USER] == DEMO_USER: genotypes = [] else: genotypes = _get_genotypes(variants[0]["CHROM"], variants[0]["POS"]) application.logger.debug( f"genotypes: {len(genotypes)} {genotypes[:1]}...") process_for_display(db_session, variants) config = query_user_config(db_session=db_session, language=language, entity="variant") config[0]["metadata"]["data"] = variants config[0]["individuals"]["data"] = variants config[0]["frequency"]["data"] = variants config[0]["consequence"]["data"] = variants config[0]["genotypes"]["data"] = genotypes return jsonify(config)
def test_create_individual_existing_individual_fails(_admin_client): individual = Individual() test_external_id = "for_test_Sample" individual.external_id = test_external_id individual.sex = "M" individual.genes = "DRAM2,TTLL5" individual.observed_features = "HP:0000001,HP:0000618" response = _admin_client.post("/individual", json=[individual.as_dict()], content_type="application/json") assert response.status_code == 200 with session_scope() as db_session: observed_individual = db_session.query(Individual).filter(Individual.external_id == test_external_id).first() assert observed_individual is not None, "Empty newly created individual" # try to create the same individual again response = _admin_client.post("/individual", json=[individual.as_dict()], content_type="application/json") assert response.status_code == 400 # cleans the database _clean_test_individuals(_admin_client, db_session, test_external_id)
def test_update_individual_with_demo_user_fails(_demo_client): # fetch current sex individual_id = "PH00008267" with session_scope() as db_session: individual = db_session.query(Individual).filter(Individual.phenopolis_id == individual_id).first() sex = individual.sex # update sex new_sex_for_api = MAPPING_SEX_REPRESENTATIONS.inverse.get(sex) response = _demo_client.post( f"/update_patient_data/{individual_id}", data=f"gender_edit[]={new_sex_for_api}", content_type="application/x-www-form-urlencoded", ) assert response.status_code == 405 # fetch new sex db_session.refresh(individual) observed_sex = individual.sex assert observed_sex == sex, "Update did work and it should not!"
def test_create_individual_with_admin_user(_admin_client, sample, sex): individual = Individual() test_external_id = sample individual.external_id = test_external_id response = _admin_client.post("/individual", json=[individual.as_dict()], content_type="application/json") assert response.status_code == 400 assert response.json == {"error": "Null individual", "success": False}, "Sex cannot be null" individual.sex = sex individual.consanguinity = "unknown" individual.genes = "DRAM2" individual.observed_features = "HP:0000001" response = _admin_client.post("/individual", json=[Individual().as_dict()], content_type="application/json") assert response.status_code == 400 assert response.json == {"error": "Null individual", "success": False}, "Empty individual" response = _admin_client.post("/individual", json={}, content_type="application/json") assert response.status_code == 400 assert response.json == {"error": "Empty payload or wrong formatting", "success": False} response = _admin_client.post("/individual", json="not_dict_nor_list", content_type="application/json") assert response.status_code == 400 assert response.json == {"error": "Payload of unexpected type: <class 'str'>", "success": False} response = _admin_client.post("/individual", json=[individual.as_dict()], content_type="application/json") assert response.status_code == 200 with session_scope() as db_session: observed_individual = db_session.query(Individual).filter(Individual.external_id == test_external_id).first() phenopolis_id = observed_individual.phenopolis_id assert observed_individual is not None, "Empty newly created individual" assert observed_individual.external_id == test_external_id assert observed_individual.sex.name == individual.sex assert observed_individual.consanguinity == individual.consanguinity response = _admin_client.post( f"/update_patient_data/{phenopolis_id}", data="genes[]=TTLL5", content_type="application/x-www-form-urlencoded", ) assert response.status_code == 200, "Test empty features" # cleans the database _clean_test_individuals(_admin_client, db_session, test_external_id)
def get_classifications_by_individual(phenopolis_id): with session_scope() as db_session: individual = _fetch_authorized_individual(db_session, phenopolis_id) # unauthorized access to individual if not individual: response = jsonify( message= "Sorry, either the patient does not exist or you are not permitted to see this patient" ) response.status_code = 401 else: classifications = ( db_session.query(IndividualVariantClassification).join( Individual, Individual.id == IndividualVariantClassification.individual_id).filter( Individual.phenopolis_id == phenopolis_id).order_by( IndividualVariantClassification.classified_on.desc( )).all()) response = jsonify([c.as_dict() for c in classifications]) return response