LSSTApplications  11.0-13-gbb96280,12.1+18,12.1+7,12.1-1-g14f38d3+72,12.1-1-g16c0db7+5,12.1-1-g5961e7a+84,12.1-1-ge22e12b+23,12.1-11-g06625e2+4,12.1-11-g0d7f63b+4,12.1-19-gd507bfc,12.1-2-g7dda0ab+38,12.1-2-gc0bc6ab+81,12.1-21-g6ffe579+2,12.1-21-gbdb6c2a+4,12.1-24-g941c398+5,12.1-3-g57f6835+7,12.1-3-gf0736f3,12.1-37-g3ddd237,12.1-4-gf46015e+5,12.1-5-g06c326c+20,12.1-5-g648ee80+3,12.1-5-gc2189d7+4,12.1-6-ga608fc0+1,12.1-7-g3349e2a+5,12.1-7-gfd75620+9,12.1-9-g577b946+5,12.1-9-gc4df26a+10
LSSTDataManagementBasePackage
Classes | Functions | Variables
lsst.utils.tests Namespace Reference

Classes

class  MemoryTestCase
 Check for memory leaks since memId0 was allocated. More...
 
class  ExecutablesTestCase
 Test that executables can be run and return good status. More...
 
class  TestCase
 Subclass of unittest.TestCase that adds some custom assertions for convenience. More...
 

Functions

def _get_open_files
 
def init
 
def run
 Exit with the status code resulting from running the provided test suite. More...
 
def sort_tests
 Go through the supplied sequence of test suites and sort them to ensure that MemoryTestCases are at the end of the test list. More...
 
def suiteClassWrapper
 
def findFileFromRoot
 Find file which is specified as a path relative to the toplevel directory; we start in $cwd and walk up until we find the file (or throw IOError if it doesn't exist) More...
 
def getTempFilePath
 Return a path suitable for a temporary file and try to delete the file on success. More...
 
def inTestCase
 A decorator to add a free function to our custom TestCase class, while also making it available as a free function. More...
 
def assertRaisesLsstCpp
 
def debugger
 Decorator to enter the debugger when there's an uncaught exception. More...
 
def plotImageDiff
 Plot the comparison of two 2-d NumPy arrays. More...
 
def assertFloatsAlmostEqual
 Highly-configurable floating point comparisons for scalars and arrays. More...
 
def assertFloatsNotEqual
 
def assertFloatsEqual
 
def assertClose
 
def assertNotClose
 

Variables

 psutil = None
 
 dafBase = None
 
int memId0 = 0
 
int nleakPrintMax = 20
 
tuple open_files = set()
 

Function Documentation

def lsst.utils.tests._get_open_files ( )
private
Return a set containing the list of open files.

Definition at line 60 of file tests.py.

60 
61 def _get_open_files():
62  """Return a set containing the list of open files."""
63  if psutil is None:
64  return set()
65  return set(p.path for p in psutil.Process().open_files())
66 
tuple open_files
Definition: tests.py:57
def _get_open_files
Definition: tests.py:60
def lsst.utils.tests.assertClose (   args,
  kwargs 
)

Definition at line 656 of file tests.py.

657 def assertClose(*args, **kwargs):
658  warnings.warn("assertClose is deprecated; please use TestCase.assertFloatsAlmostEqual",
659  DeprecationWarning)
660  return assertFloatsAlmostEqual(*args, **kwargs)
661 
662 
@inTestCase
def assertFloatsAlmostEqual
Highly-configurable floating point comparisons for scalars and arrays.
Definition: tests.py:534
def assertClose
Definition: tests.py:656
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
[in]testCaseunittest.TestCase instance the test is part of
[in]lhsLHS value(s) to compare; may be a scalar or array-like of any dimension
[in]rhsRHS value(s) to compare; may be a scalar or array-like of any dimension
[in]rtolRelative tolerance for comparison; defaults to double-precision epsilon.
[in]atolAbsolute tolerance for comparison; defaults to double-precision epsilon.
[in]relToValue to which comparison with rtol is relative.
[in]printFailuresUpon failure, print all inequal elements as part of the message.
[in]plotOnFailureUpon failure, plot the originals and their residual with matplotlib. Only 2-d arrays are supported.
[in]plotFileNameFilename to save the plot to. If None, the plot will be displayed in a a window.
[in]invertIf True, invert the comparison and fail only if any elements are equal. Used to implement assertFloatsNotEqual, which should generally be used instead for clarity.
[in]msgString to append to the error message when assert fails.

Definition at line 534 of file tests.py.

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

See assertClose (called with rtol=atol=0) for more information.

Definition at line 646 of file tests.py.

647 def assertFloatsEqual(testCase, lhs, rhs, **kwargs):
648  """
649  Assert that lhs == rhs (both numeric types, whether scalar or array).
650 
651  See assertClose (called with rtol=atol=0) for more information.
652  """
653  return assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=0, atol=0, **kwargs)
654 
655 
@inTestCase
def assertFloatsAlmostEqual
Highly-configurable floating point comparisons for scalars and arrays.
Definition: tests.py:534
def assertFloatsEqual
Definition: tests.py:646
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 assertClose for more information.

