Mostly Python

Mostly Python

Share this post

Mostly Python
Mostly Python
Testing a book's code, part 5: Testing Plotly data visualizations

Testing a book's code, part 5: Testing Plotly data visualizations

MP 82: Testing complex HTML output, and output that varies based on API calls.

Eric Matthes's avatar
Eric Matthes
Feb 08, 2024
∙ Paid
4

Share this post

Mostly Python
Mostly Python
Testing a book's code, part 5: Testing Plotly data visualizations
Share

Note: This is the fifth post in a series about testing. This post, and the ones that follow will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.


In the previous post we tested the output of programs that use Matplotlib to generate plots. Most of that work focused on testing output images, but we also dealt with randomness and metadata.

In this post we’ll test programs that use Plotly to generate visualizations. We’ll use some of what we learned in the Matplotlib tests, but we’ll also run into some new challenges in this test suite. For example, what do you do when two 3.4MB HTML files differ by only 100 characters?

Rolling dice

The first three programs we need to test simulate rolling a variety of dice. Here’s the structure of the first program:

# Create a D6.
die = Die()

# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
    ...

# Analyze the results.
frequencies = []
...

# Visualize the results.
title = "Results of Rolling One D6 1,000 Times"
labels = {'x': 'Result', 'y': 'Frequency of Result'}
fig = px.bar(x=poss_results, y=frequencies, title=title, labels=labels)
fig.show()

This program creates a model of a six-sided die, makes 1,000 rolls, and generates a histogram of the results:

Using fig.show(), Plotly generates an HTML file that shows the plot in a browser tab.

The fig.show() method writes an HTML file to a temporary location, and opens that file in a browser. In the test function, we’ll replace fig.show() with a call to fig.write_html(), and then work with that HTML file directly.

Testing die programs

In a new test module, test_plotly_programs.py, we’ll first copy the files we need to a temp directory:

Keep reading with a 7-day free trial

Subscribe to Mostly Python to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Eric Matthes
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share