You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by di...@apache.org on 2023/02/02 13:55:28 UTC

[superset] branch dm/chore/migrate-user-fav-slices-to-api-v1 created (now 67b9b31a1b)

This is an automated email from the ASF dual-hosted git repository.

diegomedina24 pushed a change to branch dm/chore/migrate-user-fav-slices-to-api-v1
in repository https://gitbox.apache.org/repos/asf/superset.git


      at 67b9b31a1b update openapi doc

This branch includes the following new commits:

     new f450aa51d0 chore: Migrate /superset/user_slices and /superset/fave_slices to API v1
     new 00d6bcad67 Merge branch 'master' of github.com:apache/superset into dm/chore/migrate-user-fav-slices-to-api-v1
     new 67b9b31a1b update openapi doc

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



[superset] 01/03: chore: Migrate /superset/user_slices and /superset/fave_slices to API v1

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diegomedina24 pushed a commit to branch dm/chore/migrate-user-fav-slices-to-api-v1
in repository https://gitbox.apache.org/repos/asf/superset.git

commit f450aa51d041aebd55ba6bf9d667f2446f18f808
Author: Diego Medina <di...@gmail.com>
AuthorDate: Thu Feb 2 10:52:54 2023 -0300

    chore: Migrate /superset/user_slices and /superset/fave_slices to API v1
---
 .../AnnotationLayerControl/AnnotationLayer.jsx     |   4 +-
 .../AnnotationLayer.test.tsx                       |   6 +-
 .../src/profile/components/Favorites.tsx           |  23 ++--
 superset/charts/api.py                             |  42 ++++++++
 superset/charts/commands/get_slices.py             |  67 ++++++++++++
 superset/charts/dao.py                             |  35 +++++-
 superset/charts/schemas.py                         |  22 ++++
 superset/constants.py                              |   1 +
 superset/views/core.py                             |   2 +
 tests/integration_tests/charts/api_tests.py        |  25 ++++-
 tests/integration_tests/charts/commands_tests.py   | 119 ++++++++++++++++++++-
 tests/unit_tests/charts/dao/dao_tests.py           |  65 +++++++++++
 12 files changed, 394 insertions(+), 17 deletions(-)

