|
3 | 3 |
|
4 | 4 | import pytest |
5 | 5 |
|
| 6 | +import altair as alt |
6 | 7 | from altair.utils.execeval import eval_block |
7 | 8 | from tests import examples_arguments_syntax |
8 | 9 | from tests import examples_methods_syntax |
@@ -48,6 +49,39 @@ def test_render_examples_to_chart(syntax_module): |
48 | 49 | ) from err |
49 | 50 |
|
50 | 51 |
|
| 52 | +@pytest.mark.parametrize( |
| 53 | + "syntax_module", [examples_arguments_syntax, examples_methods_syntax] |
| 54 | +) |
| 55 | +def test_from_and_to_json_roundtrip(syntax_module): |
| 56 | + """Tests if the to_json and from_json (and by extension to_dict and from_dict) |
| 57 | + work for all examples in the Example Gallery. |
| 58 | + """ |
| 59 | + for filename in iter_examples_filenames(syntax_module): |
| 60 | + source = pkgutil.get_data(syntax_module.__name__, filename) |
| 61 | + chart = eval_block(source) |
| 62 | + |
| 63 | + if chart is None: |
| 64 | + raise ValueError( |
| 65 | + f"Example file {filename} should define chart in its final " |
| 66 | + "statement." |
| 67 | + ) |
| 68 | + |
| 69 | + try: |
| 70 | + first_json = chart.to_json() |
| 71 | + reconstructed_chart = alt.Chart.from_json(first_json) |
| 72 | + # As the chart objects are not |
| 73 | + # necessarily the same - they could use different objects to encode the same |
| 74 | + # information - we do not test for equality of the chart objects, but rather |
| 75 | + # for equality of the json strings. |
| 76 | + second_json = reconstructed_chart.to_json() |
| 77 | + assert first_json == second_json |
| 78 | + except Exception as err: |
| 79 | + raise AssertionError( |
| 80 | + f"Example file {filename} raised an exception when " |
| 81 | + f"doing a json conversion roundtrip: {err}" |
| 82 | + ) from err |
| 83 | + |
| 84 | + |
51 | 85 | # We do not apply the save_engine mark to this test. This mark is used in |
52 | 86 | # the build GitHub Action workflow to select the tests which should be rerun |
53 | 87 | # with some of the saving engines uninstalled. This would not make sense for this test |
|
0 commit comments