有推荐的方法来编写使用Altair生成图形的Python代码测试吗?
一个简单的例子是:
df = pandas.DataFrame(...)
chart = alt.Chart(df).mark_point().encode(x='...', y='...')对于简单的图形,可以只测试DataFrame的内容,检查Altair调用没有引发异常,检查chart.save()也不会引发异常,而无需测试Altair输出的内容。
但是对于更复杂的Altair图定义,我们也想让我们的测试检查来自Altair的输出。
我一直在做的是使用一个黄金文件(即签入测试期望文件)来输出chart.to_json() ( Vega文件)。
对于更复杂的情况,需要对JSON文件进行一些调整,如下所示:
# Disabling "consolidate_datasets" makes the JSON output more
# stable, making it better to use as a golden file. Without that
# disabled, Altair deduplicates the datasets by hash, and orders
# them in the JSON output by hash, so small changes can cause the
# datasets to be reordered.
with alt.data_transformers.enable(consolidate_datasets=False):
json_data = chart.to_json() + '\n'
# Selector names can vary across runs of the test, so replace them
# with a placeholder.
json_data = re.sub(r'selector\d+', 'selectorXXX', json_data)
# Remove the schema URL so that the tests' golden files do not change
# across updates to Altair/Vega when only the version number in the
# URL changes.
json_data = re.sub(r'"\$schema": ".*"', '"$schema": "<removed>"', json_data)
self.assert_golden_file_equal('vega_graph.json', json_data)有更好的方法吗?
发布于 2022-08-12 11:16:41
您可以通过面向对象的API测试图表输出的特定部分:
assert chart.mark == 'bar'由于图表表示在显示图表后可以更改这一事实,您可能希望使用.to_dict():
assert chart.to_dict()['mark'] == 'bar'您可以使用以下语法检查现有的图表属性。
assert chart.to_dict()['encoding']['y']['field'] == 'species'
assert chart.to_dict()['encoding']['x']['type'] == 'quantitative'
assert chart.to_dict()['encoding']['x']['aggregate'] == 'count'如果分级设置支持共享变量,则可以将chart.to_dict()分配给变量,而不是每次重新创建。
您可能需要检查丢失的密钥,有时由于牛郎星/织女星-尽可能返回缩写规格。
https://stackoverflow.com/questions/73327141
复制相似问题