diff --git a/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.jsx b/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.jsx
index c444e027d9..5e44618b91 100644
--- a/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.jsx
+++ b/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.jsx
@@ -315,12 +315,12 @@ class AnnotationLayer extends React.PureComponent {
           });
         });
       } else if (requiresQuery(sourceType)) {
-        SupersetClient.get({ endpoint: '/superset/user_slices' }).then(
+        SupersetClient.get({ endpoint: '/api/v1/chart/user_slices/' }).then(
           ({ json }) => {
             const registry = getChartMetadataRegistry();
             this.setState({
               isLoadingOptions: false,
-              valueOptions: json
+              valueOptions: json.result
                 .filter(x => {
                   const metadata = registry.get(x.viz_type);
                   return (
diff --git a/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.test.tsx b/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.test.tsx
index c5fed0b865..a09b5d8a97 100644
--- a/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.test.tsx
+++ b/superset-frontend/src/explore/components/controls/AnnotationLayerControl/AnnotationLayer.test.tsx
@@ -40,9 +40,9 @@ beforeAll(() => {
     result: [{ label: 'Chart A', value: 'a' }],
   });
 
-  fetchMock.get('glob:*/superset/user_slices*', [
-    { id: 'a', title: 'Chart A', viz_type: 'table', data: {} },
-  ]);
+  fetchMock.get('glob:*/api/v1/chart/user_slices/*', {
+    result: [{ id: 'a', title: 'Chart A', viz_type: 'table', data: {} }],
+  });
 
   setupColors();
 
diff --git a/superset-frontend/src/profile/components/Favorites.tsx b/superset-frontend/src/profile/components/Favorites.tsx
index 1e28cd989a..5e5586ac45 100644
--- a/superset-frontend/src/profile/components/Favorites.tsx
+++ b/superset-frontend/src/profile/components/Favorites.tsx
@@ -28,18 +28,25 @@ interface FavoritesProps {
   user: BootstrapUser;
 }
 
+interface UserSliceResult {
+  result: (Slice & { is_favorite: boolean })[];
+}
+
 export default class Favorites extends React.PureComponent<FavoritesProps> {
   renderSliceTable() {
-    const mutator = (data: Slice[]) =>
-      data.map(slice => ({
-        slice: <a href={slice.url}>{slice.title}</a>,
-        creator: <a href={slice.creator_url}>{slice.creator}</a>,
-        favorited: moment.utc(slice.dttm).fromNow(),
-        _favorited: slice.dttm,
-      }));
+    const mutator = (payload: UserSliceResult) =>
+      payload.result
+        .filter(it => !!it.is_favorite)
+        .map(slice => ({
+          slice: <a href={slice.url}>{slice.title}</a>,
+          creator: <a href={slice.creator_url}>{slice.creator}</a>,
+          favorited: moment.utc(slice.dttm).fromNow(),
+          _favorited: slice.dttm,
+        }));
+
     return (
       <TableLoader
-        dataEndpoint={`/superset/fave_slices/${this.props.user?.userId}/`}
+        dataEndpoint={`/api/v1/chart/user_slices/${this.props.user?.userId}/`}
         className="table-condensed"
         columns={['slice', 'creator', 'favorited']}
         mutator={mutator}
diff --git a/superset/charts/api.py b/superset/charts/api.py
index e9ba4feddb..ddba4dc363 100644
--- a/superset/charts/api.py
+++ b/superset/charts/api.py
@@ -44,6 +44,7 @@ from superset.charts.commands.exceptions import (
     ChartUpdateFailedError,
 )
 from superset.charts.commands.export import ExportChartsCommand
+from superset.charts.commands.get_slices import GetUserSlicesCommand
 from superset.charts.commands.importers.dispatcher import ImportChartsCommand
 from superset.charts.commands.update import UpdateChartCommand
 from superset.charts.dao import ChartDAO
@@ -113,6 +114,7 @@ class ChartRestApi(BaseSupersetModelRestApi):
         "thumbnail",
         "screenshot",
         "cache_screenshot",
+        "get_user_slices",
     }
     class_permission_name = "Chart"
     method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
@@ -914,3 +916,43 @@ class ChartRestApi(BaseSupersetModelRestApi):
         )
         command.run()
         return self.response(200, message="OK")
+
+    @expose("/user_slices/")
+    @expose("/user_slices/<int:user_id>/")
+    @protect()
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
+        f".get_user_slices",
+        log_to_statsd=False,
+    )
+    def get_user_slices(self, user_id: Optional[int] = None) -> Response:
+        """Favorite stars for Charts
+        ---
+        get:
+          summary: >-
+            Gets the slices owned or favorited by the user_id
+          parameters:
+          - in: path
+            schema:
+              type: integer
+            name: user_id
+          responses:
+            200:
+              description:
+              content:
+                application/json:
+                  schema:
+                    $ref: "#/components/schemas/GetUserSlicesSchema"
+            400:
+              $ref: '#/components/responses/400'
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        command = GetUserSlicesCommand(user_id)
+        result = command.run()
+        return self.response(200, result=result)
diff --git a/superset/charts/commands/get_slices.py b/superset/charts/commands/get_slices.py
new file mode 100644
index 0000000000..19e2f640bf
--- /dev/null
+++ b/superset/charts/commands/get_slices.py
@@ -0,0 +1,67 @@
+# 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 logging
+from typing import cast, Optional
+
+from flask_appbuilder.models.sqla import Model
+
+from superset import security_manager
+from superset.utils.core import get_user_id
+from superset.charts.dao import ChartDAO
+from superset.commands.base import BaseCommand
+from superset.utils.dates import datetime_to_epoch
+
+logger = logging.getLogger(__name__)
+
+
+class GetUserSlicesCommand(BaseCommand):
+    _user_id: Optional[int]
+
+    def __init__(self, user_id: Optional[int] = None):
+        self._user_id = user_id
+
+    def run(self) -> Model:
+        self.validate()
+
+        slices = ChartDAO.user_slices(cast(int, self._user_id))
+
+        payload = []
+        for o in slices:
+            item = {
+                "id": o.Slice.id,
+                "title": o.Slice.slice_name,
+                "url": o.Slice.slice_url,
+                "data": o.Slice.form_data,
+                "dttm": datetime_to_epoch(
+                    o.FavStar.dttm if o.FavStar else o.Slice.changed_on
+                ),
+                "viz_type": o.Slice.viz_type,
+                "is_favorite": bool(o.FavStar),
+            }
+            if o.Slice.created_by:
+                user = o.Slice.created_by
+                item["creator"] = str(user)
+                item["creator_url"] = "/superset/profile/{}/".format(user.username)
+            payload.append(item)
+
+        return payload
+
+    def validate(self) -> None:
+        if not self._user_id:
+            self._user_id = get_user_id()
+
+        security_manager.raise_for_user_activity_access(self._user_id)
diff --git a/superset/charts/dao.py b/superset/charts/dao.py
index 384bd9a1fe..14398e1585 100644
--- a/superset/charts/dao.py
+++ b/superset/charts/dao.py
@@ -16,10 +16,12 @@
 # under the License.
 # pylint: disable=arguments-renamed
 import logging
-from typing import List, Optional, TYPE_CHECKING
+from typing import Any, List, Optional, TYPE_CHECKING
 
+from sqlalchemy import and_, or_
 from sqlalchemy.exc import SQLAlchemyError
 
+from superset import security_manager
 from superset.charts.filters import ChartFilter
 from superset.dao.base import BaseDAO
 from superset.extensions import db
@@ -82,3 +84,34 @@ class ChartDAO(BaseDAO):
             )
             .all()
         ]
+
+    @staticmethod
+    def user_slices(user_id: int) -> List[Any]:
+        owner_ids_query = (
+            db.session.query(Slice.id)
+            .join(Slice.owners)
+            .filter(security_manager.user_model.id == user_id)
+        )
+
+        return (
+            db.session.query(Slice, FavStar)
+            .join(
+                FavStar,
+                and_(
+                    FavStar.user_id == user_id,
+                    FavStar.class_name == "slice",
+                    Slice.id == FavStar.obj_id,
+                ),
+                isouter=True,
+            )
+            .filter(  # pylint: disable=comparison-with-callable
+                or_(
+                    Slice.id.in_(owner_ids_query),
+                    Slice.created_by_fk == user_id,
+                    Slice.changed_by_fk == user_id,
+                    FavStar.user_id == user_id,
+                )
+            )
+            .order_by(Slice.slice_name.asc())
+            .all()
+        )
diff --git a/superset/charts/schemas.py b/superset/charts/schemas.py
index dee73de17c..9a3491a6e7 100644
--- a/superset/charts/schemas.py
+++ b/superset/charts/schemas.py
@@ -1379,6 +1379,27 @@ class ImportV1ChartSchema(Schema):
     external_url = fields.String(allow_none=True)
 
 
+class ChartFavStarResponseResult(Schema):
+    id = fields.Integer(description="The chart id")
+    url = fields.String(description="The chart explore url")
+    title = fields.Boolean(description="The chart name")
+    is_favorite = fields.Boolean(description="Is the chart favorited by the user")
+    viz_type = fields.String(description="The chart visualization type")
+    dttm = fields.Integer(
+        description="The timestamp when the chart was favorited or the last time it was modified"
+    )
+    data = fields.Raw(allow_none=True, description="The chart form data")
+    creator = fields.String(allow_none=True, description="The creator name")
+    creator_url = fields.String(allow_none=True, description="The creator profile url")
+
+
+class GetUserSlicesSchema(Schema):
+    result = fields.List(
+        fields.Nested(ChartFavStarResponseResult),
+        description="A list of charts owned or favorited by the user",
+    )
+
+
 CHART_SCHEMAS = (
     ChartDataQueryContextSchema,
     ChartDataResponseSchema,
@@ -1402,4 +1423,5 @@ CHART_SCHEMAS = (
     ChartGetDatasourceResponseSchema,
     ChartCacheScreenshotResponseSchema,
     GetFavStarIdsSchema,
+    GetUserSlicesSchema,
 )
diff --git a/superset/constants.py b/superset/constants.py
index 5c1f0e36fe..a865848d93 100644
--- a/superset/constants.py
+++ b/superset/constants.py
@@ -143,6 +143,7 @@ MODEL_API_RW_METHOD_PERMISSION_MAP = {
     "delete_ssh_tunnel": "write",
     "get_updated_since": "read",
     "stop_query": "read",
+    "get_user_slices": "read",
 }
 
 EXTRA_FORM_DATA_APPEND_KEYS = {
diff --git a/superset/views/core.py b/superset/views/core.py
index d5cad13fa9..a94c4216b2 100755
--- a/superset/views/core.py
+++ b/superset/views/core.py
@@ -1556,6 +1556,7 @@ class Superset(BaseSupersetView):  # pylint: disable=too-many-public-methods
     @event_logger.log_this
     @expose("/user_slices", methods=["GET"])
     @expose("/user_slices/<int:user_id>/", methods=["GET"])
+    @deprecated()
     def user_slices(self, user_id: Optional[int] = None) -> FlaskResponse:
         """List of slices a user owns, created, modified or faved"""
         if not user_id:
@@ -1641,6 +1642,7 @@ class Superset(BaseSupersetView):  # pylint: disable=too-many-public-methods
     @event_logger.log_this
     @expose("/fave_slices", methods=["GET"])
     @expose("/fave_slices/<int:user_id>/", methods=["GET"])
+    @deprecated()
     def fave_slices(self, user_id: Optional[int] = None) -> FlaskResponse:
         """Favorite slices for a user"""
         if user_id is None:
diff --git a/tests/integration_tests/charts/api_tests.py b/tests/integration_tests/charts/api_tests.py
index 3d8a4695f4..d239ae9020 100644
--- a/tests/integration_tests/charts/api_tests.py
+++ b/tests/integration_tests/charts/api_tests.py
@@ -28,7 +28,7 @@ from sqlalchemy import and_
 from sqlalchemy.sql import func
 
 from superset.connectors.sqla.models import SqlaTable
-from superset.extensions import cache_manager, db
+from superset.extensions import cache_manager, db, security_manager
 from superset.models.core import Database, FavStar, FavStarClassName
 from superset.models.dashboard import Dashboard
 from superset.reports.models import ReportSchedule, ReportScheduleType
@@ -1472,3 +1472,26 @@ class TestChartApi(SupersetTestCase, ApiOwnersTestCaseMixin, InsertChartMixin):
         self.assertEqual(rv.status_code, 200)
         data = json.loads(rv.data.decode("utf-8"))
         self.assertEqual(data["count"], 8)
+
+    @pytest.mark.usefixtures("load_energy_table_with_slice")
+    def test_get_user_slices(self):
+        """
+        Chart API: Test get user slices
+        """
+        admin = security_manager.find_user(username="admin")
+        chart = db.session.query(Slice).all()[0]
+        chart.owners = [admin]
+        db.session.commit()
+
+        self.login(username="admin")
+        rv = self.client.get("api/v1/chart/user_slices/")
+        self.assertEqual(rv.status_code, 200)
+        data = json.loads(rv.data.decode("utf-8"))
+
+        assert len(data["result"]) == 1
+        assert data["result"][0]["title"] == "Average and Sum Trends"
+        assert data["result"][0]["is_favorite"] == False
+        assert data["result"][0]["viz_type"] == "dual_line"
+
+        chart.owners = []
+        db.session.commit()
diff --git a/tests/integration_tests/charts/commands_tests.py b/tests/integration_tests/charts/commands_tests.py
index 214b7cbfe7..ee0c846cdf 100644
--- a/tests/integration_tests/charts/commands_tests.py
+++ b/tests/integration_tests/charts/commands_tests.py
@@ -15,6 +15,7 @@
 # specific language governing permissions and limitations
 # under the License.
 import json
+from datetime import datetime
 from unittest.mock import patch
 
 import pytest
@@ -25,13 +26,16 @@ from superset import db, security_manager
 from superset.charts.commands.create import CreateChartCommand
 from superset.charts.commands.exceptions import ChartNotFoundError
 from superset.charts.commands.export import ExportChartsCommand
+from superset.charts.commands.get_slices import GetUserSlicesCommand
 from superset.charts.commands.importers.v1 import ImportChartsCommand
 from superset.charts.commands.update import UpdateChartCommand
 from superset.commands.exceptions import CommandInvalidError
 from superset.commands.importers.exceptions import IncorrectVersionError
 from superset.connectors.sqla.models import SqlaTable
-from superset.models.core import Database
+from superset.exceptions import SupersetSecurityException
+from superset.models.core import Database, FavStar
 from superset.models.slice import Slice
+from superset.utils.dates import datetime_to_epoch
 from tests.integration_tests.base_tests import SupersetTestCase
 from tests.integration_tests.fixtures.energy_dashboard import (
     load_energy_table_data,
@@ -409,7 +413,7 @@ class TestChartsUpdateCommand(SupersetTestCase):
     def test_query_context_update_command(self, mock_sm_g, mock_g):
         """
         Test that a user can generate the chart query context
-        payloadwithout affecting owners
+        payload without affecting owners
         """
         chart = db.session.query(Slice).all()[0]
         pk = chart.id
@@ -430,3 +434,114 @@ class TestChartsUpdateCommand(SupersetTestCase):
         assert chart.query_context == query_context
         assert len(chart.owners) == 1
         assert chart.owners[0] == admin
+
+
+class TestGetUserSlicesCommand(SupersetTestCase):
+    @patch("superset.utils.core.g")
+    @pytest.mark.usefixtures("load_energy_table_with_slice")
+    def test_get_user_slices_not_allowed(self, mock_g):
+        user = security_manager.find_user(username="admin")
+        mock_g.user = None
+
+        command = GetUserSlicesCommand(user.id)
+        with pytest.raises(SupersetSecurityException) as ex_info:
+            command.run()
+        assert str(ex_info.value) == "Access to user's activity data is restricted"
+
+    @patch("superset.utils.core.g")
+    @patch("superset.security.manager.g")
+    @pytest.mark.usefixtures("load_energy_table_with_slice")
+    def test_get_user_slices_empty(self, mock_sm_g, mock_g):
+        chart = db.session.query(Slice).all()[0]
+        admin = security_manager.find_user(username="admin")
+        chart.owners = [admin]
+        db.session.commit()
+
+        user = security_manager.find_user(username="alpha")
+        mock_g.user = mock_sm_g.user = user
+
+        command = GetUserSlicesCommand()
+        result = command.run()
+        assert len(result) == 0
+
+    @patch("superset.utils.core.g")
+    @patch("superset.security.manager.g")
+    @pytest.mark.usefixtures("load_energy_table_with_slice")
+    def test_get_user_slices_owned(self, mock_sm_g, mock_g):
+        admin = security_manager.find_user(username="admin")
+
+        chart = db.session.query(Slice).all()[0]
+        chart.owners = [admin]
+        db.session.commit()
+
+        mock_g.user = mock_sm_g.user = admin
+
+        command = GetUserSlicesCommand()
+        result = command.run()
+        assert len(result) == 1
+        assert result == [
+            {
+                "id": 1,
+                "title": chart.slice_name,
+                "url": chart.slice_url,
+                "data": chart.form_data,
+                "viz_type": chart.viz_type,
+                "dttm": datetime_to_epoch(chart.changed_on),
+                "is_favorite": False,
+            }
+        ]
+
+        chart.owners = []
+        db.session.commit()
+
+    @patch("superset.utils.core.g")
+    @patch("superset.security.manager.g")
+    @pytest.mark.usefixtures("load_energy_table_with_slice")
+    def test_get_user_slices_owned_favorited(self, mock_sm_g, mock_g):
+        admin = security_manager.find_user(username="admin")
+        mock_g.user = mock_sm_g.user = admin
+
+        own_chart = db.session.query(Slice).all()[0]
+        own_chart.owners = [admin]
+        own_chart.created_by = admin
+
+        fav_chart = db.session.query(Slice).all()[1]
+        fav_obj = FavStar(
+            class_name="slice",
+            obj_id=fav_chart.id,
+            user_id=admin.id,
+            dttm=datetime.now(),
+        )
+        db.session.add(fav_obj)
+        db.session.commit()
+
+        command = GetUserSlicesCommand()
+        result = command.run()
+        assert len(result) == 2
+        assert result == [
+            {
+                "id": 2,
+                "title": fav_chart.slice_name,
+                "url": fav_chart.slice_url,
+                "data": fav_chart.form_data,
+                "viz_type": fav_chart.viz_type,
+                "dttm": datetime_to_epoch(fav_obj.dttm),
+                "is_favorite": True,
+            },
+            {
+                "id": 1,
+                "title": own_chart.slice_name,
+                "url": own_chart.slice_url,
+                "data": own_chart.form_data,
+                "viz_type": own_chart.viz_type,
+                "dttm": datetime_to_epoch(own_chart.changed_on),
+                "is_favorite": False,
+                "creator": "admin user",
+                "creator_url": "/superset/profile/admin/",
+            },
+        ]
+
+        own_chart.owners = []
+        own_chart.created_by = None
+        db.session.delete(fav_obj)
+        db.session.commit()
diff --git a/tests/unit_tests/charts/dao/dao_tests.py b/tests/unit_tests/charts/dao/dao_tests.py
index 15310712a5..cc71862f78 100644
--- a/tests/unit_tests/charts/dao/dao_tests.py
+++ b/tests/unit_tests/charts/dao/dao_tests.py
@@ -15,11 +15,16 @@
 # specific language governing permissions and limitations
 # under the License.
 
+from datetime import datetime
 from typing import Iterator
 
 import pytest
+from flask import g
+from flask_appbuilder.security.sqla.models import User
 from sqlalchemy.orm.session import Session
 
+from superset import security_manager
+from superset.models.core import FavStar
 from superset.utils.core import DatasourceType
 
 
@@ -30,15 +35,34 @@ def session_with_data(session: Session) -> Iterator[Session]:
     engine = session.get_bind()
     Slice.metadata.create_all(engine)  # pylint: disable=no-member
 
+    user_obj = User(
+        id=1,
+        username="test",
+        first_name="test",
+        last_name="test",
+        email="test@superset.com",
+    )
+    session.add(user_obj)
+
     slice_obj = Slice(
         id=1,
         datasource_id=1,
         datasource_type=DatasourceType.TABLE,
         datasource_name="tmp_perm_table",
         slice_name="slice_name",
+        owners=[user_obj],
     )
+    session.add(slice_obj)
 
+    slice_obj = Slice(
+        id=2,
+        datasource_id=1,
+        datasource_type=DatasourceType.TABLE,
+        datasource_name="tmp_perm_table",
+        slice_name="other_slice",
+    )
     session.add(slice_obj)
+
     session.commit()
     yield session
     session.rollback()
@@ -65,3 +89,44 @@ def test_datasource_find_by_id_skip_base_filter_not_found(
         125326326, session=session_with_data, skip_base_filter=True
     )
     assert result is None
+
+
+def test_get_empty_user_slices() -> None:
+    from superset.charts.dao import ChartDAO
+
+    g.user = security_manager.find_user(username="test")
+    result = ChartDAO.user_slices(2)
+
+    assert result == []
+
+
+def test_get_own_user_slices(session_with_data: Session) -> None:
+    from superset.charts.dao import ChartDAO
+
+    g.user = security_manager.find_user(username="test")
+    result = ChartDAO.user_slices(1)
+
+    assert len(result) == 1
+    assert result[0].Slice.slice_name == "slice_name"
+    assert result[0].FavStar is None
+
+
+def test_get_user_slices_with_fav(session_with_data: Session) -> None:
+    from superset.charts.dao import ChartDAO
+
+    g.user = security_manager.find_user(username="test")
+    fav_obj = FavStar(
+        class_name="slice",
+        obj_id=2,
+        user_id=1,
+        dttm=datetime.now(),
+    )
+    session_with_data.add(fav_obj)
+
+    result = ChartDAO.user_slices(1)
+
+    assert len(result) == 2
+    assert result[0].Slice.slice_name == "other_slice"
+    assert result[0].FavStar == fav_obj
+    assert result[1].Slice.slice_name == "slice_name"
+    assert result[1].FavStar is None


[superset] 02/03: Merge branch 'master' of github.com:apache/superset into dm/chore/migrate-user-fav-slices-to-api-v1

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diegomedina24 pushed a commit to branch dm/chore/migrate-user-fav-slices-to-api-v1
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 00d6bcad67501294f709b996ba167cf2fe567fb7
Merge: f450aa51d0 ed7b3533bc
Author: Diego Medina <di...@gmail.com>
AuthorDate: Thu Feb 2 10:53:01 2023 -0300

    Merge branch 'master' of github.com:apache/superset into dm/chore/migrate-user-fav-slices-to-api-v1

 UPDATING.md                                        |  1 +
 requirements/base.txt                              |  2 +-
 setup.py                                           |  4 +-
 .../src/MixedTimeseries/buildQuery.ts              |  7 +--
 .../test/MixedTimeseries/buildQuery.test.ts        | 63 ++++++++++++++++++----
 .../AdhocFilterOption/AdhocFilterOption.test.tsx   | 27 ++++++----
 .../AddDataset/LeftPanel/LeftPanel.test.tsx        |  2 +-
 .../data/dataset/AddDataset/LeftPanel/index.tsx    |  2 +-
 superset/config.py                                 |  6 +--
 9 files changed, 82 insertions(+), 32 deletions(-)


[superset] 03/03: update openapi doc

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diegomedina24 pushed a commit to branch dm/chore/migrate-user-fav-slices-to-api-v1
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 67b9b31a1b8575c52b106b0956b910b5bc1229f9
Author: Diego Medina <di...@gmail.com>
AuthorDate: Thu Feb 2 10:54:58 2023 -0300

    update openapi doc
---
 docs/static/resources/openapi.json | 231 ++++++++++++++++++++++++++++++-------
 1 file changed, 191 insertions(+), 40 deletions(-)

diff --git a/docs/static/resources/openapi.json b/docs/static/resources/openapi.json
index cc92f091e2..b87a236f0f 100644
--- a/docs/static/resources/openapi.json
+++ b/docs/static/resources/openapi.json
@@ -1768,7 +1768,7 @@
             "type": "string"
           },
           "changed_by": {
-            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User"
+            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User2"
           },
           "changed_by_name": {
             "readOnly": true
@@ -1783,7 +1783,7 @@
             "readOnly": true
           },
           "created_by": {
-            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User2"
+            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User3"
           },
           "created_on_delta_humanized": {
             "readOnly": true
@@ -1830,7 +1830,7 @@
             "type": "string"
           },
           "last_saved_by": {
-            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User3"
+            "$ref": "#/components/schemas/ChartDataRestApi.get_list.User"
           },
           "owners": {
             "$ref": "#/components/schemas/ChartDataRestApi.get_list.User1"
@@ -1897,6 +1897,10 @@
             "maxLength": 64,
             "type": "string"
           },
+          "id": {
+            "format": "int32",
+            "type": "integer"
+          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -1940,10 +1944,6 @@
             "maxLength": 64,
             "type": "string"
           },
-          "id": {
-            "format": "int32",
-            "type": "integer"
-          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -2398,6 +2398,51 @@
         },
         "type": "object"
       },
+      "ChartFavStarResponseResult1": {
+        "properties": {
+          "creator": {
+            "description": "The creator name",
+            "nullable": true,
+            "type": "string"
+          },
+          "creator_url": {
+            "description": "The creator profile url",
+            "nullable": true,
+            "type": "string"
+          },
+          "data": {
+            "description": "The chart form data",
+            "nullable": true
+          },
+          "dttm": {
+            "description": "The timestamp when the chart was favorited or the last time it was modified",
+            "format": "int32",
+            "type": "integer"
+          },
+          "id": {
+            "description": "The chart id",
+            "format": "int32",
+            "type": "integer"
+          },
+          "is_favorite": {
+            "description": "Is the chart favorited by the user",
+            "type": "boolean"
+          },
+          "title": {
+            "description": "The chart name",
+            "type": "boolean"
+          },
+          "url": {
+            "description": "The chart explore url",
+            "type": "string"
+          },
+          "viz_type": {
+            "description": "The chart visualization type",
+            "type": "string"
+          }
+        },
+        "type": "object"
+      },
       "ChartGetDatasourceObjectDataResponse": {
         "properties": {
           "datasource_id": {
@@ -2560,7 +2605,7 @@
             "type": "string"
           },
           "changed_by": {
-            "$ref": "#/components/schemas/ChartRestApi.get_list.User"
+            "$ref": "#/components/schemas/ChartRestApi.get_list.User2"
           },
           "changed_by_name": {
             "readOnly": true
@@ -2575,7 +2620,7 @@
             "readOnly": true
           },
           "created_by": {
-            "$ref": "#/components/schemas/ChartRestApi.get_list.User2"
+            "$ref": "#/components/schemas/ChartRestApi.get_list.User3"
           },
           "created_on_delta_humanized": {
             "readOnly": true
@@ -2622,7 +2667,7 @@
             "type": "string"
           },
           "last_saved_by": {
-            "$ref": "#/components/schemas/ChartRestApi.get_list.User3"
+            "$ref": "#/components/schemas/ChartRestApi.get_list.User"
           },
           "owners": {
             "$ref": "#/components/schemas/ChartRestApi.get_list.User1"
@@ -2689,6 +2734,10 @@
             "maxLength": 64,
             "type": "string"
           },
+          "id": {
+            "format": "int32",
+            "type": "integer"
+          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -2732,10 +2781,6 @@
             "maxLength": 64,
             "type": "string"
           },
-          "id": {
-            "format": "int32",
-            "type": "integer"
-          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -3400,7 +3445,7 @@
             "type": "string"
           },
           "changed_by": {
-            "$ref": "#/components/schemas/DashboardRestApi.get_list.User"
+            "$ref": "#/components/schemas/DashboardRestApi.get_list.User1"
           },
           "changed_by_name": {
             "readOnly": true
@@ -3441,7 +3486,7 @@
             "type": "string"
           },
           "owners": {
-            "$ref": "#/components/schemas/DashboardRestApi.get_list.User1"
+            "$ref": "#/components/schemas/DashboardRestApi.get_list.User"
           },
           "position_json": {
             "nullable": true,
@@ -3489,6 +3534,10 @@
       },
       "DashboardRestApi.get_list.User": {
         "properties": {
+          "email": {
+            "maxLength": 64,
+            "type": "string"
+          },
           "first_name": {
             "maxLength": 64,
             "type": "string"
@@ -3507,6 +3556,7 @@
           }
         },
         "required": [
+          "email",
           "first_name",
           "last_name",
           "username"
@@ -3515,10 +3565,6 @@
       },
       "DashboardRestApi.get_list.User1": {
         "properties": {
-          "email": {
-            "maxLength": 64,
-            "type": "string"
-          },
           "first_name": {
             "maxLength": 64,
             "type": "string"
@@ -3537,7 +3583,6 @@
           }
         },
         "required": [
-          "email",
           "first_name",
           "last_name",
           "username"
@@ -4898,7 +4943,7 @@
             "type": "integer"
           },
           "changed_by": {
-            "$ref": "#/components/schemas/DatasetRestApi.get.User"
+            "$ref": "#/components/schemas/DatasetRestApi.get.User1"
           },
           "changed_on": {
             "format": "date-time",
@@ -4976,7 +5021,7 @@
             "type": "integer"
           },
           "owners": {
-            "$ref": "#/components/schemas/DatasetRestApi.get.User1"
+            "$ref": "#/components/schemas/DatasetRestApi.get.User"
           },
           "schema": {
             "maxLength": 255,
@@ -5173,14 +5218,23 @@
             "maxLength": 64,
             "type": "string"
           },
+          "id": {
+            "format": "int32",
+            "type": "integer"
+          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
+          },
+          "username": {
+            "maxLength": 64,
+            "type": "string"
           }
         },
         "required": [
           "first_name",
-          "last_name"
+          "last_name",
+          "username"
         ],
         "type": "object"
       },
@@ -5190,23 +5244,14 @@
             "maxLength": 64,
             "type": "string"
           },
-          "id": {
-            "format": "int32",
-            "type": "integer"
-          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
-          },
-          "username": {
-            "maxLength": 64,
-            "type": "string"
           }
         },
         "required": [
           "first_name",
-          "last_name",
-          "username"
+          "last_name"
         ],
         "type": "object"
       },
@@ -5967,6 +6012,18 @@
         },
         "type": "object"
       },
+      "GetUserSlicesSchema": {
+        "properties": {
+          "result": {
+            "description": "A list of charts owned or favorited by the user",
+            "items": {
+              "$ref": "#/components/schemas/ChartFavStarResponseResult1"
+            },
+            "type": "array"
+          }
+        },
+        "type": "object"
+      },
       "GuestTokenCreate": {
         "properties": {
           "resources": {
@@ -6950,7 +7007,7 @@
             "type": "boolean"
           },
           "changed_by": {
-            "$ref": "#/components/schemas/ReportScheduleRestApi.get_list.User"
+            "$ref": "#/components/schemas/ReportScheduleRestApi.get_list.User1"
           },
           "changed_on": {
             "format": "date-time",
@@ -7016,7 +7073,7 @@
             "type": "string"
           },
           "owners": {
-            "$ref": "#/components/schemas/ReportScheduleRestApi.get_list.User1"
+            "$ref": "#/components/schemas/ReportScheduleRestApi.get_list.User"
           },
           "recipients": {
             "$ref": "#/components/schemas/ReportScheduleRestApi.get_list.ReportRecipients"
@@ -7060,6 +7117,10 @@
             "maxLength": 64,
             "type": "string"
           },
+          "id": {
+            "format": "int32",
+            "type": "integer"
+          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -7077,10 +7138,6 @@
             "maxLength": 64,
             "type": "string"
           },
-          "id": {
-            "format": "int32",
-            "type": "integer"
-          },
           "last_name": {
             "maxLength": 64,
             "type": "string"
@@ -11539,6 +11596,100 @@
         ]
       }
     },
+    "/api/v1/chart/user_slices/": {
+      "get": {
+        "parameters": [
+          {
+            "in": "path",
+            "name": "user_id",
+            "required": true,
+            "schema": {
+              "type": "integer"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/GetUserSlicesSchema"
+                }
+              }
+            },
+            "description": "None"
+          },
+          "400": {
+            "$ref": "#/components/responses/400"
+          },
+          "401": {
+            "$ref": "#/components/responses/401"
+          },
+          "403": {
+            "$ref": "#/components/responses/403"
+          },
+          "500": {
+            "$ref": "#/components/responses/500"
+          }
+        },
+        "security": [
+          {
+            "jwt": []
+          }
+        ],
+        "summary": "Gets the slices owned or favorited by the user_id",
+        "tags": [
+          "Charts"
+        ]
+      }
+    },
+    "/api/v1/chart/user_slices/{user_id}/": {
+      "get": {
+        "parameters": [
+          {
+            "in": "path",
+            "name": "user_id",
+            "required": true,
+            "schema": {
+              "type": "integer"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/GetUserSlicesSchema"
+                }
+              }
+            },
+            "description": "None"
+          },
+          "400": {
+            "$ref": "#/components/responses/400"
+          },
+          "401": {
+            "$ref": "#/components/responses/401"
+          },
+          "403": {
+            "$ref": "#/components/responses/403"
+          },
+          "500": {
+            "$ref": "#/components/responses/500"
+          }
+        },
+        "security": [
+          {
+            "jwt": []
+          }
+        ],
+        "summary": "Gets the slices owned or favorited by the user_id",
+        "tags": [
+          "Charts"
+        ]
+      }
+    },
     "/api/v1/chart/{pk}": {
       "delete": {
         "description": "Deletes a Chart.",