Source code for schrodinger.test.unittest_utils
import contextlib
from unittest import mock
from schrodinger.Qt import QtCore
[docs]def change_booleaness(obj, truth_value):
    """
    Sets the return value for __bool__ or __nonzero__ depending on whether or
    not you are in Python 2 or Python 3
    :param obj: An object that has the __bool__ or __nonzero__ attribute
    :type obj: objects
    :param truth_value: What __bool__ or __nonzero__ should return
    :type truth_value: bool
    """
    obj.__bool__.return_value = truth_value 
[docs]def wait_until_condition_met(success_cond_func,
                             poll_interval=500,
                             timeout=5 * 60):
    """
    Call `success_cond_func` until it returns True or the time runs out.
    :param success_cond_func: Function to call until it returns True
    :type success_cond_func: callable
    :param poll_interval: How often to check for success (milliseconds)
    :type poll_interval: int
    :param timeout: When to time out (seconds)
    :type timeout: int
    :return: Whether the function timed out
    :rtype: bool
    """
    if poll_interval == 0 or timeout == 0:
        raise ValueError("Interval and timeout must be greater than 0")
    timeout_ms = timeout * 1000
    if timeout_ms <= poll_interval:
        raise ValueError(
            f"The timeout ({timeout}s) must be greater than the poll interval "
            f"({poll_interval}ms)")
    event_loop = QtCore.QEventLoop()
    timed_out = False
    def check_condition():
        if success_cond_func():
            event_loop.exit()
    def do_time_out():
        event_loop.exit()
        nonlocal timed_out
        timed_out = True
    checker = QtCore.QTimer()
    checker.timeout.connect(check_condition)
    QtCore.QTimer.singleShot(timeout_ms, do_time_out)
    checker.start(poll_interval)
    event_loop.exec()
    checker.stop()
    return timed_out 
[docs]class PatchStack(contextlib.ExitStack):
    """
    Context manager for patching multiple paths at once.
    Usage::
        with PatchStack() as stack:
            stack.patch("foo_module", return_value=bar)
    """
[docs]    def patch(self, path, *args, **kwargs):
        """
        Patch the given path. args and kwargs will be passed to mock.patch.
        """
        self.enter_context(mock.patch(path, *args, **kwargs)) 
[docs]    def patchObject(self, obj, attribute, *args, **kwargs):
        """
        Patch an object's attribute. args and kwargs will be passed to
        mock.patch.object.
        """
        self.enter_context(mock.patch.object(obj, attribute, *args, **kwargs))