LSSTApplications  17.0+124,17.0+14,17.0+73,18.0.0+37,18.0.0+80,18.0.0-4-g68ffd23+4,18.1.0-1-g0001055+12,18.1.0-1-g03d53ef+5,18.1.0-1-g1349e88+55,18.1.0-1-g2505f39+44,18.1.0-1-g5315e5e+4,18.1.0-1-g5e4b7ea+14,18.1.0-1-g7e8fceb+4,18.1.0-1-g85f8cd4+48,18.1.0-1-g8ff0b9f+4,18.1.0-1-ga2c679d+1,18.1.0-1-gd55f500+35,18.1.0-10-gb58edde+2,18.1.0-11-g0997b02+4,18.1.0-13-gfe4edf0b+12,18.1.0-14-g259bd21+21,18.1.0-19-gdb69f3f+2,18.1.0-2-g5f9922c+24,18.1.0-2-gd3b74e5+11,18.1.0-2-gfbf3545+32,18.1.0-26-g728bddb4+5,18.1.0-27-g6ff7ca9+2,18.1.0-3-g52aa583+25,18.1.0-3-g8ea57af+9,18.1.0-3-gb69f684+42,18.1.0-3-gfcaddf3+6,18.1.0-32-gd8786685a,18.1.0-4-gf3f9b77+6,18.1.0-5-g1dd662b+2,18.1.0-5-g6dbcb01+41,18.1.0-6-gae77429+3,18.1.0-7-g9d75d83+9,18.1.0-7-gae09a6d+30,18.1.0-9-gc381ef5+4,w.2019.45
LSSTDataManagementBasePackage
Classes | Functions | Variables
lsst.utils.tests Namespace Reference

Classes

class  ExecutablesTestCase
 
class  MemoryTestCase
 
class  TestCase
 

Functions

def init ()
 
def sort_tests (tests)
 
def suiteClassWrapper (tests)
 
def getTempFilePath (ext, expectOutput=True)
 
def inTestCase (func)
 
def debugger (exceptions)
 
def plotImageDiff (lhs, rhs, bad=None, diff=None, plotFileName=None)
 
def assertFloatsAlmostEqual (testCase, lhs, rhs, rtol=sys.float_info.epsilon, atol=sys.float_info.epsilon, relTo=None, printFailures=True, plotOnFailure=False, plotFileName=None, invert=False, msg=None)
 
def assertFloatsNotEqual (testCase, lhs, rhs, kwds)
 
def assertFloatsEqual (testCase, lhs, rhs, kwargs)
 

Variables

 psutil
 
 open_files
 

Function Documentation

◆ assertFloatsAlmostEqual()

def lsst.utils.tests.assertFloatsAlmostEqual (   testCase,
  lhs,
  rhs,
  rtol = sys.float_info.epsilon,
  atol = sys.float_info.epsilon,
  relTo = None,
  printFailures = True,
  plotOnFailure = False,
  plotFileName = None,
  invert = False,
  msg = None 
)
Highly-configurable floating point comparisons for scalars and arrays.

The test assertion will fail if all elements ``lhs`` and ``rhs`` are not
equal to within the tolerances specified by ``rtol`` and ``atol``.
More precisely, the comparison is:

``abs(lhs - rhs) <= relTo*rtol OR abs(lhs - rhs) <= atol``

If ``rtol`` or ``atol`` is `None`, that term in the comparison is not
performed at all.

When not specified, ``relTo`` is the elementwise maximum of the absolute
values of ``lhs`` and ``rhs``.  If set manually, it should usually be set
to either ``lhs`` or ``rhs``, or a scalar value typical of what is
expected.

Parameters
----------
testCase : `unittest.TestCase`
    Instance the test is part of.
lhs : scalar or array-like
    LHS value(s) to compare; may be a scalar or array-like of any
    dimension.
rhs : scalar or array-like
    RHS value(s) to compare; may be a scalar or array-like of any
    dimension.
rtol : `float`, optional
    Relative tolerance for comparison; defaults to double-precision
    epsilon.
atol : `float`, optional
    Absolute tolerance for comparison; defaults to double-precision
    epsilon.
