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

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 0532d7c1 was 27313b7, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

Added window title GUI for charts

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