I am currently trying to design some tests to run with pytest for a GUI. The GUI has a button that plots a graph on click. I want to make sure the button does indeed generate a graph. At this stage, I am not verifying if the graph has the correct data; I am just interested in knowing if the graph does plot something.
My thinking is to check if a mock plt.show() is called whenever I call upon the method() of GraphButton: the class I use to generate the GUI and the graph. I use a mock so that the code does not load an actual graph, as that would require to manually close the window.
Unfortunately, when I run the file with pytest, I get the following message:
def assert_called_once(self):
"""assert that the mock was called only once.
"""
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times.%s"
% (self._mock_name or 'mock',
self.call_count,
self._calls_repr()))
> raise AssertionError(msg)
E AssertionError: Expected 'show' to have been called once. Called 0 times.
I have seen this question, unfortunately, the accepted answer gives me the same issue.
Here is the simplified code I used to design the test.
In the random_file
:
import tkinter as tk
from tk import *
import matplotlib.pyplot as plt
class GraphButton:
def __init__(self, window):
self.window = window
def graph(self):
# Generate x values
x = range(-10, 11)
# Calculate y values (y = x)
y = [val for val in x]
# Plot the graph
plt.plot(x, y)
# Add labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of y = x')
# Display the graph
plt.grid(True)
plt.show()
def create_button(self):
self.button = tk.Button(self.window, text="hello", command=self.graph)
self.button.grid(column=0, row=0)
In the gui_test
:
from random_file import GraphButton
import tkinter as tk
from tk import *
from unittest.mock import patch
import matplotlib
window = tk.Tk()
window.title("test gui")
window.geometry('500x500')
@patch('matplotlib.pyplot.show')
def test_button(mock_pyplot):
base = GraphButton(window=window)
base.create_button()
base.button.invoke()
mock_pyplot.show.assert_called_once()
Do you know why this happens?
mock_pyplot.show.assert_called_once()
bymatplotlib.pyplot.show.show.assert_called_once()
. When I run pytest, I still have the same AssertionError tho...