relTo : `float`, optional
    Value to which comparison with rtol is relative.
printFailures : `bool`, optional
    Upon failure, print all inequal elements as part of the message.
plotOnFailure : `bool`, optional
    Upon failure, plot the originals and their residual with matplotlib.
    Only 2-d arrays are supported.
plotFileName : `str`, optional
    Filename to save the plot to.  If `None`, the plot will be displayed in
    a window.
invert : `bool`, optional
    If `True`, invert the comparison and fail only if any elements *are*
    equal. Used to implement `~lsst.utils.tests.assertFloatsNotEqual`,
    which should generally be used instead for clarity.
msg : `str`, optional
    String to append to the error message when assert fails.

Raises
------
AssertionError
    The values are not almost equal.

Definition at line 532 of file tests.py.

532  plotFileName=None, invert=False, msg=None):
533  """Highly-configurable floating point comparisons for scalars and arrays.
534 
535  The test assertion will fail if all elements ``lhs`` and ``rhs`` are not
536  equal to within the tolerances specified by ``rtol`` and ``atol``.
537  More precisely, the comparison is:
538 
539  ``abs(lhs - rhs) <= relTo*rtol OR abs(lhs - rhs) <= atol``
540 
541  If ``rtol`` or ``atol`` is `None`, that term in the comparison is not
542  performed at all.
543 
544  When not specified, ``relTo`` is the elementwise maximum of the absolute
545  values of ``lhs`` and ``rhs``. If set manually, it should usually be set
546  to either ``lhs`` or ``rhs``, or a scalar value typical of what is
547  expected.
548 
549  Parameters
550  ----------
551  testCase : `unittest.TestCase`
552  Instance the test is part of.
553  lhs : scalar or array-like
554  LHS value(s) to compare; may be a scalar or array-like of any
555  dimension.
556  rhs : scalar or array-like
557  RHS value(s) to compare; may be a scalar or array-like of any
558  dimension.
559  rtol : `float`, optional
560  Relative tolerance for comparison; defaults to double-precision
561  epsilon.
562  atol : `float`, optional
563  Absolute tolerance for comparison; defaults to double-precision
564  epsilon.
565  relTo : `float`, optional
566  Value to which comparison with rtol is relative.
567  printFailures : `bool`, optional
568  Upon failure, print all inequal elements as part of the message.
569  plotOnFailure : `bool`, optional
570  Upon failure, plot the originals and their residual with matplotlib.
571  Only 2-d arrays are supported.
572  plotFileName : `str`, optional
573  Filename to save the plot to. If `None`, the plot will be displayed in
574  a window.
575  invert : `bool`, optional
576  If `True`, invert the comparison and fail only if any elements *are*
577  equal. Used to implement `~lsst.utils.tests.assertFloatsNotEqual`,
578  which should generally be used instead for clarity.
579  msg : `str`, optional
580  String to append to the error message when assert fails.
581 
582  Raises
583  ------
584  AssertionError
585  The values are not almost equal.
586  """
587  if not numpy.isfinite(lhs).all():
588  testCase.fail("Non-finite values in lhs")
589  if not numpy.isfinite(rhs).all():
590  testCase.fail("Non-finite values in rhs")
591  diff = lhs - rhs
592  absDiff = numpy.abs(lhs - rhs)
593  if rtol is not None:
594  if relTo is None:
595  relTo = numpy.maximum(numpy.abs(lhs), numpy.abs(rhs))
596  else:
597  relTo = numpy.abs(relTo)
598  bad = absDiff > rtol*relTo
599  if atol is not None:
600  bad = numpy.logical_and(bad, absDiff > atol)
601  else:
602  if atol is None:
603  raise ValueError("rtol and atol cannot both be None")
604  bad = absDiff > atol
605  failed = numpy.any(bad)
606  if invert:
607  failed = not failed
608  bad = numpy.logical_not(bad)
609  cmpStr = "=="
610  failStr = "are the same"
611  else:
612  cmpStr = "!="
613  failStr = "differ"
614  errMsg = []
615  if failed:
616  if numpy.isscalar(bad):
617  if rtol is None:
618  errMsg = ["%s %s %s; diff=%s with atol=%s"
619  % (lhs, cmpStr, rhs, absDiff, atol)]
620  elif atol is None:
621  errMsg = ["%s %s %s; diff=%s/%s=%s with rtol=%s"
622  % (lhs, cmpStr, rhs, absDiff, relTo, absDiff/relTo, rtol)]
623  else:
624  errMsg = ["%s %s %s; diff=%s/%s=%s with rtol=%s, atol=%s"
625  % (lhs, cmpStr, rhs, absDiff, relTo, absDiff/relTo, rtol, atol)]
626  else:
627  errMsg = ["%d/%d elements %s with rtol=%s, atol=%s"
628  % (bad.sum(), bad.size, failStr, rtol, atol)]
629  if plotOnFailure:
630  if len(lhs.shape) != 2 or len(rhs.shape) != 2:
631  raise ValueError("plotOnFailure is only valid for 2-d arrays")
632  try:
633  plotImageDiff(lhs, rhs, bad, diff=diff, plotFileName=plotFileName)
634  except ImportError:
635  errMsg.append("Failure plot requested but matplotlib could not be imported.")
636  if printFailures:
637  # Make sure everything is an array if any of them are, so we can treat
638  # them the same (diff and absDiff are arrays if either rhs or lhs is),
639  # and we don't get here if neither is.
640  if numpy.isscalar(relTo):
641  relTo = numpy.ones(bad.shape, dtype=float) * relTo
642  if numpy.isscalar(lhs):
643  lhs = numpy.ones(bad.shape, dtype=float) * lhs
644  if numpy.isscalar(rhs):
645  rhs = numpy.ones(bad.shape, dtype=float) * rhs
646  if rtol is None:
647  for a, b, diff in zip(lhs[bad], rhs[bad], absDiff[bad]):
648  errMsg.append("%s %s %s (diff=%s)" % (a, cmpStr, b, diff))
649  else:
650  for a, b, diff, rel in zip(lhs[bad], rhs[bad], absDiff[bad], relTo[bad]):
651  errMsg.append("%s %s %s (diff=%s/%s=%s)" % (a, cmpStr, b, diff, rel, diff/rel))
652 
653  if msg is not None:
654  errMsg.append(msg)
655  testCase.assertFalse(failed, msg="\n".join(errMsg))
656 
657 
658 @inTestCase
def plotImageDiff(lhs, rhs, bad=None, diff=None, plotFileName=None)
Definition: tests.py:464
bool all(CoordinateExpr< N > const &expr) noexcept
Return true if all elements are true.

