def test_api_login(test_app, client: FlaskClient): # logout client.delete("/logout") # requires converting to base64 for http basic auth authorization = "Basic " + b64encode( 'halcyon:password'.encode('ascii')).decode('ascii') resp = client.post("/api/login", headers={"Authorization": authorization}) assert resp.status_code == 200 resp = client.get("/api/dataobjs") assert resp.status_code == 200
def test_delete_customer_should_return_422_for_invalid_id_format( client: FlaskClient, mocker: MockFixture, tenant_id: str, valid_header: dict, ): from time_tracker_api.customers.customers_namespace import customer_dao from werkzeug.exceptions import UnprocessableEntity invalid_id = fake.company() repository_remove_mock = mocker.patch.object( customer_dao.repository, 'partial_update', side_effect=UnprocessableEntity, ) response = client.delete( "/customers/%s" % invalid_id, headers=valid_header, follow_redirects=True, ) assert HTTPStatus.UNPROCESSABLE_ENTITY == response.status_code repository_remove_mock.assert_called_once_with(str(invalid_id), {'status': 'inactive'}, ANY)
def test_does_not_exist(self, client: FlaskClient, jwt_token: str) -> None: """ A 404 is returned when deleting a Todo item that does not exist """ delete_res = client.delete("/todo/1", headers={"Authorization": jwt_token}) assert delete_res.status_code == 404
def test_ballot_manifest_clear(client: FlaskClient, election_id: str, jurisdiction_ids: List[str]): set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL) rv = client.put( f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest", data={ "manifest": ( io.BytesIO(b"Batch Name,Number of Ballots\n" b"1,23\n"), "manifest.csv", ) }, ) assert_ok(rv) file_id = Jurisdiction.query.get(jurisdiction_ids[0]).manifest_file_id bgcompute_update_ballot_manifest_file() rv = client.delete( f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest", ) assert_ok(rv) rv = client.get( f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest" ) assert json.loads(rv.data) == {"file": None, "processing": None} jurisdiction = Jurisdiction.query.get(jurisdiction_ids[0]) assert jurisdiction.manifest_num_batches is None assert jurisdiction.manifest_num_ballots is None assert jurisdiction.batches == [] assert jurisdiction.manifest_file_id is None assert File.query.get(file_id) is None
def test_api_delete_nanopub(client: FlaskClient): response: Response = client.delete("/api/nanopub/" + nanopub_key) response_not_exist: Response = client.delete("/api/nanopub/not-exist") assert ( response != None and response.status_code == 200 and isinstance(response.get_json(), dict) and response.get_json()["status"] == "ok" ) assert ( response_not_exist != None and response_not_exist.status_code == 200 and isinstance(response_not_exist.get_json(), dict) and response_not_exist.get_json()["status"] == "error" and response_not_exist.get_json()["message"] == "Nanopublication not found" )
def test_delete_article_detail(client: FlaskClient, user_client: FlaskClient, stuff_client: FlaskClient, app: Flask) -> None: url = "/articles/{}" article = create_article(app) res = client.delete(url.format(article.slug)) assert res.status_code == 401 res = user_client.delete(url.format(article.slug)) assert res.status_code == 403 res = stuff_client.delete(url.format(article.slug)) assert res.status_code == 200 with app.app_context(): assert not Article.query.filter_by(slug=article.slug).first() assert not Category.query.filter_by(slug=article.category).first() res = stuff_client.delete(url.format(article.slug)) assert res.status_code == 204
def test_revoke_job(client: FlaskClient) -> None: response: Response = client.get('/tasks/') assert response.status_code == 200 data = json.loads(response.data) nonexistent_job_id = 2452424242 job_id = data[0]['id'] response: Response = client.delete(f'/tasks/{nonexistent_job_id}/') assert response.status_code == 404 response: Response = client.delete(f'/tasks/{job_id}/') assert response.status_code == 200 job = Job.query.filter_by(id=job_id).first() assert job.id == job_id assert job.state == JobState.CANCELED response: Response = client.delete(f'/tasks/{job_id}/') assert response.status_code == 400
def test_delete(self, client: FlaskClient, token: str): with client: result = client.delete(f"/api/{BASE_ROUTE}/13", headers={ "Authorization": f"Bearer {token}" }, follow_redirects=True).get_json() expected = dict(status="Success", id=13) assert result == expected
def test_edit_user(test_app, client: FlaskClient): """Tests editing a user's info, logging out and then logging in with new info.""" new_user = "******" new_pass = "******" resp = client.post("/user/edit", data={"username": new_user, "password": new_pass}, follow_redirects=True) assert request.path == "/" client.delete("/logout") resp = client.post("/login", data={"username": new_user, "password": new_pass}, follow_redirects=True) assert resp.status_code == 200 assert request.path == "/"
def delete_column(self, client: FlaskClient, layer_id: str, column_name: str, token: str) -> Response: query_string = {"token": token} data = {"column_name": column_name} result = client.delete(f"/api/layers/{layer_id}/settings", data=json.dumps(data), query_string=query_string) return result
def delete_user(cls, client: FlaskClient, uuid: str) -> None: assert Env.get_bool("MAIN_LOGIN_ENABLE") admin_headers, _ = cls.do_login(client, None, None) assert admin_headers is not None r = client.delete(f"{API_URI}/admin/users/{uuid}", headers=admin_headers) assert r.status_code == 204
def delete_tag(self, client: FlaskClient, tag_id: int, token: str = None) -> Response: if token is None: token = self.get_token(client) result = client.delete(f"/api/tags/{tag_id}", query_string={"token": token}) return result
def test_delete_technology_suceeds(client: FlaskClient, valid_header: dict, technology_dao): technology_dao.repository.delete = Mock(None) id: str = Faker().uuid4() response = client.delete(f'/technologies/{id}', headers=valid_header) assert HTTPStatus.NO_CONTENT == response.status_code assert b'' == response.data technology_dao.repository.delete.assert_called_once_with(id, ANY)
def test_leave_meeting_owner(client: FlaskClient) -> None: owner = User(uuid=example_uuid1) meeting = Meeting(uuid=example_uuid2, owner=owner) membership = Membership(meeting=meeting, user=owner) db.session.add(membership) db.session.commit() response = client.delete( f'/api/v1/memberships/{meeting.uuid}/{owner.uuid}') assert response.status_code == 403 assert response.json == {'error': 'Meeting owner cannot leave meeting'}
def test_disallowed(client: FlaskClient, pets): # delete disabled assert client.delete("/human/2").status_code == 405 # human has get_enabled assert client.get("/human/2000").status_code == 404 # pointless doesn't allow anything assert client.post("/pointless").status_code == 405 assert client.patch("/pointless/2").status_code == 405 assert client.get("/pointless/1").status_code == 405
def test_delete(test_client: FlaskClient, admin_headers: dict): first_ingredient, second_ingredient, first_step, second_step = prepare_create_receipt( ) receipt = Receipt( name='Name', description='Cool', calories=200, ingredients=[first_ingredient, second_ingredient], steps=[first_step, second_step], ) session.add(receipt) session.commit() test_client.delete(f"/api/admin/v1/receipts/{receipt.id}/", headers=admin_headers) actual = session.query(Receipt).count() expected = 0 assert actual == expected
def test_delete_user(client: FlaskClient, user_client: FlaskClient, app: Flask) -> None: url = "/auth/users/profile" res = client.delete(url) assert res.status_code == 401 res = user_client.delete(url) assert res.status_code == 200 with app.app_context(): user = User.query.filter_by(username="******").first() assert user assert not user.active res = user_client.post("/auth/token/logout") res = user_client.post("/auth/token/login", json={ "username": "******", "password": "******" }) assert res.status_code == 400
def test_qa_add_delete(client: FlaskClient, jwt_token: str): res = client.post("/admin/qa/", query_string=[('question', 'test'), ('answer', 'test')], headers={'Authorization': f'Bearer {jwt_token}'}) assert res.status_code == 201 doc_id = res.json.get('doc_id') assert doc_id is not None res = client.delete("/admin/qa/", query_string=[('doc_id', doc_id)], headers={'Authorization': f'Bearer {jwt_token}'}) assert res.status_code == 202
def delete_layer_tag(self, client: FlaskClient, data: dict, token: str = None) -> Response: if token is None: token = self.get_token(client) query_string = {"token": token} query_string.update(data) result = client.delete("/api/tags/layers", query_string=query_string) return result
def assert_crud_resource(api_gateway: FlaskClient, auth_header, path, inputs, loader_func, valid=True, delete=False): """ Generic test routine, attempt to create a resource, assert that the relevant artifacts were (or not) created """ for test_resource in inputs: resource_to_create = loader_func(test_resource["create"]) p = api_gateway.post(f"{path}", headers=auth_header, data=json.dumps(resource_to_create)) if valid: assert p.status_code == HTTPStatus.CREATED assert_json_subset(resource_to_create, p.get_json()) else: assert p.status_code == HTTPStatus.BAD_REQUEST # ToDo: assert that the response is a problem - move problems to common resource_id = p.get_json().get("id_") g = api_gateway.get(f"{path}/{resource_id}", headers=auth_header) if valid: assert g.status_code == HTTPStatus.OK assert_json_subset(resource_to_create, g.get_json()) else: assert g.status_code == HTTPStatus.NOT_FOUND # ToDo: assert that the response is a problem - move problems to common update = test_resource.get("update") if update: resource_to_update = loader_func(update) if update["type"] == "put": u = api_gateway.put(f"{path}/{resource_id}", headers=auth_header, data=json.dumps(resource_to_update)) assert_json_subset(resource_to_update, u.get_json()) elif update["type"] == "patch": u = api_gateway.patch(f"{path}/{resource_id}", headers=auth_header, data=json.dumps(resource_to_update)) patch = jsonpatch.JsonPatch.from_string(resource_to_update) baseline = patch.apply(resource_to_create) assert_json_subset(baseline, u.get_json()) if delete: d = api_gateway.delete(f"{path}/{resource_id}", headers=auth_header) assert d.status_code == HTTPStatus.NO_CONTENT
def test_delete_service_get_project(self, client: FlaskClient): token = self.get_token(client) service_1_id = self.add_service(client, token) service_2_id = self.add_service(client, token) layer_id = self.add_geojson_prg(client, token) project_data = { "name": "name", "active_layer_id": layer_id, "map_center": { "coordinates": [ 21, 52 ], "type": "Point" }, "map_zoom": 11, "service_layers_ids": [service_1_id, service_2_id], "additional_layers_ids": [] } project_id = client.post("/api/projects", data=json.dumps(project_data), query_string={"token": token} ).json["data"] expected_data = deepcopy(project_data) expected_data["id"] = project_id expected_data["permission_to_each_additional_layer"] = True actual_data_before_delete_service = client.get(f"/api/projects/{project_id}", query_string={"token": token}).json["data"] assert actual_data_before_delete_service == expected_data client.delete(f'/api/services/{service_1_id}?token={token}') expected_data["service_layers_ids"] = [service_2_id] actual_data_after_delete_service = client.get(f"/api/projects/{project_id}", query_string={"token": token}).json["data"] assert expected_data == actual_data_after_delete_service
def test_post(client: FlaskClient): """test Router.route on a POST-only endpoint""" resp = client.post('/post') assert resp.status_code == 200 assert resp.json.get('success') resp = client.get('/post') assert resp.status_code == 405 resp = client.delete('/post') assert resp.status_code == 405 resp = client.put('/post') assert resp.status_code == 405
def test_delete_category_detail(client: FlaskClient, user_client: FlaskClient, stuff_client: FlaskClient, app: Flask) -> None: url = "categories/{}" category = create_category(app) article = create_article(app) with app.app_context(): Article.query.filter_by( slug=article.slug).first().category = category.slug db.session.commit() res = client.delete(url.format(category.slug)) assert res.status_code == 401 res = user_client.delete(url.format(category.slug)) assert res.status_code == 403 res = stuff_client.delete(url.format(category.slug)) assert res.status_code == 200 with app.app_context(): assert not Category.query.filter_by(slug=category.slug).first() assert not Article.query.filter_by(slug=article.slug).first().category res = stuff_client.delete(url.format(category.slug)) assert res.status_code == 204
def test_multiple_methods(client: FlaskClient): """test Router.route on an endpoint with multiple accepted HTTP methods""" resp = client.get('/many') assert resp.status_code == 200 assert resp.json.get('method') == 'GET' resp = client.post('/many') assert resp.status_code == 200 assert resp.json.get('method') == 'POST' resp = client.put('/many') assert resp.status_code == 405 resp = client.delete('/many') assert resp.status_code == 405
def test_delete_technology_raise_http_exception_on_error( client: FlaskClient, valid_header: dict, http_exception: HTTPException, http_status: tuple, technology_dao, ): technology_dao.repository.delete = Mock(side_effect=http_exception) id: str = Faker().uuid4() response = client.delete(f"/technologies/{id}", headers=valid_header) assert http_status == response.status_code technology_dao.repository.delete.assert_called_once_with(id, ANY)
def verify_delete_issue(client: FlaskClient, team_slug: str, access_token: str, issue_uuid: str): del_response = client.delete(f'/teams/{team_slug}/issues/{issue_uuid}', headers=auth_header(access_token), follow_redirects=True) del_data = verify_api_response(del_response) assert del_data['success'] is True response = client.get(f'/teams/{team_slug}/issues/{issue_uuid}', headers=auth_header(access_token), follow_redirects=True) verify_error_response(response, 404, 'No matching issue')
def test_leave_meeting(client: FlaskClient) -> None: owner = User(uuid=example_uuid1) user = User(uuid=example_uuid2) meeting = Meeting(uuid=example_uuid3, owner=owner) membership1 = Membership(meeting=meeting, user=owner) membership2 = Membership(meeting=meeting, user=user) db.session.add(membership1) db.session.add(membership2) db.session.commit() response = client.delete(f'/api/v1/memberships/{meeting.uuid}/{user.uuid}') assert response.status_code == 204 assert response.data == b'' assert Membership.query.get((meeting.uuid, user.uuid)) is None
def test_delete_project_should_return_unprocessable_entity_for_invalid_id_format( client: FlaskClient, mocker: MockFixture, valid_header: dict): from time_tracker_api.project_types.project_types_namespace import project_type_dao from werkzeug.exceptions import UnprocessableEntity invalid_id = fake.company() repository_remove_mock = mocker.patch.object( project_type_dao.repository, 'delete', side_effect=UnprocessableEntity) response = client.delete("/project-types/%s" % invalid_id, headers=valid_header, follow_redirects=True) assert HTTPStatus.UNPROCESSABLE_ENTITY == response.status_code repository_remove_mock.assert_called_once_with(str(invalid_id), ANY)
def test_delete(self, client: FlaskClient, db): """ 测试删除账号 """ login(client) assert db.session.query(MainUser).filter_by( username=username).first() is not None # 删除账号 resp: Response = client.delete(url_for("user.UserView"), json={"password": password}) assert resp.status_code == 204 assert db.session.query(MainUser).filter_by( username=username).first() is None
def test_delete_product(client: FlaskClient, session: Session): # create product product = create_basic_db_product() session.add(product) session.commit() # request delete product_id = product.id response = client.delete(f"/products/{product_id}") # check if successful assert response.status_code == 200 # check if product deleted with pytest.raises(NotFound): Product.get(product_id)