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

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 161713c was 965fbd8, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

More merge related fixes

  • Property mode set to 100644
File size: 14.8 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[0])
162        # SATURDAY IN
163        self.assertIn(test_list1, plot_list[1])
164        # MONDAY NOT IN
165        self.assertNotIn(test_list2, plot_list[0])
166        self.assertNotIn(test_list2, plot_list[1])
167
168    def testInfoFromData(self):
169        """
170        Test Info element extraction from a plottable object
171        """
172        loader = Loader()
173        manager = DataManager()
174
175        # get Data1D
176        p_file="cyl_400_20.txt"
177        output_object = loader.load(p_file)
178        new_data = manager.create_gui_data(output_object, p_file)
179
180        # Extract Info elements into a model item
181        item = infoFromData(new_data)
182
183        # Test the item and its children
184        self.assertIsInstance(item, QtGui.QStandardItem)
185        self.assertEqual(item.rowCount(), 5)
186        self.assertEqual(item.text(), "Info")
187        self.assertIn(p_file,   item.child(0).text())
188        self.assertIn("Run",    item.child(1).text())
189        self.assertIn("Data1D", item.child(2).text())
190        self.assertIn(p_file,   item.child(3).text())
191        self.assertIn("Process",item.child(4).text())
192
193    def testOpenLink(self):
194        """
195        Opening a link in the external browser
196        """
197        good_url1 = r"http://test.test.com"
198        good_url2 = r"mailto:test@mail.com"
199        good_url3 = r"https://127.0.0.1"
200
201        bad_url1 = ""
202        bad_url2 = QtGui.QStandardItem()
203        bad_url3 = r"poop;//**I.am.a.!bad@url"
204
205        webbrowser.open = MagicMock()
206        openLink(good_url1)
207        openLink(good_url2)
208        openLink(good_url3)
209        self.assertEqual(webbrowser.open.call_count, 3)
210
211        with self.assertRaises(AttributeError):
212            openLink(bad_url1)
213        with self.assertRaises(AttributeError):
214            openLink(bad_url2)
215        with self.assertRaises(AttributeError):
216            openLink(bad_url3)
217
218    def testRetrieveData1d(self):
219        """
220        """
221        with self.assertRaises(AttributeError):
222            retrieveData1d("BOOP")
223
224        #data = Data1D()
225        #with self.assertRaises(ValueError):
226        #    retrieveData1d(data)
227
228        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0])
229
230        text = retrieveData1d(data)
231
232        self.assertIn("Temperature:", text)
233        self.assertIn("Beam_size:", text)
234        self.assertIn("X_min = 1.0:  X_max = 3.0", text)
235        self.assertIn("3.0 \t12.0 \t0.0 \t0.0", text)
236
237    def testRetrieveData2d(self):
238        """
239        """
240        with self.assertRaises(AttributeError):
241            retrieveData2d("BOOP")
242        data = Data2D(image=[1.0, 2.0, 3.0],
243                      err_image=[0.01, 0.02, 0.03],
244                      qx_data=[0.1, 0.2, 0.3],
245                      qy_data=[0.1, 0.2, 0.3])
246
247        text = retrieveData2d(data)
248
249        self.assertIn("Type:         Data2D", text)
250        self.assertIn("I_min = 1.0", text)
251        self.assertIn("I_max = 3.0", text)
252        self.assertIn("2 \t0.3 \t0.3 \t3.0 \t0.03 \t0.0 \t0.0", text)
253
254    def testOnTXTSave(self):
255        """
256        Test the file writer for saving 1d/2d data
257        """
258        path = "test123"
259        if os.path.isfile(path):
260            os.remove(path)
261
262        # Broken data
263        data = Data1D(x=[1.0, 2.0, 3.0], y=[])
264        # Expect a raise
265        with self.assertRaises(IndexError):
266            onTXTSave(data, path)
267
268        # Good data - no dX/dY
269        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0])
270        onTXTSave(data, path)
271
272        self.assertTrue(os.path.isfile(path))
273        with open(path,'r') as out:
274            data_read = out.read()
275            self.assertEqual("<X>   <Y>\n1  10\n2  11\n3  12\n", data_read)
276
277        if os.path.isfile(path):
278            os.remove(path)
279
280        # Good data - with dX/dY
281        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0],
282                      dx=[0.1, 0.2, 0.3], dy=[0.1, 0.2, 0.3])
283
284        onTXTSave(data, path)
285        with open(path,'r') as out:
286            data_read = out.read()
287            self.assertIn("<X>   <Y>   <dY>   <dX>\n", data_read)
288            self.assertIn("1  10  0.1  0.1\n", data_read)
289            self.assertIn("2  11  0.2  0.2\n", data_read)
290            self.assertIn("3  12  0.3  0.3\n", data_read)
291
292        if os.path.isfile(path):
293            os.remove(path)
294
295    def testSaveData1D(self):
296        """
297        Test the 1D file save method
298        """
299        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0],
300                      dx=[0.1, 0.2, 0.3], dy=[0.1, 0.2, 0.3])
301
302        # Test the .txt format
303        file_name = "test123_out.txt"
304        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
305        data.filename = "test123.txt"
306        saveData1D(data)
307        self.assertTrue(os.path.isfile(file_name))
308        os.remove(file_name)
309
310        # Test the .xml format
311        file_name = "test123_out.xml"
312        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
313        data.filename = "test123.xml"
314        saveData1D(data)
315        self.assertTrue(os.path.isfile(file_name))
316        os.remove(file_name)
317
318        # Test the wrong format
319        file_name = "test123_out.mp3"
320        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
321        data.filename = "test123.mp3"
322        saveData1D(data)
323        self.assertFalse(os.path.isfile(file_name))
324
325    def testSaveData2D(self):
326        """
327        Test the 1D file save method
328        """
329        data = Data2D(image=[1.0, 2.0, 3.0],
330                      err_image=[0.01, 0.02, 0.03],
331                      qx_data=[0.1, 0.2, 0.3],
332                      qy_data=[0.1, 0.2, 0.3])
333
334        # Test the .txt format
335        file_name = "test123_out.dat"
336        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
337        data.filename = "test123.dat"
338        saveData2D(data)
339        self.assertTrue(os.path.isfile(file_name))
340        os.remove(file_name)
341
342        # Test the wrong format
343        file_name = "test123_out.mp3"
344        QtGui.QFileDialog.getSaveFileName = MagicMock(return_value=file_name)
345        data.filename = "test123.mp3"
346        saveData2D(data)
347        self.assertFalse(os.path.isfile(file_name))
348
349    def testXYTransform(self):
350        """ Assure the unit/legend transformation is correct"""
351        data = Data1D(x=[1.0, 2.0, 3.0], y=[10.0, 11.0, 12.0],
352                      dx=[0.1, 0.2, 0.3], dy=[0.1, 0.2, 0.3])
353
354        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="y")
355        self.assertEqual(xLabel, "()")
356        self.assertEqual(xscale, "linear")
357        self.assertEqual(yscale, "linear")
358
359        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x^(2)", yLabel="1/y")
360        self.assertEqual(xLabel, "^{2}(()^{2})")
361        self.assertEqual(yLabel, "1/(()^{-1})")
362        self.assertEqual(xscale, "linear")
363        self.assertEqual(yscale, "linear")
364
365        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x^(4)", yLabel="ln(y)")
366        self.assertEqual(xLabel, "^{4}(()^{4})")
367        self.assertEqual(yLabel, "\\ln{()}()")
368        self.assertEqual(xscale, "linear")
369        self.assertEqual(yscale, "linear")
370
371        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="ln(x)", yLabel="y^(2)")
372        self.assertEqual(xLabel, "\\ln{()}()")
373        self.assertEqual(yLabel, "^{2}(()^{2})")
374        self.assertEqual(xscale, "linear")
375        self.assertEqual(yscale, "linear")
376
377        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="log10(x)", yLabel="y*x^(2)")
378        self.assertEqual(xLabel, "()")
379        self.assertEqual(yLabel, " \\ \\ ^{2}(()^{2})")
380        self.assertEqual(xscale, "log")
381        self.assertEqual(yscale, "linear")
382
383        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="log10(x^(4))", yLabel="y*x^(4)")
384        self.assertEqual(xLabel, "^{4}(()^{4})")
385        self.assertEqual(yLabel, " \\ \\ ^{4}(()^{16})")
386        self.assertEqual(xscale, "log")
387        self.assertEqual(yscale, "linear")
388
389        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="1/sqrt(y)")
390        self.assertEqual(yLabel, "1/\\sqrt{}(()^{-0.5})")
391        self.assertEqual(yscale, "linear")
392
393        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="log10(y)")
394        self.assertEqual(yLabel, "()")
395        self.assertEqual(yscale, "log")
396
397        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="ln(y*x)")
398        self.assertEqual(yLabel, "\\ln{( \\ \\ )}()")
399        self.assertEqual(yscale, "linear")
400
401        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="ln(y*x^(2))")
402        self.assertEqual(yLabel, "\\ln ( \\ \\ ^{2})(()^{2})")
403        self.assertEqual(yscale, "linear")
404
405        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="ln(y*x^(4))")
406        self.assertEqual(yLabel, "\\ln ( \\ \\ ^{4})(()^{4})")
407        self.assertEqual(yscale, "linear")
408
409        xLabel, yLabel, xscale, yscale = xyTransform(data, xLabel="x", yLabel="log10(y*x^(4))")
410        self.assertEqual(yLabel, " \\ \\ ^{4}(()^{4})")
411        self.assertEqual(yscale, "log")
412
413class FormulaValidatorTest(unittest.TestCase):
414    """ Test the formula validator """
415    def setUp(self):
416        '''Create the validator'''
417        self.validator = FormulaValidator()
418
419    def tearDown(self):
420        '''Destroy the validator'''
421        self.validator = None
422
423    def testValidateGood(self):
424        """Test a valid Formula """
425        formula_good = "H24O12C4C6N2Pu"
426        self.assertEqual(self.validator.validate(formula_good, 1)[0], QtGui.QValidator.Acceptable)
427
428        formula_good = "(H2O)0.5(D2O)0.5"
429        self.assertEqual(self.validator.validate(formula_good, 1)[0], QtGui.QValidator.Acceptable)
430
431    def testValidateBad(self):
432        """Test a valid Formula """
433        formula_bad = "H24 %%%O12C4C6N2Pu"
434        self.assertRaises(self.validator.validate(formula_bad, 1)[0])
435        self.assertEqual(self.validator.validate(formula_bad, 1)[0], QtGui.QValidator.Intermediate)
436
437        formula_bad = [1]
438        self.assertEqual(self.validator.validate(formula_bad, 1)[0], QtGui.QValidator.Intermediate)
439
440
441if __name__ == "__main__":
442    unittest.main()
443
Note: See TracBrowser for help on using the repository browser.