◆ assertFloatsEqual()

def lsst.utils.tests.assertFloatsEqual (   testCase,
  lhs,
  rhs,
  kwargs 
)
Assert that lhs == rhs (both numeric types, whether scalar or array).

See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with
``rtol=atol=0``) for more information.

Parameters
----------
testCase : `unittest.TestCase`
    Instance the test is part of.
lhs : scalar or array-like
    LHS value(s) to compare; may be a scalar or array-like of any
    dimension.
rhs : scalar or array-like
    RHS value(s) to compare; may be a scalar or array-like of any
    dimension.

Raises
------
AssertionError
    The values are not equal.

Definition at line 686 of file tests.py.

686 def assertFloatsEqual(testCase, lhs, rhs, **kwargs):
687  """
688  Assert that lhs == rhs (both numeric types, whether scalar or array).
689 
690  See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with
691  ``rtol=atol=0``) for more information.
692 
693  Parameters
694  ----------
695  testCase : `unittest.TestCase`
696  Instance the test is part of.
697  lhs : scalar or array-like
698  LHS value(s) to compare; may be a scalar or array-like of any
699  dimension.
700  rhs : scalar or array-like
701  RHS value(s) to compare; may be a scalar or array-like of any
702  dimension.
703 
704  Raises
705  ------
706  AssertionError
707  The values are not equal.
708  """
709  return assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=0, atol=0, **kwargs)
710 
def assertFloatsEqual(testCase, lhs, rhs, kwargs)
Definition: tests.py:686
def assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=sys.float_info.epsilon, atol=sys.float_info.epsilon, relTo=None, printFailures=True, plotOnFailure=False, plotFileName=None, invert=False, msg=None)
Definition: tests.py:532

