You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by GitBox <gi...@apache.org> on 2022/04/19 01:14:14 UTC

[GitHub] [superset] betodealmeida commented on a diff in pull request #19750: feat: query results accuracy test

betodealmeida commented on code in PR #19750:
URL: https://github.com/apache/superset/pull/19750#discussion_r852514225


##########
tests/example_data/data_loading/csv_dataset_loader.py:
##########
@@ -0,0 +1,110 @@
+#  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.
+from __future__ import annotations
+
+import os.path
+from pathlib import Path
+from typing import List, TYPE_CHECKING
+from urllib.parse import urlparse
+
+import pandas as pd
+
+from superset import config, db
+from superset.utils.database import get_example_database
+
+if TYPE_CHECKING:
+    from superset.connectors.sqla.models import SqlaTable
+
+
+class CsvDatasetLoader:
+    # A simple csvloader, should run in Superset AppContext

Review Comment:
   Nit, it's better to make this a docstring so it shows up in code tools:
   
   ```suggestion
       """A simple csvloader, should run in Superset AppContext"""
   ```



##########
tests/conftest.py:
##########
@@ -103,3 +105,23 @@ def data_loader(
     return PandasDataLoader(
         example_db_engine, pandas_loader_configuration, table_to_df_convertor
     )
+
+
+@fixture
+def superset_app_ctx():
+    with app.app_context() as ctx:
+        yield ctx
+
+
+@fixture
+def load_sales_dataset():
+    with app.app_context():
+        loader = CsvDatasetLoader(
+            "https://raw.githubusercontent.com/apache-superset/examples-data/lowercase_columns_examples/datasets/examples/sales.csv",
+            parse_dates=["order_date"],
+        )
+        loader.load_table()
+        dataset = loader.load_dataset()
+        yield dataset
+        loader.remove_dataset()
+        loader.remove_table()

Review Comment:
   You can reuse the `superset_app_ctx` fixture:
   
   ```suggestion
   def load_sales_dataset(superset_app_ctx):
       loader = CsvDatasetLoader(
           "https://raw.githubusercontent.com/apache-superset/examples-data/lowercase_columns_examples/datasets/examples/sales.csv",
           parse_dates=["order_date"],
       )
       loader.load_table()
       dataset = loader.load_dataset()
       yield dataset
       loader.remove_dataset()
       loader.remove_table()
   ```



##########
tests/example_data/data_loading/csv_dataset_loader.py:
##########
@@ -0,0 +1,110 @@
+#  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.
+from __future__ import annotations
+
+import os.path
+from pathlib import Path
+from typing import List, TYPE_CHECKING
+from urllib.parse import urlparse
+
+import pandas as pd
+
+from superset import config, db
+from superset.utils.database import get_example_database
+
+if TYPE_CHECKING:
+    from superset.connectors.sqla.models import SqlaTable
+
+
+class CsvDatasetLoader:
+    # A simple csvloader, should run in Superset AppContext
+    csv_path: str
+    df: pd.DataFrame
+    table_name: str
+    dataset: SqlaTable
+
+    def __init__(
+        self,
+        csv_path: str,
+        cache: bool = True,
+        parse_dates: List[str] = [],
+    ):
+        # read from http
+        if csv_path.startswith("http") and csv_path.endswith(".csv"):
+            filename = urlparse(csv_path).path.split("/")[-1]
+            filepath = os.path.join(config.DATA_DIR, filename)
+            if os.path.exists(filepath) and cache:
+                self.csv_path = filepath
+                self.df = pd.read_csv(filepath, parse_dates=parse_dates)
+                self.table_name = filename.replace(".csv", "")
+            else:
+                self.df = pd.read_csv(csv_path, parse_dates=parse_dates)
+                if cache:
+                    self.df.to_csv(filepath, index=False)
+                self.csv_path = filepath
+                self.table_name = filename.replace(".csv", "")
+
+        # read from fs
+        if os.path.exists(csv_path) and csv_path.endswith(".csv"):
+            self.csv_path = csv_path
+            self.df = pd.read_csv(csv_path, parse_dates=parse_dates)
+            self.table_name = Path(csv_path).name.replace(".csv", "")
+
+    def load_table(self) -> None:
+        # load table to the default schema
+        example_database = get_example_database()
+        self.df.to_sql(
+            name=self.table_name,
+            con=example_database.get_sqla_engine(),
+            index=False,
+            if_exists="replace",
+        )

Review Comment:
   We can probably reuse the logic from https://github.com/apache/superset/blob/a2d34ec4b8a89723e7468f194a98386699af0bd7/superset/datasets/commands/importers/v1/utils.py#L151-L182 here (you just need to modify it to load local files).



##########
superset/datasets/models.py:
##########
@@ -76,7 +76,11 @@ class Dataset(Model, AuditMixinNullable, ExtraJSONMixin, ImportExportMixin):
     expression = sa.Column(sa.Text)
 
     # n:n relationship
-    tables: List[Table] = relationship("Table", secondary=table_association_table)
+    tables: List[Table] = relationship(
+        "Table",
+        backref="datasets",
+        secondary=table_association_table,
+    )

Review Comment:
   Is this needed for this PR?



##########
superset/connectors/sqla/models.py:
##########
@@ -2042,6 +2042,10 @@ def after_delete(  # pylint: disable=unused-argument
         dataset = (
             session.query(NewDataset).filter_by(sqlatable_id=target.id).one_or_none()
         )
+        for tbl in dataset.tables:
+            if len(tbl.datasets) == 1 and tbl.datasets[0] == dataset:
+                session.delete(tbl)

Review Comment:
   Is this needed in this PR or just leftover?



##########
tests/integration_tests/query_context/test_time_comparion.py:
##########
@@ -0,0 +1,126 @@
+# 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.
+from __future__ import annotations
+
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from superset.common.chart_data import ChartDataResultFormat, ChartDataResultType
+from superset.common.query_context import QueryContext
+from superset.common.query_object import QueryObject
+
+if TYPE_CHECKING:
+    from superset.connectors.sqla.models import SqlaTable
+
+
+def test_time_comparison(load_sales_dataset: SqlaTable) -> None:
+    query_context = QueryContext(
+        datasource=load_sales_dataset,
+        queries=[],
+        form_data={},
+        result_type=ChartDataResultType.FULL,
+        result_format=ChartDataResultFormat.JSON,
+        force=True,
+        cache_values={},
+    )
+    query_object = QueryObject(
+        metrics=["count"],
+        columns=["order_date"],
+        orderby=[
+            (
+                "order_date",
+                True,
+            )
+        ],
+        granularity="order_date",
+        extras={"time_grain_sqla": "P1M"},
+        from_dttm=datetime(2004, 1, 1),
+        to_dttm=datetime(2005, 1, 1),
+        row_limit=100000,
+    )
+    rv_2014 = query_context.get_df_payload(query_object, force_cached=True)
+    """
+    >>> rv_2014['df']
+           order_date  count
+    0  2004-01-01     91
+    1  2004-02-01     86
+    2  2004-03-01     56
+    3  2004-04-01     64
+    4  2004-05-01     74
+    5  2004-06-01     85
+    6  2004-07-01     91
+    7  2004-08-01    133
+    8  2004-09-01     95
+    9  2004-10-01    159
+    10 2004-11-01    301
+    11 2004-12-01    110
+    """

Review Comment:
   Does this get checked by `pytest`?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org