10 from __future__
import print_function, division, absolute_import
15 from sys
import version_info
as _swig_python_version_info
16 if _swig_python_version_info >= (2, 7, 0):
17 def swig_import_helper():
19 pkg = __name__.rpartition(
'.')[0]
20 mname =
'.'.join((pkg,
'_IMP_test')).lstrip(
'.')
22 return importlib.import_module(mname)
24 return importlib.import_module(
'_IMP_test')
25 _IMP_test = swig_import_helper()
26 del swig_import_helper
27 elif _swig_python_version_info >= (2, 6, 0):
28 def swig_import_helper():
29 from os.path
import dirname
33 fp, pathname, description = imp.find_module(
'_IMP_test', [dirname(__file__)])
39 _mod = imp.load_module(
'_IMP_test', fp, pathname, description)
43 _IMP_test = swig_import_helper()
44 del swig_import_helper
47 del _swig_python_version_info
49 _swig_property = property
54 import builtins
as __builtin__
58 def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
59 if (name ==
"thisown"):
60 return self.this.own(value)
62 if type(value).__name__ ==
'SwigPyObject':
63 self.__dict__[name] = value
65 method = class_type.__swig_setmethods__.get(name,
None)
67 return method(self, value)
69 object.__setattr__(self, name, value)
71 raise AttributeError(
"You cannot add attributes to %s" % self)
74 def _swig_setattr(self, class_type, name, value):
75 return _swig_setattr_nondynamic(self, class_type, name, value, 0)
78 def _swig_getattr(self, class_type, name):
79 if (name ==
"thisown"):
80 return self.this.own()
81 method = class_type.__swig_getmethods__.get(name,
None)
84 raise AttributeError(
"'%s' object has no attribute '%s'" % (class_type.__name__, name))
89 strthis =
"proxy of " + self.this.__repr__()
90 except __builtin__.Exception:
92 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
95 def _swig_setattr_nondynamic_method(set):
96 def set_attr(self, name, value):
97 if (name ==
"thisown"):
98 return self.this.own(value)
99 if hasattr(self, name)
or (name ==
"this"):
100 set(self, name, value)
102 raise AttributeError(
"You cannot add attributes to %s" % self)
108 weakref_proxy = weakref.proxy
109 except __builtin__.Exception:
110 weakref_proxy =
lambda x: x
113 class IMP_TEST_SwigPyIterator(object):
114 """Proxy of C++ swig::IMP_TEST_SwigPyIterator class."""
116 thisown = _swig_property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
'The membership flag')
118 def __init__(self, *args, **kwargs):
119 raise AttributeError(
"No constructor defined - class is abstract")
120 __repr__ = _swig_repr
121 __swig_destroy__ = _IMP_test.delete_IMP_TEST_SwigPyIterator
122 __del__ =
lambda self:
None
125 """value(IMP_TEST_SwigPyIterator self) -> PyObject *"""
126 return _IMP_test.IMP_TEST_SwigPyIterator_value(self)
131 incr(IMP_TEST_SwigPyIterator self, size_t n=1) -> IMP_TEST_SwigPyIterator
132 incr(IMP_TEST_SwigPyIterator self) -> IMP_TEST_SwigPyIterator
134 return _IMP_test.IMP_TEST_SwigPyIterator_incr(self, n)
139 decr(IMP_TEST_SwigPyIterator self, size_t n=1) -> IMP_TEST_SwigPyIterator
140 decr(IMP_TEST_SwigPyIterator self) -> IMP_TEST_SwigPyIterator
142 return _IMP_test.IMP_TEST_SwigPyIterator_decr(self, n)
145 def distance(self, x):
146 """distance(IMP_TEST_SwigPyIterator self, IMP_TEST_SwigPyIterator x) -> ptrdiff_t"""
147 return _IMP_test.IMP_TEST_SwigPyIterator_distance(self, x)
151 """equal(IMP_TEST_SwigPyIterator self, IMP_TEST_SwigPyIterator x) -> bool"""
152 return _IMP_test.IMP_TEST_SwigPyIterator_equal(self, x)
156 """copy(IMP_TEST_SwigPyIterator self) -> IMP_TEST_SwigPyIterator"""
157 return _IMP_test.IMP_TEST_SwigPyIterator_copy(self)
161 """next(IMP_TEST_SwigPyIterator self) -> PyObject *"""
162 return _IMP_test.IMP_TEST_SwigPyIterator_next(self)
166 """__next__(IMP_TEST_SwigPyIterator self) -> PyObject *"""
167 return _IMP_test.IMP_TEST_SwigPyIterator___next__(self)
171 """previous(IMP_TEST_SwigPyIterator self) -> PyObject *"""
172 return _IMP_test.IMP_TEST_SwigPyIterator_previous(self)
175 def advance(self, n):
176 """advance(IMP_TEST_SwigPyIterator self, ptrdiff_t n) -> IMP_TEST_SwigPyIterator"""
177 return _IMP_test.IMP_TEST_SwigPyIterator_advance(self, n)
181 """__eq__(IMP_TEST_SwigPyIterator self, IMP_TEST_SwigPyIterator x) -> bool"""
182 return _IMP_test.IMP_TEST_SwigPyIterator___eq__(self, x)
186 """__ne__(IMP_TEST_SwigPyIterator self, IMP_TEST_SwigPyIterator x) -> bool"""
187 return _IMP_test.IMP_TEST_SwigPyIterator___ne__(self, x)
190 def __iadd__(self, n):
191 """__iadd__(IMP_TEST_SwigPyIterator self, ptrdiff_t n) -> IMP_TEST_SwigPyIterator"""
192 return _IMP_test.IMP_TEST_SwigPyIterator___iadd__(self, n)
195 def __isub__(self, n):
196 """__isub__(IMP_TEST_SwigPyIterator self, ptrdiff_t n) -> IMP_TEST_SwigPyIterator"""
197 return _IMP_test.IMP_TEST_SwigPyIterator___isub__(self, n)
200 def __add__(self, n):
201 """__add__(IMP_TEST_SwigPyIterator self, ptrdiff_t n) -> IMP_TEST_SwigPyIterator"""
202 return _IMP_test.IMP_TEST_SwigPyIterator___add__(self, n)
205 def __sub__(self, *args):
207 __sub__(IMP_TEST_SwigPyIterator self, ptrdiff_t n) -> IMP_TEST_SwigPyIterator
208 __sub__(IMP_TEST_SwigPyIterator self, IMP_TEST_SwigPyIterator x) -> ptrdiff_t
210 return _IMP_test.IMP_TEST_SwigPyIterator___sub__(self, *args)
214 IMP_TEST_SwigPyIterator_swigregister = _IMP_test.IMP_TEST_SwigPyIterator_swigregister
215 IMP_TEST_SwigPyIterator_swigregister(IMP_TEST_SwigPyIterator)
223 IMP_DEBUG = _IMP_test.IMP_DEBUG
224 IMP_RELEASE = _IMP_test.IMP_RELEASE
225 IMP_SILENT = _IMP_test.IMP_SILENT
226 IMP_PROGRESS = _IMP_test.IMP_PROGRESS
227 IMP_TERSE = _IMP_test.IMP_TERSE
228 IMP_VERBOSE = _IMP_test.IMP_VERBOSE
229 IMP_MEMORY = _IMP_test.IMP_MEMORY
230 IMP_NONE = _IMP_test.IMP_NONE
231 IMP_USAGE = _IMP_test.IMP_USAGE
232 IMP_INTERNAL = _IMP_test.IMP_INTERNAL
233 IMP_KERNEL_HAS_LOG4CXX = _IMP_test.IMP_KERNEL_HAS_LOG4CXX
234 IMP_COMPILER_HAS_AUTO = _IMP_test.IMP_COMPILER_HAS_AUTO
235 IMP_COMPILER_HAS_DEBUG_VECTOR = _IMP_test.IMP_COMPILER_HAS_DEBUG_VECTOR
236 IMP_COMPILER_HAS_UNIQUE_PTR = _IMP_test.IMP_COMPILER_HAS_UNIQUE_PTR
237 IMP_KERNEL_HAS_BOOST_RANDOM = _IMP_test.IMP_KERNEL_HAS_BOOST_RANDOM
238 IMP_KERNEL_HAS_GPERFTOOLS = _IMP_test.IMP_KERNEL_HAS_GPERFTOOLS
239 IMP_KERNEL_HAS_TCMALLOC_HEAPCHECKER = _IMP_test.IMP_KERNEL_HAS_TCMALLOC_HEAPCHECKER
240 IMP_KERNEL_HAS_TCMALLOC_HEAPPROFILER = _IMP_test.IMP_KERNEL_HAS_TCMALLOC_HEAPPROFILER
241 IMPKERNEL_SHOW_WARNINGS = _IMP_test.IMPKERNEL_SHOW_WARNINGS
244 class _DirectorObjects(object):
245 """@internal Simple class to keep references to director objects
246 to prevent premature deletion."""
249 def register(self, obj):
250 """Take a reference to a director object; will only work for
251 refcounted C++ classes"""
252 if hasattr(obj,
'get_ref_count'):
253 self._objects.append(obj)
255 """Only drop our reference and allow cleanup by Python if no other
256 Python references exist (we hold 3 references: one in self._objects,
257 one in x, and one in the argument list for getrefcount) *and* no
258 other C++ references exist (the Python object always holds one)"""
259 objs = [x
for x
in self._objects
if sys.getrefcount(x) > 3 \
260 or x.get_ref_count() > 1]
264 def get_object_count(self):
265 """Get number of director objects (useful for testing only)"""
266 return len(self._objects)
267 _director_objects = _DirectorObjects()
269 class _ostream(object):
270 """Proxy of C++ std::ostream class."""
272 thisown = _swig_property(
lambda x: x.this.own(),
lambda x, v: x.this.own(v), doc=
'The membership flag')
274 def __init__(self, *args, **kwargs):
275 raise AttributeError(
"No constructor defined")
276 __repr__ = _swig_repr
278 def write(self, osa_buf):
279 """write(_ostream self, char const * osa_buf)"""
280 return _IMP_test._ostream_write(self, osa_buf)
282 _ostream_swigregister = _IMP_test._ostream_swigregister
283 _ostream_swigregister(_ostream)
285 IMP_COMPILER_HAS_OVERRIDE = _IMP_test.IMP_COMPILER_HAS_OVERRIDE
286 IMP_COMPILER_HAS_FINAL = _IMP_test.IMP_COMPILER_HAS_FINAL
287 IMP_HAS_NOEXCEPT = _IMP_test.IMP_HAS_NOEXCEPT
288 IMP_C_OPEN_BINARY = _IMP_test.IMP_C_OPEN_BINARY
290 IMP_TEST_HAS_BOOST_FILESYSTEM = _IMP_test.IMP_TEST_HAS_BOOST_FILESYSTEM
291 IMP_TEST_HAS_BOOST_PROGRAMOPTIONS = _IMP_test.IMP_TEST_HAS_BOOST_PROGRAMOPTIONS
292 IMP_TEST_HAS_BOOST_RANDOM = _IMP_test.IMP_TEST_HAS_BOOST_RANDOM
293 IMP_TEST_HAS_BOOST_SYSTEM = _IMP_test.IMP_TEST_HAS_BOOST_SYSTEM
294 IMPTEST_SHOW_WARNINGS = _IMP_test.IMPTEST_SHOW_WARNINGS
297 """@namespace IMP::test
298 @brief Methods and classes for testing the IMP kernel and modules.
312 from .
import _compat_python
313 from ._compat_python
import unittest2
330 def __load_unittest_package():
332 for modname, fromlist
in ((
'unittest', []),
336 u = __import__(modname, {}, {}, fromlist)
337 if hasattr(u,
'skip'):
340 errors.append(
"'%s' does not have the 'skip' decorator" \
342 except ImportError
as e:
343 errors.append(str(e))
345 return _compat_python.unittest2
346 raise ImportError(
"IMP.test requires a newer version of Python's unittest "
347 "package than is available. Either upgrade to a new "
348 "enough Python (at least 2.7 or 3.2) or install the "
349 "unittest2 package. Encountered errors: %s" \
351 unittest = __load_unittest_package()
354 expectedFailure = unittest.expectedFailure
356 skipIf = unittest.skipIf
357 skipUnless = unittest.skipUnless
361 """Simple RAII-style class to run in a temporary directory.
362 When the object is created, the temporary directory is created
363 and becomes the current working directory. When the object goes out
364 of scope, the working directory is reset and the temporary directory
367 self.origdir = os.getcwd()
368 self.tmpdir = tempfile.mkdtemp()
369 os.chdir(self.tmpdir)
371 os.chdir(self.origdir)
372 shutil.rmtree(self.tmpdir, ignore_errors=
True)
374 @contextlib.contextmanager
376 """Simple context manager to run in a temporary directory.
377 While the context manager is active (within the 'with' block)
378 the current working directory is set to a temporary directory.
379 When the context manager exists, the working directory is reset
380 and the temporary directory deleted."""
381 origdir = os.getcwd()
382 tmpdir = tempfile.mkdtemp()
386 shutil.rmtree(tmpdir, ignore_errors=
True)
390 """Simple RAII-style class to make a temporary directory. When the object
391 is created, the temporary directory is created. When the object goes
392 out of scope, the temporary directory is deleted."""
393 def __init__(self, dir=None):
394 self.tmpdir = tempfile.mkdtemp(dir=dir)
396 shutil.rmtree(self.tmpdir, ignore_errors=
True)
398 class _TempDir(object):
399 def __init__(self, dir=None):
400 self.tmpdir = tempfile.mkdtemp(dir=dir)
402 shutil.rmtree(self.tmpdir, ignore_errors=
True)
404 @contextlib.contextmanager
406 """Simple context manager to make a temporary directory.
407 The temporary directory has the same lifetime as the context manager
408 (i.e. it is created at the start of the 'with' block, and deleted
409 at the end of the block).
410 @param dir If given, the temporary directory is made as a subdirectory
411 of that directory, rather than in the default temporary
412 directory location (e.g. /tmp)
413 @return the full path to the temporary directory.
415 tmpdir = tempfile.mkdtemp(dir=dir)
417 shutil.rmtree(tmpdir, ignore_errors=
True)
420 """Calculate the derivative of the single-value function `func` at
421 point `val`. The derivative is calculated using simple finite
422 differences starting with the given `step`; Richardson extrapolation
423 is then used to extrapolate the derivative at step=0."""
428 f1 = func(val + step)
429 f2 = func(val - step)
431 d = [[(f1 - f2) / (2.0 * step)]]
433 for i
in range(1, maxsteps):
434 d.append([0.] * (i + 1))
436 f1 = func(val + step)
437 f2 = func(val - step)
438 d[i][0] = (f1 - f2) / (2.0 * step)
440 for j
in range(1, i + 1):
441 d[i][j] = (d[i][j-1] * fac - d[i-1][j-1]) / (fac - 1.)
443 errt = max(abs(d[i][j] - d[i][j-1]),
444 abs(d[i][j] - d[i-1][j-1]))
448 if abs(d[i][i] - d[i-1][i-1]) >= safe * err:
451 raise ValueError(
"Cannot calculate numerical derivative")
456 """Calculate the x,y and z derivatives of the scoring function `sf`
457 on the `xyz` particle. The derivatives are approximated numerically
458 using the numerical_derivatives() function."""
459 class _XYZDerivativeFunc(object):
460 def __init__(self, sf, xyz, basis_vector):
463 self._basis_vector = basis_vector
464 self._starting_coordinates = xyz.get_coordinates()
466 def __call__(self, val):
467 self._xyz.set_coordinates(self._starting_coordinates + \
468 self._basis_vector * val)
469 return self._sf.evaluate(
False)
473 for x
in ((1,0,0), (0,1,0), (0,0,1))])
477 """Super class for IMP test cases.
478 This provides a number of useful IMP-specific methods on top of
479 the standard Python `unittest.TestCase` class.
480 Test scripts should generally contain a subclass of this class,
481 conventionally called `Tests` (this makes it easier to run an
482 individual test from the commane line) and use IMP::test::main()
483 as their main function."""
485 def __init__(self, *args, **keys):
486 unittest.TestCase.__init__(self, *args, **keys)
487 self._progname = os.path.abspath(sys.argv[0])
495 IMP.random_number_generator.seed(hash(time.time())%2**30)
501 if hasattr(self,
'_tmpdir'):
505 """Get the full name of an input file in the top-level
507 testdir = os.path.dirname(self._progname)
508 if self.__module__ !=
'__main__':
509 testdir = os.path.dirname(sys.modules[self.__module__].__file__)
510 dirs = testdir.split(os.path.sep)
511 for i
in range(len(dirs), 0, -1):
512 input = os.path.sep.join(dirs[:i] + [
'input'])
513 if os.path.isdir(input):
514 ret = os.path.join(input, filename)
515 if not os.path.exists(ret):
516 raise IOError(
"Test input file "+ret+
" does not exist")
518 raise IOError(
"No test input directory found")
521 """Open and return an input file in the top-level test directory."""
525 """Get the full name of an output file in the tmp directory.
526 The directory containing this file will be automatically
527 cleaned up when the test completes."""
528 if not hasattr(self,
'_tmpdir'):
529 self._tmpdir = _TempDir(os.environ[
'IMP_TMP_DIR'])
530 tmpdir = self._tmpdir.tmpdir
531 return os.path.join(tmpdir, filename)
534 """Get the magnitude of a list of floats"""
535 return sum([x*x
for x
in vector], 0)**.5
538 """Assert that the given callable object raises UsageException.
539 This differs from unittest's assertRaises in that the test
540 is skipped in fast mode (where usage checks are turned off)."""
545 """Assert that the given callable object raises InternalException.
546 This differs from unittest's assertRaises in that the test
547 is skipped in fast mode (where internal checks are turned off)."""
552 """Assert that the given callable object is not implemented."""
557 """Assert that x,y,z analytical derivatives match numerical within
558 a tolerance, or a percentage (of the analytical value), whichever
559 is larger. `sf` should be a ScoringFunction or Restraint,
560 although for backwards compatibility a Model is also accepted."""
562 derivs = xyz.get_derivatives()
564 pct = percentage / 100.0
565 self.assertAlmostEqual(self.
get_magnitude(derivs-num_derivs),0,
567 msg=
"Don't match "+str(derivs) + str(num_derivs))
568 self.assertAlmostEqual(derivs[0], num_derivs[0],
569 delta=max(tolerance, abs(derivs[0]) * pct))
570 self.assertAlmostEqual(derivs[1], num_derivs[1],
571 delta=max(tolerance, abs(derivs[1]) * pct))
572 self.assertAlmostEqual(derivs[2], num_derivs[2],
573 delta=max(tolerance, abs(derivs[2]) * pct))
576 """Make a particle with optimizable x, y and z attributes, and
577 add it to the model."""
585 """Help handle a test which is expected to fail some fraction of
586 the time. The test is run multiple times and an exception
587 is thrown only if it fails too many times.
588 @note Use of this function should be avoided. If there is a corner
589 case that results in a test 'occasionally' failing, write a
590 new test specifically for that corner case and assert that
591 it fails consistently (and remove the corner case from the
594 prob=chance_of_failure
598 prob= prob*chance_of_failure
599 for i
in range(0, tries):
607 raise AssertError(
"Too many failures")
610 """Estimate how likely a given block of code is to raise an
614 while failures < 10
and tries <1000:
620 return failures/tries
623 """Randomize the xyz coordinates of a list of particles"""
629 p.set_value(xkey, random.uniform(-deviation, deviation))
630 p.set_value(ykey, random.uniform(-deviation, deviation))
631 p.set_value(zkey, random.uniform(-deviation, deviation))
634 """Return distance between two given particles"""
638 dx = p1.get_value(xkey) - p2.get_value(xkey)
639 dy = p1.get_value(ykey) - p2.get_value(ykey)
640 dz = p1.get_value(zkey) - p2.get_value(zkey)
641 return math.sqrt(dx*dx + dy*dy + dz*dz)
644 """Check the unary function func's derivatives against numerical
645 approximations between lb and ub"""
646 for f
in [lb + i * step
for i
in range(1, int((ub-lb)/step))]:
647 (v,d)= func.evaluate_with_derivative(f)
649 self.assertAlmostEqual(d, da, delta=max(abs(.1 *d), 0.01))
652 """Make sure that the minimum of the unary function func over the
653 range between lb and ub is at expected_fmin"""
654 fmin, vmin = lb, func.evaluate(lb)
655 for f
in [lb + i * step
for i
in range(1, int((ub-lb)/step))]:
659 self.assertAlmostEqual(fmin, expected_fmin, delta=step)
662 """Check methods that every IMP::Object class should have"""
663 obj.set_was_used(
True)
666 self.assertIsNotNone(cls.get_from(obj))
667 self.assertRaises(ValueError, cls.get_from,
IMP.Model())
669 self.assertIsInstance(str(obj), str)
670 self.assertIsInstance(repr(obj), str)
672 verinf = obj.get_version_info()
681 """Create a bunch of particles in a box"""
686 for i
in range(0,num):
691 def _get_type(self, module, name):
692 return eval(
'type('+module+
"."+name+
')')
694 "Check that all the C++ classes in the module are values or objects."
696 ok = set(exceptions_list + module._value_types + module._object_types + module._raii_types + module._plural_types)
700 if self._get_type(module.__name__, name)==type
and not name.startswith(
"_"):
701 if name.find(
"SwigPyIterator") != -1:
704 if not eval(
'hasattr(%s.%s, "__swig_destroy__")' \
705 % (module.__name__, name)):
710 message=
"All IMP classes should be labeled as values or objects to get memory management correct in Python. The following are not:\n%s\nPlease add an IMP_SWIG_OBJECT or IMP_SWIG_VALUE call to the Python wrapper, or if the class has a good reason to be neither, add the name to the value_object_exceptions list in the IMPModuleTest call." \
712 self.assertEqual(len(bad), 0, message)
713 for e
in exceptions_list:
714 self.assertTrue(e
not in module._value_types
715 + module._object_types
717 + module._plural_types,
718 "Value/Object exception "+e+
" is not an exception")
720 def _check_spelling(self, word, words):
721 """Check that the word is spelled correctly"""
722 if "words" not in dir(self):
724 wordlist= fh.read().split("\n")
726 custom_words=[
"info",
"prechange",
"int",
"ints",
"optimizeds",
"graphviz",
727 "voxel",
"voxels",
"endian",
'rna',
'dna',
728 "xyzr",
"pdbs",
"fft",
"ccc",
"gaussian"]
731 exclude_words = set([
"adapter",
"grey"])
732 self.words=set(wordlist+custom_words) - exclude_words
734 for i
in "0123456789":
739 if word
in self.words:
746 """Check that all the classes in the module follow the IMP
747 naming conventions."""
751 cc=re.compile(
"([A-Z][a-z]*)")
753 if self._get_type(module.__name__, name)==type
and not name.startswith(
"_"):
754 if name.find(
"SwigPyIterator") != -1:
756 for t
in re.findall(cc, name):
757 if not self._check_spelling(t.lower(), words):
758 misspelled.append(t.lower())
761 self.assertEqual(len(bad), 0,
762 "All IMP classes should be properly spelled. The following are not: %s.\nMisspelled words: %s. Add words to the spelling_exceptions variable of the IMPModuleTest if needed." \
763 % (str(bad),
", ".join(set(misspelled))))
766 if self._get_type(module.__name__, name)==type
and not name.startswith(
"_"):
767 if name.find(
"SwigPyIterator") != -1:
769 if name.find(
'_') != -1:
771 if name.lower== name:
773 for t
in re.findall(cc, name):
774 if not self._check_spelling(t.lower(), words):
775 print(
"misspelled %s in %s" % (t, name))
777 message=
"All IMP classes should have CamelCase names. The following do not: %s." \
779 self.assertEqual(len(bad), 0, message)
781 def _check_function_name(self, prefix, name, verbs, all, exceptions, words,
784 fullname=prefix+
"."+name
787 old_exceptions=[
'unprotected_evaluate',
"unprotected_evaluate_if_good",
788 "unprotected_evaluate_if_below",
789 "after_evaluate",
"before_evaluate",
"has_attribute",
790 "decorate_particle",
"particle_is_instance"]
791 if name
in old_exceptions:
794 if fullname
in exceptions:
796 if name.endswith(
"swigregister"):
798 if name.lower() != name:
799 if name[0].lower() != name[0]
and name.split(
'_')[0]
in all:
804 tokens= name.split(
"_")
805 if tokens[0]
not in verbs:
808 if not self._check_spelling(t, words):
810 print(
"misspelled %s in %s" % (t, name))
814 def _static_method(self, module, prefix, name):
815 """For static methods of the form Foo.bar SWIG creates free functions
816 named Foo_bar. Exclude these from spelling checks since the method
817 Foo.bar has already been checked."""
818 if prefix
is None and '_' in name:
819 modobj = eval(module)
820 cls, meth = name.split(
'_', 1)
821 if hasattr(modobj, cls):
822 clsobj = eval(module +
'.' + cls)
823 if hasattr(clsobj, meth):
826 def _check_function_names(self, module, prefix, names, verbs, all,
827 exceptions, words, misspelled):
830 typ = self._get_type(module, name)
831 if name.startswith(
"_")
or name ==
"weakref_proxy":
833 if typ
in (types.BuiltinMethodType, types.MethodType) \
834 or (typ == types.FunctionType
and \
835 not self._static_method(module, prefix, name)):
836 bad.extend(self._check_function_name(prefix, name, verbs, all,
839 if typ == type
and "SwigPyIterator" not in name:
840 members=eval(
"dir("+module+
"."+name+
")")
841 bad.extend(self._check_function_names(module+
"."+name,
842 name, members, verbs, [],
848 """Check that all the functions in the module follow the IMP
849 naming conventions."""
851 verbs=set([
"add",
"remove",
"get",
"set",
"evaluate",
"compute",
"show",
"create",
"destroy",
852 "push",
"pop",
"write",
"read",
"do",
"show",
"load",
"save",
"reset",
854 "clear",
"handle",
"update",
"apply",
"optimize",
"reserve",
"dump",
855 "propose",
"setup",
"teardown",
"visit",
"find",
"run",
"swap",
"link",
858 bad=self._check_function_names(module.__name__,
None, all, verbs, all, exceptions, words, misspelled)
859 message=
"All IMP methods and functions should have lower case names separated by underscores and beginning with a verb, preferably one of ['add', 'remove', 'get', 'set', 'create', 'destroy']. Each of the words should be a properly spelled English word. The following do not (given our limited list of verbs that we check for):\n%(bad)s\nIf there is a good reason for them not to (eg it does start with a verb, just one with a meaning that is not covered by the normal list), add them to the function_name_exceptions variable in the standards_exceptions file. Otherwise, please fix. The current verb list is %(verbs)s" \
860 % {
"bad":
"\n".join(bad),
"verbs":verbs}
861 if len(misspelled) > 0:
862 message +=
"\nMisspelled words: " +
", ".join(set(misspelled)) \
863 +
". Add words to the spelling_exceptions variable " \
864 +
"of the standards_exceptions file if needed."
865 self.assertEqual(len(bad), 0, message)
869 """Check that all the classes in modulename have a show method"""
877 if not eval(
'hasattr(%s.%s, "__swig_destroy__")' \
878 % (modulename.__name__, f)):
880 if self._get_type(modulename.__name__, f) == type \
881 and not f.startswith(
"_") \
882 and not f.endswith(
"_swigregister")\
883 and f
not in exceptions\
884 and not f.endswith(
"Temp")
and not f.endswith(
"Iterator")\
885 and not f.endswith(
"Exception")
and\
886 f
not in modulename._raii_types
and \
887 f
not in modulename._plural_types:
888 if not hasattr(getattr(modulename, f),
'show'):
890 message=
"All IMP classes should support show and __str__. The following do not:\n%s\n If there is a good reason for them not to, add them to the show_exceptions variable in the IMPModuleTest call. Otherwise, please fix." \
891 %
"\n".join(not_found)
892 self.assertEqual(len(not_found), 0, message)
894 self.assertIn(e, all,
"Show exception "+e+
" is not a class in module")
895 self.assertTrue(
not hasattr(getattr(modulename, e),
'show'),
896 "Exception "+e+
" is not really a show exception")
899 """Run the named example script.
900 @return a dictionary of all the script's global variables.
901 This can be queried in a test case to make sure
902 the example performed correctly."""
907 path, name = os.path.split(filename)
908 oldsyspath = sys.path[:]
909 olssysargv= sys.argv[:]
910 sys.path.insert(0, path)
915 exec(open(filename).read(), vars)
918 except SystemExit
as e:
919 if e.code != 0
and e.code
is not None:
920 raise _FatalError(
"Example exit with code %s" % str(e.code))
924 sys.path = oldsyspath
927 return _ExecDictProxy(vars)
930 """Run a Python module as if with "python -m <modname>",
931 with the given list of arguments as sys.argv.
933 If module is an already-imported Python module, run its 'main'
934 function and return the result.
936 If module is a string, run the module in a subprocess and return
937 a subprocess.Popen-like object containing the child stdin,
940 if type(module) == type(os):
943 mod = __import__(module, {}, {}, [
''])
944 modpath = mod.__file__
945 if modpath.endswith(
'.pyc'):
946 modpath = modpath[:-1]
947 if type(module) == type(os):
948 old_sys_argv = sys.argv
950 IMP.OptionParser._use_boost_parser =
False
952 sys.argv = [modpath] + args
955 IMP.OptionParser._use_boost_parser =
True
956 sys.argv = old_sys_argv
958 return _SubprocessWrapper(sys.executable, [modpath] + args)
961 """Check a Python module designed to be runnable with 'python -m'
962 to make sure it supports standard command line options."""
965 out, err = r.communicate()
966 self.assertEqual(r.returncode, 0)
967 self.assertNotEqual(err,
"")
968 self.assertEqual(out,
"")
971 class _ExecDictProxy(object):
972 """exec returns a Python dictionary, which contains IMP objects, other
973 Python objects, as well as base Python modules (such as sys and
974 __builtins__). If we just delete this dictionary, it is entirely
975 possible that base Python modules are removed from the dictionary
976 *before* some IMP objects. This will prevent the IMP objects' Python
977 destructors from running properly, so C++ objects will not be
978 cleaned up. This class proxies the base dict class, and on deletion
979 attempts to remove keys from the dictionary in an order that allows
980 IMP destructors to fire."""
981 def __init__(self, d):
985 module_type = type(IMP)
988 if type(d[k]) != module_type:
991 for meth
in [
'__contains__',
'__getitem__',
'__iter__',
'__len__',
992 'get',
'has_key',
'items',
'keys',
'values']:
993 exec(
"def %s(self, *args, **keys): "
994 "return self._d.%s(*args, **keys)" % (meth, meth))
997 class _TestResult(unittest.TextTestResult):
999 def __init__(self, stream=None, descriptions=None, verbosity=None):
1000 super(_TestResult, self).__init__(stream, descriptions, verbosity)
1003 def stopTestRun(self):
1004 if 'IMP_TEST_DETAIL_DIR' in os.environ:
1005 fname = os.path.join(os.environ[
'IMP_TEST_DETAIL_DIR'],
1006 os.path.basename(sys.argv[0]))
1007 with open(fname,
'wb')
as fh:
1008 pickle.dump(self.all_tests, fh, -1)
1009 super(_TestResult, self).stopTestRun()
1011 def startTest(self, test):
1012 super(_TestResult, self).startTest(test)
1013 test.start_time=datetime.datetime.now()
1015 def _test_finished(self, test, state, detail=None):
1016 delta = datetime.datetime.now() - test.start_time
1018 pv= delta.total_seconds()
1019 except AttributeError:
1020 pv = (float(delta.microseconds) \
1021 + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6
1023 self.stream.write(
"in %.3fs ... " % pv)
1024 if detail
is not None and not isinstance(detail, str):
1025 detail = self._exc_info_to_string(detail, test)
1026 test_doc = self.getDescription(test)
1027 test_name = test.id()
1028 if test_name.startswith(
'__main__.'):
1029 test_name = test_name[9:]
1030 self.all_tests.append({
'name': test_name,
1031 'docstring': test_doc,
1032 'time': pv,
'state': state,
'detail': detail})
1034 def addSuccess(self, test):
1035 self._test_finished(test,
'OK')
1036 super(_TestResult, self).addSuccess(test)
1038 def addError(self, test, err):
1039 self._test_finished(test,
'ERROR', err)
1040 super(_TestResult, self).addError(test, err)
1042 def addFailure(self, test, err):
1043 self._test_finished(test,
'FAIL', err)
1044 super(_TestResult, self).addFailure(test, err)
1046 def addSkip(self, test, reason):
1047 self._test_finished(test,
'SKIP', reason)
1048 super(_TestResult, self).addSkip(test, reason)
1050 def addExpectedFailure(self, test, err):
1051 self._test_finished(test,
'EXPFAIL', err)
1052 super(_TestResult, self).addExpectedFailure(test, err)
1054 def addUnexpectedSuccess(self, test):
1055 self._test_finished(test,
'UNEXPSUC')
1056 super(_TestResult, self).addUnexpectedSuccess(test)
1058 def getDescription(self, test):
1059 doc_first_line = test.shortDescription()
1060 if self.descriptions
and doc_first_line:
1061 return doc_first_line
1066 class _TestRunner(unittest.TextTestRunner):
1067 def _makeResult(self):
1068 return _TestResult(self.stream, self.descriptions, self.verbosity)
1072 """Run a set of tests; similar to unittest.main().
1073 Obviates the need to separately import the 'unittest' module, and
1074 ensures that main() is from the same unittest module that the
1075 IMP.test testcases are. In addition, turns on some extra checks
1076 (e.g. trying to use deprecated code will cause an exception
1080 return unittest.main(testRunner=_TestRunner, *args, **keys)
1083 class _SubprocessWrapper(subprocess.Popen):
1084 def __init__(self, app, args):
1087 if sys.platform ==
'win32' and app != sys.executable:
1089 libdir = os.environ[
'PYTHONPATH'].split(
';')[0]
1090 env = os.environ.copy()
1091 env[
'PATH'] +=
';' + libdir
1094 subprocess.Popen.__init__(self, [app]+list(args),
1095 stdin=subprocess.PIPE,
1096 stdout=subprocess.PIPE,
1097 stderr=subprocess.PIPE, env=env,
1098 universal_newlines=
True)
1102 """Super class for simple IMP application test cases"""
1103 def _get_application_file_name(self, filename):
1106 if sys.platform ==
'win32':
1114 """Run an application with the given list of arguments.
1115 @return a subprocess.Popen-like object containing the child stdin,
1118 filename = self._get_application_file_name(app)
1119 if sys.platform ==
'win32':
1121 return _SubprocessWrapper(os.path.join(os.environ[
'IMP_BIN_DIR'],
1124 return _SubprocessWrapper(filename, args)
1127 """Run a Python application with the given list of arguments.
1128 The Python application should be self-runnable (i.e. it should
1129 be executable and with a #! on the first line).
1130 @return a subprocess.Popen-like object containing the child stdin,
1134 if sys.executable !=
'/usr/bin/python' and 'IMP_BIN_DIR' in os.environ:
1135 return _SubprocessWrapper(sys.executable,
1136 [os.path.join(os.environ[
'IMP_BIN_DIR'], app)] + args)
1138 return _SubprocessWrapper(app, args)
1141 """Import an installed Python application, rather than running it.
1142 This is useful to directly test components of the application.
1143 @return the Python module object."""
1145 import importlib.machinery
1149 name = os.path.splitext(app)[0]
1150 pathname = os.path.join(os.environ[
'IMP_BIN_DIR'], app)
1152 return importlib.machinery.SourceFileLoader(name,
1153 pathname).load_module()
1155 return imp.load_source(name, pathname)
1158 """Run an application with the given list of arguments.
1159 @return a subprocess.Popen-like object containing the child stdin,
1162 return _SubprocessWrapper(sys.executable, [app]+args)
1165 """Assert that the application exited cleanly (return value = 0)."""
1167 raise OSError(
"Application exited with signal %d\n" % -ret\
1170 self.assertEqual(ret, 0,
1171 "Application exited uncleanly, with exit code %d\n" % ret\
1175 """Read and return a set of shell commands from a doxygen file.
1176 Each command is assumed to be in a \code{.sh}...\endcode block.
1177 The doxygen file is specified relative to the test file itself.
1178 This is used to make sure the commands shown in an application
1179 example actually work (the testcase can also check the resulting
1180 files for correctness)."""
1181 def win32_normpath(p):
1184 return " ".join([os.path.normpath(x)
for x
in p.split()])
1185 def fix_win32_command(cmd):
1187 if cmd.startswith(
'cp -r '):
1188 return 'xcopy /E ' + win32_normpath(cmd[6:])
1189 elif cmd.startswith(
'cp '):
1190 return 'copy ' + win32_normpath(cmd[3:])
1193 d = os.path.dirname(sys.argv[0])
1194 doc = os.path.join(d, doxfile)
1198 with open(doc)
as fh:
1199 for line
in fh.readlines():
1200 if '\code{.sh}' in line:
1202 elif '\endcode' in line:
1205 cmds.append(line.rstrip(
'\r\n').replace(
1206 '<imp_example_path>', example_path))
1207 if sys.platform ==
'win32':
1208 cmds = [fix_win32_command(x)
for x
in cmds]
1212 "Print and run a shell command, as returned by read_shell_commands()"
1215 p = subprocess.call(cmd, shell=
True)
1217 raise OSError(
"%s failed with exit value %d" % (cmd, p))
1221 """Check to make sure the number of C++ object references is as expected"""
1223 def __init__(self, testcase):
1227 IMP._director_objects.cleanup()
1228 self.__testcase = testcase
1230 self.__basenum = IMP.Object.get_number_of_live_objects()
1234 "Make sure that the number of references matches the expected value."
1236 IMP._director_objects.cleanup()
1239 newnum=IMP.Object.get_number_of_live_objects()-self.__basenum
1240 t.assertEqual(newnum, expected,
1241 "Number of objects don't match: "\
1243 +
" != "+ str(expected) +
" found "+\
1249 """Check to make sure the number of director references is as expected"""
1251 def __init__(self, testcase):
1252 IMP._director_objects.cleanup()
1253 self.__testcase = testcase
1254 self.__basenum = IMP._director_objects.get_object_count()
1257 """Make sure that the number of references matches the expected value.
1258 If force_cleanup is set, clean up any unused references first before
1259 doing the assertion.
1263 IMP._director_objects.cleanup()
1264 t.assertEqual(IMP._director_objects.get_object_count() \
1265 - self.__basenum, expected)
1273 if sys.platform ==
'win32' and 'PYTHONPATH' in os.environ \
1274 and 'IMP_BIN_DIR' in os.environ:
1275 libdir = os.environ[
'PYTHONPATH'].split(
';')[0]
1276 bindir = os.environ[
'IMP_BIN_DIR']
1277 path = os.environ[
'PATH']
1278 if libdir
not in path
or bindir
not in path:
1279 os.environ[
'PATH'] = bindir +
';' + libdir +
';' + path
1282 def get_module_version():
1283 """get_module_version() -> std::string const"""
1284 return _IMP_test.get_module_version()
1287 """get_example_path(std::string fname) -> std::string"""
1288 return _IMP_test.get_example_path(fname)
1291 """get_data_path(std::string fname) -> std::string"""
1292 return _IMP_test.get_data_path(fname)
1294 from .
import _version_check
1295 _version_check.check_version(get_module_version())
1296 __version__ = get_module_version()
def run_python_module
Run a Python module as if with "python -m <modname>", with the given list of arguments as sys...
def temporary_working_directory
Simple context manager to run in a temporary directory.
def assertApplicationExitedCleanly
Assert that the application exited cleanly (return value = 0).
CheckLevel get_check_level()
Get the current audit mode.
def import_python_application
Import an installed Python application, rather than running it.
def open_input_file
Open and return an input file in the top-level test directory.
def run_application
Run an application with the given list of arguments.
def randomize_particles
Randomize the xyz coordinates of a list of particles.
A general exception for an internal error in IMP.
def main
Run a set of tests; similar to unittest.main().
An exception for an invalid usage of IMP.
Super class for simple IMP application test cases.
def assertRaisesInternalException
Assert that the given callable object raises InternalException.
std::string get_example_path(std::string file_name)
Return the full path to one of this module's example files.
def assert_number
Make sure that the number of references matches the expected value.
Check to make sure the number of director references is as expected.
def assertShow
Check that all the classes in modulename have a show method.
def run_shell_command
Print and run a shell command, as returned by read_shell_commands()
def assertRaisesUsageException
Assert that the given callable object raises UsageException.
Vector3D get_random_vector_in(const Cylinder3D &c)
Generate a random vector in a cylinder with uniform density.
Class for storing model, its restraints, constraints, and particles.
def run_python_application
Run a Python application with the given list of arguments.
def assert_number
Make sure that the number of references matches the expected value.
Simple RAII-style class to run in a temporary directory.
Strings get_live_object_names()
Return the names of all live objects.
def check_standard_object_methods
Check methods that every IMP::Object class should have.
def particle_distance
Return distance between two given particles.
def check_unary_function_deriv
Check the unary function func's derivatives against numerical approximations between lb and ub...
def get_tmp_file_name
Get the full name of an output file in the tmp directory.
Version and module information for Objects.
def run_example
Run the named example script.
def get_magnitude
Get the magnitude of a list of floats.
void set_deprecation_exceptions(bool tf)
Toggle whether an exception is thrown when a deprecated method is used.
def check_unary_function_min
Make sure that the minimum of the unary function func over the range between lb and ub is at expected...
def probabilistic_check
Help handle a test which is expected to fail some fraction of the time.
def create_particles_in_box
Create a bunch of particles in a box.
def deprecated_object
Python decorator to mark a class as deprecated.
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
def assertNotImplemented
Assert that the given callable object is not implemented.
The general base class for IMP exceptions.
def numerical_derivative
Calculate the derivative of the single-value function func at point val.
std::string get_example_path(std::string file_name)
Return the full path to one of this module's example files.
def xyz_numerical_derivatives
Calculate the x,y and z derivatives of the scoring function sf on the xyz particle.
def failure_probability
Estimate how likely a given block of code is to raise an AssertionError.
def assertClassNames
Check that all the classes in the module follow the IMP naming conventions.
def create_point_particle
Make a particle with optimizable x, y and z attributes, and add it to the model.
Class to handle individual particles of a Model object.
def read_shell_commands
Read and return a set of shell commands from a doxygen file.
std::string get_data_path(std::string file_name)
Return the full path to one of this module's data files.
Check to make sure the number of C++ object references is as expected.
Simple RAII-style class to make a temporary directory.
def assertFunctionNames
Check that all the functions in the module follow the IMP naming conventions.
def assertValueObjects
Check that all the C++ classes in the module are values or objects.
Super class for IMP test cases.
def assertXYZDerivativesInTolerance
Assert that x,y,z analytical derivatives match numerical within a tolerance, or a percentage (of the ...
def temporary_directory
Simple context manager to make a temporary directory.
def run_script
Run an application with the given list of arguments.
def get_input_file_name
Get the full name of an input file in the top-level test directory.
def check_runnable_python_module
Check a Python module designed to be runnable with 'python -m' to make sure it supports standard comm...
void set_check_level(CheckLevel tf)
Control runtime checks in the code.