◆ assertFloatsNotEqual()

def lsst.utils.tests.assertFloatsNotEqual (   testCase,
  lhs,
  rhs,
  kwds 
)
Fail a test if the given floating point values are equal to within the
given tolerances.

See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with
``rtol=atol=0``) for more information.

Parameters
----------
testCase : `unittest.TestCase`
    Instance the test is part of.
lhs : scalar or array-like
    LHS value(s) to compare; may be a scalar or array-like of any
    dimension.
rhs : scalar or array-like
    RHS value(s) to compare; may be a scalar or array-like of any
    dimension.

Raises
------
AssertionError
    The values are almost equal.

Definition at line 659 of file tests.py.

659 def assertFloatsNotEqual(testCase, lhs, rhs, **kwds):
660  """Fail a test if the given floating point values are equal to within the
661  given tolerances.
662 
663  See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with
664  ``rtol=atol=0``) for more information.
665 
666  Parameters
667  ----------
668  testCase : `unittest.TestCase`
669  Instance the test is part of.
670  lhs : scalar or array-like
671  LHS value(s) to compare; may be a scalar or array-like of any
672  dimension.
673  rhs : scalar or array-like
674  RHS value(s) to compare; may be a scalar or array-like of any
675  dimension.
676 
677  Raises
678  ------
679  AssertionError
680  The values are almost equal.
681  """
682  return assertFloatsAlmostEqual(testCase, lhs, rhs, invert=True, **kwds)
683 
684 
685 @inTestCase
def assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=sys.float_info.epsilon, atol=sys.float_info.epsilon, relTo=None, printFailures=True, plotOnFailure=False, plotFileName=None, invert=False, msg=None)
Definition: tests.py:532
def assertFloatsNotEqual(testCase, lhs, rhs, kwds)
Definition: tests.py:659

◆ debugger()

def lsst.utils.tests.debugger (   exceptions)
Decorator to enter the debugger when there's an uncaught exception

To use, just slap a ``@debugger()`` on your function.

You may provide specific exception classes to catch as arguments to
the decorator function, e.g.,
``@debugger(RuntimeError, NotImplementedError)``.
This defaults to just `AssertionError`, for use on `unittest.TestCase`
methods.

Code provided by "Rosh Oxymoron" on StackOverflow:
http://stackoverflow.com/questions/4398967/python-unit-testing-automatically-running-the-debugger-when-a-test-fails

Notes
-----
Consider using ``pytest --pdb`` instead of this decorator.

Definition at line 430 of file tests.py.

430 def debugger(*exceptions):
431  """Decorator to enter the debugger when there's an uncaught exception
432 
433  To use, just slap a ``@debugger()`` on your function.
434 
435  You may provide specific exception classes to catch as arguments to
436  the decorator function, e.g.,
437  ``@debugger(RuntimeError, NotImplementedError)``.
438  This defaults to just `AssertionError`, for use on `unittest.TestCase`
439  methods.
440 
441  Code provided by "Rosh Oxymoron" on StackOverflow:
442  http://stackoverflow.com/questions/4398967/python-unit-testing-automatically-running-the-debugger-when-a-test-fails
443 
444  Notes
445  -----
446  Consider using ``pytest --pdb`` instead of this decorator.
447  """
448  if not exceptions:
449  exceptions = (AssertionError, )
450 
451  def decorator(f):
452  @functools.wraps(f)
453  def wrapper(*args, **kwargs):
454  try:
455  return f(*args, **kwargs)
456  except exceptions:
457  import sys
458  import pdb
459  pdb.post_mortem(sys.exc_info()[2])
460  return wrapper
461  return decorator
462 
463 
def debugger(exceptions)
Definition: tests.py:430

◆ getTempFilePath()

def lsst.utils.tests.getTempFilePath (   ext,
  expectOutput = True 
)
Return a path suitable for a temporary file and try to delete the
file on success

If the with block completes successfully then the file is deleted,
if possible; failure results in a printed warning.
If a file is remains when it should not, a RuntimeError exception is
raised. This exception is also raised if a file is not present on context
manager exit when one is expected to exist.
If the block exits with an exception the file if left on disk so it can be
examined. The file name has a random component such that nested context
managers can be used with the same file suffix.