Definition at line 636 of file tests.py.

637 def assertFloatsNotEqual(testCase, lhs, rhs, **kwds):
638  """
639  Fail a test if the given floating point values are equal to within the given tolerances.
640 
641  See assertClose for more information.
642  """
643  return assertFloatsAlmostEqual(testCase, lhs, rhs, invert=True, **kwds)
644 
645 
@inTestCase
def assertFloatsNotEqual
Definition: tests.py:636
def assertFloatsAlmostEqual
Highly-configurable floating point comparisons for scalars and arrays.
Definition: tests.py:534
def lsst.utils.tests.assertNotClose (   args,
  kwargs 
)

Definition at line 663 of file tests.py.

664 def assertNotClose(*args, **kwargs):
665  warnings.warn("assertNotClose is deprecated; please use TestCase.assertFloatsNotEqual",
666  DeprecationWarning)
667  return assertFloatsNotEqual(*args, **kwargs)
def assertFloatsNotEqual
Definition: tests.py:636
def assertNotClose
Definition: tests.py:663
def lsst.utils.tests.assertRaisesLsstCpp (   testcase,
  excClass,
  callableObj,
  args,
  kwargs 
)

Definition at line 435 of file tests.py.

436 def assertRaisesLsstCpp(testcase, excClass, callableObj, *args, **kwargs):
437  warnings.warn("assertRaisesLsstCpp is deprecated; please just use TestCase.assertRaises",
438  DeprecationWarning)
439  return testcase.assertRaises(excClass, callableObj, *args, **kwargs)
440 
441 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
def assertRaisesLsstCpp
Definition: tests.py:435
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

Definition at line 445 of file tests.py.

446 def debugger(*exceptions):
447  """!Decorator to enter the debugger when there's an uncaught exception
448 
449  To use, just slap a "@debugger()" on your function.
450 
451  You may provide specific exception classes to catch as arguments to
452  the decorator function, e.g., "@debugger(RuntimeError, NotImplementedError)".
453  This defaults to just 'AssertionError', for use on unittest.TestCase methods.
454 
455  Code provided by "Rosh Oxymoron" on StackOverflow:
456  http://stackoverflow.com/questions/4398967/python-unit-testing-automatically-running-the-debugger-when-a-test-fails
457  """
458  if not exceptions:
459  exceptions = (AssertionError, )
460 
461  def decorator(f):
462  @functools.wraps(f)
463  def wrapper(*args, **kwargs):
464  try:
465  return f(*args, **kwargs)
466  except exceptions:
467  import sys
468  import pdb
469  pdb.post_mortem(sys.exc_info()[2])
470  return wrapper
471  return decorator
472 
473 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
474 
def debugger
Decorator to enter the debugger when there&#39;s an uncaught exception.
Definition: tests.py:445
def lsst.utils.tests.findFileFromRoot (   ifile)

