Exemple #1
0
 def capture_ids(self, ids, args, test_filters=None):
     params.append([self, ids, args, test_filters])
     result = Fixture()
     result.run_tests = lambda:[]
     if list_result is not None:
         result.list_tests = lambda:list(list_result)
     return result
Exemple #2
0
    def __init__(self, name, new_value=None):
        """Create a MonkeyPatch.

        :param name: The fully qualified object name to override.
        :param new_value: A value to set the name to. If set to
            MonkeyPatch.delete the attribute will be deleted.

        During setup the name will be deleted or assigned the requested value,
        and this will be restored in cleanUp.

        When patching methods, the call signature of name should be a subset
        of the parameters which can be used to call new_value.

        For instance.

        >>> class T:
        ...     def method(self, arg1):
        ...         pass
        >>> class N:
        ...     @staticmethod
        ...     def newmethod(arg1):
        ...         pass

        Patching N.newmethod on top of T.method and then calling T().method(1)
        will not work because they do not have compatible call signatures -
        self will be passed to newmethod because the callable (N.newmethod)
        is placed onto T as a regular function. This allows capturing all the
        supplied parameters while still consulting local state in your
        new_value.
        """
        Fixture.__init__(self)
        self.name = name
        self.new_value = new_value
Exemple #3
0
 def setUp(self):
     Fixture.setUp(self)
     path = sys.modules[self.packagename].__path__
     if self.directory in path:
         return
     self.addCleanup(path.remove, self.directory)
     path.append(self.directory)
Exemple #4
0
 def capture_ids(self, ids, args, test_filters=None):
     params.append([self, ids, args, test_filters])
     result = Fixture()
     result.run_tests = lambda: []
     if list_result is not None:
         result.list_tests = lambda: list(list_result)
     return result
Exemple #5
0
 def setUp(self):
     Fixture.setUp(self)
     location, attribute = self.name.rsplit('.', 1)
     # Import, swallowing all errors as any element of location may be
     # a class or some such thing.
     try:
         __import__(location, {}, {})
     except ImportError:
         pass
     components = location.split('.')
     current = __import__(components[0], {}, {})
     for component in components[1:]:
         current = getattr(current, component)
     sentinel = object()
     old_value = getattr(current, attribute, sentinel)
     if self.new_value is self.delete:
         if old_value is not sentinel:
             delattr(current, attribute)
     else:
         setattr(current, attribute, self.new_value)
     if old_value is sentinel:
         self.addCleanup(self._safe_delete, current, attribute)
     else:
         # Python 2's setattr transforms function into instancemethod
         if (sys.version_info[0] == 2
                 and isinstance(current, (type, types.ClassType))
                 and isinstance(old_value, types.FunctionType)):
             old_value = staticmethod(old_value)
         self.addCleanup(setattr, current, attribute, old_value)
 def setUp(self):
     Fixture.setUp(self)
     path = sys.modules[self.packagename].__path__
     if self.directory in path:
         return
     self.addCleanup(path.remove, self.directory)
     path.append(self.directory)
 def setUp(self):
     Fixture.setUp(self)
     location, attribute = self.name.rsplit('.', 1)
     # Import, swallowing all errors as any element of location may be
     # a class or some such thing.
     try:
         __import__(location, {}, {})
     except ImportError:
         pass
     components = location.split('.')
     current = __import__(components[0], {}, {})
     for component in components[1:]:
         current = getattr(current, component)
     sentinel = object()
     old_value = getattr(current, attribute, sentinel)
     if self.new_value is self.delete:
         if old_value is not sentinel:
             delattr(current, attribute)
     else:
         setattr(current, attribute, self.new_value)
     if old_value is sentinel:
         self.addCleanup(self._safe_delete, current, attribute)
     else:
         # Python 2's setattr transforms function into instancemethod
         if (sys.version_info[0] == 2 and
             isinstance(current, (type, types.ClassType)) and
             isinstance(old_value, types.FunctionType)):
                 old_value = staticmethod(old_value)
         self.addCleanup(setattr, current, attribute, old_value)