Parameters
----------

ext : `str`
    File name extension, e.g. ``.fits``.
expectOutput : `bool`, optional
    If `True`, a file should be created within the context manager.
    If `False`, a file should not be present when the context manager
    exits.

Returns
-------
`str`
    Path for a temporary file. The path is a combination of the caller's
    file path and the name of the top-level function

Notes
-----
::

    # file tests/testFoo.py
    import unittest
    import lsst.utils.tests
    class FooTestCase(unittest.TestCase):
        def testBasics(self):
            self.runTest()

        def runTest(self):
            with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
                # if tests/.tests exists then
                # tmpFile = "tests/.tests/testFoo_testBasics.fits"
                # otherwise tmpFile = "testFoo_testBasics.fits"
                ...
                # at the end of this "with" block the path tmpFile will be
                # deleted, but only if the file exists and the "with"
                # block terminated normally (rather than with an exception)
    ...

Definition at line 317 of file tests.py.

317 def getTempFilePath(ext, expectOutput=True):
318  """Return a path suitable for a temporary file and try to delete the
319  file on success
320 
321  If the with block completes successfully then the file is deleted,
322  if possible; failure results in a printed warning.
323  If a file is remains when it should not, a RuntimeError exception is
324  raised. This exception is also raised if a file is not present on context
325  manager exit when one is expected to exist.
326  If the block exits with an exception the file if left on disk so it can be
327  examined. The file name has a random component such that nested context
328  managers can be used with the same file suffix.
329 
330  Parameters
331  ----------
332 
333  ext : `str`
334  File name extension, e.g. ``.fits``.
335  expectOutput : `bool`, optional
336  If `True`, a file should be created within the context manager.
337  If `False`, a file should not be present when the context manager
338  exits.
339 
340  Returns
341  -------
342  `str`
343  Path for a temporary file. The path is a combination of the caller's
344  file path and the name of the top-level function
345 
346  Notes
347  -----
348  ::
349 
350  # file tests/testFoo.py
351  import unittest
352  import lsst.utils.tests
353  class FooTestCase(unittest.TestCase):
354  def testBasics(self):
355  self.runTest()
356 
357  def runTest(self):
358  with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
359  # if tests/.tests exists then
360  # tmpFile = "tests/.tests/testFoo_testBasics.fits"
361  # otherwise tmpFile = "testFoo_testBasics.fits"
362  ...
363  # at the end of this "with" block the path tmpFile will be
364  # deleted, but only if the file exists and the "with"
365  # block terminated normally (rather than with an exception)
366  ...
367  """
368  stack = inspect.stack()
369  # get name of first function in the file
370  for i in range(2, len(stack)):
371  frameInfo = inspect.getframeinfo(stack[i][0])
372  if i == 2:
373  callerFilePath = frameInfo.filename
374  callerFuncName = frameInfo.function
375  elif callerFilePath == frameInfo.filename:
376  # this function called the previous function
377  callerFuncName = frameInfo.function
378  else:
379  break
380 
381  callerDir, callerFileNameWithExt = os.path.split(callerFilePath)
382  callerFileName = os.path.splitext(callerFileNameWithExt)[0]
383  outDir = os.path.join(callerDir, ".tests")
384  if not os.path.isdir(outDir):
385  outDir = ""
386  prefix = "%s_%s-" % (callerFileName, callerFuncName)
387  outPath = tempfile.mktemp(dir=outDir, suffix=ext, prefix=prefix)
388  if os.path.exists(outPath):
389  # There should not be a file there given the randomizer. Warn and remove.
390  # Use stacklevel 3 so that the warning is reported from the end of the with block
391  warnings.warn("Unexpectedly found pre-existing tempfile named %r" % (outPath,),
392  stacklevel=3)
393  try:
394  os.remove(outPath)
395  except OSError:
396  pass
397 
398  yield outPath
399 
400  fileExists = os.path.exists(outPath)
401  if expectOutput:
402  if not fileExists:
403  raise RuntimeError("Temp file expected named {} but none found".format(outPath))
404  else:
405  if fileExists:
406  raise RuntimeError("Unexpectedly discovered temp file named {}".format(outPath))
407  # Try to clean up the file regardless
408  if fileExists:
409  try:
410  os.remove(outPath)
411  except OSError as e:
412  # Use stacklevel 3 so that the warning is reported from the end of the with block
413  warnings.warn("Warning: could not remove file %r: %s" % (outPath, e), stacklevel=3)
414 
415 
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174
def getTempFilePath(ext, expectOutput=True)
Definition: tests.py:317

