AppTest plotly charts

Python 3.11 / Streamlit 1.31.1

Hi there,

I’m writing tests for my app which produces plotly charts. The app testing cheat sheet says that chart elements are not supported, but you can use AppTest.get() to inspect most of the unsupported elements.

Since AppTest.get("plotly_chart") gives me a list of UnknownElement(), I’m guessing this approach doesn’t work for plotly charts.

Am I right in assuming that plotly charts can’t be inspected for testing, or is there another way to somehow get to my charts?

Thanks for your help.

…maybe @jcarroll can help to access plotly charts in AppTest?

Hey @lasinludwig

It’s pretty ugly but you can extract the figure spec from the underlying proto attached to the UnknownElement you mentioned. We’re hoping to add a more convenient to use method of support soon.

Here’s an example test that will print out the contents of the figure spec as a dictionary, using the plotly_chart code from the docs example. The test always fails so you can see the printed output (it’s very long).

from streamlit.testing.v1 import AppTest
import json
import pprint

APP_CODE = """
import streamlit as st
import numpy as np
import plotly.figure_factory as ff

# Add histogram data
x1 = np.random.randn(200) - 2
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 2

# Group data together
hist_data = [x1, x2, x3]

group_labels = ['Group 1', 'Group 2', 'Group 3']

# Create distplot with custom bin_size
fig = ff.create_distplot(
        hist_data, group_labels, bin_size=[.1, .25, .5])

# Plot!
st.plotly_chart(fig, use_container_width=True)
"""

def test_chart():
    at = AppTest.from_string(APP_CODE).run()
    spec = json.loads(at.get("plotly_chart")[0].proto.figure.spec)
    pprint.pprint(spec)
    assert True == False

1 Like

Thank you very much @jcarroll ! This is great.

I’ll play around with this approach until you ship that new method you mentioned. :grinning: :+1:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.