- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I write unit tests against code that uses Matplotlib?
To write unit test cases against a code, we can consider a plot that takes an array as x points and plot it as y=x^2. While testing, we would extract y_data for x data points.−
Steps
- Create a method, i.e., plot_sqr_curve(x) to plot x and x^2 using plot() method and return the plot.
- To test, use unittest.TestCase.
- Write test_curve_sqr_plot() method that includes the following statements.
- Create data points for x to plot the curve.
- Using the above x data points, create y data points.
- Using x and y data points, plot the curve.
- Using pt (from step 5), extract x and y data.
- Check whether the given expression is true or not.
Example
import unittest import numpy as np from matplotlib import pyplot as plt def plot_sqr_curve(x): """ Plotting x points with y = x^2. """ return plt.plot(x, np.square(x)) class TestSqrCurve(unittest.TestCase): def test_curve_sqr_plot(self): x = np.array([1, 3, 4]) y = np.square(x) pt, = plot_sqr_curve(x) y_data = pt.get_data()[1] x_data = pt.get_data()[0] self.assertTrue((y == y_data).all()) self.assertTrue((x == x_data).all()) if __name__ == '__main__': unittest.main()
Output
Ran 1 test in 1.587s OK
- Related Articles
- How can I get the length of a single unit on an axis in Matplotlib?
- How can one know that they are anaemic without medical tests?
- What is a Sniffer, and How Can I Protect Against Sniffing?
- How can I add debugging code to my JavaScript?
- How can I profile C++ code running in Linux?
- How can I profile C++ code running on Linux?
- How can I write a try/except block that catches all Python exceptions?
- How can I match a comma separated list against a value in MySQL?
- How can I show figures separately in Matplotlib?
- How can I plot hysteresis threshold in Matplotlib?
- Unit Testing for C# Code
- How can I plot a confusion matrix in matplotlib?
- How can I cycle through line styles in Matplotlib?
- How can I draw inline line labels in Matplotlib?
- How can I hide the axes in Matplotlib 3D?

Advertisements