Find file which is specified as a path relative to the toplevel directory; we start in $cwd and walk up until we find the file (or throw IOError if it doesn't exist)

This is useful for running tests that may be run from dir/tests or dir

Definition at line 329 of file tests.py.

330 def findFileFromRoot(ifile):
331  """!Find file which is specified as a path relative to the toplevel directory;
332  we start in $cwd and walk up until we find the file (or throw IOError if it doesn't exist)
333 
334  This is useful for running tests that may be run from _dir_/tests or _dir_"""
335 
336  if os.path.isfile(ifile):
337  return ifile
338 
339  ofile = None
340  file = ifile
341  while file != "":
342  dirname, basename = os.path.split(file)
343  if ofile:
344  ofile = os.path.join(basename, ofile)
345  else:
346  ofile = basename
347 
348  if os.path.isfile(ofile):
349  return ofile
350 
351  file = dirname
352 
353  raise IOError("Can't find %s" % ifile)
354 
355 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
356 
357 
@contextmanager
def findFileFromRoot
Find file which is specified as a path relative to the toplevel directory; we start in $cwd and walk ...
Definition: tests.py:329
def lsst.utils.tests.getTempFilePath (   ext)

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 the block exits with an exception the file if left on disk so it can be examined.

Parameters
[in]extfile name extension, e.g. ".fits"
Returns
path for a temporary file. The path is a combination of the caller's file path and the name of the top-level function, as per this simple example:
1 # file tests/testFoo.py
2 import unittest
3 import lsst.utils.tests
4 class FooTestCase(unittest.TestCase):
5  def testBasics(self):
6  self.runTest()
7 
8  def runTest(self):
9  with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
10  # if tests/.tests exists then tmpFile = "tests/.tests/testFoo_testBasics.fits"
11  # otherwise tmpFile = "testFoo_testBasics.fits"
12  ...
13  # at the end of this "with" block the path tmpFile will be deleted, but only if
14  # the file exists and the "with" block terminated normally (rather than with an exception)
15 ...

Definition at line 358 of file tests.py.

359 def getTempFilePath(ext):
360  """!Return a path suitable for a temporary file and try to delete the file on success
361 
362  If the with block completes successfully then the file is deleted, if possible;
363  failure results in a printed warning.
364  If the block exits with an exception the file if left on disk so it can be examined.
365 
366  @param[in] ext file name extension, e.g. ".fits"
367  @return path for a temporary file. The path is a combination of the caller's file path
368  and the name of the top-level function, as per this simple example:
369  @code
370  # file tests/testFoo.py
371  import unittest
372  import lsst.utils.tests
373  class FooTestCase(unittest.TestCase):
374  def testBasics(self):
375  self.runTest()
376 
377  def runTest(self):
378  with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
379  # if tests/.tests exists then tmpFile = "tests/.tests/testFoo_testBasics.fits"
380  # otherwise tmpFile = "testFoo_testBasics.fits"
381  ...
382  # at the end of this "with" block the path tmpFile will be deleted, but only if
383  # the file exists and the "with" block terminated normally (rather than with an exception)
384  ...
385  @endcode
386  """
387  stack = inspect.stack()
388  # get name of first function in the file
389  for i in range(2, len(stack)):
390  frameInfo = inspect.getframeinfo(stack[i][0])
391  if i == 2:
392  callerFilePath = frameInfo.filename
393  callerFuncName = frameInfo.function
394  elif callerFilePath == frameInfo.filename:
395  # this function called the previous function
396  callerFuncName = frameInfo.function
397  else:
398  break
399 
400  callerDir, callerFileNameWithExt = os.path.split(callerFilePath)
401  callerFileName = os.path.splitext(callerFileNameWithExt)[0]
402  outDir = os.path.join(callerDir, ".tests")
403  if not os.path.isdir(outDir):
404  outDir = ""
405  outName = "%s_%s%s" % (callerFileName, callerFuncName, ext)
406  outPath = os.path.join(outDir, outName)
407  yield outPath
408  if os.path.isfile(outPath):
409  try:
410  os.remove(outPath)
411  except OSError as e:
412  print("Warning: could not remove file %r: %s" % (outPath, e))
413  else:
414  print("Warning: could not find file %r" % (outPath,))
415 
416 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
417 
def getTempFilePath
Return a path suitable for a temporary file and try to delete the file on success.
Definition: tests.py:358
def lsst.utils.tests.init ( )
Initialize the memory tester

Definition at line 67 of file tests.py.

67 
68 def init():
69  """Initialize the memory tester"""
70  global memId0
71  global open_files
72  if dafBase:
73  memId0 = dafBase.Citizen_getNextMemId() # used by MemoryTestCase
74  # Reset the list of open files
75  open_files = _get_open_files()
76 
def _get_open_files
Definition: tests.py:60
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 424 of file tests.py.

425 def inTestCase(func):
426  """!A decorator to add a free function to our custom TestCase class, while also
427  making it available as a free function.
428  """
429  setattr(TestCase, func.__name__, func)
430  return func
431 
432 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
433 
434 
@inTestCase
def inTestCase
A decorator to add a free function to our custom TestCase class, while also making it available as a ...
Definition: tests.py:424
def lsst.utils.tests.plotImageDiff (   lhs,
  rhs,
  bad = None,
  diff = None,
  plotFileName = None 
)

Plot the comparison of two 2-d NumPy arrays.

NOTE: 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 utils).