◆ init()

def lsst.utils.tests.init ( )
Initialize the memory tester and file descriptor leak tester.

Definition at line 64 of file tests.py.

64 def init():
65  """Initialize the memory tester and file descriptor leak tester."""
66  global open_files
67  # Reset the list of open files
68  open_files = _get_open_files()
69 
70 
def init()
Definition: tests.py:64

◆ inTestCase()

def lsst.utils.tests.inTestCase (   func)
A decorator to add a free function to our custom TestCase class, while also
making it available as a free function.

Definition at line 422 of file tests.py.

422 def inTestCase(func):
423  """A decorator to add a free function to our custom TestCase class, while also
424  making it available as a free function.
425  """
426  setattr(TestCase, func.__name__, func)
427  return func
428 
429 
def inTestCase(func)
Definition: tests.py:422

◆ plotImageDiff()

def lsst.utils.tests.plotImageDiff (   lhs,
  rhs,
  bad = None,
  diff = None,
  plotFileName = None 
)
Plot the comparison of two 2-d NumPy arrays.

Parameters
----------
lhs : `numpy.ndarray`
    LHS values to compare; a 2-d NumPy array
rhs : `numpy.ndarray`
    RHS values to compare; a 2-d NumPy array
bad : `numpy.ndarray`
    A 2-d boolean NumPy array of values to emphasize in the plots
diff : `numpy.ndarray`
    difference array; a 2-d NumPy array, or None to show lhs-rhs
plotFileName : `str`
    Filename to save the plot to.  If None, the plot will be displayed in
    a window.

Notes
-----
This method uses `matplotlib` and imports it internally; it should be
wrapped in a try/except block within packages that do not depend on
`matplotlib` (including `~lsst.utils`).

Definition at line 464 of file tests.py.

464 def plotImageDiff(lhs, rhs, bad=None, diff=None, plotFileName=None):
465  """Plot the comparison of two 2-d NumPy arrays.
466 
467  Parameters
468  ----------
469  lhs : `numpy.ndarray`
470  LHS values to compare; a 2-d NumPy array
471  rhs : `numpy.ndarray`
472  RHS values to compare; a 2-d NumPy array
473  bad : `numpy.ndarray`
474  A 2-d boolean NumPy array of values to emphasize in the plots
475  diff : `numpy.ndarray`
476  difference array; a 2-d NumPy array, or None to show lhs-rhs
477  plotFileName : `str`
478  Filename to save the plot to. If None, the plot will be displayed in
479  a window.
480 
481  Notes
482  -----
483  This method uses `matplotlib` and imports it internally; it should be
484  wrapped in a try/except block within packages that do not depend on
485  `matplotlib` (including `~lsst.utils`).
486  """
487  from matplotlib import pyplot
488  if diff is None:
489  diff = lhs - rhs
490  pyplot.figure()
491  if bad is not None:
492  # make an rgba image that's red and transparent where not bad
493  badImage = numpy.zeros(bad.shape + (4,), dtype=numpy.uint8)
494  badImage[:, :, 0] = 255
495  badImage[:, :, 1] = 0
496  badImage[:, :, 2] = 0
497  badImage[:, :, 3] = 255*bad
498  vmin1 = numpy.minimum(numpy.min(lhs), numpy.min(rhs))
499  vmax1 = numpy.maximum(numpy.max(lhs), numpy.max(rhs))
500  vmin2 = numpy.min(diff)
501  vmax2 = numpy.max(diff)
502  for n, (image, title) in enumerate([(lhs, "lhs"), (rhs, "rhs"), (diff, "diff")]):
503  pyplot.subplot(2, 3, n + 1)
504  im1 = pyplot.imshow(image, cmap=pyplot.cm.gray, interpolation='nearest', origin='lower',
505  vmin=vmin1, vmax=vmax1)
506  if bad is not None:
507  pyplot.imshow(badImage, alpha=0.2, interpolation='nearest', origin='lower')
508  pyplot.axis("off")
509  pyplot.title(title)
510  pyplot.subplot(2, 3, n + 4)
511  im2 = pyplot.imshow(image, cmap=pyplot.cm.gray, interpolation='nearest', origin='lower',
512  vmin=vmin2, vmax=vmax2)
513  if bad is not None:
514  pyplot.imshow(badImage, alpha=0.2, interpolation='nearest', origin='lower')
515  pyplot.axis("off")
516  pyplot.title(title)
517  pyplot.subplots_adjust(left=0.05, bottom=0.05, top=0.92, right=0.75, wspace=0.05, hspace=0.05)
518  cax1 = pyplot.axes([0.8, 0.55, 0.05, 0.4])
519  pyplot.colorbar(im1, cax=cax1)
520  cax2 = pyplot.axes([0.8, 0.05, 0.05, 0.4])
521  pyplot.colorbar(im2, cax=cax2)
522  if plotFileName:
523  pyplot.savefig(plotFileName)
524  else:
525  pyplot.show()
526 
527 
528 @inTestCase
def plotImageDiff(lhs, rhs, bad=None, diff=None, plotFileName=None)
Definition: tests.py:464