Exemple #8
0
    def __init__(self, name, new_value=None):
        """Create a MonkeyPatch.

        :param name: The fully qualified object name to override.
        :param new_value: A value to set the name to. If set to
            MonkeyPatch.delete the attribute will be deleted.

        During setup the name will be deleted or assigned the requested value,
        and this will be restored in cleanUp.

        When patching methods, the call signature of name should be a subset
        of the parameters which can be used to call new_value.

        For instance.

        >>> class T:
        ...     def method(self, arg1):
        ...         pass
        >>> class N:
        ...     @staticmethod
        ...     def newmethod(arg1):
        ...         pass

        Patching N.newmethod on top of T.method and then calling T().method(1)
        will not work because they do not have compatible call signatures -
        self will be passed to newmethod because the callable (N.newmethod)
        is placed onto T as a regular function. This allows capturing all the
        supplied parameters while still consulting local state in your
        new_value.
        """
        Fixture.__init__(self)
        self.name = name
        self.new_value = new_value
Exemple #9
0
    def setUp(self):
        Fixture.setUp(self)
        config.push(
            'demo-fixture', '''
[launchpad]
is_demo: true
site_message = This is a demo site mmk. \
<a href="http://example.com">File a bug</a>.
            ''')
        self.addCleanup(lambda: config.pop('demo-fixture'))
    def setUpClass(cls):
        cls.logger = logging.getLogger(__name__)

        empty_conf = tempfile.NamedTemporaryFile(delete=True)
        cls.beaver_config = BeaverConfig(mock.Mock(config=empty_conf.name))

        output_file = Fixture.download_official_distribution()
        Fixture.extract_distribution(output_file)
        cls.zk = ZookeeperFixture.instance()
        cls.server = KafkaFixture.instance(0, cls.zk.host, cls.zk.port)
    def setUpClass(cls):
        cls.logger = logging.getLogger(__name__)

        empty_conf = tempfile.NamedTemporaryFile(delete=True)
        cls.beaver_config = BeaverConfig(mock.Mock(config=empty_conf.name))

        output_file = Fixture.download_official_distribution()
        Fixture.extract_distribution(output_file)
        cls.zk = ZookeeperFixture.instance()
        cls.server = KafkaFixture.instance(0, cls.zk.host, cls.zk.port)
Exemple #12
0
    def setUpClass(cls):
        cls.logger = logging.getLogger(__name__)

        empty_conf = tempfile.NamedTemporaryFile(delete=True)
        cls.beaver_config = BeaverConfig(mock.Mock(config=empty_conf.name))
        cls.beaver_config.set('transport', 'kinesis')
        cls.beaver_config.set('logstash_version', 1)

        output_file = Fixture.download_official_distribution()
        Fixture.extract_distribution(output_file)
    def setUpClass(cls):
        cls.logger = logging.getLogger(__name__)

        empty_conf = tempfile.NamedTemporaryFile(delete=True)
        cls.beaver_config = BeaverConfig(mock.Mock(config=empty_conf.name))
        cls.beaver_config.set('transport', 'kinesis')
        cls.beaver_config.set('logstash_version', 1)

        output_file = Fixture.download_official_distribution()
        Fixture.extract_distribution(output_file)
Exemple #14
0
    def __init__(self, config_fixture):
        """Initialize the LibrarianServerFixture.

        :param config_fixture: The ConfigFixture in use by our tests.
                               In the layered environment, this is
                               BaseLayer.config_fixture.
        """
        Fixture.__init__(self)
        self._pid = None
        # Track whether the fixture has been setup or not.
        self._setup = False
        self.config_fixture = config_fixture
