Skip to content

Commit

Permalink
add UT
Browse files Browse the repository at this point in the history
fix ut

fix UT
  • Loading branch information
zhaoyongjie committed May 25, 2022
1 parent eff2387 commit 21f7d66
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 9 deletions.
1 change: 1 addition & 0 deletions superset/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ class RouteMethod: # pylint: disable=too-few-public-methods
"available": "read",
"validate_sql": "read",
"get_data": "read",
"samples": "read",
}

EXTRA_FORM_DATA_APPEND_KEYS = {
Expand Down
9 changes: 5 additions & 4 deletions superset/datasets/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,13 +769,13 @@ def import_(self) -> Response:
@safe
@statsd_metrics
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}" f".samples",
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.samples",
log_to_statsd=False,
)
def samples(self, pk: int) -> Response:
"""get samples from a Dataset
---
put:
get:
description: >-
get samples from a Dataset
parameters:
Expand All @@ -796,6 +796,7 @@ def samples(self, pk: int) -> Response:
type: object
properties:
samples:
description: dataset samples
type: object
401:
$ref: '#/components/responses/401'
Expand All @@ -810,15 +811,15 @@ def samples(self, pk: int) -> Response:
"""
try:
force = parse_boolean_string(request.args.get("force"))
rv = SamplesDatasetCommand(g.user, pk).run(force_cached=force)
rv = SamplesDatasetCommand(g.user, pk, force).run()
return self.response(200, samples=rv)
except DatasetNotFoundError:
return self.response_404()
except DatasetForbiddenError:
return self.response_403()
except DatasetSamplesFailedError as ex:
logger.error(
"Error refreshing dataset %s: %s",
"Error get dataset samples %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
Expand Down
11 changes: 6 additions & 5 deletions superset/datasets/commands/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@


class SamplesDatasetCommand(BaseCommand):
def __init__(self, user: User, model_id: int):
def __init__(self, user: User, model_id: int, force: bool):
self._actor = user
self._model_id = model_id
self._force = force
self._model: Optional[SqlaTable] = None

def run(self, force_cached: bool = False) -> Dict[str, Any]:
def run(self) -> Dict[str, Any]:
self.validate()
if not self._model:
raise DatasetNotFoundError()
Expand All @@ -53,13 +54,13 @@ def run(self, force_cached: bool = False) -> Dict[str, Any]:
},
queries=[{}],
result_type=ChartDataResultType.SAMPLES,
force=force_cached,
force=self._force,
)
results = qc_instance.get_payload()
try:
return results["queries"][0]
except (IndexError, KeyError):
raise DatasetSamplesFailedError
except (IndexError, KeyError) as exc:
raise DatasetSamplesFailedError from exc

def validate(self) -> None:
# Validate/populate model exists
Expand Down
27 changes: 27 additions & 0 deletions tests/integration_tests/datasets/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1842,3 +1842,30 @@ def test_get_datasets_is_certified_filter(self):

db.session.delete(table_w_certification)
db.session.commit()

@pytest.mark.usefixtures("create_datasets")
def test_get_dataset_samples(self):
"""
Dataset API: Test get dataset samples
"""
dataset = self.get_fixture_datasets()[0]

self.login(username="admin")
uri = f"api/v1/dataset/{dataset.id}/samples"
# feeds data
self.client.get(uri)
# get from cache
rv = self.client.get(uri)
rv_data = json.loads(rv.data)
assert rv.status_code == 200
assert "samples" in rv_data
assert rv_data["samples"]["cached_dttm"] is not None

# force query
uri2 = f"api/v1/dataset/{dataset.id}/samples?force=true"
# feeds data
self.client.get(uri2)
# force query
rv2 = self.client.get(uri2)
rv_data2 = json.loads(rv2.data)
assert rv_data2["samples"]["cached_dttm"] is None

0 comments on commit 21f7d66

Please sign in to comment.