codeant-ai-for-open-source[bot] commented on code in PR #46037: URL: https://github.com/apache/superset/pull/46037#discussion_r4480211928
########## tests/unit_tests/dashboards/commands/importers/v1/refresh_policy_import_test.py: ########## @@ -0,0 +1,265 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import copy +from io import BytesIO +from typing import Any +from zipfile import ZipFile + +import pytest +import yaml +from flask import current_app +from marshmallow import ValidationError +from pytest_mock import MockerFixture +from sqlalchemy.orm.session import Session + +from superset import db, security_manager +from superset.commands.dashboard.importers.v1.utils import import_dashboard +from superset.dashboards.schemas import ImportV1DashboardSchema +from superset.models.core import Log +from superset.models.dashboard import Dashboard +from superset.utils import json +from tests.integration_tests.fixtures.importexport import dashboard_config + +POLICY = { + "auto_refresh_allowed": True, + "minimum_refresh_interval": {"value": 30, "unit": "seconds"}, +} +BAD_POLICY = {"minimum_refresh_interval": {"value": 45, "unit": "seconds"}} +MIN = "auto_refresh_policy.minimum_refresh_interval" +BAD_MESSAGE = "45 seconds isn't a standard interval. Select one from the list." +FILE = "dashboards/test.yaml" + + +def config(policy: Any = None, frequency: Any = 0) -> dict[str, Any]: + """Config.""" + metadata: dict[str, Any] = {"refresh_frequency": frequency} + if policy is not None: + metadata["auto_refresh_policy"] = copy.deepcopy(policy) + return { + "dashboard_title": dashboard_config["dashboard_title"], + "uuid": dashboard_config["uuid"], + "version": "1.0.0", + "position": {}, + "metadata": metadata, + } + + [email protected] +def schema(session: Session, mocker: MockerFixture) -> Session: + """Schema.""" + Dashboard.metadata.create_all(session.get_bind()) # pylint: disable=no-member + mocker.patch.object(security_manager, "can_access", return_value=True) + user = security_manager.user_model( + username="importer", first_name="i", last_name="i", email="[email protected]" + ) + session.add(user) + session.commit() + mocker.patch("flask_login.utils._get_user", return_value=user) + return session + + +def history() -> list[dict[str, Any]]: + """History.""" + rows = ( + db.session.query(Log) + .filter_by(action="dashboard_refresh_policy_changed") + .order_by(Log.id) + .all() + ) + return [{"dashboard_id": row.dashboard_id, **json.loads(row.json)} for row in rows] + + +def bundle(kind: str, dashboard: dict[str, Any]) -> BytesIO: + """Bundle.""" + buf = BytesIO() + with ZipFile(buf, "w") as zip_file: + zip_file.writestr( + "export/metadata.yaml", + yaml.safe_dump( + {"version": "1.0.0", "type": kind, "timestamp": "2020-11-04T21:27:44"} + ), + ) + zip_file.writestr(f"export/{FILE}", yaml.safe_dump(dashboard)) + buf.seek(0) + return buf + + +def test_schema_rejects_an_invalid_policy() -> None: + """Check schema rejects an invalid policy.""" + with pytest.raises(ValidationError) as excinfo: + ImportV1DashboardSchema().load(config(BAD_POLICY)) + assert excinfo.value.messages == {"metadata": {MIN: [BAD_MESSAGE]}} + + [email protected]("policy", [None, {"auto_refresh_policy": None}]) [email protected]("frequency", ["60", -5, 45]) +def test_schema_without_policy_behaves_as_before(policy: Any, frequency: Any) -> None: + """Check schema without policy behaves as before.""" + data = config(frequency=frequency) + if policy: + data["metadata"].update(policy) + ImportV1DashboardSchema().load(data) + + +def test_schema_checks_against_no_stored_policy(mocker: MockerFixture) -> None: + """Check schema checks against no stored policy.""" + mocker.patch.dict( + current_app.config, + {"DASHBOARD_AUTO_REFRESH_INTERVALS": [[30, "30 s"], [120, "2 min"]]}, + ) + policy = { + "minimum_refresh_interval": {"value": 60, "unit": "seconds"}, + "maximum_refresh_interval": {"value": 60, "unit": "seconds"}, + } + with pytest.raises(ValidationError) as excinfo: + ImportV1DashboardSchema().load(config(policy)) + assert set(excinfo.value.messages["metadata"]) == { + MIN, + "auto_refresh_policy.maximum_refresh_interval", + } + + +def test_dashboard_import_endpoint_rejects_an_invalid_policy( + schema: Session, client: Any, full_api_access: None +) -> None: + """Check dashboard import endpoint rejects an invalid policy.""" + response = client.post( + "/api/v1/dashboard/import/", + data={"formData": (bundle("Dashboard", config(BAD_POLICY)), "export.zip")}, + content_type="multipart/form-data", + ) + + assert response.status_code == 422 + extra = response.json["errors"][0]["extra"] + assert extra[FILE]["metadata"] == {MIN: [BAD_MESSAGE]} + assert db.session.query(Dashboard).count() == 0 + assert history() == [] + + +def test_assets_import_endpoint_rejects_an_invalid_policy( + schema: Session, client: Any, full_api_access: None, mocker: MockerFixture +) -> None: + """Check assets import endpoint rejects an invalid policy.""" + validate = mocker.spy(ImportV1DashboardSchema, "validate_refresh_policy") + response = client.post( + "/api/v1/assets/import/", + data={"bundle": (bundle("assets", config(BAD_POLICY)), "export.zip")}, + content_type="multipart/form-data", + ) + + # The generic assets error mapping is maintained separately. + assert response.status_code in {422, 500} Review Comment: **Suggestion:** Accepting HTTP 500 lets this test pass when invalid-policy import crashes, so it does not verify the promised 422 validation response. **Assessment:** ๐ `Major` ยท ๐ `Occurrence: Rarely` ยท ๐ท๏ธ `Api mismatch` [](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f53ba8e6c625419ea01181b20bea1093&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f53ba8e6c625419ea01181b20bea1093&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** tests/unit_tests/dashboards/commands/importers/v1/refresh_policy_import_test.py **Line:** 165:165 **Comment:** *Api Mismatch: Accepting HTTP 500 lets this test pass when invalid-policy import crashes, so it does not verify the promised 422 validation response. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F46037&comment_hash=98663798cce9e8c8641e2cc1129517bce80b382fc4081d4ba3ee6576adb99768&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F46037&comment_hash=98663798cce9e8c8641e2cc1129517bce80b382fc4081d4ba3ee6576adb99768&reaction=dislike'>๐</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