◆ sort_tests()

def lsst.utils.tests.sort_tests (   tests)
Sort supplied test suites such that MemoryTestCases are at the end.

`lsst.utils.tests.MemoryTestCase` tests should always run after any other
tests in the module.

Parameters
----------
tests : sequence
    Sequence of test suites.

Returns
-------
suite : `unittest.TestSuite`
    A combined `~unittest.TestSuite` with
    `~lsst.utils.tests.MemoryTestCase` at the end.

Definition at line 71 of file tests.py.

71 def sort_tests(tests):
72  """Sort supplied test suites such that MemoryTestCases are at the end.
73 
74  `lsst.utils.tests.MemoryTestCase` tests should always run after any other
75  tests in the module.
76 
77  Parameters
78  ----------
79  tests : sequence
80  Sequence of test suites.
81 
82  Returns
83  -------
84  suite : `unittest.TestSuite`
85  A combined `~unittest.TestSuite` with
86  `~lsst.utils.tests.MemoryTestCase` at the end.
87  """
88 
89  suite = unittest.TestSuite()
90  memtests = []
91  for test_suite in tests:
92  try:
93  # Just test the first test method in the suite for MemoryTestCase
94  # Use loop rather than next as it is possible for a test class
95  # to not have any test methods and the Python community prefers
96  # for loops over catching a StopIteration exception.
97  bases = None
98  for method in test_suite:
99  bases = inspect.getmro(method.__class__)
100  break
101  if bases is not None and MemoryTestCase in bases:
102  memtests.append(test_suite)
103  else:
104  suite.addTests(test_suite)
105  except TypeError:
106  if isinstance(test_suite, MemoryTestCase):
107  memtests.append(test_suite)
108  else:
109  suite.addTest(test_suite)
110  suite.addTests(memtests)
111  return suite
112 
113 
def sort_tests(tests)
Definition: tests.py:71

◆ suiteClassWrapper()

def lsst.utils.tests.suiteClassWrapper (   tests)

Definition at line 114 of file tests.py.

114 def suiteClassWrapper(tests):
115  return unittest.TestSuite(sort_tests(tests))
116 
117 
118 # Replace the suiteClass callable in the defaultTestLoader
119 # so that we can reorder the test ordering. This will have
120 # no effect if no memory test cases are found.
121 unittest.defaultTestLoader.suiteClass = suiteClassWrapper
122 
123 
def suiteClassWrapper(tests)
Definition: tests.py:114
def sort_tests(tests)
Definition: tests.py:71

Variable Documentation

◆ open_files

lsst.utils.tests.open_files

Definition at line 47 of file tests.py.

◆ psutil

lsst.utils.tests.psutil

Definition at line 44 of file tests.py.