source: sasview/src/sas/qtgui/Plotting/UnitTesting/PlotterTest.py @ e4c475b7

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since e4c475b7 was 63319b0, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

unit tests for constraints: FittingWidget?, FittingPerspective?

  • Property mode set to 100644
File size: 16.3 KB
RevLine 
[6d05e1d]1import sys
2import unittest
[b2a5042]3import platform
[6d05e1d]4
[53c771e]5from PyQt5 import QtGui, QtWidgets, QtPrintSupport
6from PyQt5 import QtCore
7from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
[7fb471d]8from unittest.mock import MagicMock
9from unittest.mock import patch
[6d05e1d]10
11####### TEMP
[416fa8f]12import path_prepare
[6d05e1d]13#######
[dc5ef15]14from sas.qtgui.Plotting.PlotterData import Data1D
15from sas.qtgui.Plotting.PlotterData import Data2D
16from sas.qtgui.UnitTesting.TestUtils import WarningTestNotImplemented
[83eb5208]17from sas.qtgui.Plotting.LinearFit import LinearFit
18from sas.qtgui.Plotting.PlotProperties import PlotProperties
[6d05e1d]19
20# Tested module
[83eb5208]21import sas.qtgui.Plotting.Plotter as Plotter
[6d05e1d]22
[53c771e]23if not QtWidgets.QApplication.instance():
24    app = QtWidgets.QApplication(sys.argv)
[6d05e1d]25
[87cc73a]26
[6d05e1d]27class PlotterTest(unittest.TestCase):
28    '''Test the Plotter 1D class'''
29    def setUp(self):
30        '''create'''
[257bd57]31
[6d05e1d]32        self.plotter = Plotter.Plotter(None, quickplot=True)
33        self.data = Data1D(x=[1.0, 2.0, 3.0],
34                           y=[10.0, 11.0, 12.0],
35                           dx=[0.1, 0.2, 0.3],
36                           dy=[0.1, 0.2, 0.3])
37        self.data.title="Test data"
[aadf0af1]38        self.data.name="Test name"
[6d05e1d]39        self.data.id = 1
[b2a5042]40        self.isWindows = platform.system=="Windows"
[6d05e1d]41
42    def tearDown(self):
43        '''destroy'''
44        self.plotter = None
45
46    def testDataProperty(self):
47        """ Adding data """
48        self.plotter.data = self.data
49
50        self.assertEqual(self.plotter.data, self.data)
[aadf0af1]51        self.assertEqual(self.plotter._title, self.data.name)
[63319b0]52        self.assertEqual(self.plotter.xLabel, "")
53        self.assertEqual(self.plotter.yLabel, "")
[6d05e1d]54
[fecfe28]55    def testPlotWithErrors(self):
56        """ Look at the plotting with error bars"""
[6d05e1d]57        self.plotter.data = self.data
58        self.plotter.show()
[53c771e]59        FigureCanvas.draw_idle = MagicMock()
[6d05e1d]60
[fecfe28]61        self.plotter.plot(hide_error=False)
[6d05e1d]62
[fecfe28]63        self.assertEqual(self.plotter.ax.get_xscale(), 'log')
[53c771e]64        self.assertTrue(FigureCanvas.draw_idle.called)
65
66        self.plotter.figure.clf()
[fecfe28]67
68    def testPlotWithoutErrors(self):
69        """ Look at the plotting without error bars"""
70        self.plotter.data = self.data
71        self.plotter.show()
[53c771e]72        FigureCanvas.draw_idle = MagicMock()
[fecfe28]73
74        self.plotter.plot(hide_error=True)
75
76        self.assertEqual(self.plotter.ax.get_yscale(), 'log')
[53c771e]77        self.assertTrue(FigureCanvas.draw_idle.called)
78        self.plotter.figure.clf()
[6d05e1d]79
[749b715]80    def testPlotWithSesans(self):
81        """ Ensure that Sesans data is plotted in linear cooredinates"""
82        data = Data1D(x=[1.0, 2.0, 3.0],
83                      y=[10.0, 11.0, 12.0],
84                      dx=[0.1, 0.2, 0.3],
85                      dy=[0.1, 0.2, 0.3])
86        data.title = "Sesans data"
87        data.name = "Test Sesans"
88        data.isSesans = True
89        data.id = 2
90
91        self.plotter.data = data
92        self.plotter.show()
[63319b0]93        FigureCanvas.draw_idle = MagicMock()
[749b715]94
95        self.plotter.plot(hide_error=True)
96
97        self.assertEqual(self.plotter.ax.get_xscale(), 'linear')
98        self.assertEqual(self.plotter.ax.get_yscale(), 'linear')
[63319b0]99        self.assertTrue(FigureCanvas.draw_idle.called)
[749b715]100
[b46f285]101    def testCreateContextMenuQuick(self):
[6d05e1d]102        """ Test the right click menu """
[aadf0af1]103        self.plotter.createContextMenuQuick()
[6d05e1d]104        actions = self.plotter.contextMenu.actions()
105        self.assertEqual(len(actions), 7)
106
107        # Trigger Save Image and make sure the method is called
108        self.assertEqual(actions[0].text(), "Save Image")
109        self.plotter.toolbar.save_figure = MagicMock()
110        actions[0].trigger()
111        self.assertTrue(self.plotter.toolbar.save_figure.called)
112
113        # Trigger Print Image and make sure the method is called
114        self.assertEqual(actions[1].text(), "Print Image")
[53c771e]115        QtPrintSupport.QPrintDialog.exec_ = MagicMock(return_value=QtWidgets.QDialog.Rejected)
[6d05e1d]116        actions[1].trigger()
[53c771e]117        self.assertTrue(QtPrintSupport.QPrintDialog.exec_.called)
[6d05e1d]118
119        # Trigger Copy to Clipboard and make sure the method is called
120        self.assertEqual(actions[2].text(), "Copy to Clipboard")
121
122        # Trigger Toggle Grid and make sure the method is called
123        self.assertEqual(actions[4].text(), "Toggle Grid On/Off")
124        self.plotter.ax.grid = MagicMock()
125        actions[4].trigger()
126        self.assertTrue(self.plotter.ax.grid.called)
127
128        # Trigger Change Scale and make sure the method is called
129        self.assertEqual(actions[6].text(), "Change Scale")
[53c771e]130        self.plotter.properties.exec_ = MagicMock(return_value=QtWidgets.QDialog.Rejected)
[6d05e1d]131        actions[6].trigger()
132        self.assertTrue(self.plotter.properties.exec_.called)
133
[b2a5042]134        # Spy on cliboard's dataChanged() signal
135        if not self.isWindows:
136            return
137        self.clipboard_called = False
138        def done():
139            self.clipboard_called = True
[53c771e]140        QtCore.QObject.connect(QtWidgets.qApp.clipboard(), QtCore.SIGNAL("dataChanged()"), done)
[b2a5042]141        actions[2].trigger()
[53c771e]142        QtWidgets.qApp.processEvents()
[b2a5042]143        # Make sure clipboard got updated.
144        self.assertTrue(self.clipboard_called)
145
[b46f285]146    def testXyTransform(self):
147        """ Tests the XY transformation and new chart update """
[257bd57]148        self.plotter.plot(self.data)
[6d05e1d]149
[b46f285]150        # Transform the points
151        self.plotter.xyTransform(xLabel="x", yLabel="log10(y)")
[6d05e1d]152
[b46f285]153        # Assure new plot has correct labels
[64f1e93]154        self.assertEqual(self.plotter.ax.get_xlabel(), "$()$")
155        self.assertEqual(self.plotter.ax.get_ylabel(), "$()$")
[b46f285]156        # ... and scale
157        self.assertEqual(self.plotter.xscale, "linear")
158        self.assertEqual(self.plotter.yscale, "log")
159        # See that just one plot is present
160        self.assertEqual(len(self.plotter.plot_dict), 1)
161        self.assertEqual(len(self.plotter.ax.collections), 1)
[53c771e]162        self.plotter.figure.clf()
[64f1e93]163
[9290b1a]164    def testAddText(self):
165        """ Checks the functionality of adding text to graph """
[257bd57]166
167        self.plotter.plot(self.data)
168        self.plotter.x_click = 100.0
169        self.plotter.y_click = 100.0
170        # modify the text edit control
171        test_text = "Smoke in cabin"
172        test_font = QtGui.QFont("Arial", 16, QtGui.QFont.Bold)
173        test_color = "#00FF00"
174        self.plotter.addText.textEdit.setText(test_text)
175
176        # Return the requested font parameters
177        self.plotter.addText.font = MagicMock(return_value = test_font)
178        self.plotter.addText.color = MagicMock(return_value = test_color)
179        # Return OK from the dialog
[53c771e]180        self.plotter.addText.exec_ = MagicMock(return_value = QtWidgets.QDialog.Accepted)
[257bd57]181        # Add text to graph
182        self.plotter.onAddText()
183        self.plotter.show()
184        # Check if the text was added properly
185        self.assertEqual(len(self.plotter.textList), 1)
186        self.assertEqual(self.plotter.textList[0].get_text(), test_text)
187        self.assertEqual(self.plotter.textList[0].get_color(), test_color)
188        self.assertEqual(self.plotter.textList[0].get_fontproperties().get_family()[0], 'Arial')
189        self.assertEqual(self.plotter.textList[0].get_fontproperties().get_size(), 16)
[53c771e]190        self.plotter.figure.clf()
[9290b1a]191
192    def testOnRemoveText(self):
193        """ Cheks if annotations can be removed from the graph """
[257bd57]194
195        # Add some text
196        self.plotter.plot(self.data)
197        test_text = "Safety instructions"
198        self.plotter.addText.textEdit.setText(test_text)
199        # Return OK from the dialog
[53c771e]200        self.plotter.addText.exec_ = MagicMock(return_value = QtWidgets.QDialog.Accepted)
[257bd57]201        # Add text to graph
[63319b0]202        self.plotter.x_click = 1.0
203        self.plotter.y_click = 5.0
[257bd57]204        self.plotter.onAddText()
205        self.plotter.show()
206        # Check if the text was added properly
207        self.assertEqual(len(self.plotter.textList), 1)
208
209        # Now, remove the text
210        self.plotter.onRemoveText()
211
212        # And assure no text is displayed
213        self.assertEqual(self.plotter.textList, [])
214
215        # Attempt removal on empty and check
216        self.plotter.onRemoveText()
217        self.assertEqual(self.plotter.textList, [])
[53c771e]218        self.plotter.figure.clf()
[9290b1a]219
[d3ca363]220    def testOnSetGraphRange(self):
221        """ Cheks if the graph can be resized for range """
[257bd57]222        new_x = (1,2)
223        new_y = (10,11)
224        self.plotter.plot(self.data)
225        self.plotter.show()
[53c771e]226        self.plotter.setRange.exec_ = MagicMock(return_value = QtWidgets.QDialog.Accepted)
[257bd57]227        self.plotter.setRange.xrange = MagicMock(return_value = new_x)
228        self.plotter.setRange.yrange = MagicMock(return_value = new_y)
229
230        # Call the tested method
231        self.plotter.onSetGraphRange()
232        # See that ranges changed accordingly
233        self.assertEqual(self.plotter.ax.get_xlim(), new_x)
234        self.assertEqual(self.plotter.ax.get_ylim(), new_y)
[53c771e]235        self.plotter.figure.clf()
[d3ca363]236
237    def testOnResetGraphRange(self):
238        """ Cheks if the graph can be reset after resizing for range """
[257bd57]239        # New values
240        new_x = (1,2)
241        new_y = (10,11)
242        # define the plot
243        self.plotter.plot(self.data)
244        self.plotter.show()
245
246        # mock setRange methods
[53c771e]247        self.plotter.setRange.exec_ = MagicMock(return_value = QtWidgets.QDialog.Accepted)
[257bd57]248        self.plotter.setRange.xrange = MagicMock(return_value = new_x)
249        self.plotter.setRange.yrange = MagicMock(return_value = new_y)
250
251        # Change the axes range
252        self.plotter.onSetGraphRange()
253
254        # Now, reset the range back
255        self.plotter.onResetGraphRange()
256
257        # See that ranges are changed
258        self.assertNotEqual(self.plotter.ax.get_xlim(), new_x)
259        self.assertNotEqual(self.plotter.ax.get_ylim(), new_y)
[53c771e]260        self.plotter.figure.clf()
[9290b1a]261
[b46f285]262    def testOnLinearFit(self):
263        """ Checks the response to LinearFit call """
[2e3e959]264        self.plotter.plot(self.data)
265        self.plotter.show()
[53c771e]266        QtWidgets.QDialog.exec_ = MagicMock(return_value=QtWidgets.QDialog.Accepted)
[2e3e959]267
268        # Just this one plot
[7fb471d]269        self.assertEqual(len(list(self.plotter.plot_dict.keys())), 1)
[2e3e959]270        self.plotter.onLinearFit(1)
271
272        # Check that exec_ got called
[53c771e]273        self.assertTrue(QtWidgets.QDialog.exec_.called)
274        self.plotter.figure.clf()
[b46f285]275
276    def testOnRemovePlot(self):
277        """ Assure plots get removed when requested """
[2e3e959]278        # Add two plots
279        self.plotter.show()
280        self.plotter.plot(self.data)
281        data2 = Data1D(x=[1.0, 2.0, 3.0],
282                       y=[11.0, 12.0, 13.0],
283                       dx=[0.1, 0.2, 0.3],
284                       dy=[0.1, 0.2, 0.3])
285        data2.title="Test data 2"
286        data2.name="Test name 2"
287        data2.id = 2
288        self.plotter.plot(data2)
289
290        # Assure the plotter window is visible
[0268aed]291        #self.assertTrue(self.plotter.isVisible())
[2e3e959]292
293        # Assure we have two sets
[7fb471d]294        self.assertEqual(len(list(self.plotter.plot_dict.keys())), 2)
[2e3e959]295
296        # Delete one set
297        self.plotter.onRemovePlot(2)
298        # Assure we have two sets
[7fb471d]299        self.assertEqual(len(list(self.plotter.plot_dict.keys())), 1)
[2e3e959]300
301        self.plotter.manager = MagicMock()
302
303        # Delete the remaining set
304        self.plotter.onRemovePlot(1)
305        # Assure we have no plots
[7fb471d]306        self.assertEqual(len(list(self.plotter.plot_dict.keys())), 0)
[2e3e959]307        # Assure the plotter window is closed
308        self.assertFalse(self.plotter.isVisible())
[53c771e]309        self.plotter.figure.clf()
[b46f285]310
311    def testRemovePlot(self):
312        """ Test plot removal """
[2e3e959]313        # Add two plots
314        self.plotter.show()
315        self.plotter.plot(self.data)
316        data2 = Data1D(x=[1.0, 2.0, 3.0],
317                       y=[11.0, 12.0, 13.0],
318                       dx=[0.1, 0.2, 0.3],
319                       dy=[0.1, 0.2, 0.3])
320        data2.title="Test data 2"
321        data2.name="Test name 2"
322        data2.id = 2
323        data2._xaxis = "XAXIS"
324        data2._xunit = "furlong*fortnight^{-1}"
325        data2._yaxis = "YAXIS"
326        data2._yunit = "cake"
327        data2.hide_error = True
328        self.plotter.plot(data2)
329
330        # delete plot 1
331        self.plotter.removePlot(1)
332
333        # See that the labels didn't change
334        xl = self.plotter.ax.xaxis.label.get_text()
335        yl = self.plotter.ax.yaxis.label.get_text()
336        self.assertEqual(xl, "$XAXIS(furlong*fortnight^{-1})$")
337        self.assertEqual(yl, "$YAXIS(cake)$")
338        # The hide_error flag should also remain
339        self.assertTrue(self.plotter.plot_dict[2].hide_error)
[53c771e]340        self.plotter.figure.clf()
[b46f285]341
342    def testOnToggleHideError(self):
343        """ Test the error bar toggle on plots """
[2e3e959]344        # Add two plots
345        self.plotter.show()
346        self.plotter.plot(self.data)
347        data2 = Data1D(x=[1.0, 2.0, 3.0],
348                       y=[11.0, 12.0, 13.0],
349                       dx=[0.1, 0.2, 0.3],
350                       dy=[0.1, 0.2, 0.3])
351        data2.title="Test data 2"
352        data2.name="Test name 2"
353        data2.id = 2
354        data2._xaxis = "XAXIS"
355        data2._xunit = "furlong*fortnight^{-1}"
356        data2._yaxis = "YAXIS"
357        data2._yunit = "cake"
358        error_status = True
359        data2.hide_error = error_status
360        self.plotter.plot(data2)
361
362        # Reverse the toggle
363        self.plotter.onToggleHideError(2)
364        # See that the labels didn't change
365        xl = self.plotter.ax.xaxis.label.get_text()
366        yl = self.plotter.ax.yaxis.label.get_text()
367        self.assertEqual(xl, "$XAXIS(furlong*fortnight^{-1})$")
368        self.assertEqual(yl, "$YAXIS(cake)$")
369        # The hide_error flag should toggle
370        self.assertEqual(self.plotter.plot_dict[2].hide_error, not error_status)
[53c771e]371        self.plotter.figure.clf()
[b46f285]372
373    def testOnFitDisplay(self):
374        """ Test the fit line display on the chart """
[2e3e959]375        self.assertIsInstance(self.plotter.fit_result, Data1D)
376        self.assertEqual(self.plotter.fit_result.symbol, 13)
377        self.assertEqual(self.plotter.fit_result.name, "Fit")
378
379        # fudge some init data
380        fit_data = [[0.0,0.0], [5.0,5.0]]
381        # Call the method
382        self.plotter.plot = MagicMock()
383        self.plotter.onFitDisplay(fit_data)
384        self.assertTrue(self.plotter.plot.called)
385        # Look at arguments passed to .plot()
386        self.plotter.plot.assert_called_with(data=self.plotter.fit_result,
387                                             hide_error=True, marker='-')
[53c771e]388        self.plotter.figure.clf()
[87cc73a]389
390    def testReplacePlot(self):
391        """ Test the plot refresh functionality """
[2e3e959]392        # Add original data
393        self.plotter.show()
394        self.plotter.plot(self.data)
395        # See the default labels
396        xl = self.plotter.ax.xaxis.label.get_text()
397        yl = self.plotter.ax.yaxis.label.get_text()
[63319b0]398        self.assertEqual(xl, "")
399        self.assertEqual(yl, "")
[2e3e959]400
401        # Prepare new data
402        data2 = Data1D(x=[1.0, 2.0, 3.0],
403                       y=[11.0, 12.0, 13.0],
404                       dx=[0.1, 0.2, 0.3],
405                       dy=[0.1, 0.2, 0.3])
406        data2.title="Test data 2"
407        data2.name="Test name 2"
408        data2.id = 2
409        data2._xaxis = "XAXIS"
410        data2._xunit = "furlong*fortnight^{-1}"
411        data2._yaxis = "YAXIS"
412        data2._yunit = "cake"
413        error_status = True
414        data2.hide_error = error_status
415
416        # Replace data in plot
417        self.plotter.replacePlot(1, data2)
418
419        # See that the labels changed
420        xl = self.plotter.ax.xaxis.label.get_text()
421        yl = self.plotter.ax.yaxis.label.get_text()
422        self.assertEqual(xl, "$XAXIS(furlong*fortnight^{-1})$")
423        self.assertEqual(yl, "$YAXIS(cake)$")
424        # The hide_error flag should be as set
425        self.assertEqual(self.plotter.plot_dict[2].hide_error, error_status)
[53c771e]426        self.plotter.figure.clf()
[87cc73a]427
[83eb5208]428    def notestOnModifyPlot(self):
[87cc73a]429        """ Test the functionality for changing plot properties """
[2e3e959]430        # Prepare new data
431        data2 = Data1D(x=[1.0, 2.0, 3.0],
432                       y=[11.0, 12.0, 13.0],
433                       dx=[0.1, 0.2, 0.3],
434                       dy=[0.1, 0.2, 0.3])
435        data2.title="Test data 2"
436        data2.name="Test name 2"
437        data2.id = 2
438        data2.custom_color = None
439        data2.symbol = 1
440        data2.markersize = 11
441
442        self.plotter.plot(data2)
443
[83eb5208]444        with patch('sas.qtgui.Plotting.PlotProperties.PlotProperties') as mock:
[2e3e959]445            instance = mock.return_value
[53c771e]446            QtWidgets.QDialog.exec_ = MagicMock(return_value=QtWidgets.QDialog.Accepted)
[2e3e959]447            instance.symbol.return_value = 7
448
449            self.plotter.onModifyPlot(2)
[53c771e]450        self.plotter.figure.clf()
[2e3e959]451
[b46f285]452
[6d05e1d]453if __name__ == "__main__":
454    unittest.main()
Note: See TracBrowser for help on using the repository browser.