source: sasview/src/sas/qtgui/UnitTesting/GuiUtilsTest.py @ ded2ce3

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 ded2ce3 was 8548d739, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

Further work on the main QStandardItemModel

  • Property mode set to 100644
File size: 11.9 KB
RevLine 
[a281ab8]1import sys
2import unittest
[f82ab8c]3import webbrowser
[a281ab8]4
[1042dba]5from PyQt4 import QtCore
6from PyQt4 import QtGui
[f82ab8c]7from mock import MagicMock
[1042dba]8
[31c5b58]9# set up import paths
10import path_prepare
11
[1042dba]12# SV imports
13from sas.sascalc.dataloader.loader import Loader
14from sas.sasgui.guiframe.data_manager import DataManager
[39551a68]15from sas.sasgui.guiframe.dataFitting import Data1D
16from sas.sasgui.guiframe.dataFitting import Data2D
[1042dba]17
[a281ab8]18# Tested module
19from GuiUtils import *
20
[39551a68]21app = QtGui.QApplication(sys.argv)
[28a84e9]22
[a281ab8]23class GuiUtilsTest(unittest.TestCase):
24    '''Test the GUI Utilities methods'''
25    def setUp(self):
26        '''Empty'''
27        pass
28
29    def tearDown(self):
[1042dba]30        '''Empty'''
[a281ab8]31        pass
32
33    def testDefaults(self):
34        """
35        Test all the global constants defined in the file.
36        """
37        # Should probably test the constants in the file,
38        # but this will done after trimming down GuiUtils
39        # and retaining only necessary variables.
40        pass
41
42    def testGetAppDir(self):
43        """
44        """
45        pass
46
47    def testGetUserDirectory(self):
48        """
49        Simple test of user directory getter
50        """
51        home_dir = os.path.expanduser("~")
52        self.assertIn(home_dir, get_user_directory())
53
54    def testCommunicate(self):
55        """
56        Test the container class with signal definitions
57        """
58        com = Communicate()
59
60        # All defined signals
61        list_of_signals = [
62            'fileReadSignal',
63            'fileDataReceivedSignal',
64            'statusBarUpdateSignal',
65            'updatePerspectiveWithDataSignal',
[f82ab8c]66            'updateModelFromPerspectiveSignal',
[e540cd2]67            'plotRequestedSignal',
68            'progressBarUpdateSignal',
[a281ab8]69        ]
70
71        # Assure all signals are defined.
72        for signal in list_of_signals:
73            self.assertIn(signal, dir(com))
74
[8548d739]75    def testupdateModelItem(self):
76        """
77        Test the generic QModelItem update method
78        """
79        test_item = QtGui.QStandardItem()
80        test_list = ['aa', 4, True, ]
81        name = "Black Sabbath"
82
83        # update the item
84        updateModelItem(test_item, test_list, name)
85
86        # Make sure test_item got all data added
87        self.assertEqual(test_item.child(0).text(), name)
88        list_from_item = test_item.child(0).data().toList()
89        self.assertIsInstance(list_from_item, list)
90        self.assertEqual(list_from_item[0].toPyObject(), test_list[0])
91        self.assertEqual(list_from_item[1].toPyObject(), test_list[1])
92        self.assertEqual(list_from_item[2].toPyObject(), test_list[2])
[a281ab8]93
[8548d739]94    def testupdateModelItemWithPlot(self):
[a281ab8]95        """
[8548d739]96        Test the QModelItem checkbox update method
[a281ab8]97        """
98        test_item = QtGui.QStandardItem()
99        test_list = ['aa','11']
100        update_data = QtCore.QVariant(test_list)
101        name = "Black Sabbath"
102
103        # update the item
[8548d739]104        updateModelItemWithPlot(test_item, update_data, name)
[a281ab8]105       
106        # Make sure test_item got all data added
107        self.assertEqual(test_item.child(0).text(), name)
108        self.assertTrue(test_item.child(0).isCheckable())
109        list_from_item = test_item.child(0).child(0).data().toPyObject()
110        self.assertIsInstance(list_from_item, list)
111        self.assertEqual(str(list_from_item[0]), test_list[0])
112        self.assertEqual(str(list_from_item[1]), test_list[1])
113
[1042dba]114
115    def testPlotsFromCheckedItems(self):
116        """
117        Test addition of a plottable to the model
118        """
119
120        # Mockup data
121        test_list0 = "FRIDAY"
122        test_list1 = "SATURDAY"
123        test_list2 = "MONDAY"
124
125        # Main item ("file")
126        checkbox_model = QtGui.QStandardItemModel()
127        checkbox_item = QtGui.QStandardItem(True)
128        checkbox_item.setCheckable(True)
129        checkbox_item.setCheckState(QtCore.Qt.Checked)
130        test_item0 = QtGui.QStandardItem()
131        test_item0.setData(QtCore.QVariant(test_list0))
132
133        # Checked item 1
134        test_item1 = QtGui.QStandardItem(True)
135        test_item1.setCheckable(True)
136        test_item1.setCheckState(QtCore.Qt.Checked)
137        object_item = QtGui.QStandardItem()
138        object_item.setData(QtCore.QVariant(test_list1))
139        test_item1.setChild(0, object_item)
140
141        checkbox_item.setChild(0, test_item0)
142        checkbox_item.appendRow(test_item1)
143
144        # Unchecked item 2
145        test_item2 = QtGui.QStandardItem(True)
146        test_item2.setCheckable(True)
147        test_item2.setCheckState(QtCore.Qt.Unchecked)
148        object_item = QtGui.QStandardItem()
149        object_item.setData(QtCore.QVariant(test_list2))
150        test_item2.setChild(0, object_item)
151        checkbox_item.appendRow(test_item2)
152
153        checkbox_model.appendRow(checkbox_item)
154
155        # Pull out the "plottable" documents
156        plot_list = plotsFromCheckedItems(checkbox_model)
157
158        # Make sure only the checked data is present
159        # FRIDAY IN
160        self.assertIn(test_list0, plot_list)
161        # SATURDAY IN
162        self.assertIn(test_list1, plot_list)
163        # MONDAY NOT IN
164        self.assertNotIn(test_list2, plot_list)
165
166    def testInfoFromData(self):
167        """
168        Test Info element extraction from a plottable object
169        """
170        loader = Loader()
171        manager = DataManager()
172
173        # get Data1D
174        p_file="cyl_400_20.txt"
175        output_object = loader.load(p_file)
176        new_data = manager.create_gui_data(output_object, p_file)
177
178        # Extract Info elements into a model item
179        item = infoFromData(new_data)
180
181        # Test the item and its children
182        self.assertIsInstance(item, QtGui.QStandardItem)
183        self.assertEqual(item.rowCount(), 5)
184        self.assertEqual(item.text(), "Info")
185        self.assertIn(p_file,   item.child(0).text())
186        self.assertIn("Run",    item.child(1).text())
187        self.assertIn("Data1D", item.child(2).text())
188        self.assertIn(p_file,   item.child(3).text())
189        self.assertIn("Process",item.child(4).text())
190
[f82ab8c]191    def testOpenLink(self):
192        """
193        Opening a link in the external browser
194        """
195        good_url1 = r"http://test.test.com"
196        good_url2 = r"mailto:test@mail.com"
197        good_url3 = r"https://127.0.0.1"
198
199        bad_url1 = ""
200        bad_url2 = QtGui.QStandardItem()
201        bad_url3 = r"poop;//**I.am.a.!bad@url"
202
203        webbrowser.open = MagicMock()
204        openLink(good_url1)
205        openLink(good_url2)
206        openLink(good_url3)
207        self.assertEqual(webbrowser.open.call_count, 3)
208
209        with self.assertRaises(AttributeError):
210            openLink(bad_url1)
211        with self.assertRaises(AttributeError):
212            openLink(bad_url2)
213        with self.assertRaises(AttributeError):
214            openLink(bad_url3)
[1042dba]215
[28a84e9]216    def testRetrieveData1d(self):
217        """
218        """
[39551a68]219        with self.assertRaises(AttributeError):
220            retrieveData1d("BOOP")
[28a84e9]221
[9968d6a]222        #data = Data1D()
223        #with self.assertRaises(ValueError):
224        #    retrieveData1d(data)
[39551a68]225
226        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0])
227
228        text = retrieveData1d(data)
229
230        self.assertIn("Temperature:", text)
231        self.assertIn("Beam_size:", text)
232        self.assertIn("X_min = 1.0:  X_max = 3.0", text)
233        self.assertIn("3.0 \t12.0 \t0.0 \t0.0", text)
[28a84e9]234
235    def testRetrieveData2d(self):
236        """
237        """
[39551a68]238        with self.assertRaises(AttributeError):
239            retrieveData2d("BOOP")
240        data = Data2D(image=[1.0, 2.0, 3.0],
241                      err_image=[0.01, 0.02, 0.03],
242                      qx_data=[0.1, 0.2, 0.3],
243                      qy_data=[0.1, 0.2, 0.3])
244
245        text = retrieveData2d(data)
246
247        self.assertIn("Type:         Data2D", text)
248        self.assertIn("I_min = 1.0", text)
249        self.assertIn("I_max = 3.0", text)
250        self.assertIn("2 \t0.3 \t0.3 \t3.0 \t0.03 \t0.0 \t0.0", text)
[28a84e9]251
252    def testOnTXTSave(self):
253        """
[39551a68]254        Test the file writer for saving 1d/2d data
[28a84e9]255        """
[39551a68]256        path = "test123"
257        if os.path.isfile(path):
258            os.remove(path)
259
260        # Broken data
261        data = Data1D(x=[1.0, 2.0, 3.0], y=[])
262        # Expect a raise
263        with self.assertRaises(IndexError):
264            onTXTSave(data, path)
265
266        # Good data - no dX/dY
267        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0])
268        onTXTSave(data, path)
269
270        self.assertTrue(os.path.isfile(path))
271        with open(path,'r') as out:
272            data_read = out.read()
273            self.assertEqual("<X>   <Y>\n1  10\n2  11\n3  12\n", data_read)
274
275        if os.path.isfile(path):
276            os.remove(path)
277
278        # Good data - with dX/dY
279        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0],
280                      dx=[0.1, 0.2, 0.3], dy=[0.1, 0.2, 0.3])
281
282        onTXTSave(data, path)
283        with open(path,'r') as out:
284            data_read = out.read()
285            self.assertIn("<X>   <Y>   <dY>   <dX>\n", data_read)
286            self.assertIn("1  10  0.1  0.1\n", data_read)
287            self.assertIn("2  11  0.2  0.2\n", data_read)
288            self.assertIn("3  12  0.3  0.3\n", data_read)
289
290        if os.path.isfile(path):
291            os.remove(path)
[28a84e9]292
293    def testSaveData1D(self):
294        """
[39551a68]295        Test the 1D file save method
[28a84e9]296        """
[39551a68]297        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0],
298                      dx=[0.1, 0.2, 0.3], dy=[0.1, 0.2, 0.3])
299
300        # Test the .txt format
301        file_name = "test123_out.txt"
302        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
303        data.filename = "test123.txt"
304        saveData1D(data)
305        self.assertTrue(os.path.isfile(file_name))
306        os.remove(file_name)
307
308        # Test the .xml format
309        file_name = "test123_out.xml"
310        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
311        data.filename = "test123.xml"
312        saveData1D(data)
313        self.assertTrue(os.path.isfile(file_name))
314        os.remove(file_name)
315
316        # Test the wrong format
317        file_name = "test123_out.mp3"
318        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
319        data.filename = "test123.mp3"
320        saveData1D(data)
321        self.assertFalse(os.path.isfile(file_name))
[28a84e9]322
323    def testSaveData2D(self):
324        """
[39551a68]325        Test the 1D file save method
[28a84e9]326        """
[39551a68]327        data = Data2D(image=[1.0, 2.0, 3.0],
328                      err_image=[0.01, 0.02, 0.03],
329                      qx_data=[0.1, 0.2, 0.3],
330                      qy_data=[0.1, 0.2, 0.3])
331
332        # Test the .txt format
333        file_name = "test123_out.dat"
334        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
335        data.filename = "test123.dat"
336        saveData2D(data)
337        self.assertTrue(os.path.isfile(file_name))
338        os.remove(file_name)
339
340        # Test the wrong format
341        file_name = "test123_out.mp3"
342        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
343        data.filename = "test123.mp3"
344        saveData2D(data)
345        self.assertFalse(os.path.isfile(file_name))
346
[e4676c8]347class FormulaValidatorTest(unittest.TestCase):
348    """ Test the formula validator """
349    def setUp(self):
350        '''Create the validator'''
351        self.validator = FormulaValidator()
352
353    def tearDown(self):
354        '''Destroy the validator'''
355        self.validator = None
356
357    def testValidateGood(self):
358        """Test a valid Formula """
359        formula_good = "H24O12C4C6N2Pu"
360        self.assertEqual(self.validator.validate(formula_good, 1)[0], QtGui.QValidator.Acceptable)
361
362        formula_good = "(H2O)0.5(D2O)0.5"
363        self.assertEqual(self.validator.validate(formula_good, 1)[0], QtGui.QValidator.Acceptable)
364
365    def testValidateBad(self):
366        """Test a valid Formula """
367        formula_bad = "H24 %%%O12C4C6N2Pu"
368        self.assertRaises(self.validator.validate(formula_bad, 1)[0])
369        self.assertEqual(self.validator.validate(formula_bad, 1)[0], QtGui.QValidator.Intermediate)
370
371        formula_bad = [1]
372        self.assertEqual(self.validator.validate(formula_bad, 1)[0], QtGui.QValidator.Intermediate)
373
[28a84e9]374
[a281ab8]375if __name__ == "__main__":
376    unittest.main()
377
Note: See TracBrowser for help on using the repository browser.