# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
#     NScD Oak Ridge National Laboratory, European Spallation Source
#     & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
"""
Test one can import paraview.simple in MantidPlot
"""
import mantidplottests
from mantidplottests import *
from paraview.simple import *


class MantidPlotPVPythonTest(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_PVPython(self):
        self.assertEqual(GetParaViewVersion().major, 5)

# Run the unit tests
mantidplottests.runTests(MantidPlotPVPythonTest)
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
#     NScD Oak Ridge National Laboratory, European Spallation Source
#     & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
"""
Test one can import paraview.simple in MantidPlot
"""
import mantidplottests
from mantidplottests import *
from paraview.simple import *


class MantidPlotPVPythonTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_PVPython(self):
        self.assertEqual(GetParaViewVersion().major, 5)


# Run the unit tests
mantidplottests.runTests(MantidPlotPVPythonTest)
        try:
            self.assertRaises(ValueError, plotBin(WrongWorkspaceName, -5),
                              "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotBin_fail_indexTooBig(self):
        try:
            self.assertRaises(ValueError, plotBin(WrongWorkspaceName, 100),
                              "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotMD_fail_NonMD(self):
        try:
            self.assertRaises(ValueError, plotMD(WorkspaceName2D, 0),
                              "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotMD_fail_nonIntegrated(self):
        try:
            self.assertRaises(ValueError, plotMD(MDWWorkspaceName, 100),
                              "wont see this tab")
        except:
            print("Failed, as it should")


# Run the unit tests
mantidplottests.runTests(MantidPlotInputArgsCheck)
        tw = newTiledWindow()
        t1 = newTable()
        t2 = newTable()
        t3 = newTable()
        t4 = newGraph()

        tw.addWidget(t1,0,0)
        tw.addWidget(t2,0,1)
        tw.addWidget(t3,1,0)
        tw.addWidget(t4,1,1)

        self.assertTrue( isinstance(tw.getWidget(0,1)._getHeldObject(), _qti.Table) )

        t5 = newGraph()
        tw.insertWidget(t5,0,1)
        self.assertEqual( tw.rowCount(), 3 )
        self.assertEqual( tw.columnCount(), 2 )
        self.assertTrue( isinstance(tw.getWidget(0,1)._getHeldObject(), _qti.Graph) )

        t6 = newGraph()
        tw.insertWidget(t6,0,0)
        self.assertEqual( tw.rowCount(), 3 )
        self.assertEqual( tw.columnCount(), 2 )
        self.assertTrue( isinstance(tw.getWidget(0,0)._getHeldObject(), _qti.Graph) )
        self.assertTrue( isinstance(tw.getWidget(0,1)._getHeldObject(), _qti.Table) )

        tw.close()

# Run the unit tests
runTests(MantidPlotTiledWindowTest)
Example #5
0
        time.sleep(0.2)

    def test_1d_plot(self):
        x, y = np.arange(1.0,10.0), np.arange(1.0,10.)
        ax = plt.plot(x,y)
        self.assertNotEqual(ax, None)
        plt.show()
        time.sleep(0.2)
        plt.close()

    def test_image_plot(self):
        delta = 0.025
        x = y = np.arange(-3.0, 3.0, delta)
        X, Y = np.meshgrid(x, y)
        Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
        Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
        Z = Z2 - Z1  # difference of Gaussians

        im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                        origin='lower', extent=[-3, 3, -3, 3],
                        vmax=abs(Z).max(), vmin=-abs(Z).max())
        plt.show()
        time.sleep(0.2)
        plt.close()

# Run the unit tests
if HAVE_MPL:
    mantidplottests.runTests(MantidPlotMatplotlibTest)
else:
    print("Matplotlib unavailable. Tests skipped.")
    __target_algorithm__ = "CreateMDWorkspace"
    __clean_properties__ = True

    def test_OpenDialog(self):
        interface_manager = mantidqtpython.MantidQt.API.InterfaceManager()
        parent = None
        dialog = threadsafe_call( interface_manager.createDialogFromName, self.__target_algorithm__, -1, parent, self.__clean_properties__)
        is_instance_of_alg_dialog = isinstance(dialog, mantidqtpython.MantidQt.API.AlgorithmDialog)
        self.assertEqual(is_instance_of_alg_dialog, True, "Did not get an AlgorithmDialog instance back.")
        threadsafe_call( dialog.close )

    def test_ScreenShotDialog(self):
        interface_manager = mantidqtpython.MantidQt.API.InterfaceManager()
        parent = None
        dialog = threadsafe_call( interface_manager.createDialogFromName, self.__target_algorithm__, -1, parent, self.__clean_properties__)
        screenshotdir = tempfile.gettempdir();
        filename = "CreateMDWorkspace_screenshot.png"
        screenshot_to_dir(widget=dialog, filename=filename, screenshot_dir=screenshotdir)
        threadsafe_call(dialog.close)
        file_abs = os.path.join(screenshotdir, filename)
        file_exists = os.path.isfile(file_abs)
        self.assertEquals(file_exists, True, "Screenshot was not written out as expected.")
        if file_exists:
            os.remove(file_abs)

# Run the unit tests
mantidplottests.runTests(MantidPlotAlgorithmDialogTest)



    def test_colour_range_can_be_changed(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.setMinValue(1.25)
        render_tab.setMaxValue(1.75)
        render_tab.setRange(1.35,1.85)

    def test_display_options(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.showAxes(True)
        render_tab.displayDetectorsOnly(True)
        render_tab.setColorMapAutoscaling(False)
        render_tab.setSurfaceType(0)
        render_tab.setAxis("Y-")
        render_tab.flipUnwrappedView(True)
		
    def test_window_render_tab(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.setSurfaceType(InstrumentWidgetRenderTab.FULL3D)
        self.assertTrue(render_tab is not None)
        current_scale = render_tab.getScaleType()
        self.assertTrue(isinstance(current_scale, GraphOptions.ScaleType))
        render_tab.setScaleType(GraphOptions.Log10)
        
    def test_closing_window_invalidates_reference(self):
        inst = getInstrumentView("loq_inst")
        inst.close()
        self.assertTrue(inst._getHeldObject() is None)

# Run the unit tests
mantidplottests.runTests(MantidPlotInstrumentViewTest)
        # Now clear the PeaksOverlays
        sv.clearPeaksWorkspaces()

    def test_integrateMDHistoWorkspace(self):
        CreateMDWorkspace(Dimensions=4, Extents='-10,10,-10,10,-10,10,-10,10', Names='a,b,c,d', Units='u,u,u,u', OutputWorkspace='ws')
        FakeMDEventData(InputWorkspace='ws', PeakParams='10000,0,0,0,0,1')
        CutMD(InputWorkspace='ws', P1Bin='1', P2Bin='1', P3Bin='1', P4Bin='1', OutputWorkspace='ws2', NoPix=True)

        svw = plotSlice('ws2')
        sv = svw.getSlicer()
        lv = svw.getLiner()
        lv.setStartXY(-3, 0)
        lv.setEndXY(3, 0)
        lv.setPlanarWidth(2)
        lv.apply()

        time.sleep(1)
        lws = mtd['ws2_line']
        ranHisto = False
        for alg in lws.getHistory():
            if alg.name() == "IntegrateMDHistoWorkspace":
                ranHisto = True
                break

        self.assertTrue(ranHisto, "IntegrateMDHistoWorkspace was used when possible")

# Run the unit tests
mantidplottests.runTests(MantidPlotSliceViewerTest)

        tw.addWidget(t1, 0, 0)
        tw.addWidget(t2, 0, 1)
        tw.addWidget(t3, 1, 0)
        tw.addWidget(t4, 1, 1)

        self.assertTrue(
            isinstance(tw.getWidget(0, 1)._getHeldObject(), _qti.Table))

        t5 = newGraph()
        tw.insertWidget(t5, 0, 1)
        self.assertEqual(tw.rowCount(), 3)
        self.assertEqual(tw.columnCount(), 2)
        self.assertTrue(
            isinstance(tw.getWidget(0, 1)._getHeldObject(), _qti.Graph))

        t6 = newGraph()
        tw.insertWidget(t6, 0, 0)
        self.assertEqual(tw.rowCount(), 3)
        self.assertEqual(tw.columnCount(), 2)
        self.assertTrue(
            isinstance(tw.getWidget(0, 0)._getHeldObject(), _qti.Graph))
        self.assertTrue(
            isinstance(tw.getWidget(0, 1)._getHeldObject(), _qti.Table))

        tw.close()


# Run the unit tests
runTests(MantidPlotTiledWindowTest)
        else:
            # Old versions of matplotlib.pyplot.close work without this
            # in a normal script session but fail here. The workaround
            # is to ensure this happens on the same thread too.
            gui_cmd(plt.close, 'all')

    def test_1d_plot(self):
        x, y = np.arange(1.0,10.0), np.arange(1.0,10.)
        ax = plt.plot(x,y)
        self.assertTrue(ax is not None)
        plt.show()

    def test_image_plot(self):
        delta = 0.025
        x = y = np.arange(-3.0, 3.0, delta)
        X, Y = np.meshgrid(x, y)
        Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
        Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
        Z = Z2 - Z1  # difference of Gaussians

        im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                        origin='lower', extent=[-3, 3, -3, 3],
                        vmax=abs(Z).max(), vmin=-abs(Z).max())
        plt.show()

# Run the unit tests
if HAVE_MPL:
    mantidplottests.runTests(MantidPlotMatplotlibTest)
else:
    print("Matplotlib unavailable. Tests skipped.")
Example #11
0
        deleteFolder(f)

    def test_Folder_deletinging_windows(self):
        """ Access windows through a folder """
        f, windows = self.setup_folder("fld")
        n = 4
        for w in windows:
            w.close()
            n -= 1
            self.assertEqual(len(f.windows()), n)
        deleteFolder(f)

    def test_switchFolder_windows(self):
        """ Access windows through a folder """
        f1, windows1 = self.setup_folder("folder1")
        f2, windows2 = self.setup_folder("folder2")
        for w in windows1:
            self.assertFalse( w.isVisible(), "Window in closed folder is hidden." )
        for w in windows2:
            self.assertTrue( w.isVisible(), "Window in active folder is visible." )
        # Go back to folder 1
        changeFolder(f1)
        for w in windows2:
            self.assertFalse( w.isVisible(), "Window in closed folder is hidden." )
        for w in windows1:
            self.assertTrue( w.isVisible(), "Window in active folder is visible." )


# Run the unit tests
mantidplottests.runTests(MantidPlotFoldersTest)
class MantidPlotMdiSubWindowTest(unittest.TestCase):

    def test_table(self):

        self.doTest( newTable() )

    def test_graph(self):

        self.doTest( newGraph() )

    def doTest(self, w):
        if w.isFloating():
            w.dock()
        self.assertFalse( w.isFloating() )
        self.assertTrue( w.isDocked() )
        size = w.size()
        w.undock()
        self.assertTrue( w.isFloating() )
        self.assertFalse( w.isDocked() )
        w.dock()
        self.assertFalse( w.isFloating() )
        self.assertTrue( w.isDocked() )
        # TODO: sizes are not equal. Should we fix it?
        # self.assertEqual( size, w.size() )
        w.close()


# Run the unit tests
mantidplottests.runTests(MantidPlotMdiSubWindowTest)

                        DataY=[1, 2, 3],
                        NSpec=1)
        threadsafe_call(_qti.app.saveRecoveryCheckpoint)

        cleanUp()
        #Test that it cleaned up after itself
        self.assertEqual(len(glob(os.path.join(path, "*", ""))), 0)

    def test_checkpoint_creation(self):
        CreateWorkspace(OutputWorkspace="ws",
                        DataX=[1, 2, 3],
                        DataY=[1, 2, 3],
                        NSpec=1)

        listOfCheckpointsBefore = glob(os.path.join(path, "*", ""))
        for ii in listOfCheckpointsBefore:
            shutil.rmtree(ii)

        threadsafe_call(_qti.app.saveRecoveryCheckpoint)
        listOfCheckpointsAfter = glob(os.path.join(path, "*", ""))

        self.assertEqual(len(listOfCheckpointsAfter), 1)

        cleanUp()
        #Test that it cleaned up after itself
        self.assertEqual(len(glob(os.path.join(path, "*", ""))), 0)


# Run the unit tests
mantidplottests.runTests(MantidPlotProjectRecovery)
Example #14
0
        self.assertEqual(load.readBool(), True)

    def test_sections(self):
        lines = self.genLines()
        tmp = mantidqtpython.MantidQt.API.TSVSerialiser()
        tmp.writeSection("Section", lines)
        lines = tmp.outputLines()

        tmp2 = mantidqtpython.MantidQt.API.TSVSerialiser()
        tmp2.writeSection("Big", lines)
        lines = tmp2.outputLines()

        # read the sections back
        load = mantidqtpython.MantidQt.API.TSVSerialiser(lines)
        secs = load.sections("Big")
        load = mantidqtpython.MantidQt.API.TSVSerialiser(secs[0])

        secs = load.sections("Section")
        load = mantidqtpython.MantidQt.API.TSVSerialiser(secs[0])

        load.selectLine("test")
        self.assertEqual(load.readDouble(), 1.1)
        self.assertEqual(load.readInt(), 2)

        load.selectLine("line2")
        self.assertEqual(load.readString(), "Hello World")
        self.assertEqual(load.readBool(), True)


mantidplottests.runTests(TSVSerialiserTest)
            self.assertRaises(ValueError, plotBin(WrongWorkspaceName, 0), "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotBin_fail_indexNeg(self):
        try:
            self.assertRaises(ValueError, plotBin(WrongWorkspaceName, -5), "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotBin_fail_indexTooBig(self):
        try:
            self.assertRaises(ValueError, plotBin(WrongWorkspaceName, 100), "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotMD_fail_NonMD(self):
        try:
            self.assertRaises(ValueError, plotMD(WorkspaceName2D, 0), "wont see this tab")
        except:
            print("Failed, as it should")

    def test_plotMD_fail_nonIntegrated(self):
        try:
            self.assertRaises(ValueError, plotMD(MDWWorkspaceName, 100), "wont see this tab")
        except:
            print("Failed, as it should")

# Run the unit tests
mantidplottests.runTests(MantidPlotInputArgsCheck)
Example #16
0
        f, old_windows = self.setup_folder("fld")
        windows = f.windows()
        self.assertEqual(len(windows), 4, "4 windows in folder")
        self.assertTrue( f.window("table-fld") is not None)
        self.assertTrue( f.table("table-fld") is not None)
        self.assertTrue( f.matrix("matrix-fld") is not None)
        self.assertTrue( f.graph("graph-fld") is not None)
        for w in windows: w.close()
        deleteFolder(f)
        
    def test_switchFolder_windows(self):
        """ Access windows through a folder """
        f1, windows1 = self.setup_folder("folder1")
        f2, windows2 = self.setup_folder("folder2")
        for w in windows1:
            self.assertFalse( w.isVisible(), "Window in closed folder is hidden." )
        for w in windows2:
            self.assertTrue( w.isVisible(), "Window in active folder is visible." )
        # Go back to folder 1
        changeFolder(f1)
        for w in windows2:
            self.assertFalse( w.isVisible(), "Window in closed folder is hidden." )
        for w in windows1:
            self.assertTrue( w.isVisible(), "Window in active folder is visible." )
            
   

            
# Run the unit tests
mantidplottests.runTests(MantidPlotFoldersTest)
                                 self.__target_algorithm__, -1, parent,
                                 self.__clean_properties__)
        is_instance_of_alg_dialog = isinstance(
            dialog, mantidqtpython.MantidQt.API.AlgorithmDialog)
        self.assertEqual(is_instance_of_alg_dialog, True,
                         "Did not get an AlgorithmDialog instance back.")
        threadsafe_call(dialog.close)

    def test_ScreenShotDialog(self):
        interface_manager = mantidqtpython.MantidQt.API.InterfaceManager()
        parent = None
        dialog = threadsafe_call(interface_manager.createDialogFromName,
                                 self.__target_algorithm__, -1, parent,
                                 self.__clean_properties__)
        screenshotdir = tempfile.gettempdir()
        filename = "CreateMDWorkspace_screenshot.png"
        screenshot_to_dir(widget=dialog,
                          filename=filename,
                          screenshot_dir=screenshotdir)
        threadsafe_call(dialog.close)
        file_abs = os.path.join(screenshotdir, filename)
        file_exists = os.path.isfile(file_abs)
        self.assertEquals(file_exists, True,
                          "Screenshot was not written out as expected.")
        if file_exists:
            os.remove(file_abs)


# Run the unit tests
mantidplottests.runTests(MantidPlotAlgorithmDialogTest)
import mantidplottests
from mantidplottests import *
import time
import sys
import types


class MantidPlotPythonImportTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        """Clean up by closing the created window """
        pass

    def test_NewAPIIsDefault(self):
        self.assertTrue('mantid' in sys.modules)

    def test_ConjoinFilesExistsAsAFunction(self):
        # This means the Python algs were loaded
        self.assertTrue('ConjoinFiles' in globals())
        self.assertTrue(callable(ConjoinFiles))

    def test_V3D_is_New_API_Version(self):
        import mantid
        self.assertTrue(isinstance(V3D(), mantid.kernel.V3D))


# Run the unit tests
mantidplottests.runTests(MantidPlotPythonImportTest)
import unittest
import mantidplottests
from mantidplottests import *
import time
import sys
import types

class MantidPlotPythonImportTest(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        """Clean up by closing the created window """
        pass

    def test_NewAPIIsDefault(self):
        self.assertTrue('mantid' in sys.modules)

    def test_ConjoinFilesExistsAsAFunction(self):
        # This means the Python algs were loaded
        self.assertTrue('ConjoinFiles' in globals())
        self.assertEquals(type(ConjoinFiles),types.FunctionType)

    def test_V3D_is_New_API_Version(self):
        import mantid
        self.assertTrue(isinstance(V3D(), mantid.kernel.V3D))

# Run the unit tests
mantidplottests.runTests(MantidPlotPythonImportTest)
Example #20
0
        screenshot(g, "convertToWaterfall", "Call to convertToWaterfall() on a workspace.")
        self.try_closing(g, "convertToWaterfall()")

    def test_dock_method_produces_docked_window_on_matrix(self):
        self.do_dock_test_and_close(importMatrixWorkspace("fake", visible=True))

    def test_dock_method_produces_docked_window_on_1D_graph(self):
        self.do_dock_test_and_close(plotSpectrum("fake", 0))

    def test_dock_method_produces_docked_window_on_2D_graph(self):
        mm = importMatrixWorkspace("fake", visible=True)
        g = mm.plotGraph2D()
        self.do_dock_test_and_close(g)
        mm.confirmClose(False)
        mm.close()

    def test_dock_method_produces_docked_window_on_instrument_view(self):
        iv = getInstrumentView("IRS26173")
        self.do_dock_test_and_close(iv)

    def do_dock_test_and_close(self, win):
        win.dock()
        self.assertTrue(win.isDocked())
        win.confirmClose(False)
        win.close()


# Run the unit tests
mantidplottests.runTests(MantidPlotProxiesTest)

Example #21
0
        self.assertEqual(load.readBool(), True)

    def test_sections(self):
        lines = self.genLines()
        tmp = mantidqtpython.MantidQt.API.TSVSerialiser()
        tmp.writeSection("Section", lines)
        lines = tmp.outputLines()

        tmp2 = mantidqtpython.MantidQt.API.TSVSerialiser()
        tmp2.writeSection("Big", lines)
        lines = tmp2.outputLines()

        # read the sections back
        load = mantidqtpython.MantidQt.API.TSVSerialiser(lines)
        secs = load.sections("Big")
        load = mantidqtpython.MantidQt.API.TSVSerialiser(secs[0])

        secs = load.sections("Section")
        load = mantidqtpython.MantidQt.API.TSVSerialiser(secs[0])

        load.selectLine("test")
        self.assertEqual(load.readDouble(), 1.1)
        self.assertEqual(load.readInt(), 2)

        load.selectLine("line2")
        self.assertEqual(load.readString(), "Hello World")
        self.assertEqual(load.readBool(), True)


mantidplottests.runTests(TSVSerialiserTest)
    def test_colour_range_can_be_changed(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.setMinValue(1.25)
        render_tab.setMaxValue(1.75)
        render_tab.setRange(1.35,1.85)

    def test_display_options(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.showAxes(True)
        render_tab.displayDetectorsOnly(True)
        render_tab.setColorMapAutoscaling(False)
        render_tab.setSurfaceType(0)
        render_tab.setAxis("Y-")
        render_tab.flipUnwrappedView(True)
		
    def test_window_render_tab(self):
        render_tab = INST_WIN.getTab("Render")
        render_tab.setSurfaceType(InstrumentWindowRenderTab.FULL3D)
        self.assertTrue(render_tab is not None)
        current_scale = render_tab.getScaleType()
        self.assertTrue(isinstance(current_scale, GraphOptions.ScaleType))
        render_tab.setScaleType(GraphOptions.Log10)
        
    def test_closing_window_invalidates_reference(self):
        inst = getInstrumentView("loq_inst")
        inst.close()
        self.assertTrue(inst._getHeldObject() is None)

# Run the unit tests
mantidplottests.runTests(MantidPlotInstrumentViewTest)
        self.check_output_lines(lines, 2)
        self.close_win(lines)

    def test_multi_plot_commands(self):
        lines = plot(WorkspaceName2D, [0,1], SecondWorkspaceName2D, [0, 1, 2])
        self.check_output_lines(lines, 5)
        self.close_win(lines)

        lines = plot(WorkspaceName2D, [0,1], SecondWorkspaceName2D, [0, 1, 2])
        self.check_output_lines(lines, 5)
        self.close_win(lines)

        # this one mixes up positional and kw args
        self.assertRaises(ValueError, plot,
                          WorkspaceName2D, [0,1], WorkspaceName2D, tool='plot_spectrum')

    def test_savefig(self):
        # save a minimal figure just to check that the file is written
        import os

        lines = plot([0, 0.5, 0.1])
        tmp_figname = 'pyplot_tmp_fig_test.png'
        savefig(tmp_figname)
        self.close_win(lines)

        self.assertTrue(os.path.exists(tmp_figname))
        os.remove(tmp_figname)

# Run the unit tests
mantidplottests.runTests(MantidPlotPyplotGeneralTest)
        for key in data.keys():
            data[key] = parse_project_file(data[key], pattern)

    # parse individual property lines
    lines = contents.strip().split('\n')
    for line in lines:
        properties = line.strip().split('\t')
        key = properties[0]
        values = properties[1:]
        if key in data.keys():
            # if it already exists then add multiple entries as a dictionary
            # with numberical keys corresponding to the order added
            if not isinstance(data[key], dict):
                data[key] = {0: data[key]}
            data[key][max(data[key]) + 1] = values
        elif len(properties) == 2:
            data[key] = values[0]
        else:
            data[key] = values
    return data


def read_project_file(folder_name):
    """ Read and parse a Mantid project file """
    contents = get_project_file_contents(folder_name)
    return parse_project_file(contents)


# Run the unit tests
mantidplottests.runTests(MantidPlotProjectSerialiseTest)
        self.check_output_lines(lines, 2)
        self.close_win(lines)

        lines = plot(SecondWorkspaceName2D, [0,1, 2], tool='plot_spectrum', linewidth=3, linestyle='-.', marker='v')
        self.check_output_lines(lines, 3)
        self.close_win(lines)

    def test_wrong_kwargs(self):
        # funny kwargs should have no big consequences
        lines = plot(WorkspaceName2D, [0,1], tool='plot_spectrum', linewidth=3, linestyle='-.', marker='v', funny_foo='bar', funny_baz='qux')
        self.check_output_lines(lines, 2)
        self.close_win(lines)

    def test_multi_plot_commands(self):
        lines = plot(WorkspaceName2D, [0,1], SecondWorkspaceName2D, [0, 1, 2])
        self.check_output_lines(lines, 5)
        self.close_win(lines)

        lines = plot(WorkspaceName2D, [0,1], SecondWorkspaceName2D, [0, 1, 2])
        self.check_output_lines(lines, 5)
        self.close_win(lines)

        # this one mixes up positional and kw args
        try:
            self.assertRaises(ValueError, plot(WorkspaceName2D, [0,1], WorkspaceName2D, tool='plot_spectrum'), "wont see this")
        except:
            print "Failed, as it should"

# Run the unit tests
mantidplottests.runTests(MantidPlotFuturePyplotGeneralTest)
Example #26
0
    def test_plotBin_with_single_index_outside_number_histograms_but_still_valid_produces_plot(self):
        g = plotBin("fake", 5)
        self.assertTrue(g is not None)
        self.g = g

    def test_plotBin_with_invalid_raises_ValueError(self):
        self.assertRaises(ValueError, plotBin, "fake", 100)
        self.g = None

    def test_plotBin_command_with_list(self):
        g = plotBin("fake", [0,1])
        self.assertTrue(g is not None)
        self.g = g

    def test_plotBin_command_with_tuple(self):
        g = plotBin("fake", (0,1))
        self.assertTrue(g is not None)
        self.g = g

    # ---------------- Non-test methods ----------------
    def _check_graph_contents(self, g, curve_titles):
        layer = g.activeLayer()
        self.assertEqual(len(curve_titles), layer.numCurves())
        for i, title in enumerate(curve_titles):
            self.assertEqual(title, layer.curveTitle(i))


# Run the unit tests
mantidplottests.runTests(MantidPlot1DPlotTest)
        for x, y in match:
            data[x] = y
        for key in data.keys():
            data[key] = parse_project_file(data[key], pattern)

    # parse individual property lines
    lines = contents.strip().split('\n')
    for line in lines:
        properties = line.strip().split('\t')
        key = properties[0]
        values = properties[1:]
        if key in data.keys():
            # if it already exists then add multiple entries as a dictionary
            # with numberical keys corresponding to the order added
            if not isinstance(data[key], dict):
                data[key] = {0: data[key]}
            data[key][max(data[key])+1] = values
        elif len(properties) == 2:
            data[key] = values[0]
        else:
            data[key] = values
    return data

def read_project_file(folder_name):
    """ Read and parse a Mantid project file """
    contents = get_project_file_contents(folder_name)
    return parse_project_file(contents)

# Run the unit tests
mantidplottests.runTests(MantidPlotProjectSerialiseTest)