Exemple #15
0
    def setUp(self):
        Fixture.setUp(self)
        config.push(
            "demo-fixture",
            """
[launchpad]
is_demo: true
site_message = This is a demo site mmk. \
<a href="http://example.com">File a bug</a>.
            """,
        )
        self.addCleanup(lambda: config.pop("demo-fixture"))
Exemple #16
0
    def __init__(self, name, new_value=None):
        """Create a MonkeyPatch.

        :param name: The fully qualified object name to override.
        :param new_value: A value to set the name to. If set to
            MonkeyPatch.delete the attribute will be deleted.

        During setup the name will be deleted or assigned the requested value,
        and this will be restored in cleanUp.
        """
        Fixture.__init__(self)
        self.name = name
        self.new_value = new_value
Exemple #17
0
    def __init__(self, name, new_value=None):
        """Create a MonkeyPatch.

        :param name: The fully qualified object name to override.
        :param new_value: A value to set the name to. If set to
            MonkeyPatch.delete the attribute will be deleted.

        During setup the name will be deleted or assigned the requested value,
        and this will be restored in cleanUp.
        """
        Fixture.__init__(self)
        self.name = name
        self.new_value = new_value
Exemple #18
0
    def setUp(self):
        Fixture.setUp(self)

        self.tree = self.testcase.make_branch_and_tree('.')

        self.filecontents = ('some\nmultiline\ndata\n'
                             'with<htmlspecialchars\n')
        filenames = ['myfilename', 'anotherfile<']
        self.testcase.build_tree_contents(
            (filename, self.filecontents) for filename in filenames)
        for filename in filenames:
            self.tree.add(filename, '%s-id' % filename)
        self.fileid = self.tree.path2id('myfilename')
        self.msg = 'a very exciting commit message <'
        self.revid = self.tree.commit(message=self.msg)
Exemple #19
0
    def setUp(self):
        """Fixture API: install as the librarian."""
        Fixture.setUp(self)
        self.aliases = {}
        self.download_url = config.librarian.download_url
        transaction.manager.registerSynch(self)
        self.addCleanup(transaction.manager.unregisterSynch, self)

        site_manager = zope.component.getGlobalSiteManager()
        for utility in self.provided_utilities:
            original = zope.component.getUtility(utility)
            if site_manager.unregisterUtility(original, utility):
                # We really disabled a utility, restore it later.
                self.addCleanup(
                    zope.component.provideUtility, original, utility)
            zope.component.provideUtility(self, utility)
            self.addCleanup(site_manager.unregisterUtility, self, utility)
 def setUp(self):
     Fixture.setUp(self)
     self.base = self.useFixture(TempDir()).path
     base = self.base
     root = os.path.join(base, self.packagename)
     os.mkdir(root)
     init_seen = not self.init
     for modulename, contents in self.modulelist:
         stream = open(os.path.join(root, modulename), 'wb')
         try:
             stream.write(contents)
         finally:
             stream.close()
         if modulename == '__init__.py':
             init_seen = True
     if not init_seen:
         open(os.path.join(root, '__init__.py'), 'wb').close()
Exemple #21
0
 def setUp(self):
     Fixture.setUp(self)
     self.base = self.useFixture(TempDir()).path
     base = self.base
     root = os.path.join(base, self.packagename)
     os.mkdir(root)
     init_seen = not self.init
     for modulename, contents in self.modulelist:
         stream = open(os.path.join(root, modulename), 'wb')
         try:
             stream.write(contents)
         finally:
             stream.close()
         if modulename == '__init__.py':
             init_seen = True
     if not init_seen:
         open(os.path.join(root, '__init__.py'), 'wb').close()
