diff options
Diffstat (limited to 'silx/test')
-rw-r--r-- | silx/test/__init__.py | 104 | ||||
-rw-r--r-- | silx/test/test_resources.py | 200 | ||||
-rw-r--r-- | silx/test/test_sx.py | 292 | ||||
-rw-r--r-- | silx/test/test_version.py | 49 | ||||
-rw-r--r-- | silx/test/utils.py | 204 |
5 files changed, 0 insertions, 849 deletions
diff --git a/silx/test/__init__.py b/silx/test/__init__.py deleted file mode 100644 index 2063ab5..0000000 --- a/silx/test/__init__.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding: utf-8 -# /*########################################################################## -# -# Copyright (c) 2015-2019 European Synchrotron Radiation Facility -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# ###########################################################################*/ -"""This package provides access to the full silx test suite. - -It is possible to disable tests depending on Qt by setting -`silx.test.utils.test_options.WITH_QT_TEST = False` -It will skip all tests from :mod:`silx.test.gui`. -""" - -__authors__ = ["T. Vincent"] -__license__ = "MIT" -__date__ = "21/12/2018" - - -import logging -import unittest - -from silx.test.utils import test_options - - -logger = logging.getLogger(__name__) - - -def suite(): - # In case Qt tests are not run, do not load sx as it loads Qt - # instead add a skipped test class to the suite - if not test_options.WITH_QT_TEST: - # Explicitly disabled tests - msg = "silx.sx tests disabled %s" % test_options.WITH_QT_TEST_REASON - logger.warning(msg) - - class SkipSXTest(unittest.TestCase): - def runTest(self): - self.skipTest(test_options.WITH_QT_TEST_REASON) - - def test_sx_suite(): - suite = unittest.TestSuite() - suite.addTest(SkipSXTest()) - return suite - else: - from .test_sx import suite as test_sx_suite - - from . import test_version - from . import test_resources - from ..io import test as test_io - from ..math import test as test_math - from ..image import test as test_image - from ..gui import test as test_gui - from ..utils import test as test_utils - from ..opencl import test as test_ocl - from ..app import test as test_app - - test_suite = unittest.TestSuite() - # test sx first cause qui tests load ipython module - test_suite.addTest(test_sx_suite()) - test_suite.addTest(test_gui.suite()) - # then test no-gui tests - test_suite.addTest(test_utils.suite()) - test_suite.addTest(test_version.suite()) - test_suite.addTest(test_resources.suite()) - test_suite.addTest(test_io.suite()) - test_suite.addTest(test_math.suite()) - test_suite.addTest(test_image.suite()) - test_suite.addTest(test_ocl.suite()) - test_suite.addTest(test_app.suite()) - - return test_suite - - -def run_tests(*args, **kwargs): - """Run test complete test_suite - - Provided arguments are passed to :class:`unittest.TextTestRunner`. - """ - test_options.configure() - runner = unittest.TextTestRunner(*args, **kwargs) - if not runner.run(suite()).wasSuccessful(): - print("Test suite failed") - return 1 - else: - print("Test suite succeeded") - return 0 diff --git a/silx/test/test_resources.py b/silx/test/test_resources.py deleted file mode 100644 index 7f5f432..0000000 --- a/silx/test/test_resources.py +++ /dev/null @@ -1,200 +0,0 @@ -# coding: utf-8 -# /*########################################################################## -# -# Copyright (c) 2016-2018 European Synchrotron Radiation Facility -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# ###########################################################################*/ -"""Test for resource files management.""" - -__authors__ = ["T. Vincent"] -__license__ = "MIT" -__date__ = "08/03/2019" - - -import os -import unittest -import shutil -import tempfile - -import silx.resources - - -class TestResources(unittest.TestCase): - - @classmethod - def setUpClass(cls): - super(TestResources, cls).setUpClass() - - cls.tmpDirectory = tempfile.mkdtemp(prefix="resource_") - os.mkdir(os.path.join(cls.tmpDirectory, "gui")) - destination_dir = os.path.join(cls.tmpDirectory, "gui", "icons") - os.mkdir(destination_dir) - source = silx.resources.resource_filename("gui/icons/zoom-in.png") - destination = os.path.join(destination_dir, "foo.png") - shutil.copy(source, destination) - source = silx.resources.resource_filename("gui/icons/zoom-out.svg") - destination = os.path.join(destination_dir, "close.png") - shutil.copy(source, destination) - - @classmethod - def tearDownClass(cls): - super(TestResources, cls).tearDownClass() - shutil.rmtree(cls.tmpDirectory) - - def setUp(self): - # Store the original configuration - self._oldResources = dict(silx.resources._RESOURCE_DIRECTORIES) - unittest.TestCase.setUp(self) - - def tearDown(self): - unittest.TestCase.tearDown(self) - # Restiture the original configuration - silx.resources._RESOURCE_DIRECTORIES = self._oldResources - - def test_resource_dir(self): - """Get a resource directory""" - icons_dirname = silx.resources.resource_filename('gui/icons/') - self.assertTrue(os.path.isdir(icons_dirname)) - - def test_resource_file(self): - """Get a resource file name""" - filename = silx.resources.resource_filename('gui/icons/colormap.png') - self.assertTrue(os.path.isfile(filename)) - - def test_resource_nonexistent(self): - """Get a non existent resource""" - filename = silx.resources.resource_filename('non_existent_file.txt') - self.assertFalse(os.path.exists(filename)) - - def test_isdir(self): - self.assertTrue(silx.resources.is_dir('gui/icons')) - - def test_not_isdir(self): - self.assertFalse(silx.resources.is_dir('gui/icons/colormap.png')) - - def test_list_dir(self): - result = silx.resources.list_dir('gui/icons') - self.assertTrue(len(result) > 10) - - # With prefixed resources - - def test_resource_dir_with_prefix(self): - """Get a resource directory""" - icons_dirname = silx.resources.resource_filename('silx:gui/icons/') - self.assertTrue(os.path.isdir(icons_dirname)) - - def test_resource_file_with_prefix(self): - """Get a resource file name""" - filename = silx.resources.resource_filename('silx:gui/icons/colormap.png') - self.assertTrue(os.path.isfile(filename)) - - def test_resource_nonexistent_with_prefix(self): - """Get a non existent resource""" - filename = silx.resources.resource_filename('silx:non_existent_file.txt') - self.assertFalse(os.path.exists(filename)) - - def test_isdir_with_prefix(self): - self.assertTrue(silx.resources.is_dir('silx:gui/icons')) - - def test_not_isdir_with_prefix(self): - self.assertFalse(silx.resources.is_dir('silx:gui/icons/colormap.png')) - - def test_list_dir_with_prefix(self): - result = silx.resources.list_dir('silx:gui/icons') - self.assertTrue(len(result) > 10) - - # Test new repository - - def test_repository_not_exists(self): - """The resource from 'test' is available""" - self.assertRaises(ValueError, silx.resources.resource_filename, 'test:foo.png') - - def test_adding_test_directory(self): - """The resource from 'test' is available""" - silx.resources.register_resource_directory("test", "silx.test.resources", forced_path=self.tmpDirectory) - path = silx.resources.resource_filename('test:gui/icons/foo.png') - self.assertTrue(os.path.exists(path)) - - def test_adding_test_directory_no_override(self): - """The resource from 'silx' is still available""" - silx.resources.register_resource_directory("test", "silx.test.resources", forced_path=self.tmpDirectory) - filename1 = silx.resources.resource_filename('gui/icons/close.png') - filename2 = silx.resources.resource_filename('silx:gui/icons/close.png') - filename3 = silx.resources.resource_filename('test:gui/icons/close.png') - self.assertTrue(os.path.isfile(filename1)) - self.assertTrue(os.path.isfile(filename2)) - self.assertTrue(os.path.isfile(filename3)) - self.assertEqual(filename1, filename2) - self.assertNotEqual(filename1, filename3) - - def test_adding_test_directory_non_existing(self): - """A resource while not exists in test is not available anyway it exists - in silx""" - silx.resources.register_resource_directory("test", "silx.test.resources", forced_path=self.tmpDirectory) - resource_name = "gui/icons/colormap.png" - path = silx.resources.resource_filename('test:' + resource_name) - path2 = silx.resources.resource_filename('silx:' + resource_name) - self.assertFalse(os.path.exists(path)) - self.assertTrue(os.path.exists(path2)) - - -class TestResourcesWithoutPkgResources(TestResources): - - @classmethod - def setUpClass(cls): - super(TestResourcesWithoutPkgResources, cls).setUpClass() - cls._old = silx.resources.pkg_resources - silx.resources.pkg_resources = None - - @classmethod - def tearDownClass(cls): - silx.resources.pkg_resources = cls._old - del cls._old - super(TestResourcesWithoutPkgResources, cls).tearDownClass() - - -class TestResourcesWithCustomDirectory(TestResources): - - @classmethod - def setUpClass(cls): - super(TestResourcesWithCustomDirectory, cls).setUpClass() - cls._old = silx.resources._RESOURCES_DIR - base = os.path.dirname(silx.resources.__file__) - silx.resources._RESOURCES_DIR = base - - @classmethod - def tearDownClass(cls): - silx.resources._RESOURCES_DIR = cls._old - del cls._old - super(TestResourcesWithCustomDirectory, cls).tearDownClass() - - -def suite(): - loadTests = unittest.defaultTestLoader.loadTestsFromTestCase - test_suite = unittest.TestSuite() - test_suite.addTest(loadTests(TestResources)) - test_suite.addTest(loadTests(TestResourcesWithoutPkgResources)) - test_suite.addTest(loadTests(TestResourcesWithCustomDirectory)) - return test_suite - - -if __name__ == '__main__': - unittest.main(defaultTest='suite') diff --git a/silx/test/test_sx.py b/silx/test/test_sx.py deleted file mode 100644 index a32cc06..0000000 --- a/silx/test/test_sx.py +++ /dev/null @@ -1,292 +0,0 @@ -# coding: utf-8 -# /*########################################################################## -# -# Copyright (c) 2016-2019 European Synchrotron Radiation Facility -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# ###########################################################################*/ -__authors__ = ["T. Vincent", "P. Knobel"] -__license__ = "MIT" -__date__ = "06/11/2018" - - -import logging -import unittest -import numpy - -from silx.utils.testutils import ParametricTestCase -from silx.test.utils import test_options - -from silx.gui import qt -# load TestCaseQt before sx -from silx.gui.utils.testutils import TestCaseQt -from silx.gui.colors import rgba -from silx.gui.colors import Colormap - - -_logger = logging.getLogger(__name__) - - -class SXTest(TestCaseQt, ParametricTestCase): - """Test the sx module""" - - def _expose_and_close(self, plot): - self.qWaitForWindowExposed(plot) - self.qapp.processEvents() - plot.setAttribute(qt.Qt.WA_DeleteOnClose) - plot.close() - - def test_plot(self): - """Test plot function""" - from silx import sx # Lazy loading to avoid it to create QApplication - - y = numpy.random.random(100) - x = numpy.arange(len(y)) * 0.5 - - # Nothing - plt = sx.plot() - self._expose_and_close(plt) - - # y - plt = sx.plot(y, title='y') - self._expose_and_close(plt) - - # y, style - plt = sx.plot(y, 'blued ', title='y, "blued "') - self._expose_and_close(plt) - - # x, y - plt = sx.plot(x, y, title='x, y') - self._expose_and_close(plt) - - # x, y, style - plt = sx.plot(x, y, 'ro-', xlabel='x', title='x, y, "ro-"') - self._expose_and_close(plt) - - # x, y, style, y - plt = sx.plot(x, y, 'ro-', y ** 2, xlabel='x', ylabel='y', - title='x, y, "ro-", y ** 2') - self._expose_and_close(plt) - - # x, y, style, y, style - plt = sx.plot(x, y, 'ro-', y ** 2, 'b--', - title='x, y, "ro-", y ** 2, "b--"') - self._expose_and_close(plt) - - # x, y, style, x, y, style - plt = sx.plot(x, y, 'ro-', x, y ** 2, 'b--', - title='x, y, "ro-", x, y ** 2, "b--"') - self._expose_and_close(plt) - - # x, y, x, y - plt = sx.plot(x, y, x, y ** 2, title='x, y, x, y ** 2') - self._expose_and_close(plt) - - def test_imshow(self): - """Test imshow function""" - from silx import sx # Lazy loading to avoid it to create QApplication - - img = numpy.arange(100.).reshape(10, 10) + 1 - - # Nothing - plt = sx.imshow() - self._expose_and_close(plt) - - # image - plt = sx.imshow(img) - self._expose_and_close(plt) - - # image, named cmap - plt = sx.imshow(img, cmap='jet', title='jet cmap') - self._expose_and_close(plt) - - # image, custom colormap - plt = sx.imshow(img, cmap=Colormap(), title='custom colormap') - self._expose_and_close(plt) - - # image, log cmap - plt = sx.imshow(img, norm='log', title='log cmap') - self._expose_and_close(plt) - - # image, fixed range - plt = sx.imshow(img, vmin=10, vmax=20, - title='[10,20] cmap') - self._expose_and_close(plt) - - # image, keep ratio - plt = sx.imshow(img, aspect=True, - title='keep ratio') - self._expose_and_close(plt) - - # image, change origin and scale - plt = sx.imshow(img, origin=(10, 10), scale=(2, 2), - title='origin=(10, 10), scale=(2, 2)') - self._expose_and_close(plt) - - # image, origin='lower' - plt = sx.imshow(img, origin='upper', title='origin="lower"') - self._expose_and_close(plt) - - def test_scatter(self): - """Test scatter function""" - from silx import sx # Lazy loading to avoid it to create QApplication - - x = numpy.arange(100) - y = numpy.arange(100) - values = numpy.arange(100) - - # simple scatter - plt = sx.scatter(x, y, values) - self._expose_and_close(plt) - - # No value - plt = sx.scatter(x, y, values) - self._expose_and_close(plt) - - # single value - plt = sx.scatter(x, y, 10.) - self._expose_and_close(plt) - - # set size - plt = sx.scatter(x, y, values, size=20) - self._expose_and_close(plt) - - # set colormap - plt = sx.scatter(x, y, values, cmap='jet') - self._expose_and_close(plt) - - # set colormap range - plt = sx.scatter(x, y, values, vmin=2, vmax=50) - self._expose_and_close(plt) - - # set colormap normalisation - plt = sx.scatter(x, y, values, norm='log') - self._expose_and_close(plt) - - def test_ginput(self): - """Test ginput function - - This does NOT perform interactive tests - """ - from silx import sx # Lazy loading to avoid it to create QApplication - - for create_plot in (sx.plot, sx.imshow, sx.scatter): - with self.subTest(create_plot.__name__): - plt = create_plot() - self.qWaitForWindowExposed(plt) - self.qapp.processEvents() - - result = sx.ginput(1, timeout=0.1) - self.assertEqual(len(result), 0) - - plt.setAttribute(qt.Qt.WA_DeleteOnClose) - plt.close() - - @unittest.skipUnless(test_options.WITH_GL_TEST, - test_options.WITH_GL_TEST_REASON) - def test_contour3d(self): - """Test contour3d function""" - from silx import sx # Lazy loading to avoid it to create QApplication - - coords = numpy.linspace(-10, 10, 64) - z = coords.reshape(-1, 1, 1) - y = coords.reshape(1, -1, 1) - x = coords.reshape(1, 1, -1) - data = numpy.sin(x * y * z) / (x * y * z) - - # Just data - window = sx.contour3d(data) - - isosurfaces = window.getIsosurfaces() - self.assertEqual(len(isosurfaces), 1) - - if not window.getPlot3DWidget().isValid(): - self.skipTest("OpenGL context is not valid") - - # N contours + color - colors = ['red', 'green', 'blue'] - window = sx.contour3d(data, copy=False, contours=len(colors), - color=colors) - - isosurfaces = window.getIsosurfaces() - self.assertEqual(len(isosurfaces), len(colors)) - for iso, color in zip(isosurfaces, colors): - self.assertEqual(rgba(iso.getColor()), rgba(color)) - - # by isolevel, single color - contours = 0.2, 0.5 - window = sx.contour3d(data, copy=False, contours=contours, - color='yellow') - - isosurfaces = window.getIsosurfaces() - self.assertEqual(len(isosurfaces), len(contours)) - for iso, level in zip(isosurfaces, contours): - self.assertEqual(iso.getLevel(), level) - self.assertEqual(rgba(iso.getColor()), - rgba('yellow')) - - # Single isolevel, colormap - window = sx.contour3d(data, copy=False, contours=0.5, - colormap='gray', vmin=0.6, opacity=0.4) - - isosurfaces = window.getIsosurfaces() - self.assertEqual(len(isosurfaces), 1) - self.assertEqual(isosurfaces[0].getLevel(), 0.5) - self.assertEqual(rgba(isosurfaces[0].getColor()), - (0., 0., 0., 0.4)) - - @unittest.skipUnless(test_options.WITH_GL_TEST, - test_options.WITH_GL_TEST_REASON) - def test_points3d(self): - """Test points3d function""" - from silx import sx # Lazy loading to avoid it to create QApplication - - x = numpy.random.random(1024) - y = numpy.random.random(1024) - z = numpy.random.random(1024) - values = numpy.random.random(1024) - - # 3D positions, no value - window = sx.points3d(x, y, z) - - if not window.getSceneWidget().isValid(): - self.skipTest("OpenGL context is not valid") - - # 3D positions, values - window = sx.points3d(x, y, z, values, mode='2dsquare', - colormap='magma', vmin=0.4, vmax=0.5) - - # 2D positions, no value - window = sx.points3d(x, y) - - # 2D positions, values - window = sx.points3d(x, y, values=values, mode=',', - colormap='magma', vmin=0.4, vmax=0.5) - - -def suite(): - test_suite = unittest.TestSuite() - test_suite.addTest( - unittest.defaultTestLoader.loadTestsFromTestCase(SXTest)) - return test_suite - - -if __name__ == '__main__': - unittest.main(defaultTest='suite') diff --git a/silx/test/test_version.py b/silx/test/test_version.py deleted file mode 100644 index bb91e4e..0000000 --- a/silx/test/test_version.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 -# /*########################################################################## -# -# Copyright (c) 2015-2016 European Synchrotron Radiation Facility -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# ###########################################################################*/ -"""Basic test of top-level package import and existence of version info.""" - -__authors__ = ["T. Vincent"] -__license__ = "MIT" -__date__ = "26/02/2016" - -import unittest - -import silx - - -class TestVersion(unittest.TestCase): - def test_version(self): - self.assertTrue(isinstance(silx.version, str)) - - -def suite(): - test_suite = unittest.TestSuite() - test_suite.addTest( - unittest.defaultTestLoader.loadTestsFromTestCase(TestVersion)) - return test_suite - - -if __name__ == '__main__': - unittest.main(defaultTest='suite') diff --git a/silx/test/utils.py b/silx/test/utils.py deleted file mode 100644 index 77746c6..0000000 --- a/silx/test/utils.py +++ /dev/null @@ -1,204 +0,0 @@ -# coding: utf-8 -# /*########################################################################## -# -# Copyright (c) 2016-2019 European Synchrotron Radiation Facility -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# ###########################################################################*/ -"""Utilities for writing tests. - -- :func:`temp_dir` provides a with context to create/delete a temporary - directory. -""" - -__authors__ = ["T. Vincent"] -__license__ = "MIT" -__date__ = "03/01/2019" - - -import sys -import contextlib -import os -import numpy -import shutil -import tempfile -from ..resources import ExternalResources - - -utilstest = ExternalResources(project="silx", - url_base="http://www.silx.org/pub/silx/", - env_key="SILX_DATA", - timeout=60) -"This is the instance to be used. Singleton-like feature provided by module" - - -class _TestOptions(object): - - def __init__(self): - self.WITH_QT_TEST = True - """Qt tests are included""" - - self.WITH_QT_TEST_REASON = "" - """Reason for Qt tests are disabled if any""" - - self.WITH_OPENCL_TEST = True - """OpenCL tests are included""" - - self.WITH_GL_TEST = True - """OpenGL tests are included""" - - self.WITH_GL_TEST_REASON = "" - """Reason for OpenGL tests are disabled if any""" - - self.TEST_LOW_MEM = False - """Skip tests using too much memory""" - - def configure(self, parsed_options=None): - """Configure the TestOptions class from the command line arguments and the - environment variables - """ - if parsed_options is not None and not parsed_options.gui: - self.WITH_QT_TEST = False - self.WITH_QT_TEST_REASON = "Skipped by command line" - elif os.environ.get('WITH_QT_TEST', 'True') == 'False': - self.WITH_QT_TEST = False - self.WITH_QT_TEST_REASON = "Skipped by WITH_QT_TEST env var" - elif sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''): - self.WITH_QT_TEST = False - self.WITH_QT_TEST_REASON = "DISPLAY env variable not set" - - if (parsed_options is not None and not parsed_options.opencl) or os.environ.get('SILX_OPENCL', 'True') == 'False': - self.WITH_OPENCL_TEST = False - # That's an easy way to skip OpenCL tests - # It disable the use of OpenCL on the full silx project - os.environ['SILX_OPENCL'] = "False" - - if parsed_options is not None and not parsed_options.opengl: - self.WITH_GL_TEST = False - self.WITH_GL_TEST_REASON = "Skipped by command line" - elif os.environ.get('WITH_GL_TEST', 'True') == 'False': - self.WITH_GL_TEST = False - self.WITH_GL_TEST_REASON = "Skipped by WITH_GL_TEST env var" - elif sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''): - self.WITH_GL_TEST = False - self.WITH_GL_TEST_REASON = "DISPLAY env variable not set" - else: - try: - import OpenGL - except ImportError: - self.WITH_GL_TEST = False - self.WITH_GL_TEST_REASON = "OpenGL package not available" - - if (parsed_options is not None and parsed_options.low_mem) or os.environ.get('SILX_TEST_LOW_MEM', 'True') == 'False': - self.TEST_LOW_MEM = True - - if self.WITH_QT_TEST: - try: - from silx.gui import qt - except ImportError: - pass - else: - if sys.platform == "win32" and qt.qVersion() == "5.9.2": - self.SKIP_TEST_FOR_ISSUE_936 = True - - def add_parser_argument(self, parser): - """Add extrat arguments to the test argument parser - - :param ArgumentParser parser: An argument parser - """ - - parser.add_argument("-x", "--no-gui", dest="gui", default=True, - action="store_false", - help="Disable the test of the graphical use interface") - parser.add_argument("-g", "--no-opengl", dest="opengl", default=True, - action="store_false", - help="Disable tests using OpenGL") - parser.add_argument("-o", "--no-opencl", dest="opencl", default=True, - action="store_false", - help="Disable the test of the OpenCL part") - parser.add_argument("-l", "--low-mem", dest="low_mem", default=False, - action="store_true", - help="Disable test with large memory consumption (>100Mbyte") - - -test_options = _TestOptions() -"""Singleton providing configuration information for all the tests""" - - -# Temporary directory context ################################################# - -@contextlib.contextmanager -def temp_dir(): - """with context providing a temporary directory. - - >>> import os.path - >>> with temp_dir() as tmp: - ... print(os.path.isdir(tmp)) # Use tmp directory - """ - tmp_dir = tempfile.mkdtemp() - try: - yield tmp_dir - finally: - shutil.rmtree(tmp_dir) - - -# Synthetic data and random noise ############################################# -def add_gaussian_noise(y, stdev=1., mean=0.): - """Add random gaussian noise to synthetic data. - - :param ndarray y: Array of synthetic data - :param float mean: Mean of the gaussian distribution of noise. - :param float stdev: Standard deviation of the gaussian distribution of - noise. - :return: Array of data with noise added - """ - noise = numpy.random.normal(mean, stdev, size=y.size) - noise.shape = y.shape - return y + noise - - -def add_poisson_noise(y): - """Add random noise from a poisson distribution to synthetic data. - - :param ndarray y: Array of synthetic data - :return: Array of data with noise added - """ - yn = numpy.random.poisson(y) - yn.shape = y.shape - return yn - - -def add_relative_noise(y, max_noise=5.): - """Add relative random noise to synthetic data. The maximum noise level - is given in percents. - - An array of noise in the interval [-max_noise, max_noise] (continuous - uniform distribution) is generated, and applied to the data the - following way: - - :math:`yn = y * (1. + noise / 100.)` - - :param ndarray y: Array of synthetic data - :param float max_noise: Maximum percentage of noise - :return: Array of data with noise added - """ - noise = max_noise * (2 * numpy.random.random(size=y.size) - 1) - noise.shape = y.shape - return y * (1. + noise / 100.) |