Parameters
[in]lhsLHS values to compare; a 2-d NumPy array
[in]rhsRHS values to compare; a 2-d NumPy array
[in]badA 2-d boolean NumPy array of values to emphasize in the plots
[in]diffdifference array; a 2-d NumPy array, or None to show lhs-rhs
[in]plotFileNameFilename to save the plot to. If None, the plot will be displayed in a a window.

Definition at line 475 of file tests.py.

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

Exit with the status code resulting from running the provided test suite.

Definition at line 77 of file tests.py.

77 
78 def run(suite, exit=True):
79  """!Exit with the status code resulting from running the provided test suite"""
80 
81  if unittest.TextTestRunner().run(suite).wasSuccessful():
82  status = 0
83  else:
84  status = 1
85 
86  if exit:
87  sys.exit(status)
88  else:
89  return status
90 
def run
Exit with the status code resulting from running the provided test suite.
Definition: tests.py:77
def lsst.utils.tests.sort_tests (   tests)

Go through the supplied sequence of test suites and sort them to ensure that MemoryTestCases are at the end of the test list.

Returns a combined TestSuite.

Definition at line 91 of file tests.py.

91 
92 def sort_tests(tests):
93  """!Go through the supplied sequence of test suites and sort them to ensure that
94  MemoryTestCases are at the end of the test list. Returns a combined
95  TestSuite."""
96 
97  suite = unittest.TestSuite()
98  memtests = []
99  for test_suite in tests:
100  try:
101  # Just test the first test method in the suite for MemoryTestCase
102  # Use loop rather than next as it is possible for a test class
103  # to not have any test methods and the Python community prefers
104  # for loops over catching a StopIteration exception.
105  bases = None
106  for method in test_suite:
107  bases = inspect.getmro(method.__class__)
108  break
109  if bases is not None and MemoryTestCase in bases:
110  memtests.append(test_suite)
111  else:
112  suite.addTests(test_suite)
113  except TypeError:
114  if isinstance(test_suite, MemoryTestCase):
115  memtests.append(test_suite)
116  else:
117  suite.addTest(test_suite)
118  suite.addTests(memtests)
119  return suite
120 
def sort_tests
Go through the supplied sequence of test suites and sort them to ensure that MemoryTestCases are at t...
Definition: tests.py:91
def lsst.utils.tests.suiteClassWrapper (   tests)

Definition at line 121 of file tests.py.

122 def suiteClassWrapper(tests):
123  return unittest.TestSuite(sort_tests(tests))
124 
125 # Replace the suiteClass callable in the defaultTestLoader
126 # so that we can reorder the test ordering. This will have
127 # no effect if no memory test cases are found.
128 unittest.defaultTestLoader.suiteClass = suiteClassWrapper
129 
130 # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
131 
def sort_tests
Go through the supplied sequence of test suites and sort them to ensure that MemoryTestCases are at t...
Definition: tests.py:91
def suiteClassWrapper
Definition: tests.py:121

Variable Documentation

lsst.utils.tests.dafBase = None

Definition at line 48 of file tests.py.

int lsst.utils.tests.memId0 = 0

Definition at line 53 of file tests.py.

int lsst.utils.tests.nleakPrintMax = 20

Definition at line 54 of file tests.py.

tuple lsst.utils.tests.open_files = set()

Definition at line 57 of file tests.py.

lsst.utils.tests.psutil = None

Definition at line 43 of file tests.py.