Exemple #22
0
    def setUp(self):
        """Fixture API: install as the librarian."""
        Fixture.setUp(self)
        self.aliases = {}
        self.download_url = config.librarian.download_url
        transaction.manager.registerSynch(self)
        self.addCleanup(transaction.manager.unregisterSynch, self)

        site_manager = zope.component.getGlobalSiteManager()
        for utility in self.provided_utilities:
            original = zope.component.getUtility(utility)
            if site_manager.unregisterUtility(original, utility):
                # We really disabled a utility, restore it later.
                self.addCleanup(zope.component.provideUtility, original,
                                utility)
            zope.component.provideUtility(self, utility)
            self.addCleanup(site_manager.unregisterUtility, self, utility)
Exemple #23
0
    def run(self, timeout, function, *args, **kwargs):
        """Run 'function' in a reactor.

        If 'function' returns a Deferred, the reactor will keep spinning until
        the Deferred fires and its chain completes or until the timeout is
        reached -- whichever comes first.

        :raise TimeoutError: If 'timeout' is reached before the Deferred
            returned by 'function' has completed its callback chain.
        :raise NoResultError: If the reactor is somehow interrupted before
            the Deferred returned by 'function' has completed its callback
            chain.
        :raise StaleJunkError: If there's junk in the spinner from a previous
            run.
        :return: Whatever is at the end of the function's callback chain.  If
            it's an error, then raise that.
        """
        if self._debug:
            debug_settings = DebugTwisted(True)
        else:
            debug_settings = Fixture()

        with debug_settings:
            junk = self.get_junk()
            if junk:
                raise StaleJunkError(junk)
            self._save_signals()
            self._timeout_call = self._reactor.callLater(
                timeout, self._timed_out, function, timeout)
            # Calling 'stop' on the reactor will make it impossible to
            # re-start the reactor.  Since the default signal handlers for
            # TERM, BREAK and INT all call reactor.stop(), we'll patch it over
            # with crash.  XXX: It might be a better idea to either install
            # custom signal handlers or to override the methods that are
            # Twisted's signal handlers.
            real_stop, self._reactor.stop = self._reactor.stop, self._fake_stop

            def run_function():
                d = defer.maybeDeferred(function, *args, **kwargs)
                d.addCallbacks(self._got_success, self._got_failure)
                d.addBoth(self._stop_reactor)

            try:
                self._reactor.callWhenRunning(run_function)
                self._spinning = True
                self._reactor.run()
            finally:
                self._reactor.stop = real_stop
                self._restore_signals()
            try:
                return self._get_result()
            finally:
                self._clean()
    def setUp(cls):
        # Fixture to hold other fixtures.
        cls._fixture = Fixture()
        cls._fixture.setUp()

        cls.pgbouncer_fixture = PGBouncerFixture()
        # Install the PGBouncer fixture so we shut it down to
        # create database outages.
        cls._fixture.useFixture(cls.pgbouncer_fixture)

        # Bring up the Librarian, which will be connecting via
        # pgbouncer.
        cls.librarian_fixture = LibrarianServerFixture(
            BaseLayer.config_fixture)
        cls._fixture.useFixture(cls.librarian_fixture)
Exemple #25
0
 def setUp(self):
     Fixture.setUp(self)
     webapp.adapter.set_request_started(time.time())
     self.timeline = get_request_timeline(get_current_browser_request())
     self.addCleanup(webapp.adapter.clear_request_started)
Exemple #26
0
 def setUp(self):
     Fixture.setUp(self)
     if self.directory in sys.path:
         return
     self.addCleanup(sys.path.remove, self.directory)
     sys.path.append(self.directory)
Exemple #27
0
 def setUp(self):
     Fixture.setUp(self)
     webapp.adapter.set_request_started(time.time())
     self.timeline = get_request_timeline(get_current_browser_request())
     self.addCleanup(webapp.adapter.clear_request_started)
 def __init__(self, root):
     Fixture.__init__(self)
     self.root = root
Exemple #29
0
 def setUp(self):
     Fixture.setUp(self)
     if self.directory in sys.path:
         return
     self.addCleanup(sys.path.remove, self.directory)
     sys.path.append(self.directory)