From 673ac7d3207224d750ca5962b860fa146ccbd61d Mon Sep 17 00:00:00 2001 From: pawel Date: Tue, 5 May 2020 14:20:04 +0200 Subject: [PATCH] plot: check field exists --- dvc/repo/plot/template.py | 20 ++++++++++++++++++++ tests/func/test_plot.py | 13 +++++++++++++ 2 files changed, 33 insertions(+) diff --git a/dvc/repo/plot/template.py b/dvc/repo/plot/template.py index 2850a6220f..f36d90a9a0 100644 --- a/dvc/repo/plot/template.py +++ b/dvc/repo/plot/template.py @@ -24,6 +24,13 @@ def __init__(self, template_path): ) +class NoFieldInDataError(DvcException): + def __init__(self, field_name): + super().__init__( + "Field '{}' does not exist in provided data.".format(field_name) + ) + + class Template: INDENT = 4 SEPARATORS = (",", ": ") @@ -91,6 +98,11 @@ def fill( with open(template_path, "r") as fobj: result_content = fobj.read() + if x_field: + Template._check_field_exists(data, x_field) + if y_field: + Template._check_field_exists(data, y_field) + result_content = Template._replace_data_anchors( result_content, data, priority_datafile ) @@ -101,6 +113,14 @@ def fill( return result_content + @staticmethod + def _check_field_exists(data, field): + for file, data_points in data.items(): + if not any( + field in data_point.keys() for data_point in data_points + ): + raise NoFieldInDataError(field) + @staticmethod def _replace_metadata_anchors( result_content, title, x_field, x_title, y_field, y_title diff --git a/tests/func/test_plot.py b/tests/func/test_plot.py index 6be11320f8..76ea8b3f6e 100644 --- a/tests/func/test_plot.py +++ b/tests/func/test_plot.py @@ -18,6 +18,7 @@ from dvc.repo.plot.template import ( TemplateNotFoundError, NoDataForTemplateError, + NoFieldInDataError, ) from dvc.repo.plot import NoDataOrTemplateProvided @@ -502,3 +503,15 @@ def test_plot_yaml(tmp_dir, scm, dvc): {"val": 2, PlotData.INDEX_FIELD: 0, "rev": "workspace"}, {"val": 3, PlotData.INDEX_FIELD: 1, "rev": "workspace"}, ] + + +def test_raise_on_wrong_field(tmp_dir, scm, dvc): + metric = [{"val": 2}, {"val": 3}] + _write_json(tmp_dir, metric, "metric.json") + _run_with_metric(tmp_dir, "metric.json", "first run") + + with pytest.raises(NoFieldInDataError): + dvc.plot("metric.json", x_field="no_val") + + with pytest.raises(NoFieldInDataError): + dvc.plot("metric.json", y_field="no_val")