source: sasview/src/sas/qtgui/Utilities/UnitTesting/GridPanelTest.py @ 80468f6

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 80468f6 was 80468f6, checked in by Piotr Rozyczko <rozyczko@…>, 4 years ago

Fixed a few unit test files

  • Property mode set to 100644
File size: 5.5 KB
Line 
1import sys
2import numpy as np
3import unittest
4from unittest.mock import mock_open, patch
5import webbrowser
6import logging
7
8from unittest.mock import MagicMock
9
10from PyQt5 import QtGui, QtWidgets
11
12# set up import paths
13import path_prepare
14
15from sas.qtgui.UnitTesting.TestUtils import QtSignalSpy
16
17from sas.sascalc.fit.AbstractFitEngine import FResult
18from sas.sascalc.fit.AbstractFitEngine import FitData1D
19from sasmodels.sasview_model import load_standard_models
20from sas.qtgui.Plotting.PlotterData import Data1D
21
22import sas.qtgui.Utilities.GuiUtils as GuiUtils
23# Local
24from sas.qtgui.Utilities.GridPanel import BatchOutputPanel
25
26if not QtWidgets.QApplication.instance():
27    app = QtWidgets.QApplication(sys.argv)
28
29class BatchOutputPanelTest(unittest.TestCase):
30    '''Test the batch output dialog'''
31    def setUp(self):
32        '''Create the dialog'''
33        # dummy perspective
34        class dummy_manager(object):
35            _parent = QtWidgets.QWidget()
36            def communicator(self):
37                return GuiUtils.Communicate()
38            def communicate(self):
39                return GuiUtils.Communicate()
40        self.widget = BatchOutputPanel(parent=dummy_manager(), output_data=self.output_for_test())
41        test_table = {"p1":[1,2,3],
42                      "p2":[4,5,None],
43                      "":["a",credits,],
44                      "":[]}
45
46    def tearDown(self):
47        '''Destroy the GUI'''
48        self.widget.close()
49        self.widget = None
50
51    def output_for_test(self):
52        ''' define DATA1D structure for testing'''
53        # dummy parameter set
54        m = None
55        for m in load_standard_models():
56            if m.name == "core_shell_ellipsoid":
57                model = m()
58        self.assertIsNotNone(m)
59        data = Data1D(x=[1,2], y=[3,4], dx=[0.1, 0.1], dy=[0.,0.])
60        fit_data = FitData1D(x=[1,2], y=[3,4], data=data)
61        param_list = ['sld_shell', 'sld_solvent']
62        output = FResult(model=model, data=fit_data, param_list=param_list)
63        output.sas_data = data
64        output.theory = np.array([0.1,0.2])
65        output.pvec = np.array([0.1, 0.02])
66        output.residuals = np.array([0.01, 0.02])
67        output.fitness = 9000.0
68        output.fitter_id = 200
69        output.stderr = [0.001, 0.001]
70        output_data = [[output],[output]]
71        return output_data
72
73    def testDefaults(self):
74        '''Test the GUI in its default state'''
75        self.assertIsInstance(self.widget, QtWidgets.QMainWindow)
76        # Default title
77        self.assertEqual(self.widget.windowTitle(), "Batch Fitting Results")
78
79        # non-modal window
80        self.assertFalse(self.widget.isModal())
81
82    def testActionLoadData(self):
83        '''Test CSV data loader'''
84        test_csv = mock_open(read_data = ("""\
85File generated by SasView\n
86Chi2,Data,scale,background,radius_equat_core,x_core,thick_shell,x_polar_shell,sld_core,sld_shell,sld_solvent,theta,phi,\n
871917.8,cyl_400_40.txt,1,0.001,20,3,30,1,-85.088,-97.636,-92.797,0,0,\n
882.6169,cyl_400_20.txt,1,0.001,20,3,30,1,914.64,906.09,905.67,0,0,\n
89"""))
90        logging.info = MagicMock()
91        self.widget.setupTableFromCSV = MagicMock()
92
93        # No filename given
94        QtWidgets.QFileDialog.getOpenFileName = MagicMock(return_value=[""])
95        self.widget.actionLoadData()
96        # Assure parser wasn't called and logging got a message
97        self.assertTrue(logging.info.called_once())
98        self.assertIn("No data", logging.info.call_args[0][0])
99
100        # Filename given
101        QtWidgets.QFileDialog.getOpenFileName = MagicMock(return_value="test")
102        with patch('builtins.open', test_csv):
103            self.widget.actionLoadData()
104            # Assure parser was called
105            self.assertTrue(self.widget.actionLoadData)
106            self.widget.setupTableFromCSV.assert_called_once()
107            self.assertIn("File generated by SasView", self.widget.setupTableFromCSV.call_args[0][0][0])
108
109    def notestPlotFits(self):
110        '''Test plot generation from selected table rows'''
111        # mock tested calls
112        #GuiUtils.Communicate.plot
113        spy_plot_signal = QtSignalSpy(self.widget.communicate, self.widget.communicate().plotFromFilenameSignal)
114        # Select row #1
115        self.widget.tblParams.selectRow(0)
116        QtWidgets.QApplication.processEvents()
117
118        # See that the signal was emitted
119        self.assertEqual(spy_plot_signal.count(), 1)
120        self.assertIn("ddd", str(spy_plot_signal.called()[0]['args'][0]))
121
122
123    def testDataFromTable(self):
124        '''Test dictionary generation from data'''
125        params = self.widget.dataFromTable(self.widget.tblParams)
126        self.assertEqual(len(params), 13)
127        self.assertEqual(params['Chi2'][0], '9000')
128        self.assertEqual(params['Data'][1], '')
129        self.assertEqual(params['sld_solvent'][1], '0.02')
130
131    def testActionSendToExcel(self):
132        '''Test Excel bindings'''
133        pass
134
135    def testActionSaveFile(self):
136        '''Test file save'''
137        self.widget.writeBatchToFile = MagicMock()
138
139        # user cancels dialog
140        QtWidgets.QFileDialog.getSaveFileName = MagicMock(return_value=("","BOOP"))
141        # write not called
142        self.widget.actionSaveFile()
143        self.widget.writeBatchToFile.assert_not_called()
144
145        # user chooses proper name
146        QtWidgets.QFileDialog.getSaveFileName = MagicMock(return_value=("plop","BOOP"))
147        # write called
148        self.widget.actionSaveFile()
149        self.widget.writeBatchToFile.assert_called_once()
150
151    def testSetupTableFromCSV(self):
152        '''Test generation of grid table rows from a CSV file'''
153        pass
154
155
Note: See TracBrowser for help on using the repository browser.