diff options
Diffstat (limited to 'lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit')
146 files changed, 0 insertions, 39344 deletions
diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/__init__.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/__init__.py +++ /dev/null diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_base.py deleted file mode 100644 index 250115aa..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_base.py +++ /dev/null @@ -1,228 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import config, locks -from buildbot.buildslave import base -from buildbot.test.fake import fakemaster, pbmanager -from buildbot.test.fake.botmaster import FakeBotMaster - -class TestAbstractBuildSlave(unittest.TestCase): - - class ConcreteBuildSlave(base.AbstractBuildSlave): - pass - - def test_constructor_minimal(self): - bs = self.ConcreteBuildSlave('bot', 'pass') - self.assertEqual(bs.slavename, 'bot') - self.assertEqual(bs.password, 'pass') - self.assertEqual(bs.max_builds, None) - self.assertEqual(bs.notify_on_missing, []) - self.assertEqual(bs.missing_timeout, 3600) - self.assertEqual(bs.properties.getProperty('slavename'), 'bot') - self.assertEqual(bs.access, []) - self.assertEqual(bs.keepalive_interval, 3600) - - def test_constructor_full(self): - lock1, lock2 = mock.Mock(name='lock1'), mock.Mock(name='lock2') - bs = self.ConcreteBuildSlave('bot', 'pass', - max_builds=2, - notify_on_missing=['me@me.com'], - missing_timeout=120, - properties={'a':'b'}, - locks=[lock1, lock2], - keepalive_interval=60) - self.assertEqual(bs.max_builds, 2) - self.assertEqual(bs.notify_on_missing, ['me@me.com']) - self.assertEqual(bs.missing_timeout, 120) - self.assertEqual(bs.properties.getProperty('a'), 'b') - self.assertEqual(bs.access, [lock1, lock2]) - self.assertEqual(bs.keepalive_interval, 60) - - def test_constructor_notify_on_missing_not_list(self): - bs = self.ConcreteBuildSlave('bot', 'pass', - notify_on_missing='foo@foo.com') - # turned into a list: - self.assertEqual(bs.notify_on_missing, ['foo@foo.com']) - - def test_constructor_notify_on_missing_not_string(self): - self.assertRaises(config.ConfigErrors, lambda : - self.ConcreteBuildSlave('bot', 'pass', - notify_on_missing=['a@b.com', 13])) - - @defer.inlineCallbacks - def do_test_reconfigService(self, old, old_port, new, new_port): - master = self.master = fakemaster.make_master() - old.master = master - if old_port: - self.old_registration = old.registration = \ - pbmanager.FakeRegistration(master.pbmanager, old_port, old.slavename) - old.registered_port = old_port - old.missing_timer = mock.Mock(name='missing_timer') - old.startService() - - new_config = mock.Mock() - new_config.slavePortnum = new_port - new_config.slaves = [ new ] - - yield old.reconfigService(new_config) - - @defer.inlineCallbacks - def test_reconfigService_attrs(self): - old = self.ConcreteBuildSlave('bot', 'pass', - max_builds=2, - notify_on_missing=['me@me.com'], - missing_timeout=120, - properties={'a':'b'}, - keepalive_interval=60) - new = self.ConcreteBuildSlave('bot', 'pass', - max_builds=3, - notify_on_missing=['her@me.com'], - missing_timeout=121, - properties={'a':'c'}, - keepalive_interval=61) - - old.updateSlave = mock.Mock(side_effect=lambda : defer.succeed(None)) - - yield self.do_test_reconfigService(old, 'tcp:1234', new, 'tcp:1234') - - self.assertEqual(old.max_builds, 3) - self.assertEqual(old.notify_on_missing, ['her@me.com']) - self.assertEqual(old.missing_timeout, 121) - self.assertEqual(old.properties.getProperty('a'), 'c') - self.assertEqual(old.keepalive_interval, 61) - self.assertEqual(self.master.pbmanager._registrations, []) - self.assertTrue(old.updateSlave.called) - - @defer.inlineCallbacks - def test_reconfigService_has_properties(self): - old = self.ConcreteBuildSlave('bot', 'pass') - yield self.do_test_reconfigService(old, 'tcp:1234', old, 'tcp:1234') - self.assertTrue(old.properties.getProperty('slavename'), 'bot') - - @defer.inlineCallbacks - def test_reconfigService_initial_registration(self): - old = self.ConcreteBuildSlave('bot', 'pass') - yield self.do_test_reconfigService(old, None, old, 'tcp:1234') - self.assertEqual(self.master.pbmanager._registrations, [('tcp:1234', 'bot', 'pass')]) - - @defer.inlineCallbacks - def test_reconfigService_reregister_password(self): - old = self.ConcreteBuildSlave('bot', 'pass') - new = self.ConcreteBuildSlave('bot', 'newpass') - - yield self.do_test_reconfigService(old, 'tcp:1234', new, 'tcp:1234') - - self.assertEqual(old.password, 'newpass') - self.assertEqual(self.master.pbmanager._unregistrations, [('tcp:1234', 'bot')]) - self.assertEqual(self.master.pbmanager._registrations, [('tcp:1234', 'bot', 'newpass')]) - - @defer.inlineCallbacks - def test_reconfigService_reregister_port(self): - old = self.ConcreteBuildSlave('bot', 'pass') - new = self.ConcreteBuildSlave('bot', 'pass') - - yield self.do_test_reconfigService(old, 'tcp:1234', new, 'tcp:5678') - - self.assertEqual(self.master.pbmanager._unregistrations, [('tcp:1234', 'bot')]) - self.assertEqual(self.master.pbmanager._registrations, [('tcp:5678', 'bot', 'pass')]) - - @defer.inlineCallbacks - def test_stopService(self): - master = self.master = fakemaster.make_master() - slave = self.ConcreteBuildSlave('bot', 'pass') - slave.master = master - slave.startService() - - config = mock.Mock() - config.slavePortnum = "tcp:1234" - config.slaves = [ slave ] - - yield slave.reconfigService(config) - yield slave.stopService() - - self.assertEqual(self.master.pbmanager._unregistrations, [('tcp:1234', 'bot')]) - self.assertEqual(self.master.pbmanager._registrations, [('tcp:1234', 'bot', 'pass')]) - - # FIXME: Test that reconfig properly deals with - # 1) locks - # 2) telling slave about builder - # 3) missing timer - # in both the initial config and a reconfiguration. - - def test_startMissingTimer_no_parent(self): - bs = self.ConcreteBuildSlave('bot', 'pass', - notify_on_missing=['abc'], - missing_timeout=10) - bs.startMissingTimer() - self.assertEqual(bs.missing_timer, None) - - def test_startMissingTimer_no_timeout(self): - bs = self.ConcreteBuildSlave('bot', 'pass', - notify_on_missing=['abc'], - missing_timeout=0) - bs.parent = mock.Mock() - bs.startMissingTimer() - self.assertEqual(bs.missing_timer, None) - - def test_startMissingTimer_no_notify(self): - bs = self.ConcreteBuildSlave('bot', 'pass', - missing_timeout=3600) - bs.parent = mock.Mock() - bs.startMissingTimer() - self.assertEqual(bs.missing_timer, None) - - def test_missing_timer(self): - bs = self.ConcreteBuildSlave('bot', 'pass', - notify_on_missing=['abc'], - missing_timeout=100) - bs.parent = mock.Mock() - bs.startMissingTimer() - self.assertNotEqual(bs.missing_timer, None) - bs.stopMissingTimer() - self.assertEqual(bs.missing_timer, None) - - def test_setServiceParent_started(self): - master = self.master = fakemaster.make_master() - botmaster = FakeBotMaster(master) - botmaster.startService() - bs = self.ConcreteBuildSlave('bot', 'pass') - bs.setServiceParent(botmaster) - self.assertEqual(bs.botmaster, botmaster) - self.assertEqual(bs.master, master) - - def test_setServiceParent_masterLocks(self): - """ - http://trac.buildbot.net/ticket/2278 - """ - master = self.master = fakemaster.make_master() - botmaster = FakeBotMaster(master) - botmaster.startService() - lock = locks.MasterLock('masterlock') - bs = self.ConcreteBuildSlave('bot', 'pass', locks = [lock.access("counting")]) - bs.setServiceParent(botmaster) - - def test_setServiceParent_slaveLocks(self): - """ - http://trac.buildbot.net/ticket/2278 - """ - master = self.master = fakemaster.make_master() - botmaster = FakeBotMaster(master) - botmaster.startService() - lock = locks.SlaveLock('lock') - bs = self.ConcreteBuildSlave('bot', 'pass', locks = [lock.access("counting")]) - bs.setServiceParent(botmaster) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_libvirt.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_libvirt.py deleted file mode 100644 index 2478e46c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_libvirt.py +++ /dev/null @@ -1,282 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer, reactor, utils -from twisted.python import failure -from buildbot import config -from buildbot.test.fake import libvirt -from buildbot.test.util import compat -from buildbot.buildslave import libvirt as libvirtbuildslave - - -class TestLibVirtSlave(unittest.TestCase): - - class ConcreteBuildSlave(libvirtbuildslave.LibVirtSlave): - pass - - def setUp(self): - self.patch(libvirtbuildslave, "libvirt", libvirt) - self.conn = libvirtbuildslave.Connection("test://") - self.lvconn = self.conn.connection - - def test_constructor_nolibvirt(self): - self.patch(libvirtbuildslave, "libvirt", None) - self.assertRaises(config.ConfigErrors, self.ConcreteBuildSlave, - 'bot', 'pass', None, 'path', 'path') - - def test_constructor_minimal(self): - bs = self.ConcreteBuildSlave('bot', 'pass', self.conn, 'path', 'otherpath') - yield bs._find_existing_deferred - self.assertEqual(bs.slavename, 'bot') - self.assertEqual(bs.password, 'pass') - self.assertEqual(bs.connection, self.conn) - self.assertEqual(bs.image, 'path') - self.assertEqual(bs.base_image, 'otherpath') - self.assertEqual(bs.keepalive_interval, 3600) - - @defer.inlineCallbacks - def test_find_existing(self): - d = self.lvconn.fake_add("bot") - - bs = self.ConcreteBuildSlave('bot', 'pass', self.conn, 'p', 'o') - yield bs._find_existing_deferred - - self.assertEqual(bs.domain.domain, d) - self.assertEqual(bs.substantiated, True) - - @defer.inlineCallbacks - def test_prepare_base_image_none(self): - self.patch(utils, "getProcessValue", mock.Mock()) - utils.getProcessValue.side_effect = lambda x,y: defer.succeed(0) - - bs = self.ConcreteBuildSlave('bot', 'pass', self.conn, 'p', None) - yield bs._find_existing_deferred - yield bs._prepare_base_image() - - self.assertEqual(utils.getProcessValue.call_count, 0) - - @defer.inlineCallbacks - def test_prepare_base_image_cheap(self): - self.patch(utils, "getProcessValue", mock.Mock()) - utils.getProcessValue.side_effect = lambda x,y: defer.succeed(0) - - bs = self.ConcreteBuildSlave('bot', 'pass', self.conn, 'p', 'o') - yield bs._find_existing_deferred - yield bs._prepare_base_image() - - utils.getProcessValue.assert_called_with( - "qemu-img", ["create", "-b", "o", "-f", "qcow2", "p"]) - - @defer.inlineCallbacks - def test_prepare_base_image_full(self): - pass - self.patch(utils, "getProcessValue", mock.Mock()) - utils.getProcessValue.side_effect = lambda x,y: defer.succeed(0) - - bs = self.ConcreteBuildSlave('bot', 'pass', self.conn, 'p', 'o') - yield bs._find_existing_deferred - bs.cheap_copy = False - yield bs._prepare_base_image() - - utils.getProcessValue.assert_called_with( - "cp", ["o", "p"]) - - @defer.inlineCallbacks - def test_start_instance(self): - bs = self.ConcreteBuildSlave('b', 'p', self.conn, 'p', 'o', - xml='<xml/>') - - prep = mock.Mock() - prep.side_effect = lambda: defer.succeed(0) - self.patch(bs, "_prepare_base_image", prep) - - yield bs._find_existing_deferred - started = yield bs.start_instance(mock.Mock()) - - self.assertEqual(started, True) - - @compat.usesFlushLoggedErrors - @defer.inlineCallbacks - def test_start_instance_create_fails(self): - bs = self.ConcreteBuildSlave('b', 'p', self.conn, 'p', 'o', - xml='<xml/>') - - prep = mock.Mock() - prep.side_effect = lambda: defer.succeed(0) - self.patch(bs, "_prepare_base_image", prep) - - create = mock.Mock() - create.side_effect = lambda self : defer.fail( - failure.Failure(RuntimeError('oh noes'))) - self.patch(libvirtbuildslave.Connection, 'create', create) - - yield bs._find_existing_deferred - started = yield bs.start_instance(mock.Mock()) - - self.assertEqual(bs.domain, None) - self.assertEqual(started, False) - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - - @defer.inlineCallbacks - def setup_canStartBuild(self): - bs = self.ConcreteBuildSlave('b', 'p', self.conn, 'p', 'o') - yield bs._find_existing_deferred - bs.updateLocks() - defer.returnValue(bs) - - @defer.inlineCallbacks - def test_canStartBuild(self): - bs = yield self.setup_canStartBuild() - self.assertEqual(bs.canStartBuild(), True) - - @defer.inlineCallbacks - def test_canStartBuild_notready(self): - """ - If a LibVirtSlave hasnt finished scanning for existing VMs then we shouldn't - start builds on it as it might create a 2nd VM when we want to reuse the existing - one. - """ - bs = yield self.setup_canStartBuild() - bs.ready = False - self.assertEqual(bs.canStartBuild(), False) - - @defer.inlineCallbacks - def test_canStartBuild_domain_and_not_connected(self): - """ - If we've found that the VM this slave would instance already exists but hasnt - connected then we shouldn't start builds or we'll end up with a dupe. - """ - bs = yield self.setup_canStartBuild() - bs.domain = mock.Mock() - self.assertEqual(bs.canStartBuild(), False) - - @defer.inlineCallbacks - def test_canStartBuild_domain_and_connected(self): - """ - If we've found an existing VM and it is connected then we should start builds - """ - bs = yield self.setup_canStartBuild() - bs.domain = mock.Mock() - isconnected = mock.Mock() - isconnected.return_value = True - self.patch(bs, "isConnected", isconnected) - self.assertEqual(bs.canStartBuild(), True) - - -class TestWorkQueue(unittest.TestCase): - - def setUp(self): - self.queue = libvirtbuildslave.WorkQueue() - - def delayed_success(self): - def work(): - d = defer.Deferred() - reactor.callLater(0, d.callback, True) - return d - return work - - def delayed_errback(self): - def work(): - d = defer.Deferred() - reactor.callLater(0, d.errback, - failure.Failure(RuntimeError("Test failure"))) - return d - return work - - def expect_errback(self, d): - def shouldnt_get_called(f): - self.failUnlessEqual(True, False) - d.addCallback(shouldnt_get_called) - def errback(f): - #log.msg("errback called?") - pass - d.addErrback(errback) - return d - - def test_handle_exceptions(self): - def work(): - raise ValueError - return self.expect_errback(self.queue.execute(work)) - - def test_handle_immediate_errback(self): - def work(): - return defer.fail(RuntimeError("Sad times")) - return self.expect_errback(self.queue.execute(work)) - - def test_handle_delayed_errback(self): - work = self.delayed_errback() - return self.expect_errback(self.queue.execute(work)) - - def test_handle_immediate_success(self): - def work(): - return defer.succeed(True) - return self.queue.execute(work) - - def test_handle_delayed_success(self): - work = self.delayed_success() - return self.queue.execute(work) - - def test_single_pow_fires(self): - return self.queue.execute(self.delayed_success()) - - def test_single_pow_errors_gracefully(self): - d = self.queue.execute(self.delayed_errback()) - return self.expect_errback(d) - - def test_fail_doesnt_break_further_work(self): - self.expect_errback(self.queue.execute(self.delayed_errback())) - return self.queue.execute(self.delayed_success()) - - def test_second_pow_fires(self): - self.queue.execute(self.delayed_success()) - return self.queue.execute(self.delayed_success()) - - def test_work(self): - # We want these deferreds to fire in order - flags = {1: False, 2: False, 3: False } - - # When first deferred fires, flags[2] and flags[3] should still be false - # flags[1] shouldnt already be set, either - d1 = self.queue.execute(self.delayed_success()) - def cb1(res): - self.failUnlessEqual(flags[1], False) - flags[1] = True - self.failUnlessEqual(flags[2], False) - self.failUnlessEqual(flags[3], False) - d1.addCallback(cb1) - - # When second deferred fires, only flags[3] should be set - # flags[2] should definitely be False - d2 = self.queue.execute(self.delayed_success()) - def cb2(res): - assert flags[2] == False - flags[2] = True - assert flags[1] == True - assert flags[3] == False - d2.addCallback(cb2) - - # When third deferred fires, only flags[3] should be unset - d3 = self.queue.execute(self.delayed_success()) - def cb3(res): - assert flags[3] == False - flags[3] = True - assert flags[1] == True - assert flags[2] == True - d3.addCallback(cb3) - - return defer.DeferredList([d1, d2, d3], fireOnOneErrback=True) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_openstack.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_openstack.py deleted file mode 100644 index dcb0916f..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_buildslave_openstack.py +++ /dev/null @@ -1,110 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Portions Copyright Buildbot Team Members -# Portions Copyright 2013 Cray Inc. - -import mock -from twisted.trial import unittest -from buildbot import config, interfaces -from buildbot.buildslave import openstack -import buildbot.test.fake.openstack as novaclient - -class TestOpenStackBuildSlave(unittest.TestCase): - - def setUp(self): - self.patch(openstack, "nce", novaclient) - self.patch(openstack, "client", novaclient) - - def test_constructor_nonova(self): - self.patch(openstack, "nce", None) - self.patch(openstack, "client", None) - self.assertRaises(config.ConfigErrors, - openstack.OpenStackLatentBuildSlave, 'bot', 'pass', flavor=1, - image='image', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - - def test_constructor_minimal(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - self.assertEqual(bs.slavename, 'bot') - self.assertEqual(bs.password, 'pass') - self.assertEqual(bs.flavor, 1) - self.assertEqual(bs.image, 'image') - self.assertEqual(bs.os_username, 'user') - self.assertEqual(bs.os_password, 'pass') - self.assertEqual(bs.os_tenant_name, 'tenant') - self.assertEqual(bs.os_auth_url, 'auth') - - def test_getImage_string(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - self.assertEqual('image-uuid', bs._getImage(None)) - - def test_getImage_callable(self): - def image_callable(images): - return images[0] - - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image=image_callable, os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - os_client = novaclient.Client('user', 'pass', 'tenant', 'auth') - os_client.images.images = ['uuid1', 'uuid2', 'uuid2'] - self.assertEqual('uuid1', bs._getImage(os_client)) - - def test_start_instance_already_exists(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - bs.instance = mock.Mock() - self.assertRaises(ValueError, bs.start_instance, None) - - def test_start_instance_fail_to_find(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - bs._poll_resolution = 0 - self.patch(novaclient.Servers, 'fail_to_get', True) - self.assertRaises(interfaces.LatentBuildSlaveFailedToSubstantiate, - bs._start_instance) - - def test_start_instance_fail_to_start(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - bs._poll_resolution = 0 - self.patch(novaclient.Servers, 'fail_to_start', True) - self.assertRaises(interfaces.LatentBuildSlaveFailedToSubstantiate, - bs._start_instance) - - def test_start_instance_success(self): - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth') - bs._poll_resolution = 0 - uuid, image_uuid, time_waiting = bs._start_instance() - self.assertTrue(uuid) - self.assertEqual(image_uuid, 'image-uuid') - self.assertTrue(time_waiting) - - def test_start_instance_check_meta(self): - meta_arg = {'some_key': 'some-value'} - bs = openstack.OpenStackLatentBuildSlave('bot', 'pass', flavor=1, - image='image-uuid', os_username='user', os_password='pass', - os_tenant_name='tenant', os_auth_url='auth', meta=meta_arg) - bs._poll_resolution = 0 - uuid, image_uuid, time_waiting = bs._start_instance() - self.assertIn('meta', bs.instance.boot_kwargs) - self.assertIdentical(bs.instance.boot_kwargs['meta'], meta_arg) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_base.py deleted file mode 100644 index 5024b3c6..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_base.py +++ /dev/null @@ -1,81 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer, reactor, task -from buildbot.test.util import changesource, compat -from buildbot.changes import base - -class TestPollingChangeSource(changesource.ChangeSourceMixin, unittest.TestCase): - class Subclass(base.PollingChangeSource): - pass - - def setUp(self): - # patch in a Clock so we can manipulate the reactor's time - self.clock = task.Clock() - self.patch(reactor, 'callLater', self.clock.callLater) - self.patch(reactor, 'seconds', self.clock.seconds) - - d = self.setUpChangeSource() - def create_changesource(_): - self.attachChangeSource(self.Subclass()) - d.addCallback(create_changesource) - return d - - def tearDown(self): - return self.tearDownChangeSource() - - def runClockFor(self, _, secs): - self.clock.pump([1.0] * secs) - - def test_loop_loops(self): - # track when poll() gets called - loops = [] - self.changesource.poll = \ - lambda : loops.append(self.clock.seconds()) - - self.changesource.pollInterval = 5 - self.startChangeSource() - - d = defer.Deferred() - d.addCallback(self.runClockFor, 12) - def check(_): - # note that it does *not* poll at time 0 - self.assertEqual(loops, [5.0, 10.0]) - d.addCallback(check) - reactor.callWhenRunning(d.callback, None) - return d - - @compat.usesFlushLoggedErrors - def test_loop_exception(self): - # track when poll() gets called - loops = [] - def poll(): - loops.append(self.clock.seconds()) - raise RuntimeError("oh noes") - self.changesource.poll = poll - - self.changesource.pollInterval = 5 - self.startChangeSource() - - d = defer.Deferred() - d.addCallback(self.runClockFor, 12) - def check(_): - # note that it keeps looping after error - self.assertEqual(loops, [5.0, 10.0]) - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 2) - d.addCallback(check) - reactor.callWhenRunning(d.callback, None) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_bonsaipoller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_bonsaipoller.py deleted file mode 100644 index 03338876..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_bonsaipoller.py +++ /dev/null @@ -1,283 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from copy import deepcopy -import re - -from twisted.trial import unittest -from twisted.internet import defer -from twisted.web import client -from buildbot.test.util import changesource -from buildbot.util import epoch2datetime -from buildbot.changes.bonsaipoller import FileNode, CiNode, BonsaiResult, \ - BonsaiParser, BonsaiPoller, InvalidResultError, EmptyResult - -log1 = "Add Bug 338541a" -who1 = "sar@gmail.com" -date1 = 1161908700 -log2 = "bug 357427 add static ctor/dtor methods" -who2 = "aarrg@ooacm.org" -date2 = 1161910620 -log3 = "Testing log #3 lbah blah" -who3 = "huoents@hueont.net" -date3 = 1089822728 -rev1 = "1.8" -file1 = "mozilla/testing/mochitest/tests/index.html" -rev2 = "1.1" -file2 = "mozilla/testing/mochitest/tests/test_bug338541.xhtml" -rev3 = "1.1812" -file3 = "mozilla/xpcom/threads/nsAutoLock.cpp" -rev4 = "1.3" -file4 = "mozilla/xpcom/threads/nsAutoLock.h" -rev5 = "2.4" -file5 = "mozilla/xpcom/threads/test.cpp" - -nodes = [] -files = [] -files.append(FileNode(rev1,file1)) -nodes.append(CiNode(log1, who1, date1, files)) - -files = [] -files.append(FileNode(rev2, file2)) -files.append(FileNode(rev3, file3)) -nodes.append(CiNode(log2, who2, date2, files)) - -nodes.append(CiNode(log3, who3, date3, [])) - -goodParsedResult = BonsaiResult(nodes) - -goodUnparsedResult = """\ -<?xml version="1.0"?> -<queryResults> -<ci who="%s" date="%d"> - <log>%s</log> - <files> - <f rev="%s">%s</f> - </files> -</ci> -<ci who="%s" date="%d"> - <log>%s</log> - <files> - <f rev="%s">%s</f> - <f rev="%s">%s</f> - </files> -</ci> -<ci who="%s" date="%d"> - <log>%s</log> - <files> - </files> -</ci> -</queryResults> -""" % (who1, date1, log1, rev1, file1, - who2, date2, log2, rev2, file2, rev3, file3, - who3, date3, log3) - -badUnparsedResult = deepcopy(goodUnparsedResult) -badUnparsedResult = badUnparsedResult.replace("</queryResults>", "") - -invalidDateResult = deepcopy(goodUnparsedResult) -invalidDateResult = invalidDateResult.replace(str(date1), "foobar") - -missingFilenameResult = deepcopy(goodUnparsedResult) -missingFilenameResult = missingFilenameResult.replace(file2, "") - -duplicateLogResult = deepcopy(goodUnparsedResult) -duplicateLogResult = re.sub("<log>"+log1+"</log>", - "<log>blah</log><log>blah</log>", - duplicateLogResult) - -duplicateFilesResult = deepcopy(goodUnparsedResult) -duplicateFilesResult = re.sub("<files>\s*</files>", - "<files></files><files></files>", - duplicateFilesResult) - -missingCiResult = deepcopy(goodUnparsedResult) -r = re.compile("<ci.*</ci>", re.DOTALL | re.MULTILINE) -missingCiResult = re.sub(r, "", missingCiResult) - -badResultMsgs = { 'badUnparsedResult': - "BonsaiParser did not raise an exception when given a bad query", - 'invalidDateResult': - "BonsaiParser did not raise an exception when given an invalid date", - 'missingRevisionResult': - "BonsaiParser did not raise an exception when a revision was missing", - 'missingFilenameResult': - "BonsaiParser did not raise an exception when a filename was missing", - 'duplicateLogResult': - "BonsaiParser did not raise an exception when there was two <log> tags", - 'duplicateFilesResult': - "BonsaiParser did not raise an exception when there was two <files> tags", - 'missingCiResult': - "BonsaiParser did not raise an exception when there was no <ci> tags" -} - -noCheckinMsgResult = """\ -<?xml version="1.0"?> -<queryResults> -<ci who="johndoe@domain.tld" date="12345678"> - <log></log> - <files> - <f rev="1.1">first/file.ext</f> - </files> -</ci> -<ci who="johndoe@domain.tld" date="12345678"> - <log></log> - <files> - <f rev="1.2">second/file.ext</f> - </files> -</ci> -<ci who="johndoe@domain.tld" date="12345678"> - <log></log> - <files> - <f rev="1.3">third/file.ext</f> - </files> -</ci> -</queryResults> -""" - -noCheckinMsgRef = [dict(filename="first/file.ext", - revision="1.1"), - dict(filename="second/file.ext", - revision="1.2"), - dict(filename="third/file.ext", - revision="1.3")] - -class TestBonsaiParser(unittest.TestCase): - def testFullyFormedResult(self): - br = BonsaiParser(goodUnparsedResult) - result = br.getData() - # make sure the result is a BonsaiResult - self.failUnless(isinstance(result, BonsaiResult)) - # test for successful parsing - self.failUnlessEqual(goodParsedResult, result, - "BonsaiParser did not return the expected BonsaiResult") - - def testBadUnparsedResult(self): - try: - BonsaiParser(badUnparsedResult) - self.fail(badResultMsgs["badUnparsedResult"]) - except InvalidResultError: - pass - - def testInvalidDateResult(self): - try: - BonsaiParser(invalidDateResult) - self.fail(badResultMsgs["invalidDateResult"]) - except InvalidResultError: - pass - - def testMissingFilenameResult(self): - try: - BonsaiParser(missingFilenameResult) - self.fail(badResultMsgs["missingFilenameResult"]) - except InvalidResultError: - pass - - def testDuplicateLogResult(self): - try: - BonsaiParser(duplicateLogResult) - self.fail(badResultMsgs["duplicateLogResult"]) - except InvalidResultError: - pass - - def testDuplicateFilesResult(self): - try: - BonsaiParser(duplicateFilesResult) - self.fail(badResultMsgs["duplicateFilesResult"]) - except InvalidResultError: - pass - - def testMissingCiResult(self): - try: - BonsaiParser(missingCiResult) - self.fail(badResultMsgs["missingCiResult"]) - except EmptyResult: - pass - - def testMergeEmptyLogMsg(self): - """Ensure that BonsaiPoller works around the bonsai xml output - issue when the check-in comment is empty""" - bp = BonsaiParser(noCheckinMsgResult) - result = bp.getData() - self.failUnlessEqual(len(result.nodes), 1) - self.failUnlessEqual(result.nodes[0].who, "johndoe@domain.tld") - self.failUnlessEqual(result.nodes[0].date, 12345678) - self.failUnlessEqual(result.nodes[0].log, "") - for file, ref in zip(result.nodes[0].files, noCheckinMsgRef): - self.failUnlessEqual(file.filename, ref['filename']) - self.failUnlessEqual(file.revision, ref['revision']) - -class TestBonsaiPoller(changesource.ChangeSourceMixin, unittest.TestCase): - def setUp(self): - d = self.setUpChangeSource() - def create_poller(_): - self.attachChangeSource(BonsaiPoller('http://bonsai.mozilla.org', - 'all', 'seamonkey')) - d.addCallback(create_poller) - return d - - def tearDown(self): - return self.tearDownChangeSource() - - def fakeGetPage(self, result): - """Install a fake getPage that puts the requested URL in C{self.getPage_got_url} - and return C{result}""" - self.getPage_got_url = None - def fake(url, timeout=None): - self.getPage_got_url = url - return defer.succeed(result) - self.patch(client, "getPage", fake) - - # tests - - def test_describe(self): - assert re.search(r'bonsai\.mozilla\.org', self.changesource.describe()) - - def test_poll_bad(self): - # Make sure a change is not submitted if the BonsaiParser fails, and - # that the poll operation catches the exception correctly - self.fakeGetPage(badUnparsedResult) - d = self.changesource.poll() - def check(_): - self.assertEqual(len(self.changes_added), 0) - d.addCallback(check) - return d - - def test_poll_good(self): - self.fakeGetPage(goodUnparsedResult) - d = self.changesource.poll() - def check(_): - self.assertEqual(len(self.changes_added), 3) - self.assertEqual(self.changes_added[0]['author'], who1) - self.assertEqual(self.changes_added[0]['when_timestamp'], - epoch2datetime(date1)) - self.assertEqual(self.changes_added[0]['comments'], log1) - self.assertEqual(self.changes_added[0]['branch'], 'seamonkey') - self.assertEqual(self.changes_added[0]['files'], - [ '%s (revision %s)' % (file1, rev1) ]) - self.assertEqual(self.changes_added[1]['author'], who2) - self.assertEqual(self.changes_added[1]['when_timestamp'], - epoch2datetime(date2)) - self.assertEqual(self.changes_added[1]['comments'], log2) - self.assertEqual(self.changes_added[1]['files'], - [ '%s (revision %s)' % (file2, rev2), - '%s (revision %s)' % (file3, rev3) ]) - self.assertEqual(self.changes_added[2]['author'], who3) - self.assertEqual(self.changes_added[2]['comments'], log3) - self.assertEqual(self.changes_added[2]['when_timestamp'], - epoch2datetime(date3)) - self.assertEqual(self.changes_added[2]['files'], []) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_changes.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_changes.py deleted file mode 100644 index 6dcee925..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_changes.py +++ /dev/null @@ -1,113 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import textwrap -import re -from twisted.trial import unittest -from buildbot.test.fake import fakedb -from buildbot.changes import changes - -class Change(unittest.TestCase): - - change23_rows = [ - fakedb.Change(changeid=23, author="dustin", comments="fix whitespace", - is_dir=0, branch="warnerdb", revision="deadbeef", - when_timestamp=266738404, revlink='http://warner/0e92a098b', - category='devel', repository='git://warner', codebase='mainapp', - project='Buildbot'), - - fakedb.ChangeFile(changeid=23, filename='master/README.txt'), - fakedb.ChangeFile(changeid=23, filename='slave/README.txt'), - - fakedb.ChangeProperty(changeid=23, property_name='notest', - property_value='["no","Change"]'), - - fakedb.ChangeUser(changeid=23, uid=27), - ] - - def setUp(self): - self.change23 = changes.Change(**dict( # using **dict(..) forces kwargs - category='devel', - isdir=0, - repository=u'git://warner', - codebase=u'mainapp', - who=u'dustin', - when=266738404, - comments=u'fix whitespace', - project=u'Buildbot', - branch=u'warnerdb', - revlink=u'http://warner/0e92a098b', - properties={'notest':"no"}, - files=[u'master/README.txt', u'slave/README.txt'], - revision=u'deadbeef')) - self.change23.number = 23 - - def test_str(self): - string = str(self.change23) - self.assertTrue(re.match(r"Change\(.*\)", string), string) - - def test_asText(self): - text = self.change23.asText() - self.assertTrue(re.match(textwrap.dedent(u'''\ - Files: - master/README.txt - slave/README.txt - On: git://warner - For: Buildbot - At: .* - Changed By: dustin - Comments: fix whitespaceProperties: - notest: no - - '''), text), text) - - def test_asDict(self): - dict = self.change23.asDict() - self.assertIn('1978', dict['at']) # timezone-sensitive - del dict['at'] - self.assertEqual(dict, { - 'branch': u'warnerdb', - 'category': u'devel', - 'codebase': u'mainapp', - 'comments': u'fix whitespace', - 'files': [{'name': u'master/README.txt'}, - {'name': u'slave/README.txt'}], - 'number': 23, - 'project': u'Buildbot', - 'properties': [('notest', 'no', 'Change')], - 'repository': u'git://warner', - 'rev': u'deadbeef', - 'revision': u'deadbeef', - 'revlink': u'http://warner/0e92a098b', - 'when': 266738404, - 'who': u'dustin'}) - - def test_getShortAuthor(self): - self.assertEqual(self.change23.getShortAuthor(), 'dustin') - - def test_getTime(self): - # careful, or timezones will hurt here - self.assertIn('Jun 1978', self.change23.getTime()) - - def test_getTimes(self): - self.assertEqual(self.change23.getTimes(), (266738404, None)) - - def test_getText(self): - self.change23.who = 'nasty < nasty' # test the html escaping (ugh!) - self.assertEqual(self.change23.getText(), ['nasty < nasty']) - - def test_getLogs(self): - self.assertEqual(self.change23.getLogs(), {}) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_filter.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_filter.py deleted file mode 100644 index 35c2d316..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_filter.py +++ /dev/null @@ -1,129 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import re - -from twisted.trial import unittest - -from buildbot.changes import filter -from buildbot.test.fake.state import State - -class Change(State): - project = '' - repository = '' - branch = '' - category = '' - codebase = '' - -class ChangeFilter(unittest.TestCase): - - def setUp(self): - self.results = [] # (got, expected, msg) - self.filt = None - - def tearDown(self): - if self.results: - raise RuntimeError("test forgot to call check()") - - def setfilter(self, **kwargs): - self.filt = filter.ChangeFilter(**kwargs) - - def yes(self, change, msg): - self.results.append((self.filt.filter_change(change), True, msg)) - - def no(self, change, msg): - self.results.append((self.filt.filter_change(change), False, msg)) - - def check(self): - errs = [] - for r in self.results: - if (r[0] or r[1]) and not (r[0] and r[1]): - errs.append(r[2]) - self.results = [] - if errs: - self.fail("; ".join(errs)) - - def test_filter_change_filter_fn(self): - self.setfilter(filter_fn = lambda ch : ch.x > 3) - self.no(Change(x=2), "filter_fn returns False") - self.yes(Change(x=4), "filter_fn returns True") - self.check() - - def test_filter_change_filt_str(self): - self.setfilter(project = "myproj") - self.no(Change(project="yourproj"), "non-matching PROJECT returns False") - self.yes(Change(project="myproj"), "matching PROJECT returns True") - self.check() - - def test_filter_change_filt_list(self): - self.setfilter(repository = ["vc://a", "vc://b"]) - self.yes(Change(repository="vc://a"), "matching REPOSITORY vc://a returns True") - self.yes(Change(repository="vc://b"), "matching REPOSITORY vc://b returns True") - self.no(Change(repository="vc://c"), "non-matching REPOSITORY returns False") - self.no(Change(repository=None), "None for REPOSITORY returns False") - self.check() - - def test_filter_change_filt_list_None(self): - self.setfilter(branch = ["mybr", None]) - self.yes(Change(branch="mybr"), "matching BRANCH mybr returns True") - self.yes(Change(branch=None), "matching BRANCH None returns True") - self.no(Change(branch="misc"), "non-matching BRANCH returns False") - self.check() - - def test_filter_change_filt_re(self): - self.setfilter(category_re = "^a.*") - self.yes(Change(category="albert"), "matching CATEGORY returns True") - self.no(Change(category="boris"), "non-matching CATEGORY returns False") - self.check() - - def test_filter_change_branch_re(self): # regression - see #927 - self.setfilter(branch_re = "^t.*") - self.yes(Change(branch="trunk"), "matching BRANCH returns True") - self.no(Change(branch="development"), "non-matching BRANCH returns False") - self.no(Change(branch=None), "branch=None returns False") - self.check() - - def test_filter_change_filt_re_compiled(self): - self.setfilter(category_re = re.compile("^b.*", re.I)) - self.no(Change(category="albert"), "non-matching CATEGORY returns False") - self.yes(Change(category="boris"), "matching CATEGORY returns True") - self.yes(Change(category="Bruce"), "matching CATEGORY returns True, using re.I") - self.check() - - def test_filter_change_combination(self): - self.setfilter(project='p', repository='r', branch='b', category='c', - codebase='cb') - self.no(Change(project='x', repository='x', branch='x', category='x'), - "none match -> False") - self.no(Change(project='p', repository='r', branch='b', category='x'), - "three match -> False") - self.no(Change(project='p', repository='r', branch='b', category='c', - codebase='x'), "four match -> False") - self.yes(Change(project='p', repository='r', branch='b', category='c', - codebase='cb'), "all match -> True") - self.check() - - def test_filter_change_combination_filter_fn(self): - self.setfilter(project='p', repository='r', branch='b', category='c', - filter_fn = lambda c : c.ff) - self.no(Change(project='x', repository='x', branch='x', category='x', ff=False), - "none match and fn returns False -> False") - self.no(Change(project='p', repository='r', branch='b', category='c', ff=False), - "all match and fn returns False -> False") - self.no(Change(project='x', repository='x', branch='x', category='x', ff=True), - "none match and fn returns True -> False") - self.yes(Change(project='p', repository='r', branch='b', category='c', ff=True), - "all match and fn returns True -> False") - self.check() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gerritchangesource.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gerritchangesource.py deleted file mode 100644 index bcd8fe32..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gerritchangesource.py +++ /dev/null @@ -1,85 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc[''], 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.util import json -from buildbot.test.util import changesource -from buildbot.changes import gerritchangesource - -class TestGerritChangeSource(changesource.ChangeSourceMixin, - unittest.TestCase): - def setUp(self): - return self.setUpChangeSource() - - def tearDown(self): - return self.tearDownChangeSource() - - def newChangeSource(self, host, user): - s = gerritchangesource.GerritChangeSource(host, user) - self.attachChangeSource(s) - return s - - # tests - - def test_describe(self): - s = self.newChangeSource('somehost', 'someuser') - self.assertSubstring("GerritChangeSource", s.describe()) - - # TODO: test the backoff algorithm - - # this variable is reused in test_steps_source_repo - # to ensure correct integration between change source and repo step - expected_change = {'category': u'patchset-created', - 'files': ['unknown'], - 'repository': u'ssh://someuser@somehost:29418/pr', - 'author': u'Dustin <dustin@mozilla.com>', - 'comments': u'fix 1234', - 'project': u'pr', - 'branch': u'br/4321', - 'revlink': u'http://buildbot.net', - 'properties': {u'event.change.owner.email': u'dustin@mozilla.com', - u'event.change.subject': u'fix 1234', - u'event.change.project': u'pr', - u'event.change.owner.name': u'Dustin', - u'event.change.number': u'4321', - u'event.change.url': u'http://buildbot.net', - u'event.change.branch': u'br', - u'event.type': u'patchset-created', - u'event.patchSet.revision': u'abcdef', - u'event.patchSet.number': u'12'}, - u'revision': u'abcdef'} - - def test_lineReceived_patchset_created(self): - s = self.newChangeSource('somehost', 'someuser') - d = s.lineReceived(json.dumps(dict( - type="patchset-created", - change=dict( - branch="br", - project="pr", - number="4321", - owner=dict(name="Dustin", email="dustin@mozilla.com"), - url="http://buildbot.net", - subject="fix 1234" - ), - patchSet=dict(revision="abcdef", number="12") - ))) - - def check(_): - self.failUnlessEqual(len(self.changes_added), 1) - c = self.changes_added[0] - for k, v in c.items(): - self.assertEqual(self.expected_change[k], v) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gitpoller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gitpoller.py deleted file mode 100644 index 3067492a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_gitpoller.py +++ /dev/null @@ -1,580 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.changes import base, gitpoller -from buildbot.test.util import changesource, config, gpo -from buildbot.util import epoch2datetime - -# Test that environment variables get propagated to subprocesses (See #2116) -os.environ['TEST_THAT_ENVIRONMENT_GETS_PASSED_TO_SUBPROCESSES'] = 'TRUE' - -class GitOutputParsing(gpo.GetProcessOutputMixin, unittest.TestCase): - """Test GitPoller methods for parsing git output""" - def setUp(self): - self.poller = gitpoller.GitPoller('git@example.com:foo/baz.git') - self.setUpGetProcessOutput() - - dummyRevStr = '12345abcde' - def _perform_git_output_test(self, methodToTest, args, - desiredGoodOutput, desiredGoodResult, - emptyRaisesException=True): - - # make this call to self.patch here so that we raise a SkipTest if it - # is not supported - self.expectCommands( - gpo.Expect('git', *args) - .path('gitpoller-work'), - ) - - d = defer.succeed(None) - def call_empty(_): - # we should get an Exception with empty output from git - return methodToTest(self.dummyRevStr) - d.addCallback(call_empty) - - def cb_empty(_): - if emptyRaisesException: - self.fail("getProcessOutput should have failed on empty output") - def eb_empty(f): - if not emptyRaisesException: - self.fail("getProcessOutput should NOT have failed on empty output") - d.addCallbacks(cb_empty, eb_empty) - d.addCallback(lambda _: self.assertAllCommandsRan()) - - # and the method shouldn't supress any exceptions - self.expectCommands( - gpo.Expect('git', *args) - .path('gitpoller-work') - .exit(1), - ) - def call_exception(_): - return methodToTest(self.dummyRevStr) - d.addCallback(call_exception) - - def cb_exception(_): - self.fail("getProcessOutput should have failed on stderr output") - def eb_exception(f): - pass - d.addCallbacks(cb_exception, eb_exception) - d.addCallback(lambda _: self.assertAllCommandsRan()) - - # finally we should get what's expected from good output - self.expectCommands( - gpo.Expect('git', *args) - .path('gitpoller-work') - .stdout(desiredGoodOutput) - ) - def call_desired(_): - return methodToTest(self.dummyRevStr) - d.addCallback(call_desired) - - def cb_desired(r): - self.assertEquals(r, desiredGoodResult) - d.addCallback(cb_desired) - d.addCallback(lambda _: self.assertAllCommandsRan()) - - def test_get_commit_author(self): - authorStr = 'Sammy Jankis <email@example.com>' - return self._perform_git_output_test(self.poller._get_commit_author, - ['log', '--no-walk', '--format=%aN <%aE>', self.dummyRevStr, '--'], - authorStr, authorStr) - - def test_get_commit_comments(self): - commentStr = 'this is a commit message\n\nthat is multiline' - return self._perform_git_output_test(self.poller._get_commit_comments, - ['log', '--no-walk', '--format=%s%n%b', self.dummyRevStr, '--'], - commentStr, commentStr) - - def test_get_commit_files(self): - filesStr = 'file1\nfile2' - return self._perform_git_output_test(self.poller._get_commit_files, - ['log', '--name-only', '--no-walk', '--format=%n', self.dummyRevStr, '--'], - filesStr, filesStr.split(), emptyRaisesException=False) - - def test_get_commit_timestamp(self): - stampStr = '1273258009' - return self._perform_git_output_test(self.poller._get_commit_timestamp, - ['log', '--no-walk', '--format=%ct', self.dummyRevStr, '--'], - stampStr, float(stampStr)) - - # _get_changes is tested in TestGitPoller, below - -class TestGitPoller(gpo.GetProcessOutputMixin, - changesource.ChangeSourceMixin, - unittest.TestCase): - - REPOURL = 'git@example.com:foo/baz.git' - REPOURL_QUOTED = 'git%40example.com%3Afoo%2Fbaz.git' - - def setUp(self): - self.setUpGetProcessOutput() - d = self.setUpChangeSource() - def create_poller(_): - self.poller = gitpoller.GitPoller(self.REPOURL) - self.poller.master = self.master - d.addCallback(create_poller) - return d - - def tearDown(self): - return self.tearDownChangeSource() - - def test_describe(self): - self.assertSubstring("GitPoller", self.poller.describe()) - - def test_poll_initial(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), - ) - - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(self.poller.lastRev, { - 'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5' - }) - self.master.db.state.assertStateByClass( - name=self.REPOURL, class_name='GitPoller', - lastRev={ - 'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5' - }) - return d - - def test_poll_failInit(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work') - .exit(1), - ) - - d = self.assertFailure(self.poller.poll(), EnvironmentError) - - d.addCallback(lambda _: self.assertAllCommandsRan) - return d - - def test_poll_failFetch(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .exit(1), - ) - - d = self.assertFailure(self.poller.poll(), EnvironmentError) - d.addCallback(lambda _: self.assertAllCommandsRan) - return d - - def test_poll_failRevParse(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .exit(1), - ) - - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(len(self.flushLoggedErrors()), 1) - self.assertEqual(self.poller.lastRev, {}) - - def test_poll_failLog(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'log', - '--format=%H', - 'fa3ae8ed68e664d4db24798611b352e3c6509930..4423cdbcbb89c14e50dd5f4152415afd686c5241', - '--') - .path('gitpoller-work') - .exit(1), - ) - - # do the poll - self.poller.lastRev = { - 'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930' - } - d = self.poller.poll() - - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(len(self.flushLoggedErrors()), 1) - self.assertEqual(self.poller.lastRev, { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - }) - - def test_poll_nothingNew(self): - # Test that environment variables get propagated to subprocesses - # (See #2116) - self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) - self.addGetProcessOutputExpectEnv({'ENVVAR': 'TRUE'}) - - - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('no interesting output'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'log', - '--format=%H', - '4423cdbcbb89c14e50dd5f4152415afd686c5241..4423cdbcbb89c14e50dd5f4152415afd686c5241', - '--') - .path('gitpoller-work') - .stdout(''), - ) - - self.poller.lastRev = { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - } - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.master.db.state.assertStateByClass( - name=self.REPOURL, class_name='GitPoller', - lastRev={ - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - }) - return d - - def test_poll_multipleBranches_initial(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED, - '+release:refs/buildbot/%s/release' % self.REPOURL_QUOTED) - .path('gitpoller-work'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/release' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), - ) - - # do the poll - self.poller.branches = ['master', 'release'] - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(self.poller.lastRev, { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', - 'release': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2' - }) - - return d - - - def test_poll_multipleBranches(self): - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED, - '+release:refs/buildbot/%s/release' % self.REPOURL_QUOTED) - .path('gitpoller-work'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'log', - '--format=%H', - 'fa3ae8ed68e664d4db24798611b352e3c6509930..4423cdbcbb89c14e50dd5f4152415afd686c5241', - '--') - .path('gitpoller-work') - .stdout('\n'.join([ - '64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', - '4423cdbcbb89c14e50dd5f4152415afd686c5241'])), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/release' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), - gpo.Expect('git', 'log', - '--format=%H', - 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5..9118f4ab71963d23d02d4bdc54876ac8bf05acf2', - '--') - .path('gitpoller-work') - .stdout( '\n'.join([ - '9118f4ab71963d23d02d4bdc54876ac8bf05acf2' - ])), - ) - - # and patch out the _get_commit_foo methods which were already tested - # above - def timestamp(rev): - return defer.succeed(1273258009.0) - self.patch(self.poller, '_get_commit_timestamp', timestamp) - def author(rev): - return defer.succeed('by:' + rev[:8]) - self.patch(self.poller, '_get_commit_author', author) - def files(rev): - return defer.succeed(['/etc/' + rev[:3]]) - self.patch(self.poller, '_get_commit_files', files) - def comments(rev): - return defer.succeed('hello!') - self.patch(self.poller, '_get_commit_comments', comments) - - # do the poll - self.poller.branches = ['master', 'release'] - self.poller.lastRev = { - 'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', - 'release': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5' - } - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(self.poller.lastRev, { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', - 'release': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2' - }) - - self.assertEqual(len(self.changes_added), 3) - - self.assertEqual(self.changes_added[0]['author'], 'by:4423cdbc') - self.assertEqual(self.changes_added[0]['when_timestamp'], - epoch2datetime(1273258009)) - self.assertEqual(self.changes_added[0]['comments'], 'hello!') - self.assertEqual(self.changes_added[0]['branch'], 'master') - self.assertEqual(self.changes_added[0]['files'], [ '/etc/442' ]) - self.assertEqual(self.changes_added[0]['src'], 'git') - - self.assertEqual(self.changes_added[1]['author'], 'by:64a5dc2a') - self.assertEqual(self.changes_added[1]['when_timestamp'], - epoch2datetime(1273258009)) - self.assertEqual(self.changes_added[1]['comments'], 'hello!') - self.assertEqual(self.changes_added[1]['files'], [ '/etc/64a' ]) - self.assertEqual(self.changes_added[1]['src'], 'git') - - self.assertEqual(self.changes_added[2]['author'], 'by:9118f4ab') - self.assertEqual(self.changes_added[2]['when_timestamp'], - epoch2datetime(1273258009)) - self.assertEqual(self.changes_added[2]['comments'], 'hello!') - self.assertEqual(self.changes_added[2]['files'], [ '/etc/911' ]) - self.assertEqual(self.changes_added[2]['src'], 'git') - - return d - - - def test_poll_noChanges(self): - # Test that environment variables get propagated to subprocesses - # (See #2116) - self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) - self.addGetProcessOutputExpectEnv({'ENVVAR': 'TRUE'}) - - - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('no interesting output'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'log', - '--format=%H', - '4423cdbcbb89c14e50dd5f4152415afd686c5241..4423cdbcbb89c14e50dd5f4152415afd686c5241', - '--') - .path('gitpoller-work') - .stdout(''), - ) - - self.poller.lastRev = { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - } - d = self.poller.poll() - @d.addCallback - def cb(_): - self.assertAllCommandsRan() - self.assertEqual(self.poller.lastRev, { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - }) - return d - - def test_poll_old(self): - # Test that environment variables get propagated to subprocesses - # (See #2116) - self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) - self.addGetProcessOutputExpectEnv({'ENVVAR': 'TRUE'}) - - # patch out getProcessOutput and getProcessOutputAndValue for the - # benefit of the _get_changes method - self.expectCommands( - gpo.Expect('git', 'init', '--bare', 'gitpoller-work'), - gpo.Expect('git', 'fetch', self.REPOURL, - '+master:refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('no interesting output'), - gpo.Expect('git', 'rev-parse', - 'refs/buildbot/%s/master' % self.REPOURL_QUOTED) - .path('gitpoller-work') - .stdout('4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), - gpo.Expect('git', 'log', - '--format=%H', - 'fa3ae8ed68e664d4db24798611b352e3c6509930..4423cdbcbb89c14e50dd5f4152415afd686c5241', - '--') - .path('gitpoller-work') - .stdout('\n'.join([ - '64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', - '4423cdbcbb89c14e50dd5f4152415afd686c5241' - ])), - ) - - # and patch out the _get_commit_foo methods which were already tested - # above - def timestamp(rev): - return defer.succeed(1273258009.0) - self.patch(self.poller, '_get_commit_timestamp', timestamp) - def author(rev): - return defer.succeed('by:' + rev[:8]) - self.patch(self.poller, '_get_commit_author', author) - def files(rev): - return defer.succeed(['/etc/' + rev[:3]]) - self.patch(self.poller, '_get_commit_files', files) - def comments(rev): - return defer.succeed('hello!') - self.patch(self.poller, '_get_commit_comments', comments) - - # do the poll - self.poller.lastRev = { - 'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930' - } - d = self.poller.poll() - - # check the results - def check_changes(_): - self.assertEqual(self.poller.lastRev, { - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - }) - self.assertEqual(len(self.changes_added), 2) - self.assertEqual(self.changes_added[0]['author'], 'by:4423cdbc') - self.assertEqual(self.changes_added[0]['when_timestamp'], - epoch2datetime(1273258009)) - self.assertEqual(self.changes_added[0]['comments'], 'hello!') - self.assertEqual(self.changes_added[0]['branch'], 'master') - self.assertEqual(self.changes_added[0]['files'], [ '/etc/442' ]) - self.assertEqual(self.changes_added[0]['src'], 'git') - self.assertEqual(self.changes_added[1]['author'], 'by:64a5dc2a') - self.assertEqual(self.changes_added[1]['when_timestamp'], - epoch2datetime(1273258009)) - self.assertEqual(self.changes_added[1]['comments'], 'hello!') - self.assertEqual(self.changes_added[1]['files'], [ '/etc/64a' ]) - self.assertEqual(self.changes_added[1]['src'], 'git') - self.assertAllCommandsRan() - - self.master.db.state.assertStateByClass( - name=self.REPOURL, class_name='GitPoller', - lastRev={ - 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' - }) - d.addCallback(check_changes) - - return d - - # We mock out base.PollingChangeSource.startService, since it calls - # reactor.callWhenRunning, which leaves a dirty reactor if a synchronous - # deferred is returned from a test method. - def test_startService(self): - startService = mock.Mock() - self.patch(base.PollingChangeSource, "startService", startService) - d = self.poller.startService() - def check(_): - self.assertEqual(self.poller.workdir, os.path.join('basedir', 'gitpoller-work')) - self.assertEqual(self.poller.lastRev, {}) - startService.assert_called_once_with(self.poller) - d.addCallback(check) - return d - - def test_startService_loadLastRev(self): - startService = mock.Mock() - self.patch(base.PollingChangeSource, "startService", startService) - self.master.db.state.fakeState( - name=self.REPOURL, class_name='GitPoller', - lastRev={"master": "fa3ae8ed68e664d4db24798611b352e3c6509930"}, - ) - - d = self.poller.startService() - def check(_): - self.assertEqual(self.poller.lastRev, { - "master": "fa3ae8ed68e664d4db24798611b352e3c6509930" - }) - startService.assert_called_once_with(self.poller) - d.addCallback(check) - return d - - -class TestGitPollerConstructor(unittest.TestCase, config.ConfigErrorsMixin): - def test_deprecatedFetchRefspec(self): - self.assertRaisesConfigError("fetch_refspec is no longer supported", - lambda: gitpoller.GitPoller("/tmp/git.git", - fetch_refspec='not-supported')) - - def test_oldPollInterval(self): - poller = gitpoller.GitPoller("/tmp/git.git", pollinterval=10) - self.assertEqual(poller.pollInterval, 10) - - def test_branches_default(self): - poller = gitpoller.GitPoller("/tmp/git.git") - self.assertEqual(poller.branches, ["master"]) - - def test_branches_oldBranch(self): - poller = gitpoller.GitPoller("/tmp/git.git", branch='magic') - self.assertEqual(poller.branches, ["magic"]) - - def test_branches(self): - poller = gitpoller.GitPoller("/tmp/git.git", - branches=['magic', 'marker']) - self.assertEqual(poller.branches, ["magic", "marker"]) - - def test_branches_andBranch(self): - self.assertRaisesConfigError("can't specify both branch and branches", - lambda: gitpoller.GitPoller("/tmp/git.git", - branch='bad', branches=['listy'])) - - def test_gitbin_default(self): - poller = gitpoller.GitPoller("/tmp/git.git") - self.assertEqual(poller.gitbin, "git") diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_hgpoller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_hgpoller.py deleted file mode 100644 index c6bf128b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_hgpoller.py +++ /dev/null @@ -1,178 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.changes import hgpoller -from buildbot.test.util import changesource, gpo -from buildbot.test.fake.fakedb import FakeDBConnector -from buildbot.util import epoch2datetime - -ENVIRON_2116_KEY = 'TEST_THAT_ENVIRONMENT_GETS_PASSED_TO_SUBPROCESSES' - -class TestHgPoller(gpo.GetProcessOutputMixin, - changesource.ChangeSourceMixin, - unittest.TestCase): - - def setUp(self): - # To test that environment variables get propagated to subprocesses - # (See #2116) - os.environ[ENVIRON_2116_KEY] = 'TRUE' - self.setUpGetProcessOutput() - d = self.setUpChangeSource() - self.remote_repo = 'ssh://example.com/foo/baz' - self.repo_ready = True - def _isRepositoryReady(): - return self.repo_ready - def create_poller(_): - self.poller = hgpoller.HgPoller(self.remote_repo, - workdir='/some/dir') - self.poller.master = self.master - self.poller._isRepositoryReady = _isRepositoryReady - def create_db(_): - db = self.master.db = FakeDBConnector(self) - return db.setup() - d.addCallback(create_poller) - d.addCallback(create_db) - return d - - def tearDown(self): - del os.environ[ENVIRON_2116_KEY] - return self.tearDownChangeSource() - - def gpoFullcommandPattern(self, commandName, *expected_args): - """Match if the command is commandName and arg list start as expected. - - This allows to test a bit more if expected GPO are issued, be it - by obscure failures due to the result not being given. - """ - def matchesSubcommand(bin, given_args, **kwargs): - return bin == commandName and tuple( - given_args[:len(expected_args)]) == expected_args - return matchesSubcommand - - def test_describe(self): - self.assertSubstring("HgPoller", self.poller.describe()) - - def test_hgbin_default(self): - self.assertEqual(self.poller.hgbin, "hg") - - def test_poll_initial(self): - self.repo_ready = False - # Test that environment variables get propagated to subprocesses - # (See #2116) - expected_env = {ENVIRON_2116_KEY: 'TRUE'} - self.addGetProcessOutputExpectEnv(expected_env) - self.expectCommands( - gpo.Expect('hg', 'init', '/some/dir'), - gpo.Expect('hg', 'pull', '-b', 'default', - 'ssh://example.com/foo/baz') - .path('/some/dir'), - gpo.Expect('hg', 'heads', 'default', '--template={rev}' + os.linesep) - .path('/some/dir').stdout("73591"), - gpo.Expect('hg', 'log', '-b', 'default', '-r', '73591:73591', # only fetches that head - '--template={rev}:{node}\\n') - .path('/some/dir').stdout(os.linesep.join(['73591:4423cdb'])), - gpo.Expect('hg', 'log', '-r', '4423cdb', - '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + '{files}' + os.linesep + '{desc|strip}') - .path('/some/dir').stdout(os.linesep.join([ - '1273258100.0 -7200', - 'Bob Test <bobtest@example.org>', - 'file1 dir/file2', - 'This is rev 73591', - ''])), - ) - - # do the poll - d = self.poller.poll() - - # check the results - def check_changes(_): - self.assertEqual(len(self.changes_added), 1) - - change = self.changes_added[0] - self.assertEqual(change['revision'], '4423cdb') - self.assertEqual(change['author'], - 'Bob Test <bobtest@example.org>') - self.assertEqual(change['when_timestamp'], - epoch2datetime(1273258100)), - self.assertEqual(change['files'], ['file1', 'dir/file2']) - self.assertEqual(change['src'], 'hg') - self.assertEqual(change['branch'], 'default') - self.assertEqual(change['comments'], 'This is rev 73591') - - d.addCallback(check_changes) - d.addCallback(self.check_current_rev(73591)) - return d - - def check_current_rev(self, wished): - def check_on_rev(_): - d = self.poller._getCurrentRev() - d.addCallback(lambda oid_rev: self.assertEqual(oid_rev[1], wished)) - return check_on_rev - - @defer.inlineCallbacks - def test_poll_several_heads(self): - # If there are several heads on the named branch, the poller musn't - # climb (good enough for now, ideally it should even go to the common - # ancestor) - self.expectCommands( - gpo.Expect('hg', 'pull', '-b', 'default', - 'ssh://example.com/foo/baz') - .path('/some/dir'), - gpo.Expect('hg', 'heads', 'default', '--template={rev}' + os.linesep) - .path('/some/dir').stdout('5' + os.linesep + '6' + os.linesep), - ) - - yield self.poller._setCurrentRev(3) - - # do the poll: we must stay at rev 3 - d = self.poller.poll() - d.addCallback(self.check_current_rev(3)) - - @defer.inlineCallbacks - def test_poll_regular(self): - # normal operation. There's a previous revision, we get a new one. - self.expectCommands( - gpo.Expect('hg', 'pull', '-b', 'default', - 'ssh://example.com/foo/baz') - .path('/some/dir'), - gpo.Expect('hg', 'heads', 'default', '--template={rev}' + os.linesep) - .path('/some/dir').stdout('5' + os.linesep), - gpo.Expect('hg', 'log', '-b', 'default', '-r', '5:5', - '--template={rev}:{node}\\n') - .path('/some/dir').stdout('5:784bd' + os.linesep), - gpo.Expect('hg', 'log', '-r', '784bd', - '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + '{files}' + os.linesep + '{desc|strip}') - .path('/some/dir').stdout(os.linesep.join([ - '1273258009.0 -7200', - 'Joe Test <joetest@example.org>', - 'file1 file2', - 'Comment for rev 5', - ''])), - ) - - yield self.poller._setCurrentRev(4) - - d = self.poller.poll() - d.addCallback(self.check_current_rev(5)) - - def check_changes(_): - self.assertEquals(len(self.changes_added), 1) - change = self.changes_added[0] - self.assertEqual(change['revision'], '784bd') - self.assertEqual(change['comments'], 'Comment for rev 5') - d.addCallback(check_changes) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail.py deleted file mode 100644 index d4c7d210..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail.py +++ /dev/null @@ -1,99 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -from twisted.trial import unittest -from buildbot.test.util import changesource, dirs -from buildbot.changes import mail - -class TestMaildirSource(changesource.ChangeSourceMixin, dirs.DirsMixin, - unittest.TestCase): - - def setUp(self): - self.maildir = os.path.abspath("maildir") - - d = self.setUpChangeSource() - d.addCallback(lambda _ : self.setUpDirs(self.maildir)) - return d - - def populateMaildir(self): - "create a fake maildir with a fake new message ('newmsg') in it" - newdir = os.path.join(self.maildir, "new") - os.makedirs(newdir) - - curdir = os.path.join(self.maildir, "cur") - os.makedirs(curdir) - - fake_message = "Subject: test\n\nthis is a test" - mailfile = os.path.join(newdir, "newmsg") - with open(mailfile, "w") as f: - f.write(fake_message) - - def assertMailProcessed(self): - self.assertFalse(os.path.exists(os.path.join(self.maildir, "new", "newmsg"))) - self.assertTrue(os.path.exists(os.path.join(self.maildir, "cur", "newmsg"))) - - def tearDown(self): - d = self.tearDownDirs() - d.addCallback(lambda _ : self.tearDownChangeSource()) - return d - - # tests - - def test_describe(self): - mds = mail.MaildirSource(self.maildir) - self.assertSubstring(self.maildir, mds.describe()) - - def test_messageReceived_svn(self): - self.populateMaildir() - mds = mail.MaildirSource(self.maildir) - self.attachChangeSource(mds) - - # monkey-patch in a parse method - def parse(message, prefix): - assert 'this is a test' in message.get_payload() - return ('svn', dict(fake_chdict=1)) - mds.parse = parse - - d = mds.messageReceived('newmsg') - def check(_): - self.assertMailProcessed() - self.assertEqual(len(self.changes_added), 1) - self.assertEqual(self.changes_added[0]['fake_chdict'], 1) - self.assertEqual(self.changes_added[0]['src'], 'svn') - d.addCallback(check) - return d - - def test_messageReceived_bzr(self): - self.populateMaildir() - mds = mail.MaildirSource(self.maildir) - self.attachChangeSource(mds) - - # monkey-patch in a parse method - def parse(message, prefix): - assert 'this is a test' in message.get_payload() - return ('bzr', dict(fake_chdict=1)) - mds.parse = parse - - d = mds.messageReceived('newmsg') - def check(_): - self.assertMailProcessed() - self.assertEqual(len(self.changes_added), 1) - self.assertEqual(self.changes_added[0]['fake_chdict'], 1) - self.assertEqual(self.changes_added[0]['src'], 'bzr') - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail_CVSMaildirSource.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail_CVSMaildirSource.py deleted file mode 100644 index 44e3c7ef..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_mail_CVSMaildirSource.py +++ /dev/null @@ -1,214 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest - -from email import message_from_string -from email.Utils import parsedate_tz, mktime_tz -from buildbot.changes.mail import CVSMaildirSource - -# -# Sample message from CVS version 1.11 -# - -cvs1_11_msg = """From: Andy Howell <andy@example.com> -To: buildbot@example.com -Subject: cvs module MyModuleName -Date: Sat, 07 Aug 2010 11:11:49 +0000 -X-Mailer: Python buildbot-cvs-mail $Revision: 1.3 $ - -Cvsmode: 1.11 -Category: None -CVSROOT: :ext:cvshost.example.com:/cvsroot -Files: base/module/src/make GNUmakefile,1.362,1.363 -Project: MyModuleName -Update of /cvsroot/base/moduel/src/make -In directory cvshost:/tmp/cvs-serv10922 - -Modified Files: - GNUmakefile -Log Message: -Commented out some stuff. -""" - -# -# Sample message from CVS version 1.12 -# -# Paths are handled differently by the two versions -# - -cvs1_12_msg="""Date: Wed, 11 Aug 2010 04:56:44 +0000 -From: andy@example.com -To: buildbot@example.com -Subject: cvs update for project RaiCore -X-Mailer: Python buildbot-cvs-mail $Revision: 1.3 $ - -Cvsmode: 1.12 -Category: None -CVSROOT: :ext:cvshost.example.com:/cvsroot -Files: file1.cpp 1.77 1.78 file2.cpp 1.75 1.76 -Path: base/module/src -Project: MyModuleName -Update of /cvsroot/base/module/src -In directory example.com:/tmp/cvs-serv26648/InsightMonAgent - -Modified Files: - file1.cpp file2.cpp -Log Message: -Changes for changes sake -""" - -class TestCVSMaildirSource(unittest.TestCase): - def test_CVSMaildirSource_create_change_from_cvs1_11msg(self): - m = message_from_string(cvs1_11_msg) - src = CVSMaildirSource('/dev/null') - try: - src, chdict = src.parse( m ) - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict != None) - self.assert_(chdict['author'] == 'andy') - self.assert_(len(chdict['files']) == 1) - self.assert_(chdict['files'][0] == 'base/module/src/make/GNUmakefile') - self.assert_(chdict['comments'] == 'Commented out some stuff.\n') - self.assert_(chdict['isdir'] == False) - self.assert_(chdict['revision'] == '2010-08-07 11:11:49') - dateTuple = parsedate_tz('Sat, 07 Aug 2010 11:11:49 +0000') - self.assert_(chdict['when'] == mktime_tz(dateTuple)) - self.assert_(chdict['branch'] == None) - self.assert_(chdict['repository'] == ':ext:cvshost.example.com:/cvsroot') - self.assert_(chdict['project'] == 'MyModuleName') - self.assert_(len(chdict['properties']) == 0) - self.assert_(src == 'cvs') - - def test_CVSMaildirSource_create_change_from_cvs1_12msg(self): - m = message_from_string(cvs1_12_msg) - src = CVSMaildirSource('/dev/null') - try: - src, chdict = src.parse( m ) - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict != None) - self.assert_(chdict['author'] == 'andy') - self.assert_(len(chdict['files']) == 2) - self.assert_(chdict['files'][0] == 'base/module/src/file1.cpp') - self.assert_(chdict['files'][1] == 'base/module/src/file2.cpp') - self.assert_(chdict['comments'] == 'Changes for changes sake\n') - self.assert_(chdict['isdir'] == False) - self.assert_(chdict['revision'] == '2010-08-11 04:56:44') - dateTuple = parsedate_tz('Wed, 11 Aug 2010 04:56:44 +0000') - self.assert_(chdict['when'] == mktime_tz(dateTuple)) - self.assert_(chdict['branch'] == None) - self.assert_(chdict['repository'] == ':ext:cvshost.example.com:/cvsroot') - self.assert_(chdict['project'] == 'MyModuleName') - self.assert_(len(chdict['properties']) == 0) - self.assert_(src == 'cvs') - - def test_CVSMaildirSource_create_change_from_cvs1_12_with_no_path(self): - msg = cvs1_12_msg.replace('Path: base/module/src', '') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - assert src.parse( m )[1] - except ValueError: - pass - else: - self.fail('Expect ValueError.') - - def test_CVSMaildirSource_create_change_with_bad_cvsmode(self): - # Branch is indicated afer 'Tag:' in modified file list - msg = cvs1_11_msg.replace('Cvsmode: 1.11', 'Cvsmode: 9.99') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - assert src.parse( m )[1] - except ValueError: - pass - else: - self.fail('Expected ValueError') - - def test_CVSMaildirSource_create_change_with_branch(self): - # Branch is indicated afer 'Tag:' in modified file list - msg = cvs1_11_msg.replace(' GNUmakefile', - ' Tag: Test_Branch\n GNUmakefile') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['branch'] == 'Test_Branch') - - def test_CVSMaildirSource_create_change_with_category(self): - msg = cvs1_11_msg.replace('Category: None', 'Category: Test category') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['category'] == 'Test category') - - def test_CVSMaildirSource_create_change_with_no_comment(self): - # Strip off comments - msg = cvs1_11_msg[:cvs1_11_msg.find('Commented out some stuff')] - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['comments'] == None ) - - def test_CVSMaildirSource_create_change_with_no_files(self): - # A message with no files is likely not for us - msg = cvs1_11_msg.replace('Files: base/module/src/make GNUmakefile,1.362,1.363','') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m ) - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict == None ) - - def test_CVSMaildirSource_create_change_with_no_project(self): - msg = cvs1_11_msg.replace('Project: MyModuleName', '') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['project'] == None ) - - def test_CVSMaildirSource_create_change_with_no_repository(self): - msg = cvs1_11_msg.replace('CVSROOT: :ext:cvshost.example.com:/cvsroot', '') - m = message_from_string(msg) - src = CVSMaildirSource('/dev/null') - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['repository'] == None ) - - def test_CVSMaildirSource_create_change_with_property(self): - m = message_from_string(cvs1_11_msg) - propDict = { 'foo' : 'bar' } - src = CVSMaildirSource('/dev/null', properties=propDict) - try: - chdict = src.parse( m )[1] - except: - self.fail('Failed to get change from email message.') - self.assert_(chdict['properties']['foo'] == 'bar') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_manager.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_manager.py deleted file mode 100644 index 7eaec2ee..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_manager.py +++ /dev/null @@ -1,58 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.application import service -from buildbot.changes import manager - -class FakeChangeSource(service.Service): - pass - -class TestChangeManager(unittest.TestCase): - def setUp(self): - self.master = mock.Mock() - self.cm = manager.ChangeManager(self.master) - self.new_config = mock.Mock() - - def make_sources(self, n): - for i in range(n): - src = FakeChangeSource() - src.setName('ChangeSource %d' % i) - yield src - - def test_reconfigService_add(self): - src1, src2 = self.make_sources(2) - src1.setServiceParent(self.cm) - self.new_config.change_sources = [ src1, src2 ] - - d = self.cm.reconfigService(self.new_config) - @d.addCallback - def check(_): - self.assertIdentical(src2.parent, self.cm) - self.assertIdentical(src2.master, self.master) - return d - - def test_reconfigService_remove(self): - src1, = self.make_sources(1) - src1.setServiceParent(self.cm) - self.new_config.change_sources = [ ] - - d = self.cm.reconfigService(self.new_config) - @d.addCallback - def check(_): - self.assertIdentical(src1.parent, None) - self.assertIdentical(src1.master, None) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_p4poller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_p4poller.py deleted file mode 100644 index 02e0f67f..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_p4poller.py +++ /dev/null @@ -1,238 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import time -from twisted.trial import unittest -from buildbot.changes.p4poller import P4Source, get_simple_split, P4PollerError -from buildbot.test.util import changesource, gpo -from buildbot.util import epoch2datetime - -first_p4changes = \ -"""Change 1 on 2006/04/13 by slamb@testclient 'first rev' -""" - -second_p4changes = \ -"""Change 3 on 2006/04/13 by bob@testclient 'short desc truncated' -Change 2 on 2006/04/13 by slamb@testclient 'bar' -""" - -third_p4changes = \ -"""Change 5 on 2006/04/13 by mpatel@testclient 'first rev' -""" - -change_4_log = \ -"""Change 4 by mpatel@testclient on 2006/04/13 21:55:39 - - short desc truncated because this is a long description. -""" - -change_3_log = \ -u"""Change 3 by bob@testclient on 2006/04/13 21:51:39 - - short desc truncated because this is a long description. - ASDF-GUI-P3-\u2018Upgrade Icon\u2019 disappears sometimes. -""" - -change_2_log = \ -"""Change 2 by slamb@testclient on 2006/04/13 21:46:23 - - creation -""" - -p4change = { - 3: change_3_log + -"""Affected files ... - -... //depot/myproject/branch_b/branch_b_file#1 add -... //depot/myproject/branch_b/whatbranch#1 branch -... //depot/myproject/branch_c/whatbranch#1 branch -""", - 2: change_2_log + -"""Affected files ... - -... //depot/myproject/trunk/whatbranch#1 add -... //depot/otherproject/trunk/something#1 add -""", - 5: change_4_log + -"""Affected files ... - -... //depot/myproject/branch_b/branch_b_file#1 add -... //depot/myproject/branch_b#75 edit -... //depot/myproject/branch_c/branch_c_file#1 add -""", -} - - -class TestP4Poller(changesource.ChangeSourceMixin, - gpo.GetProcessOutputMixin, - unittest.TestCase): - def setUp(self): - self.setUpGetProcessOutput() - return self.setUpChangeSource() - - def tearDown(self): - return self.tearDownChangeSource() - - def add_p4_describe_result(self, number, result): - self.expectCommands( - gpo.Expect('p4', 'describe', '-s', str(number)).stdout(result)) - - def makeTime(self, timestring): - datefmt = '%Y/%m/%d %H:%M:%S' - when = time.mktime(time.strptime(timestring, datefmt)) - return epoch2datetime(when) - - # tests - - def test_describe(self): - self.attachChangeSource( - P4Source(p4port=None, p4user=None, - p4base='//depot/myproject/', - split_file=lambda x: x.split('/', 1))) - self.assertSubstring("p4source", self.changesource.describe()) - - def do_test_poll_successful(self, **kwargs): - encoding = kwargs.get('encoding', 'utf8') - self.attachChangeSource( - P4Source(p4port=None, p4user=None, - p4base='//depot/myproject/', - split_file=lambda x: x.split('/', 1), - **kwargs)) - self.expectCommands( - gpo.Expect('p4', 'changes', '-m', '1', '//depot/myproject/...').stdout(first_p4changes), - gpo.Expect('p4', 'changes', '//depot/myproject/...@2,now').stdout(second_p4changes), - ) - encoded_p4change = p4change.copy() - encoded_p4change[3] = encoded_p4change[3].encode(encoding) - self.add_p4_describe_result(2, encoded_p4change[2]) - self.add_p4_describe_result(3, encoded_p4change[3]) - - # The first time, it just learns the change to start at. - self.assert_(self.changesource.last_change is None) - d = self.changesource.poll() - def check_first_check(_): - self.assertEquals(self.changes_added, []) - self.assertEquals(self.changesource.last_change, 1) - d.addCallback(check_first_check) - - # Subsequent times, it returns Change objects for new changes. - d.addCallback(lambda _ : self.changesource.poll()) - def check_second_check(res): - self.assertEquals(len(self.changes_added), 3) - self.assertEquals(self.changesource.last_change, 3) - - # They're supposed to go oldest to newest, so this one must be first. - self.assertEquals(self.changes_added[0], - dict(author='slamb', - files=['whatbranch'], - project='', - comments=change_2_log, - revision='2', - when_timestamp=self.makeTime("2006/04/13 21:46:23"), - branch='trunk')) - - # These two can happen in either order, since they're from the same - # Perforce change. - if self.changes_added[1]['branch'] == 'branch_c': - self.changes_added[1:] = reversed(self.changes_added[1:]) - - self.assertEquals(self.changes_added[1], - dict(author='bob', - files=['branch_b_file', - 'whatbranch'], - project='', - comments=change_3_log, # converted to unicode correctly - revision='3', - when_timestamp=self.makeTime("2006/04/13 21:51:39"), - branch='branch_b')) - self.assertEquals(self.changes_added[2], - dict(author='bob', - files=['whatbranch'], - project='', - comments=change_3_log, # converted to unicode correctly - revision='3', - when_timestamp=self.makeTime("2006/04/13 21:51:39"), - branch='branch_c')) - self.assertAllCommandsRan() - d.addCallback(check_second_check) - return d - - def test_poll_successful_default_encoding(self): - return self.do_test_poll_successful() - - def test_poll_successful_macroman_encoding(self): - return self.do_test_poll_successful(encoding='macroman') - - def test_poll_failed_changes(self): - self.attachChangeSource( - P4Source(p4port=None, p4user=None, - p4base='//depot/myproject/', - split_file=lambda x: x.split('/', 1))) - self.expectCommands( - gpo.Expect('p4', 'changes', '-m', '1', '//depot/myproject/...').stdout('Perforce client error:\n...')) - - # call _poll, so we can catch the failure - d = self.changesource._poll() - return self.assertFailure(d, P4PollerError) - - def test_poll_failed_describe(self): - self.attachChangeSource( - P4Source(p4port=None, p4user=None, - p4base='//depot/myproject/', - split_file=lambda x: x.split('/', 1))) - self.expectCommands( - gpo.Expect('p4', 'changes', '//depot/myproject/...@3,now').stdout(second_p4changes), - ) - self.add_p4_describe_result(2, p4change[2]) - self.add_p4_describe_result(3, 'Perforce client error:\n...') - - self.changesource.last_change = 2 # tell poll() that it's already been called once - - # call _poll, so we can catch the failure - d = self.changesource._poll() - self.assertFailure(d, P4PollerError) - @d.addCallback - def check(_): - # check that 2 was processed OK - self.assertEquals(self.changesource.last_change, 2) - self.assertAllCommandsRan() - return d - - def test_poll_split_file(self): - """Make sure split file works on branch only changes""" - self.attachChangeSource( - P4Source(p4port=None, p4user=None, - p4base='//depot/myproject/', - split_file=get_simple_split)) - self.expectCommands( - gpo.Expect('p4', 'changes', '//depot/myproject/...@51,now').stdout(third_p4changes), - ) - self.add_p4_describe_result(5, p4change[5]) - - self.changesource.last_change = 50 - d = self.changesource.poll() - def check(res): - self.assertEquals(len(self.changes_added), 2) - self.assertEquals(self.changesource.last_change, 5) - self.assertAllCommandsRan() - d.addCallback(check) - return d - -class TestSplit(unittest.TestCase): - def test_get_simple_split(self): - self.assertEqual(get_simple_split('foo/bar'), ('foo', 'bar')) - self.assertEqual(get_simple_split('foo-bar'), (None, None)) - self.assertEqual(get_simple_split('/bar'), ('', 'bar')) - self.assertEqual(get_simple_split('foo/'), ('foo', '')) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_pb.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_pb.py deleted file mode 100644 index 6a34b5d6..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_pb.py +++ /dev/null @@ -1,265 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - - -""" -Test the PB change source. -""" - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.changes import pb -from buildbot.test.util import changesource, pbmanager -from buildbot.util import epoch2datetime - -class TestPBChangeSource( - changesource.ChangeSourceMixin, - pbmanager.PBManagerMixin, - unittest.TestCase): - - def setUp(self): - self.setUpPBChangeSource() - d = self.setUpChangeSource() - @d.addCallback - def setup(_): - self.master.pbmanager = self.pbmanager - - return d - - def test_registration_no_slaveport(self): - return self._test_registration(None, - user='alice', passwd='sekrit') - - def test_registration_global_slaveport(self): - return self._test_registration(('9999', 'alice', 'sekrit'), - slavePort='9999', user='alice', passwd='sekrit') - - def test_registration_custom_port(self): - return self._test_registration(('8888', 'alice', 'sekrit'), - user='alice', passwd='sekrit', port='8888') - - def test_registration_no_userpass(self): - return self._test_registration(('9939', 'change', 'changepw'), - slavePort='9939') - - def test_registration_no_userpass_no_global(self): - return self._test_registration(None) - - @defer.inlineCallbacks - def _test_registration(self, exp_registration, slavePort=None, - **constr_kwargs): - config = mock.Mock() - config.slavePortnum = slavePort - self.attachChangeSource(pb.PBChangeSource(**constr_kwargs)) - - self.startChangeSource() - yield self.changesource.reconfigService(config) - - if exp_registration: - self.assertRegistered(*exp_registration) - else: - self.assertNotRegistered() - - yield self.stopChangeSource() - - if exp_registration: - self.assertUnregistered(*exp_registration) - self.assertEqual(self.changesource.registration, None) - - def test_perspective(self): - self.attachChangeSource(pb.PBChangeSource('alice', 'sekrit', port='8888')) - persp = self.changesource.getPerspective(mock.Mock(), 'alice') - self.assertIsInstance(persp, pb.ChangePerspective) - - def test_describe(self): - cs = pb.PBChangeSource() - self.assertSubstring("PBChangeSource", cs.describe()) - - def test_describe_prefix(self): - cs = pb.PBChangeSource(prefix="xyz") - self.assertSubstring("PBChangeSource", cs.describe()) - self.assertSubstring("xyz", cs.describe()) - - def test_describe_int(self): - cs = pb.PBChangeSource(port=9989) - self.assertSubstring("PBChangeSource", cs.describe()) - - @defer.inlineCallbacks - def test_reconfigService_no_change(self): - config = mock.Mock() - self.attachChangeSource(pb.PBChangeSource(port='9876')) - - self.startChangeSource() - yield self.changesource.reconfigService(config) - - self.assertRegistered('9876', 'change', 'changepw') - - yield self.stopChangeSource() - - self.assertUnregistered('9876', 'change', 'changepw') - - @defer.inlineCallbacks - def test_reconfigService_default_changed(self): - config = mock.Mock() - config.slavePortnum = '9876' - self.attachChangeSource(pb.PBChangeSource()) - - self.startChangeSource() - yield self.changesource.reconfigService(config) - - self.assertRegistered('9876', 'change', 'changepw') - - config.slavePortnum = '1234' - - yield self.changesource.reconfigService(config) - - self.assertUnregistered('9876', 'change', 'changepw') - self.assertRegistered('1234', 'change', 'changepw') - - yield self.stopChangeSource() - - self.assertUnregistered('1234', 'change', 'changepw') - - -class TestChangePerspective(unittest.TestCase): - def setUp(self): - self.added_changes = [] - self.master = mock.Mock() - - def addChange(**chdict): - self.added_changes.append(chdict) - return defer.succeed(mock.Mock()) - self.master.addChange = addChange - - def test_addChange_noprefix(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(who="bar", files=['a'])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author="bar", files=['a']) ]) - d.addCallback(check) - return d - - def test_addChange_codebase(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(who="bar", files=[], codebase='cb')) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author="bar", files=[], codebase='cb') ]) - d.addCallback(check) - return d - - def test_addChange_prefix(self): - cp = pb.ChangePerspective(self.master, 'xx/') - d = cp.perspective_addChange( - dict(who="bar", files=['xx/a', 'yy/b'])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author="bar", files=['a']) ]) - d.addCallback(check) - return d - - def test_addChange_sanitize_None(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange( - dict(project=None, revlink=None, repository=None) - ) - def check(_): - self.assertEqual(self.added_changes, - [ dict(project="", revlink="", repository="", - files=[]) ]) - d.addCallback(check) - return d - - def test_addChange_when_None(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange( - dict(when=None) - ) - def check(_): - self.assertEqual(self.added_changes, - [ dict(when_timestamp=None, files=[]) ]) - d.addCallback(check) - return d - - def test_addChange_files_tuple(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange( - dict(files=('a', 'b')) - ) - def check(_): - self.assertEqual(self.added_changes, - [ dict(files=['a', 'b']) ]) - d.addCallback(check) - return d - - def test_addChange_unicode(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(author=u"\N{SNOWMAN}", - comments=u"\N{SNOWMAN}", - files=[u'\N{VERY MUCH GREATER-THAN}'])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author=u"\N{SNOWMAN}", - comments=u"\N{SNOWMAN}", - files=[u'\N{VERY MUCH GREATER-THAN}']) ]) - d.addCallback(check) - return d - - def test_addChange_unicode_as_bytestring(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(author=u"\N{SNOWMAN}".encode('utf8'), - comments=u"\N{SNOWMAN}".encode('utf8'), - files=[u'\N{VERY MUCH GREATER-THAN}'.encode('utf8')])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author=u"\N{SNOWMAN}", - comments=u"\N{SNOWMAN}", - files=[u'\N{VERY MUCH GREATER-THAN}']) ]) - d.addCallback(check) - return d - - def test_addChange_non_utf8_bytestring(self): - cp = pb.ChangePerspective(self.master, None) - bogus_utf8 = '\xff\xff\xff\xff' - replacement = bogus_utf8.decode('utf8', 'replace') - d = cp.perspective_addChange(dict(author=bogus_utf8, files=['a'])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(author=replacement, files=['a']) ]) - d.addCallback(check) - return d - - def test_addChange_old_param_names(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(isdir=1, who='me', when=1234, - files=[])) - def check(_): - self.assertEqual(self.added_changes, - [ dict(is_dir=1, author='me', files=[], - when_timestamp=epoch2datetime(1234)) ]) - d.addCallback(check) - return d - - def test_createUserObject_git_src(self): - cp = pb.ChangePerspective(self.master, None) - d = cp.perspective_addChange(dict(who="c <h@c>", src='git')) - def check_change(_): - self.assertEqual(self.added_changes, [ dict(author="c <h@c>", - files=[], - src='git') ]) - d.addCallback(check_change) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_svnpoller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_svnpoller.py deleted file mode 100644 index be288d8d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_changes_svnpoller.py +++ /dev/null @@ -1,627 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import xml.dom.minidom -from twisted.internet import defer -from twisted.trial import unittest -from buildbot.test.util import changesource, gpo, compat -from buildbot.changes import svnpoller - -# this is the output of "svn info --xml -# svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" -prefix_output = """\ -<?xml version="1.0"?> -<info> -<entry - kind="dir" - path="trunk" - revision="18354"> -<url>svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk</url> -<repository> -<root>svn+ssh://svn.twistedmatrix.com/svn/Twisted</root> -<uuid>bbbe8e31-12d6-0310-92fd-ac37d47ddeeb</uuid> -</repository> -<commit - revision="18352"> -<author>jml</author> -<date>2006-10-01T02:37:34.063255Z</date> -</commit> -</entry> -</info> -""" - -# and this is "svn info --xml svn://svn.twistedmatrix.com/svn/Twisted". I -# think this is kind of a degenerate case.. it might even be a form of error. -prefix_output_2 = """\ -<?xml version="1.0"?> -<info> -</info> -""" - -# this is the svn info output for a local repository, svn info --xml -# file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository -prefix_output_3 = """\ -<?xml version="1.0"?> -<info> -<entry - kind="dir" - path="SVN-Repository" - revision="3"> -<url>file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</url> -<repository> -<root>file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</root> -<uuid>c0f47ff4-ba1e-0410-96b5-d44cc5c79e7f</uuid> -</repository> -<commit - revision="3"> -<author>warner</author> -<date>2006-10-01T07:37:04.182499Z</date> -</commit> -</entry> -</info> -""" - -# % svn info --xml file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk - -prefix_output_4 = """\ -<?xml version="1.0"?> -<info> -<entry - kind="dir" - path="trunk" - revision="3"> -<url>file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk</url> -<repository> -<root>file:///home/warner/stuff/Projects/BuildBot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</root> -<uuid>c0f47ff4-ba1e-0410-96b5-d44cc5c79e7f</uuid> -</repository> -<commit - revision="1"> -<author>warner</author> -<date>2006-10-01T07:37:02.286440Z</date> -</commit> -</entry> -</info> -""" - - - -# output from svn log on .../SVN-Repository/sample -# (so it includes trunk and branches) -sample_base = ("file:///usr/home/warner/stuff/Projects/BuildBot/trees/misc/" + - "_trial_temp/test_vc/repositories/SVN-Repository/sample") -sample_logentries = [None] * 6 - -sample_logentries[5] = """\ -<logentry - revision="6"> -<author>warner</author> -<date>2006-10-01T19:35:16.165664Z</date> -<paths> -<path - action="D">/sample/branch/version.c</path> -</paths> -<msg>revised_to_2</msg> -</logentry> -""" - -sample_logentries[4] = """\ -<logentry - revision="5"> -<author>warner</author> -<date>2006-10-01T19:35:16.165664Z</date> -<paths> -<path - action="D">/sample/branch</path> -</paths> -<msg>revised_to_2</msg> -</logentry> -""" - -sample_logentries[3] = """\ -<logentry - revision="4"> -<author>warner</author> -<date>2006-10-01T19:35:16.165664Z</date> -<paths> -<path - action="M">/sample/trunk/version.c</path> -</paths> -<msg>revised_to_2</msg> -</logentry> -""" - -sample_logentries[2] = """\ -<logentry - revision="3"> -<author>warner</author> -<date>2006-10-01T19:35:10.215692Z</date> -<paths> -<path - action="M">/sample/branch/main.c</path> -</paths> -<msg>commit_on_branch</msg> -</logentry> -""" - -sample_logentries[1] = """\ -<logentry - revision="2"> -<author>warner</author> -<date>2006-10-01T19:35:09.154973Z</date> -<paths> -<path - copyfrom-path="/sample/trunk" - copyfrom-rev="1" - action="A">/sample/branch</path> -</paths> -<msg>make_branch</msg> -</logentry> -""" - -sample_logentries[0] = """\ -<logentry - revision="1"> -<author>warner</author> -<date>2006-10-01T19:35:08.642045Z</date> -<paths> -<path - action="A">/sample</path> -<path - action="A">/sample/trunk</path> -<path - action="A">/sample/trunk/subdir/subdir.c</path> -<path - action="A">/sample/trunk/main.c</path> -<path - action="A">/sample/trunk/version.c</path> -<path - action="A">/sample/trunk/subdir</path> -</paths> -<msg>sample_project_files</msg> -</logentry> -""" - -sample_info_output = """\ -<?xml version="1.0"?> -<info> -<entry - kind="dir" - path="sample" - revision="4"> -<url>file:///usr/home/warner/stuff/Projects/BuildBot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository/sample</url> -<repository> -<root>file:///usr/home/warner/stuff/Projects/BuildBot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository</root> -<uuid>4f94adfc-c41e-0410-92d5-fbf86b7c7689</uuid> -</repository> -<commit - revision="4"> -<author>warner</author> -<date>2006-10-01T19:35:16.165664Z</date> -</commit> -</entry> -</info> -""" - - -changes_output_template = """\ -<?xml version="1.0"?> -<log> -%s</log> -""" - -def make_changes_output(maxrevision): - # return what 'svn log' would have just after the given revision was - # committed - logs = sample_logentries[0:maxrevision] - assert len(logs) == maxrevision - logs.reverse() - output = changes_output_template % ("".join(logs)) - return output - -def make_logentry_elements(maxrevision): - "return the corresponding logentry elements for the given revisions" - doc = xml.dom.minidom.parseString(make_changes_output(maxrevision)) - return doc.getElementsByTagName("logentry") - -def split_file(path): - pieces = path.split("/") - if pieces[0] == "branch": - return dict(branch="branch", path="/".join(pieces[1:])) - if pieces[0] == "trunk": - return dict(path="/".join(pieces[1:])) - raise RuntimeError("there shouldn't be any files like %r" % path) - - -class TestSVNPoller(gpo.GetProcessOutputMixin, - changesource.ChangeSourceMixin, - unittest.TestCase): - - def setUp(self): - self.setUpGetProcessOutput() - return self.setUpChangeSource() - - def tearDown(self): - return self.tearDownChangeSource() - - def attachSVNPoller(self, *args, **kwargs): - s = svnpoller.SVNPoller(*args, **kwargs) - self.attachChangeSource(s) - return s - - def add_svn_command_result(self, command, result): - self.expectCommands( - gpo.Expect('svn', command).stdout(result)) - - - # tests - - def test_describe(self): - s = self.attachSVNPoller('file://') - self.assertSubstring("SVNPoller", s.describe()) - - def test_strip_svnurl(self): - base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" - s = self.attachSVNPoller(base + "/") - self.failUnlessEqual(s.svnurl, base) - - def do_test_get_prefix(self, base, output, expected): - s = self.attachSVNPoller(base) - self.expectCommands(gpo.Expect('svn', 'info', '--xml', '--non-interactive', base).stdout(output)) - d = s.get_prefix() - def check(prefix): - self.failUnlessEqual(prefix, expected) - self.assertAllCommandsRan() - d.addCallback(check) - return d - - def test_get_prefix_1(self): - base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" - return self.do_test_get_prefix(base, prefix_output, 'trunk') - - def test_get_prefix_2(self): - base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted" - return self.do_test_get_prefix(base, prefix_output_2, '') - - def test_get_prefix_3(self): - base = ("file:///home/warner/stuff/Projects/BuildBot/trees/" + - "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository") - return self.do_test_get_prefix(base, prefix_output_3, '') - - def test_get_prefix_4(self): - base = ("file:///home/warner/stuff/Projects/BuildBot/trees/" + - "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk") - return self.do_test_get_prefix(base, prefix_output_3, 'sample/trunk') - - def test_log_parsing(self): - s = self.attachSVNPoller('file:///foo') - output = make_changes_output(4) - entries = s.parse_logs(output) - # no need for elaborate assertions here; this is minidom's logic - self.assertEqual(len(entries), 4) - - def test_get_new_logentries(self): - s = self.attachSVNPoller('file:///foo') - entries = make_logentry_elements(4) - - s.last_change = 4 - new = s.get_new_logentries(entries) - self.assertEqual(s.last_change, 4) - self.assertEqual(len(new), 0) - - s.last_change = 3 - new = s.get_new_logentries(entries) - self.assertEqual(s.last_change, 4) - self.assertEqual(len(new), 1) - - s.last_change = 1 - new = s.get_new_logentries(entries) - self.assertEqual(s.last_change, 4) - self.assertEqual(len(new), 3) - - # special case: if last_change is None, then no new changes are queued - s.last_change = None - new = s.get_new_logentries(entries) - self.assertEqual(s.last_change, 4) - self.assertEqual(len(new), 0) - - def test_create_changes(self): - base = ("file:///home/warner/stuff/Projects/BuildBot/trees/" + - "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample") - s = self.attachSVNPoller(base, split_file=split_file) - s._prefix = "sample" - - logentries = dict(zip(xrange(1, 7), reversed(make_logentry_elements(6)))) - changes = s.create_changes(reversed([ logentries[3], logentries[2] ])) - self.failUnlessEqual(len(changes), 2) - # note that parsing occurs in reverse - self.failUnlessEqual(changes[0]['branch'], "branch") - self.failUnlessEqual(changes[0]['revision'], '2') - self.failUnlessEqual(changes[0]['project'], '') - self.failUnlessEqual(changes[0]['repository'], base) - self.failUnlessEqual(changes[1]['branch'], "branch") - self.failUnlessEqual(changes[1]['files'], ["main.c"]) - self.failUnlessEqual(changes[1]['revision'], '3') - self.failUnlessEqual(changes[1]['project'], '') - self.failUnlessEqual(changes[1]['repository'], base) - - changes = s.create_changes([ logentries[4] ]) - self.failUnlessEqual(len(changes), 1) - self.failUnlessEqual(changes[0]['branch'], None) - self.failUnlessEqual(changes[0]['revision'], '4') - self.failUnlessEqual(changes[0]['files'], ["version.c"]) - - # r5 should *not* create a change as it's a branch deletion - changes = s.create_changes([ logentries[5] ]) - self.failUnlessEqual(len(changes), 0) - - # r6 should create a change as it's not deleting an entire branch - changes = s.create_changes([ logentries[6] ]) - self.failUnlessEqual(len(changes), 1) - self.failUnlessEqual(changes[0]['branch'], 'branch') - self.failUnlessEqual(changes[0]['revision'], '6') - self.failUnlessEqual(changes[0]['files'], ["version.c"]) - - def makeInfoExpect(self): - return gpo.Expect('svn', 'info', '--xml', '--non-interactive', sample_base, - '--username=dustin', '--password=bbrocks') - - def makeLogExpect(self): - return gpo.Expect('svn', 'log', '--xml', '--verbose', '--non-interactive', - '--username=dustin', '--password=bbrocks', - '--limit=100', sample_base) - def test_create_changes_overriden_project(self): - def custom_split_file(path): - f = split_file(path) - if f: - f["project"] = "overriden-project" - f["repository"] = "overriden-repository" - f["codebase"] = "overriden-codebase" - return f - - base = ("file:///home/warner/stuff/Projects/BuildBot/trees/" + - "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample") - s = self.attachSVNPoller(base, split_file=custom_split_file) - s._prefix = "sample" - - logentries = dict(zip(xrange(1, 7), reversed(make_logentry_elements(6)))) - changes = s.create_changes(reversed([ logentries[3], logentries[2] ])) - self.failUnlessEqual(len(changes), 2) - - # note that parsing occurs in reverse - self.failUnlessEqual(changes[0]['branch'], "branch") - self.failUnlessEqual(changes[0]['revision'], '2') - self.failUnlessEqual(changes[0]['project'], "overriden-project") - self.failUnlessEqual(changes[0]['repository'], "overriden-repository") - self.failUnlessEqual(changes[0]['codebase'], "overriden-codebase") - - self.failUnlessEqual(changes[1]['branch'], "branch") - self.failUnlessEqual(changes[1]['files'], ["main.c"]) - self.failUnlessEqual(changes[1]['revision'], '3') - self.failUnlessEqual(changes[1]['project'], "overriden-project") - self.failUnlessEqual(changes[1]['repository'], "overriden-repository") - self.failUnlessEqual(changes[1]['codebase'], "overriden-codebase") - - def test_poll(self): - s = self.attachSVNPoller(sample_base, split_file=split_file, - svnuser='dustin', svnpasswd='bbrocks') - - d = defer.succeed(None) - - - self.expectCommands( - self.makeInfoExpect().stdout(sample_info_output), - self.makeLogExpect().stdout(make_changes_output(1)), - self.makeLogExpect().stdout(make_changes_output(1)), - self.makeLogExpect().stdout(make_changes_output(2)), - self.makeLogExpect().stdout(make_changes_output(4)), - ) - # fire it the first time; it should do nothing - d.addCallback(lambda _ : s.poll()) - def check_first(_): - # no changes generated on the first iteration - self.assertEqual(self.changes_added, []) - self.failUnlessEqual(s.last_change, 1) - d.addCallback(check_first) - - # now fire it again, nothing changing - d.addCallback(lambda _ : s.poll()) - def check_second(_): - self.assertEqual(self.changes_added, []) - self.failUnlessEqual(s.last_change, 1) - d.addCallback(check_second) - - # and again, with r2 this time - d.addCallback(lambda _ : s.poll()) - def check_third(_): - self.assertEqual(len(self.changes_added), 1) - c = self.changes_added[0] - self.failUnlessEqual(c['branch'], "branch") - self.failUnlessEqual(c['revision'], '2') - self.failUnlessEqual(c['files'], ['']) # signals a new branch - self.failUnlessEqual(c['comments'], "make_branch") - self.failUnlessEqual(c['src'], "svn") - self.failUnlessEqual(s.last_change, 2) - d.addCallback(check_third) - - # and again with both r3 and r4 appearing together - def setup_fourth(_): - self.changes_added = [] - d.addCallback(setup_fourth) - d.addCallback(lambda _ : s.poll()) - def check_fourth(_): - self.assertEqual(len(self.changes_added), 2) - c = self.changes_added[0] - self.failUnlessEqual(c['branch'], "branch") - self.failUnlessEqual(c['revision'], '3') - self.failUnlessEqual(c['files'], ["main.c"]) - self.failUnlessEqual(c['comments'], "commit_on_branch") - self.failUnlessEqual(c['src'], "svn") - c = self.changes_added[1] - self.failUnlessEqual(c['branch'], None) - self.failUnlessEqual(c['revision'], '4') - self.failUnlessEqual(c['files'], ["version.c"]) - self.failUnlessEqual(c['comments'], "revised_to_2") - self.failUnlessEqual(c['src'], "svn") - self.failUnlessEqual(s.last_change, 4) - self.assertAllCommandsRan() - d.addCallback(check_fourth) - - return d - - @compat.usesFlushLoggedErrors - def test_poll_get_prefix_exception(self): - s = self.attachSVNPoller(sample_base, split_file=split_file, - svnuser='dustin', svnpasswd='bbrocks') - - self.expectCommands( - self.makeInfoExpect().stderr("error")) - d = s.poll() - @d.addCallback - def check(_): - # should have logged the RuntimeError, but not errback'd from poll - self.assertEqual(len(self.flushLoggedErrors(IOError)), 1) - self.assertAllCommandsRan() - return d - - @compat.usesFlushLoggedErrors - def test_poll_get_logs_exception(self): - s = self.attachSVNPoller(sample_base, split_file=split_file, - svnuser='dustin', svnpasswd='bbrocks') - s._prefix = "abc" # skip the get_prefix stuff - - self.expectCommands( - self.makeLogExpect().stderr("some error")) - d = s.poll() - @d.addCallback - def check(_): - # should have logged the RuntimeError, but not errback'd from poll - self.assertEqual(len(self.flushLoggedErrors(IOError)), 1) - self.assertAllCommandsRan() - return d - - def test_cachepath_empty(self): - cachepath = os.path.abspath('revcache') - if os.path.exists(cachepath): - os.unlink(cachepath) - s = self.attachSVNPoller(sample_base, cachepath=cachepath) - self.assertEqual(s.last_change, None) - - def test_cachepath_full(self): - cachepath = os.path.abspath('revcache') - with open(cachepath, "w") as f: - f.write('33') - s = self.attachSVNPoller(sample_base, cachepath=cachepath) - self.assertEqual(s.last_change, 33) - - s.last_change = 44 - s.finished_ok(None) - with open(cachepath) as f: - self.assertEqual(f.read().strip(), '44') - - @compat.usesFlushLoggedErrors - def test_cachepath_bogus(self): - cachepath = os.path.abspath('revcache') - with open(cachepath, "w") as f: - f.write('nine') - s = self.attachSVNPoller(sample_base, cachepath=cachepath) - self.assertEqual(s.last_change, None) - self.assertEqual(s.cachepath, None) - # it should have called log.err once with a ValueError - self.assertEqual(len(self.flushLoggedErrors(ValueError)), 1) - - def test_constructor_pollinterval(self): - self.attachSVNPoller(sample_base, pollinterval=100) # just don't fail! - - def test_extra_args(self): - extra_args = ['--no-auth-cache',] - base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" - - s = self.attachSVNPoller(svnurl=base, extra_args=extra_args) - self.failUnlessEqual(s.extra_args, extra_args) - -class TestSplitFile(unittest.TestCase): - def test_split_file_alwaystrunk(self): - self.assertEqual(svnpoller.split_file_alwaystrunk('foo'), dict(path='foo')) - - def test_split_file_branches_trunk(self): - self.assertEqual( - svnpoller.split_file_branches('trunk/'), - (None, '')) - - def test_split_file_branches_trunk_subdir(self): - self.assertEqual( - svnpoller.split_file_branches('trunk/subdir/'), - (None, 'subdir/')) - - def test_split_file_branches_trunk_subfile(self): - self.assertEqual( - svnpoller.split_file_branches('trunk/subdir/file.c'), - (None, 'subdir/file.c')) - - def test_split_file_branches_trunk_invalid(self): - # file named trunk (not a directory): - self.assertEqual( - svnpoller.split_file_branches('trunk'), - None) - - def test_split_file_branches_branch(self): - self.assertEqual( - svnpoller.split_file_branches('branches/1.5.x/'), - ('branches/1.5.x', '')) - - def test_split_file_branches_branch_subdir(self): - self.assertEqual( - svnpoller.split_file_branches('branches/1.5.x/subdir/'), - ('branches/1.5.x', 'subdir/')) - - def test_split_file_branches_branch_subfile(self): - self.assertEqual( - svnpoller.split_file_branches('branches/1.5.x/subdir/file.c'), - ('branches/1.5.x', 'subdir/file.c')) - - def test_split_file_branches_branch_invalid(self): - # file named branches/1.5.x (not a directory): - self.assertEqual( - svnpoller.split_file_branches('branches/1.5.x'), - None) - - def test_split_file_branches_otherdir(self): - # other dirs are ignored: - self.assertEqual( - svnpoller.split_file_branches('tags/testthis/subdir/'), - None) - - def test_split_file_branches_otherfile(self): - # other files are ignored: - self.assertEqual( - svnpoller.split_file_branches('tags/testthis/subdir/file.c'), - None) - - def test_split_file_projects_branches(self): - self.assertEqual( - svnpoller.split_file_projects_branches('buildbot/trunk/subdir/file.c'), - dict(project='buildbot', path='subdir/file.c')) - self.assertEqual( - svnpoller.split_file_projects_branches('buildbot/branches/1.5.x/subdir/file.c'), - dict(project='buildbot', branch='branches/1.5.x', path='subdir/file.c')) - # tags are ignored: - self.assertEqual( - svnpoller.split_file_projects_branches('buildbot/tags/testthis/subdir/file.c'), - None) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_sendchange.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_sendchange.py deleted file mode 100644 index a403694d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_sendchange.py +++ /dev/null @@ -1,237 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - - -import mock -from twisted.trial import unittest -from twisted.spread import pb -from twisted.internet import defer, reactor -from buildbot.clients import sendchange - -class Sender(unittest.TestCase): - - def setUp(self): - # patch out some PB components and make up some mocks - self.patch(pb, 'PBClientFactory', self._fake_PBClientFactory) - self.patch(reactor, 'connectTCP', self._fake_connectTCP) - - self.factory = mock.Mock(name='PBClientFactory') - self.factory.login = self._fake_login - self.factory.login_d = defer.Deferred() - - self.remote = mock.Mock(name='PB Remote') - self.remote.callRemote = self._fake_callRemote - self.remote.broker.transport.loseConnection = self._fake_loseConnection - - # results - self.creds = None - self.conn_host = self.conn_port = None - self.lostConnection = False - self.added_changes = [] - self.vc_used = None - - def _fake_PBClientFactory(self): - return self.factory - - def _fake_login(self, creds): - self.creds = creds - return self.factory.login_d - - def _fake_connectTCP(self, host, port, factory): - self.conn_host = host - self.conn_port = port - self.assertIdentical(factory, self.factory) - self.factory.login_d.callback(self.remote) - - def _fake_callRemote(self, method, change): - self.assertEqual(method, 'addChange') - self.added_changes.append(change) - return defer.succeed(None) - - def _fake_loseConnection(self): - self.lostConnection = True - - def assertProcess(self, host, port, username, password, changes): - self.assertEqual([host, port, username, password, changes], - [ self.conn_host, self.conn_port, - self.creds.username, self.creds.password, - self.added_changes]) - - def test_send_minimal(self): - s = sendchange.Sender('localhost:1234') - d = s.send('branch', 'rev', 'comm', ['a']) - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project='', repository='', who=None, files=['a'], - comments='comm', branch='branch', revision='rev', - category=None, when=None, properties={}, revlink='', - src=None)]) - d.addCallback(check) - return d - - def test_send_auth(self): - s = sendchange.Sender('localhost:1234', auth=('me','sekrit')) - d = s.send('branch', 'rev', 'comm', ['a']) - def check(_): - self.assertProcess('localhost', 1234, 'me', 'sekrit', [ - dict(project='', repository='', who=None, files=['a'], - comments='comm', branch='branch', revision='rev', - category=None, when=None, properties={}, revlink='', - src=None)]) - d.addCallback(check) - return d - - def test_send_full(self): - s = sendchange.Sender('localhost:1234') - d = s.send('branch', 'rev', 'comm', ['a'], who='me', category='cats', - when=1234, properties={'a':'b'}, repository='r', vc='git', - project='p', revlink='rl') - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project='p', repository='r', who='me', files=['a'], - comments='comm', branch='branch', revision='rev', - category='cats', when=1234, properties={'a':'b'}, - revlink='rl', src='git')]) - d.addCallback(check) - return d - - def test_send_files_tuple(self): - # 'buildbot sendchange' sends files as a tuple, rather than a list.. - s = sendchange.Sender('localhost:1234') - d = s.send('branch', 'rev', 'comm', ('a', 'b')) - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project='', repository='', who=None, files=['a', 'b'], - comments='comm', branch='branch', revision='rev', - category=None, when=None, properties={}, revlink='', - src=None)]) - d.addCallback(check) - return d - - def test_send_codebase(self): - s = sendchange.Sender('localhost:1234') - d = s.send('branch', 'rev', 'comm', ['a'], codebase='mycb') - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project='', repository='', who=None, files=['a'], - comments='comm', branch='branch', revision='rev', - category=None, when=None, properties={}, revlink='', - src=None, codebase='mycb')]) - d.addCallback(check) - return d - - def test_send_unicode(self): - s = sendchange.Sender('localhost:1234') - d = s.send(u'\N{DEGREE SIGN}', - u'\U0001f49e', - u'\N{POSTAL MARK FACE}', - [u'\U0001F4C1'], - project=u'\N{SKULL AND CROSSBONES}', - repository=u'\N{SNOWMAN}', - who=u'\N{THAI CHARACTER KHOMUT}', - category=u'\U0001F640', - when=1234, - properties={u'\N{LATIN SMALL LETTER A WITH MACRON}':'b'}, - revlink=u'\U0001F517') - - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project=u'\N{SKULL AND CROSSBONES}', - repository=u'\N{SNOWMAN}', - who=u'\N{THAI CHARACTER KHOMUT}', - files=[u'\U0001F4C1'], # FILE FOLDER - comments=u'\N{POSTAL MARK FACE}', - branch=u'\N{DEGREE SIGN}', - revision=u'\U0001f49e', # REVOLVING HEARTS - category=u'\U0001F640', # WEARY CAT FACE - when=1234, - properties={u'\N{LATIN SMALL LETTER A WITH MACRON}':'b'}, - revlink=u'\U0001F517', # LINK SYMBOL - src=None)]) - d.addCallback(check) - return d - - def test_send_unicode_utf8(self): - s = sendchange.Sender('localhost:1234') - - d = s.send(u'\N{DEGREE SIGN}'.encode('utf8'), - u'\U0001f49e'.encode('utf8'), - u'\N{POSTAL MARK FACE}'.encode('utf8'), - [u'\U0001F4C1'.encode('utf8')], - project=u'\N{SKULL AND CROSSBONES}'.encode('utf8'), - repository=u'\N{SNOWMAN}'.encode('utf8'), - who=u'\N{THAI CHARACTER KHOMUT}'.encode('utf8'), - category=u'\U0001F640'.encode('utf8'), - when=1234, - properties={ - u'\N{LATIN SMALL LETTER A WITH MACRON}'.encode('utf8') - : 'b'}, - revlink=u'\U0001F517'.encode('utf8')) - - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project=u'\N{SKULL AND CROSSBONES}', - repository=u'\N{SNOWMAN}', - who=u'\N{THAI CHARACTER KHOMUT}', - files=[u'\U0001F4C1'], # FILE FOLDER - comments=u'\N{POSTAL MARK FACE}', - branch=u'\N{DEGREE SIGN}', - revision=u'\U0001f49e', # REVOLVING HEARTS - category=u'\U0001F640', # WEARY CAT FACE - when=1234, - ## NOTE: not decoded! - properties={'\xc4\x81':'b'}, - revlink=u'\U0001F517', # LINK SYMBOL - src=None)]) - d.addCallback(check) - return d - - def test_send_unicode_latin1(self): - # hand send() a bunch of latin1 strings, and expect them recoded - # to unicode - s = sendchange.Sender('localhost:1234', encoding='latin1') - - d = s.send(u'\N{YEN SIGN}'.encode('latin1'), - u'\N{POUND SIGN}'.encode('latin1'), - u'\N{BROKEN BAR}'.encode('latin1'), - [u'\N{NOT SIGN}'.encode('latin1')], - project=u'\N{DEGREE SIGN}'.encode('latin1'), - repository=u'\N{SECTION SIGN}'.encode('latin1'), - who=u'\N{MACRON}'.encode('latin1'), - category=u'\N{PILCROW SIGN}'.encode('latin1'), - when=1234, - properties={ - u'\N{SUPERSCRIPT ONE}'.encode('latin1') - : 'b'}, - revlink=u'\N{INVERTED QUESTION MARK}'.encode('latin1')) - - def check(_): - self.assertProcess('localhost', 1234, 'change', 'changepw', [ - dict(project=u'\N{DEGREE SIGN}', - repository=u'\N{SECTION SIGN}', - who=u'\N{MACRON}', - files=[u'\N{NOT SIGN}'], - comments=u'\N{BROKEN BAR}', - branch=u'\N{YEN SIGN}', - revision=u'\N{POUND SIGN}', - category=u'\N{PILCROW SIGN}', - when=1234, - ## NOTE: not decoded! - properties={'\xb9':'b'}, - revlink=u'\N{INVERTED QUESTION MARK}', - src=None)]) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_tryclient.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_tryclient.py deleted file mode 100644 index e4f61d3c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_tryclient.py +++ /dev/null @@ -1,135 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -from twisted.trial import unittest - -from buildbot.clients import tryclient -from buildbot.util import json - - -class createJobfile(unittest.TestCase): - - def makeNetstring(self, *strings): - return ''.join(['%d:%s,' % (len(s), s) for s in strings]) - - # version 1 is deprecated and not produced by the try client - - def test_createJobfile_v2_one_builder(self): - jobid = '123-456' - branch = 'branch' - baserev = 'baserev' - patch_level = 0 - patch_body = 'diff...' - repository = 'repo' - project = 'proj' - who = None - comment = None - builderNames = ['runtests'] - properties = {} - job = tryclient.createJobfile( - jobid, branch, baserev, patch_level, patch_body, repository, - project, who, comment, builderNames, properties) - jobstr = self.makeNetstring( - '2', jobid, branch, baserev, str(patch_level), patch_body, - repository, project, builderNames[0]) - self.assertEqual(job, jobstr) - - def test_createJobfile_v2_two_builders(self): - jobid = '123-456' - branch = 'branch' - baserev = 'baserev' - patch_level = 0 - patch_body = 'diff...' - repository = 'repo' - project = 'proj' - who = None - comment = None - builderNames = ['runtests', 'moretests'] - properties = {} - job = tryclient.createJobfile( - jobid, branch, baserev, patch_level, patch_body, repository, - project, who, comment, builderNames, properties) - jobstr = self.makeNetstring( - '2', jobid, branch, baserev, str(patch_level), patch_body, - repository, project, builderNames[0], builderNames[1]) - self.assertEqual(job, jobstr) - - def test_createJobfile_v3(self): - jobid = '123-456' - branch = 'branch' - baserev = 'baserev' - patch_level = 0 - patch_body = 'diff...' - repository = 'repo' - project = 'proj' - who = 'someuser' - comment = None - builderNames = ['runtests'] - properties = {} - job = tryclient.createJobfile( - jobid, branch, baserev, patch_level, patch_body, repository, - project, who, comment, builderNames, properties) - jobstr = self.makeNetstring( - '3', jobid, branch, baserev, str(patch_level), patch_body, - repository, project, who, builderNames[0]) - self.assertEqual(job, jobstr) - - def test_createJobfile_v4(self): - jobid = '123-456' - branch = 'branch' - baserev = 'baserev' - patch_level = 0 - patch_body = 'diff...' - repository = 'repo' - project = 'proj' - who = 'someuser' - comment = 'insightful comment' - builderNames = ['runtests'] - properties = {} - job = tryclient.createJobfile( - jobid, branch, baserev, patch_level, patch_body, repository, - project, who, comment, builderNames, properties) - jobstr = self.makeNetstring( - '4', jobid, branch, baserev, str(patch_level), patch_body, - repository, project, who, comment, builderNames[0]) - self.assertEqual(job, jobstr) - - def test_createJobfile_v5(self): - jobid = '123-456' - branch = 'branch' - baserev = 'baserev' - patch_level = 0 - patch_body = 'diff...' - repository = 'repo' - project = 'proj' - who = 'someuser' - comment = 'insightful comment' - builderNames = ['runtests'] - properties = {'foo': 'bar'} - job = tryclient.createJobfile( - jobid, branch, baserev, patch_level, patch_body, repository, - project, who, comment, builderNames, properties) - jobstr = self.makeNetstring( - '5', - json.dumps({ - 'jobid': jobid, 'branch': branch, 'baserev': baserev, - 'patch_level': patch_level, 'patch_body': patch_body, - 'repository': repository, 'project': project, 'who': who, - 'comment': comment, 'builderNames': builderNames, - 'properties': properties, - })) - self.assertEqual(job, jobstr) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_usersclient.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_usersclient.py deleted file mode 100644 index 23f1ea1a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_clients_usersclient.py +++ /dev/null @@ -1,86 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.spread import pb -from twisted.internet import defer, reactor -from buildbot.clients import usersclient - -class TestUsersClient(unittest.TestCase): - - def setUp(self): - # patch out some PB components and make up some mocks - self.patch(pb, 'PBClientFactory', self._fake_PBClientFactory) - self.patch(reactor, 'connectTCP', self._fake_connectTCP) - - self.factory = mock.Mock(name='PBClientFactory') - self.factory.login = self._fake_login - self.factory.login_d = defer.Deferred() - - self.remote = mock.Mock(name='PB Remote') - self.remote.callRemote = self._fake_callRemote - self.remote.broker.transport.loseConnection = self._fake_loseConnection - - # results - self.conn_host = self.conn_port = None - self.lostConnection = False - - def _fake_PBClientFactory(self): - return self.factory - - def _fake_login(self, creds): - return self.factory.login_d - - def _fake_connectTCP(self, host, port, factory): - self.conn_host = host - self.conn_port = port - self.assertIdentical(factory, self.factory) - self.factory.login_d.callback(self.remote) - - def _fake_callRemote(self, method, op, bb_username, bb_password, ids, info): - self.assertEqual(method, 'commandline') - self.called_with = dict(op=op, bb_username=bb_username, - bb_password=bb_password, ids=ids, info=info) - return defer.succeed(None) - - def _fake_loseConnection(self): - self.lostConnection = True - - def assertProcess(self, host, port, called_with): - self.assertEqual([host, port, called_with], - [self.conn_host, self.conn_port, self.called_with]) - - def test_usersclient_info(self): - uc = usersclient.UsersClient('localhost', "user", "userpw", 1234) - d = uc.send('update', 'bb_user', 'hashed_bb_pass', None, - [{'identifier':'x', 'svn':'x'}]) - def check(_): - self.assertProcess('localhost', 1234, - dict(op='update', bb_username='bb_user', - bb_password='hashed_bb_pass', ids=None, - info=[dict(identifier='x', svn='x')])) - d.addCallback(check) - return d - - def test_usersclient_ids(self): - uc = usersclient.UsersClient('localhost', "user", "userpw", 1234) - d = uc.send('remove', None, None, ['x'], None) - def check(_): - self.assertProcess('localhost', 1234, - dict(op='remove', bb_username=None, - bb_password=None, ids=['x'], info=None)) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_config.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_config.py deleted file mode 100644 index 9b6f6c1d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_config.py +++ /dev/null @@ -1,1207 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import re -import os -import textwrap -import mock -import __builtin__ -from zope.interface import implements -from twisted.trial import unittest -from twisted.application import service -from twisted.internet import defer -from buildbot import config, buildslave, interfaces, revlinks, locks -from buildbot.process import properties, factory -from buildbot.test.util import dirs, compat -from buildbot.test.util.config import ConfigErrorsMixin -from buildbot.changes import base as changes_base -from buildbot.schedulers import base as schedulers_base -from buildbot.status import base as status_base - -global_defaults = dict( - title='Buildbot', - titleURL='http://buildbot.net', - buildbotURL='http://localhost:8080/', - changeHorizon=None, - eventHorizon=50, - logHorizon=None, - buildHorizon=None, - logCompressionLimit=4096, - logCompressionMethod='bz2', - logMaxTailSize=None, - logMaxSize=None, - properties=properties.Properties(), - mergeRequests=None, - prioritizeBuilders=None, - slavePortnum=None, - multiMaster=False, - debugPassword=None, - manhole=None, -) - - -class FakeChangeSource(changes_base.ChangeSource): - pass - - -class FakeStatusReceiver(status_base.StatusReceiver): - pass - - -class FakeScheduler(object): - implements(interfaces.IScheduler) - def __init__(self, name): - self.name = name - -class FakeBuilder(object): - - def __init__(self, **kwargs): - self.__dict__.update(kwargs) - - -class ConfigErrors(unittest.TestCase): - - def test_constr(self): - ex = config.ConfigErrors(['a', 'b']) - self.assertEqual(ex.errors, ['a', 'b']) - - def test_addError(self): - ex = config.ConfigErrors(['a']) - ex.addError('c') - self.assertEqual(ex.errors, ['a', 'c']) - - def test_nonempty(self): - empty = config.ConfigErrors() - full = config.ConfigErrors(['a']) - self.failUnless(not empty) - self.failIf(not full) - - def test_error_raises(self): - e = self.assertRaises(config.ConfigErrors, config.error, "message") - self.assertEqual(e.errors, ["message"]) - - def test_error_no_raise(self): - e = config.ConfigErrors() - self.patch(config, "_errors", e) - config.error("message") - self.assertEqual(e.errors, ["message"]) - - def test_str(self): - ex = config.ConfigErrors() - self.assertEqual(str(ex), "") - - ex = config.ConfigErrors(["a"]) - self.assertEqual(str(ex), "a") - - ex = config.ConfigErrors(["a", "b"]) - self.assertEqual(str(ex), "a\nb") - - ex = config.ConfigErrors(["a"]) - ex.addError('c') - self.assertEqual(str(ex), "a\nc") - - -class MasterConfig(ConfigErrorsMixin, dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.basedir = os.path.abspath('basedir') - self.filename = os.path.join(self.basedir, 'test.cfg') - return self.setUpDirs('basedir') - - def tearDown(self): - return self.tearDownDirs() - - # utils - - def patch_load_helpers(self): - # patch out all of the "helpers" for laodConfig with null functions - for n in dir(config.MasterConfig): - if n.startswith('load_'): - typ = 'loader' - elif n.startswith('check_'): - typ = 'checker' - else: - continue - - v = getattr(config.MasterConfig, n) - if callable(v): - if typ == 'loader': - self.patch(config.MasterConfig, n, - mock.Mock(side_effect= - lambda filename, config_dict: None)) - else: - self.patch(config.MasterConfig, n, - mock.Mock(side_effect= - lambda: None)) - - - def install_config_file(self, config_file, other_files={}): - config_file = textwrap.dedent(config_file) - with open(os.path.join(self.basedir, self.filename), "w") as f: - f.write(config_file) - for file, contents in other_files.items(): - with open(file, "w") as f: - f.write(contents) - - - # tests - - def test_defaults(self): - cfg = config.MasterConfig() - expected = dict( - #validation, - db=dict( - db_url='sqlite:///state.sqlite', - db_poll_interval=None), - metrics = None, - caches = dict(Changes=10, Builds=15), - schedulers = {}, - builders = [], - slaves = [], - change_sources = [], - status = [], - user_managers = [], - revlink = revlinks.default_revlink_matcher - ) - expected.update(global_defaults) - got = dict([ - (attr, getattr(cfg, attr)) - for attr, exp in expected.iteritems() ]) - self.assertEqual(got, expected) - - def test_defaults_validation(self): - # re's aren't comparable, but we can make sure the keys match - cfg = config.MasterConfig() - self.assertEqual(sorted(cfg.validation.keys()), - sorted([ - 'branch', 'revision', 'property_name', 'property_value', - ])) - - def test_loadConfig_missing_file(self): - self.assertRaisesConfigError( - re.compile("configuration file .* does not exist"), - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - def test_loadConfig_missing_basedir(self): - self.assertRaisesConfigError( - re.compile("basedir .* does not exist"), - lambda : config.MasterConfig.loadConfig( - os.path.join(self.basedir, 'NO'), 'test.cfg')) - - def test_loadConfig_open_error(self): - """ - Check that loadConfig() raises correct ConfigError exception in cases - when configure file is found, but we fail to open it. - """ - - def raise_IOError(*args): - raise IOError("error_msg") - - self.install_config_file('#dummy') - - # override build-in open() function to always rise IOError - self.patch(__builtin__, "open", raise_IOError) - - # check that we got the expected ConfigError exception - self.assertRaisesConfigError( - re.compile("unable to open configuration file .*: error_msg"), - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - @compat.usesFlushLoggedErrors - def test_loadConfig_parse_error(self): - self.install_config_file('def x:\nbar') - self.assertRaisesConfigError( - re.compile("error while parsing.*traceback in logfile"), - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - self.assertEqual(len(self.flushLoggedErrors(SyntaxError)), 1) - - def test_loadConfig_eval_ConfigError(self): - self.install_config_file("""\ - from buildbot import config - BuildmasterConfig = { 'multiMaster': True } - config.error('oh noes!')""") - self.assertRaisesConfigError("oh noes", - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - def test_loadConfig_eval_ConfigErrors(self): - # We test a config that has embedded errors, as well - # as semantic errors that get added later. If an exception is raised - # prematurely, then the semantic errors wouldn't get reported. - self.install_config_file("""\ - from buildbot import config - BuildmasterConfig = {} - config.error('oh noes!') - config.error('noes too!')""") - e = self.assertRaises(config.ConfigErrors, - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - self.assertEqual(e.errors, ['oh noes!', 'noes too!', - 'no slaves are configured', - 'no builders are configured']) - - def test_loadConfig_no_BuildmasterConfig(self): - self.install_config_file('x=10') - self.assertRaisesConfigError("does not define 'BuildmasterConfig'", - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - def test_loadConfig_unknown_key(self): - self.patch_load_helpers() - self.install_config_file("""\ - BuildmasterConfig = dict(foo=10) - """) - self.assertRaisesConfigError("Unknown BuildmasterConfig key foo", - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - def test_loadConfig_unknown_keys(self): - self.patch_load_helpers() - self.install_config_file("""\ - BuildmasterConfig = dict(foo=10, bar=20) - """) - self.assertRaisesConfigError("Unknown BuildmasterConfig keys bar, foo", - lambda : config.MasterConfig.loadConfig( - self.basedir, self.filename)) - - def test_loadConfig_success(self): - self.patch_load_helpers() - self.install_config_file("""\ - BuildmasterConfig = dict() - """) - rv = config.MasterConfig.loadConfig( - self.basedir, self.filename) - self.assertIsInstance(rv, config.MasterConfig) - - # make sure all of the loaders and checkers are called - self.failUnless(rv.load_global.called) - self.failUnless(rv.load_validation.called) - self.failUnless(rv.load_db.called) - self.failUnless(rv.load_metrics.called) - self.failUnless(rv.load_caches.called) - self.failUnless(rv.load_schedulers.called) - self.failUnless(rv.load_builders.called) - self.failUnless(rv.load_slaves.called) - self.failUnless(rv.load_change_sources.called) - self.failUnless(rv.load_status.called) - self.failUnless(rv.load_user_managers.called) - - self.failUnless(rv.check_single_master.called) - self.failUnless(rv.check_schedulers.called) - self.failUnless(rv.check_locks.called) - self.failUnless(rv.check_builders.called) - self.failUnless(rv.check_status.called) - self.failUnless(rv.check_horizons.called) - self.failUnless(rv.check_slavePortnum.called) - - def test_loadConfig_with_local_import(self): - self.patch_load_helpers() - self.install_config_file("""\ - from subsidiary_module import x - BuildmasterConfig = dict() - """, - {'basedir/subsidiary_module.py' : "x = 10"}) - rv = config.MasterConfig.loadConfig( - self.basedir, self.filename) - self.assertIsInstance(rv, config.MasterConfig) - - -class MasterConfig_loaders(ConfigErrorsMixin, unittest.TestCase): - - filename = 'test.cfg' - - def setUp(self): - self.cfg = config.MasterConfig() - self.errors = config.ConfigErrors() - self.patch(config, '_errors', self.errors) - - # utils - - def assertResults(self, **expected): - self.failIf(self.errors, self.errors.errors) - got = dict([ - (attr, getattr(self.cfg, attr)) - for attr, exp in expected.iteritems() ]) - self.assertEqual(got, expected) - - # tests - - def test_load_global_defaults(self): - self.cfg.load_global(self.filename, {}) - self.assertResults(**global_defaults) - - def test_load_global_string_param_not_string(self): - self.cfg.load_global(self.filename, - dict(title=10)) - self.assertConfigError(self.errors, 'must be a string') - - def test_load_global_int_param_not_int(self): - self.cfg.load_global(self.filename, - dict(changeHorizon='yes')) - self.assertConfigError(self.errors, 'must be an int') - - def do_test_load_global(self, config_dict, **expected): - self.cfg.load_global(self.filename, config_dict) - self.assertResults(**expected) - - def test_load_global_title(self): - self.do_test_load_global(dict(title='hi'), title='hi') - - def test_load_global_projectURL(self): - self.do_test_load_global(dict(projectName='hey'), title='hey') - - def test_load_global_titleURL(self): - self.do_test_load_global(dict(titleURL='hi'), titleURL='hi') - - def test_load_global_buildbotURL(self): - self.do_test_load_global(dict(buildbotURL='hey'), buildbotURL='hey') - - def test_load_global_changeHorizon(self): - self.do_test_load_global(dict(changeHorizon=10), changeHorizon=10) - - def test_load_global_changeHorizon_none(self): - self.do_test_load_global(dict(changeHorizon=None), changeHorizon=None) - - def test_load_global_eventHorizon(self): - self.do_test_load_global(dict(eventHorizon=10), eventHorizon=10) - - def test_load_global_logHorizon(self): - self.do_test_load_global(dict(logHorizon=10), logHorizon=10) - - def test_load_global_buildHorizon(self): - self.do_test_load_global(dict(buildHorizon=10), buildHorizon=10) - - def test_load_global_logCompressionLimit(self): - self.do_test_load_global(dict(logCompressionLimit=10), - logCompressionLimit=10) - - def test_load_global_logCompressionMethod(self): - self.do_test_load_global(dict(logCompressionMethod='gz'), - logCompressionMethod='gz') - - def test_load_global_logCompressionMethod_invalid(self): - self.cfg.load_global(self.filename, - dict(logCompressionMethod='foo')) - self.assertConfigError(self.errors, "must be 'bz2' or 'gz'") - - def test_load_global_codebaseGenerator(self): - func = lambda _: "dummy" - self.do_test_load_global(dict(codebaseGenerator=func), - codebaseGenerator=func) - - def test_load_global_codebaseGenerator_invalid(self): - self.cfg.load_global(self.filename, - dict(codebaseGenerator='dummy')) - self.assertConfigError(self.errors, - "codebaseGenerator must be a callable " - "accepting a dict and returning a str") - - def test_load_global_logMaxSize(self): - self.do_test_load_global(dict(logMaxSize=123), logMaxSize=123) - - def test_load_global_logMaxTailSize(self): - self.do_test_load_global(dict(logMaxTailSize=123), logMaxTailSize=123) - - def test_load_global_properties(self): - exp = properties.Properties() - exp.setProperty('x', 10, self.filename) - self.do_test_load_global(dict(properties=dict(x=10)), properties=exp) - - def test_load_global_properties_invalid(self): - self.cfg.load_global(self.filename, - dict(properties='yes')) - self.assertConfigError(self.errors, "must be a dictionary") - - def test_load_global_mergeRequests_bool(self): - self.do_test_load_global(dict(mergeRequests=False), - mergeRequests=False) - - def test_load_global_mergeRequests_callable(self): - callable = lambda : None - self.do_test_load_global(dict(mergeRequests=callable), - mergeRequests=callable) - - def test_load_global_mergeRequests_invalid(self): - self.cfg.load_global(self.filename, - dict(mergeRequests='yes')) - self.assertConfigError(self.errors, - "must be a callable, True, or False") - - def test_load_global_prioritizeBuilders_callable(self): - callable = lambda : None - self.do_test_load_global(dict(prioritizeBuilders=callable), - prioritizeBuilders=callable) - - def test_load_global_prioritizeBuilders_invalid(self): - self.cfg.load_global(self.filename, - dict(prioritizeBuilders='yes')) - self.assertConfigError(self.errors, "must be a callable") - - def test_load_global_slavePortnum_int(self): - self.do_test_load_global(dict(slavePortnum=123), - slavePortnum='tcp:123') - - def test_load_global_slavePortnum_str(self): - self.do_test_load_global(dict(slavePortnum='udp:123'), - slavePortnum='udp:123') - - def test_load_global_multiMaster(self): - self.do_test_load_global(dict(multiMaster=1), multiMaster=1) - - def test_load_global_debugPassword(self): - self.do_test_load_global(dict(debugPassword='xyz'), - debugPassword='xyz') - - def test_load_global_manhole(self): - mh = mock.Mock(name='manhole') - self.do_test_load_global(dict(manhole=mh), manhole=mh) - - def test_load_global_revlink_callable(self): - callable = lambda : None - self.do_test_load_global(dict(revlink=callable), - revlink=callable) - - def test_load_global_revlink_invalid(self): - self.cfg.load_global(self.filename, dict(revlink='')) - self.assertConfigError(self.errors, "must be a callable") - - def test_load_validation_defaults(self): - self.cfg.load_validation(self.filename, {}) - self.assertEqual(sorted(self.cfg.validation.keys()), - sorted([ - 'branch', 'revision', 'property_name', 'property_value', - ])) - - def test_load_validation_invalid(self): - self.cfg.load_validation(self.filename, - dict(validation='plz')) - self.assertConfigError(self.errors, "must be a dictionary") - - def test_load_validation_unk_keys(self): - self.cfg.load_validation(self.filename, - dict(validation=dict(users='.*'))) - self.assertConfigError(self.errors, "unrecognized validation key(s)") - - def test_load_validation(self): - r = re.compile('.*') - self.cfg.load_validation(self.filename, - dict(validation=dict(branch=r))) - self.assertEqual(self.cfg.validation['branch'], r) - # check that defaults are still around - self.assertIn('revision', self.cfg.validation) - - - def test_load_db_defaults(self): - self.cfg.load_db(self.filename, {}) - self.assertResults( - db=dict(db_url='sqlite:///state.sqlite', db_poll_interval=None)) - - def test_load_db_db_url(self): - self.cfg.load_db(self.filename, dict(db_url='abcd')) - self.assertResults(db=dict(db_url='abcd', db_poll_interval=None)) - - def test_load_db_db_poll_interval(self): - self.cfg.load_db(self.filename, dict(db_poll_interval=2)) - self.assertResults( - db=dict(db_url='sqlite:///state.sqlite', db_poll_interval=2)) - - def test_load_db_dict(self): - self.cfg.load_db(self.filename, - dict(db=dict(db_url='abcd', db_poll_interval=10))) - self.assertResults(db=dict(db_url='abcd', db_poll_interval=10)) - - def test_load_db_unk_keys(self): - self.cfg.load_db(self.filename, - dict(db=dict(db_url='abcd', db_poll_interval=10, bar='bar'))) - self.assertConfigError(self.errors, "unrecognized keys in") - - def test_load_db_not_int(self): - self.cfg.load_db(self.filename, - dict(db=dict(db_url='abcd', db_poll_interval='ten'))) - self.assertConfigError(self.errors, "must be an int") - - - def test_load_metrics_defaults(self): - self.cfg.load_metrics(self.filename, {}) - self.assertResults(metrics=None) - - def test_load_metrics_invalid(self): - self.cfg.load_metrics(self.filename, dict(metrics=13)) - self.assertConfigError(self.errors, "must be a dictionary") - - def test_load_metrics(self): - self.cfg.load_metrics(self.filename, - dict(metrics=dict(foo=1))) - self.assertResults(metrics=dict(foo=1)) - - - def test_load_caches_defaults(self): - self.cfg.load_caches(self.filename, {}) - self.assertResults(caches=dict(Changes=10, Builds=15)) - - def test_load_caches_invalid(self): - self.cfg.load_caches(self.filename, dict(caches=13)) - self.assertConfigError(self.errors, "must be a dictionary") - - def test_load_caches_buildCacheSize(self): - self.cfg.load_caches(self.filename, - dict(buildCacheSize=13)) - self.assertResults(caches=dict(Builds=13, Changes=10)) - - def test_load_caches_buildCacheSize_and_caches(self): - self.cfg.load_caches(self.filename, - dict(buildCacheSize=13, caches=dict(builds=11))) - self.assertConfigError(self.errors, "cannot specify") - - def test_load_caches_changeCacheSize(self): - self.cfg.load_caches(self.filename, - dict(changeCacheSize=13)) - self.assertResults(caches=dict(Changes=13, Builds=15)) - - def test_load_caches_changeCacheSize_and_caches(self): - self.cfg.load_caches(self.filename, - dict(changeCacheSize=13, caches=dict(changes=11))) - self.assertConfigError(self.errors, "cannot specify") - - def test_load_caches(self): - self.cfg.load_caches(self.filename, - dict(caches=dict(foo=1))) - self.assertResults(caches=dict(Changes=10, Builds=15, foo=1)) - - def test_load_caches_entries_test(self): - self.cfg.load_caches(self.filename, - dict(caches=dict(foo="1"))) - self.assertConfigError(self.errors, - "value for cache size 'foo' must be an integer") - - def test_load_schedulers_defaults(self): - self.cfg.load_schedulers(self.filename, {}) - self.assertResults(schedulers={}) - - def test_load_schedulers_not_list(self): - self.cfg.load_schedulers(self.filename, - dict(schedulers=dict())) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_schedulers_not_instance(self): - self.cfg.load_schedulers(self.filename, - dict(schedulers=[mock.Mock()])) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_schedulers_dupe(self): - sch1 = FakeScheduler(name='sch') - sch2 = FakeScheduler(name='sch') - self.cfg.load_schedulers(self.filename, - dict(schedulers=[ sch1, sch2 ])) - self.assertConfigError(self.errors, - "scheduler name 'sch' used multiple times") - - def test_load_schedulers(self): - class Sch(schedulers_base.BaseScheduler): - def __init__(self, name): - self.name = name - sch = Sch('sch') - self.cfg.load_schedulers(self.filename, - dict(schedulers=[sch])) - self.assertResults(schedulers=dict(sch=sch)) - - - def test_load_builders_defaults(self): - self.cfg.load_builders(self.filename, {}) - self.assertResults(builders=[]) - - def test_load_builders_not_list(self): - self.cfg.load_builders(self.filename, - dict(builders=dict())) - self.assertConfigError(self.errors, "must be a list") - - def test_load_builders_not_instance(self): - self.cfg.load_builders(self.filename, - dict(builders=[mock.Mock()])) - self.assertConfigError(self.errors, "is not a builder config (in c['builders']") - - def test_load_builders(self): - bldr = config.BuilderConfig(name='x', - factory=factory.BuildFactory(), slavename='x') - self.cfg.load_builders(self.filename, - dict(builders=[bldr])) - self.assertResults(builders=[bldr]) - - def test_load_builders_dict(self): - bldr = dict(name='x', factory=factory.BuildFactory(), slavename='x') - self.cfg.load_builders(self.filename, - dict(builders=[bldr])) - self.assertIsInstance(self.cfg.builders[0], config.BuilderConfig) - self.assertEqual(self.cfg.builders[0].name, 'x') - - @compat.usesFlushWarnings - def test_load_builders_abs_builddir(self): - bldr = dict(name='x', factory=factory.BuildFactory(), slavename='x', - builddir=os.path.abspath('.')) - self.cfg.load_builders(self.filename, - dict(builders=[bldr])) - self.assertEqual( - len(self.flushWarnings([self.cfg.load_builders])), - 1) - - def test_load_slaves_defaults(self): - self.cfg.load_slaves(self.filename, {}) - self.assertResults(slaves=[]) - - def test_load_slaves_not_list(self): - self.cfg.load_slaves(self.filename, - dict(slaves=dict())) - self.assertConfigError(self.errors, "must be a list") - - def test_load_slaves_not_instance(self): - self.cfg.load_slaves(self.filename, - dict(slaves=[mock.Mock()])) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_slaves_reserved_names(self): - for name in 'debug', 'change', 'status': - self.cfg.load_slaves(self.filename, - dict(slaves=[buildslave.BuildSlave(name, 'x')])) - self.assertConfigError(self.errors, "is reserved") - self.errors.errors[:] = [] # clear out the errors - - def test_load_slaves(self): - sl = buildslave.BuildSlave('foo', 'x') - self.cfg.load_slaves(self.filename, - dict(slaves=[sl])) - self.assertResults(slaves=[sl]) - - - def test_load_change_sources_defaults(self): - self.cfg.load_change_sources(self.filename, {}) - self.assertResults(change_sources=[]) - - def test_load_change_sources_not_instance(self): - self.cfg.load_change_sources(self.filename, - dict(change_source=[mock.Mock()])) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_change_sources_single(self): - chsrc = FakeChangeSource() - self.cfg.load_change_sources(self.filename, - dict(change_source=chsrc)) - self.assertResults(change_sources=[chsrc]) - - def test_load_change_sources_list(self): - chsrc = FakeChangeSource() - self.cfg.load_change_sources(self.filename, - dict(change_source=[chsrc])) - self.assertResults(change_sources=[chsrc]) - - def test_load_status_not_list(self): - self.cfg.load_status(self.filename, dict(status="not-list")) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_status_not_status_rec(self): - self.cfg.load_status(self.filename, dict(status=['fo'])) - self.assertConfigError(self.errors, "must be a list of") - - def test_load_user_managers_defaults(self): - self.cfg.load_user_managers(self.filename, {}) - self.assertResults(user_managers=[]) - - def test_load_user_managers_not_list(self): - self.cfg.load_user_managers(self.filename, - dict(user_managers='foo')) - self.assertConfigError(self.errors, "must be a list") - - def test_load_user_managers(self): - um = mock.Mock() - self.cfg.load_user_managers(self.filename, - dict(user_managers=[um])) - self.assertResults(user_managers=[um]) - -class MasterConfig_checkers(ConfigErrorsMixin, unittest.TestCase): - - def setUp(self): - self.cfg = config.MasterConfig() - self.errors = config.ConfigErrors() - self.patch(config, '_errors', self.errors) - - # utils - - def setup_basic_attrs(self): - # set up a basic config for checking; this will be modified below - sch = mock.Mock() - sch.name = 'sch' - sch.listBuilderNames = lambda : [ 'b1', 'b2' ] - - b1 = mock.Mock() - b1.name = 'b1' - - b2 = mock.Mock() - b2.name = 'b2' - - self.cfg.schedulers = dict(sch=sch) - self.cfg.slaves = [ mock.Mock() ] - self.cfg.builders = [ b1, b2 ] - - def setup_builder_locks(self, - builder_lock=None, - dup_builder_lock=False, - bare_builder_lock=False): - """Set-up two mocked builders with specified locks. - - @type builder_lock: string or None - @param builder_lock: Name of the lock to add to first builder. - If None, no lock is added. - - @type dup_builder_lock: boolean - @param dup_builder_lock: if True, add a lock with duplicate name - to the second builder - - @type dup_builder_lock: boolean - @param bare_builder_lock: if True, add bare lock objects, don't wrap - them into locks.LockAccess object - """ - def bldr(name): - b = mock.Mock() - b.name = name - b.locks = [] - b.factory.steps = [ ('cls', (), dict(locks=[])) ] - return b - - def lock(name): - l = mock.Mock(spec=locks.MasterLock) - l.name = name - if bare_builder_lock: - return l - return locks.LockAccess(l, "counting", _skipChecks=True) - - b1, b2 = bldr('b1'), bldr('b2') - self.cfg.builders = [ b1, b2 ] - if builder_lock: - b1.locks.append(lock(builder_lock)) - if dup_builder_lock: - b2.locks.append(lock(builder_lock)) - - # tests - - def test_check_single_master_multimaster(self): - self.cfg.multiMaster = True - self.cfg.check_single_master() - self.assertNoConfigErrors(self.errors) - - def test_check_single_master_no_builders(self): - self.setup_basic_attrs() - self.cfg.builders = [ ] - self.cfg.check_single_master() - self.assertConfigError(self.errors, "no builders are configured") - - def test_check_single_master_no_slaves(self): - self.setup_basic_attrs() - self.cfg.slaves = [ ] - self.cfg.check_single_master() - self.assertConfigError(self.errors, "no slaves are configured") - - def test_check_single_master_unsch_builder(self): - self.setup_basic_attrs() - b3 = mock.Mock() - b3.name = 'b3' - self.cfg.builders.append(b3) - self.cfg.check_single_master() - self.assertConfigError(self.errors, "have no schedulers to drive them") - - - def test_check_schedulers_unknown_builder(self): - self.setup_basic_attrs() - del self.cfg.builders[1] # remove b2, leaving b1 - - self.cfg.check_schedulers() - self.assertConfigError(self.errors, "Unknown builder 'b2'") - - def test_check_schedulers_ignored_in_multiMaster(self): - self.setup_basic_attrs() - del self.cfg.builders[1] # remove b2, leaving b1 - self.cfg.multiMaster = True - self.cfg.check_schedulers() - self.assertNoConfigErrors(self.errors) - - def test_check_schedulers(self): - self.setup_basic_attrs() - self.cfg.check_schedulers() - self.assertNoConfigErrors(self.errors) - - - def test_check_locks_dup_builder_lock(self): - self.setup_builder_locks(builder_lock='l', dup_builder_lock=True) - self.cfg.check_locks() - self.assertConfigError(self.errors, "Two locks share") - - def test_check_locks(self): - self.setup_builder_locks(builder_lock='bl') - self.cfg.check_locks() - self.assertNoConfigErrors(self.errors) - - def test_check_locks_none(self): - # no locks in the whole config, should be fine - self.setup_builder_locks() - self.cfg.check_locks() - self.assertNoConfigErrors(self.errors) - - def test_check_locks_bare(self): - # check_locks() should be able to handle bare lock object, - # lock objects that are not wrapped into LockAccess() object - self.setup_builder_locks(builder_lock='oldlock', - bare_builder_lock=True) - self.cfg.check_locks() - self.assertNoConfigErrors(self.errors) - - - def test_check_builders_unknown_slave(self): - sl = mock.Mock() - sl.slavename = 'xyz' - self.cfg.slaves = [ sl ] - - b1 = FakeBuilder(slavenames=[ 'xyz', 'abc' ], builddir='x', name='b1') - self.cfg.builders = [ b1 ] - - self.cfg.check_builders() - self.assertConfigError(self.errors, - "builder 'b1' uses unknown slaves 'abc'") - - def test_check_builders_duplicate_name(self): - b1 = FakeBuilder(slavenames=[], name='b1', builddir='1') - b2 = FakeBuilder(slavenames=[], name='b1', builddir='2') - self.cfg.builders = [ b1, b2 ] - - self.cfg.check_builders() - self.assertConfigError(self.errors, - "duplicate builder name 'b1'") - - def test_check_builders_duplicate_builddir(self): - b1 = FakeBuilder(slavenames=[], name='b1', builddir='dir') - b2 = FakeBuilder(slavenames=[], name='b2', builddir='dir') - self.cfg.builders = [ b1, b2 ] - - self.cfg.check_builders() - self.assertConfigError(self.errors, - "duplicate builder builddir 'dir'") - - def test_check_builders(self): - sl = mock.Mock() - sl.slavename = 'a' - self.cfg.slaves = [ sl ] - - b1 = FakeBuilder(slavenames=[ 'a' ], name='b1', builddir='dir1') - b2 = FakeBuilder(slavenames=[ 'a' ], name='b2', builddir='dir2') - self.cfg.builders = [ b1, b2 ] - - self.cfg.check_builders() - self.assertNoConfigErrors(self.errors) - - - def test_check_status_fails(self): - st = FakeStatusReceiver() - st.checkConfig = lambda status: config.error("oh noes") - self.cfg.status = [ st ] - - self.cfg.check_status() - - self.assertConfigError(self.errors, "oh noes") - - def test_check_status(self): - st = FakeStatusReceiver() - st.checkConfig = mock.Mock() - self.cfg.status = [ st ] - - self.cfg.check_status() - - self.assertNoConfigErrors(self.errors) - st.checkConfig.assert_called_once_with(self.cfg.status) - - def test_check_horizons(self): - self.cfg.logHorizon = 100 - self.cfg.buildHorizon = 50 - self.cfg.check_horizons() - - self.assertConfigError(self.errors, "logHorizon must be less") - - def test_check_slavePortnum_set(self): - self.cfg.slavePortnum = 10 - self.cfg.check_slavePortnum() - self.assertNoConfigErrors(self.errors) - - def test_check_slavePortnum_not_set_slaves(self): - self.cfg.slaves = [ mock.Mock() ] - self.cfg.check_slavePortnum() - self.assertConfigError(self.errors, - "slaves are configured, but no slavePortnum is set") - - def test_check_slavePortnum_not_set_debug(self): - self.cfg.debugPassword = 'ssh' - self.cfg.check_slavePortnum() - self.assertConfigError(self.errors, - "debug client is configured, but no slavePortnum is set") - - -class BuilderConfig(ConfigErrorsMixin, unittest.TestCase): - - factory = factory.BuildFactory() - - # utils - - def assertAttributes(self, cfg, **expected): - got = dict([ - (attr, getattr(cfg, attr)) - for attr, exp in expected.iteritems() ]) - self.assertEqual(got, expected) - - # tests - - def test_no_name(self): - self.assertRaisesConfigError( - "builder's name is required", - lambda : config.BuilderConfig( - factory=self.factory, slavenames=['a'])) - - def test_reserved_name(self): - self.assertRaisesConfigError( - "builder names must not start with an underscore: '_a'", - lambda : config.BuilderConfig(name='_a', - factory=self.factory, slavenames=['a'])) - - def test_no_factory(self): - self.assertRaisesConfigError( - "builder 'a' has no factory", - lambda : config.BuilderConfig( - name='a', slavenames=['a'])) - - def test_wrong_type_factory(self): - self.assertRaisesConfigError( - "builder 'a's factory is not", - lambda : config.BuilderConfig( - factory=[], name='a', slavenames=['a'])) - - def test_no_slavenames(self): - self.assertRaisesConfigError( - "builder 'a': at least one slavename is required", - lambda : config.BuilderConfig( - name='a', factory=self.factory)) - - def test_bogus_slavenames(self): - self.assertRaisesConfigError( - "slavenames must be a list or a string", - lambda : config.BuilderConfig( - name='a', slavenames={1:2}, factory=self.factory)) - - def test_bogus_slavename(self): - self.assertRaisesConfigError( - "slavename must be a string", - lambda : config.BuilderConfig( - name='a', slavename=1, factory=self.factory)) - - def test_bogus_category(self): - self.assertRaisesConfigError( - "category must be a string", - lambda : config.BuilderConfig(category=13, - name='a', slavenames=['a'], factory=self.factory)) - - def test_inv_nextSlave(self): - self.assertRaisesConfigError( - "nextSlave must be a callable", - lambda : config.BuilderConfig(nextSlave="foo", - name="a", slavenames=['a'], factory=self.factory)) - - def test_inv_nextBuild(self): - self.assertRaisesConfigError( - "nextBuild must be a callable", - lambda : config.BuilderConfig(nextBuild="foo", - name="a", slavenames=['a'], factory=self.factory)) - - def test_inv_canStartBuild(self): - self.assertRaisesConfigError( - "canStartBuild must be a callable", - lambda : config.BuilderConfig(canStartBuild="foo", - name="a", slavenames=['a'], factory=self.factory)) - - def test_inv_env(self): - self.assertRaisesConfigError( - "builder's env must be a dictionary", - lambda : config.BuilderConfig(env="foo", - name="a", slavenames=['a'], factory=self.factory)) - - def test_defaults(self): - cfg = config.BuilderConfig( - name='a b c', slavename='a', factory=self.factory) - self.assertIdentical(cfg.factory, self.factory) - self.assertAttributes(cfg, - name='a b c', - slavenames=['a'], - builddir='a_b_c', - slavebuilddir='a_b_c', - category='', - nextSlave=None, - locks=[], - env={}, - properties={}, - mergeRequests=None, - description=None) - - def test_args(self): - cfg = config.BuilderConfig( - name='b', slavename='s1', slavenames='s2', builddir='bd', - slavebuilddir='sbd', factory=self.factory, category='c', - nextSlave=lambda : 'ns', nextBuild=lambda : 'nb', locks=['l'], - env=dict(x=10), properties=dict(y=20), mergeRequests='mr', - description='buzz') - self.assertIdentical(cfg.factory, self.factory) - self.assertAttributes(cfg, - name='b', - slavenames=['s2', 's1'], - builddir='bd', - slavebuilddir='sbd', - category='c', - locks=['l'], - env={'x':10}, - properties={'y':20}, - mergeRequests='mr', - description='buzz') - - def test_getConfigDict(self): - ns = lambda : 'ns' - nb = lambda : 'nb' - cfg = config.BuilderConfig( - name='b', slavename='s1', slavenames='s2', builddir='bd', - slavebuilddir='sbd', factory=self.factory, category='c', - nextSlave=ns, nextBuild=nb, locks=['l'], - env=dict(x=10), properties=dict(y=20), mergeRequests='mr', - description='buzz') - self.assertEqual(cfg.getConfigDict(), {'builddir': 'bd', - 'category': 'c', - 'description': 'buzz', - 'env': {'x': 10}, - 'factory': self.factory, - 'locks': ['l'], - 'mergeRequests': 'mr', - 'name': 'b', - 'nextBuild': nb, - 'nextSlave': ns, - 'properties': {'y': 20}, - 'slavebuilddir': 'sbd', - 'slavenames': ['s2', 's1'], - }) - - - -class FakeService(config.ReconfigurableServiceMixin, - service.Service): - - succeed = True - call_index = 1 - - def reconfigService(self, new_config): - self.called = FakeService.call_index - FakeService.call_index += 1 - d = config.ReconfigurableServiceMixin.reconfigService(self, new_config) - if not self.succeed: - @d.addCallback - def fail(_): - raise ValueError("oh noes") - return d - - - -class FakeMultiService(config.ReconfigurableServiceMixin, - service.MultiService): - - def reconfigService(self, new_config): - self.called = True - d = config.ReconfigurableServiceMixin.reconfigService(self, new_config) - return d - - - -class ReconfigurableServiceMixin(unittest.TestCase): - - def test_service(self): - svc = FakeService() - d = svc.reconfigService(mock.Mock()) - @d.addCallback - def check(_): - self.assertTrue(svc.called) - return d - - @defer.inlineCallbacks - def test_service_failure(self): - svc = FakeService() - svc.succeed = False - try: - yield svc.reconfigService(mock.Mock()) - except ValueError: - pass - else: - self.fail("should have raised ValueError") - - def test_multiservice(self): - svc = FakeMultiService() - ch1 = FakeService() - ch1.setServiceParent(svc) - ch2 = FakeMultiService() - ch2.setServiceParent(svc) - ch3 = FakeService() - ch3.setServiceParent(ch2) - d = svc.reconfigService(mock.Mock()) - @d.addCallback - def check(_): - self.assertTrue(svc.called) - self.assertTrue(ch1.called) - self.assertTrue(ch2.called) - self.assertTrue(ch3.called) - return d - - def test_multiservice_priority(self): - parent = FakeMultiService() - svc128 = FakeService() - svc128.setServiceParent(parent) - - services = [ svc128 ] - for i in range(20, 1, -1): - svc = FakeService() - svc.reconfig_priority = i - svc.setServiceParent(parent) - services.append(svc) - - d = parent.reconfigService(mock.Mock()) - @d.addCallback - def check(_): - prio_order = [ svc.called for svc in services ] - called_order = sorted(prio_order) - self.assertEqual(prio_order, called_order) - return d - - @compat.usesFlushLoggedErrors - @defer.inlineCallbacks - def test_multiservice_nested_failure(self): - svc = FakeMultiService() - ch1 = FakeService() - ch1.setServiceParent(svc) - ch1.succeed = False - try: - yield svc.reconfigService(mock.Mock()) - except ValueError: - pass - else: - self.fail("should have raised ValueError") diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_contrib_buildbot_cvs_mail.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_contrib_buildbot_cvs_mail.py deleted file mode 100644 index 30aaad07..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_contrib_buildbot_cvs_mail.py +++ /dev/null @@ -1,191 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sys -import re -import os - -from twisted.python import log -from twisted.trial import unittest -from twisted.internet import protocol, defer, utils, reactor - -test = ''' -Update of /cvsroot/test -In directory example:/tmp/cvs-serv21085 - -Modified Files: - README hello.c -Log Message: -two files checkin - -''' -golden_1_11_regex=[ - '^From:', - '^To: buildbot@example.com$', - '^Reply-To: noreply@example.com$', - '^Subject: cvs update for project test$', - '^Date:', - '^X-Mailer: Python buildbot-cvs-mail', - '^$', - '^Cvsmode: 1.11$', - '^Category: None', - '^CVSROOT: \"ext:example:/cvsroot\"', - '^Files: test README 1.1,1.2 hello.c 2.2,2.3$', - '^Project: test$', - '^$', - '^Update of /cvsroot/test$', - '^In directory example:/tmp/cvs-serv21085$', - '^$', - '^Modified Files:$', - 'README hello.c$', - 'Log Message:$', - '^two files checkin', - '^$', - '^$'] - -golden_1_12_regex=[ - '^From: ', - '^To: buildbot@example.com$', - '^Reply-To: noreply@example.com$', - '^Subject: cvs update for project test$', - '^Date: ', - '^X-Mailer: Python buildbot-cvs-mail', - '^$', - '^Cvsmode: 1.12$', - '^Category: None$', - '^CVSROOT: \"ext:example.com:/cvsroot\"$', - '^Files: README 1.1 1.2 hello.c 2.2 2.3$', - '^Path: test$', - '^Project: test$', - '^$', - '^Update of /cvsroot/test$', - '^In directory example:/tmp/cvs-serv21085$', - '^$', - '^Modified Files:$', - 'README hello.c$', - '^Log Message:$', - 'two files checkin', - '^$', - '^$' ] - -class _SubprocessProtocol(protocol.ProcessProtocol): - def __init__(self, input, deferred): - self.input = input - self.deferred = deferred - self.output = '' - - def outReceived(self, s): - self.output += s - errReceived = outReceived - - def connectionMade(self): - # push the input and send EOF - self.transport.write(self.input) - self.transport.closeStdin() - - def processEnded(self, reason): - self.deferred.callback((self.output, reason.value.exitCode)) - -def getProcessOutputAndValueWithInput(executable, args, input): - "similar to getProcessOutputAndValue, but also allows injection of input on stdin" - d = defer.Deferred() - p = _SubprocessProtocol(input, d) - reactor.spawnProcess(p, executable, (executable,) + tuple(args)) - return d - -class TestBuildbotCvsMail(unittest.TestCase): - buildbot_cvs_mail_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../contrib/buildbot_cvs_mail.py')) - if not os.path.exists(buildbot_cvs_mail_path): - skip = ("'%s' does not exist (normal unless run from git)" - % buildbot_cvs_mail_path) - - def assertOutputOk(self, (output, code), regexList): - "assert that the output from getProcessOutputAndValueWithInput matches expectations" - try: - self.failUnlessEqual(code, 0, "subprocess exited uncleanly") - lines = output.splitlines() - self.failUnlessEqual(len(lines), len(regexList), - "got wrong number of lines of output") - - misses = [] - for line, regex in zip(lines, regexList): - m = re.search(regex, line) - if not m: - misses.append((regex,line)) - self.assertEqual(misses, [], "got non-matching lines") - except: - log.msg("got output:\n" + output) - raise - - def test_buildbot_cvs_mail_from_cvs1_11(self): - # Simulate CVS 1.11 - d = getProcessOutputAndValueWithInput(sys.executable, - [ self.buildbot_cvs_mail_path, '--cvsroot=\"ext:example:/cvsroot\"', - '--email=buildbot@example.com', '-P', 'test', '-R', 'noreply@example.com', '-t', - 'test', 'README', '1.1,1.2', 'hello.c', '2.2,2.3' ], - input=test) - d.addCallback(self.assertOutputOk, golden_1_11_regex) - return d - - def test_buildbot_cvs_mail_from_cvs1_12(self): - # Simulate CVS 1.12, with --path option - d = getProcessOutputAndValueWithInput(sys.executable, - [ self.buildbot_cvs_mail_path, '--cvsroot=\"ext:example.com:/cvsroot\"', - '--email=buildbot@example.com', '-P', 'test', '--path', 'test', - '-R', 'noreply@example.com', '-t', - 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3' ], - input=test) - d.addCallback(self.assertOutputOk, golden_1_12_regex) - return d - - def test_buildbot_cvs_mail_no_args_exits_with_error(self): - d = utils.getProcessOutputAndValue(sys.executable, [ self.buildbot_cvs_mail_path ]) - def check((stdout, stderr, code)): - self.assertEqual(code, 2) - d.addCallback(check) - return d - - def test_buildbot_cvs_mail_without_email_opt_exits_with_error(self): - d = utils.getProcessOutputAndValue(sys.executable, [ self.buildbot_cvs_mail_path, - '--cvsroot=\"ext:example.com:/cvsroot\"', - '-P', 'test', '--path', 'test', - '-R', 'noreply@example.com', '-t', - 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3']) - def check((stdout, stderr, code)): - self.assertEqual(code, 2) - d.addCallback(check) - return d - - def test_buildbot_cvs_mail_without_cvsroot_opt_exits_with_error(self): - d = utils.getProcessOutputAndValue(sys.executable, [ self.buildbot_cvs_mail_path, - '--complete-garbage-opt=gomi', - '--cvsroot=\"ext:example.com:/cvsroot\"', - '--email=buildbot@example.com','-P', 'test', '--path', - 'test', '-R', 'noreply@example.com', '-t', - 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3']) - def check((stdout, stderr, code)): - self.assertEqual(code, 2) - d.addCallback(check) - return d - - def test_buildbot_cvs_mail_with_unknown_opt_exits_with_error(self): - d = utils.getProcessOutputAndValue(sys.executable, [ self.buildbot_cvs_mail_path, - '--email=buildbot@example.com','-P', 'test', '--path', - 'test', '-R', 'noreply@example.com', '-t', - 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3']) - def check((stdout, stderr, code)): - self.assertEqual(code, 2) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_base.py deleted file mode 100644 index 24c8492c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_base.py +++ /dev/null @@ -1,106 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -import mock -from buildbot.db import base -from twisted.trial import unittest -from twisted.internet import defer - -class TestBase(unittest.TestCase): - - def setUp(self): - meta = sa.MetaData() - self.tbl = sa.Table('tbl', meta, - sa.Column('str32', sa.String(length=32)), - sa.Column('txt', sa.Text)) - self.db = mock.Mock() - self.db.pool.engine.dialect.name = 'mysql' - self.comp = base.DBConnectorComponent(self.db) - - def test_check_length_ok(self): - self.comp.check_length(self.tbl.c.str32, "short string") - - def test_check_length_long(self): - self.assertRaises(RuntimeError, lambda : - self.comp.check_length(self.tbl.c.str32, "long string" * 5)) - - def test_check_length_text(self): - self.assertRaises(AssertionError, lambda : - self.comp.check_length(self.tbl.c.txt, "long string" * 5)) - - def test_check_length_long_not_mysql(self): - self.db.pool.engine.dialect.name = 'sqlite' - self.comp.check_length(self.tbl.c.str32, "long string" * 5) - # run that again since the method gets stubbed out - self.comp.check_length(self.tbl.c.str32, "long string" * 5) - -class TestCachedDecorator(unittest.TestCase): - - def setUp(self): - # set this to True to check that cache.get isn't called (for - # no_cache=1) - self.cache_get_raises_exception = False - - class TestConnectorComponent(base.DBConnectorComponent): - invocations = None - @base.cached("mycache") - def getThing(self, key): - if self.invocations is None: - self.invocations = [] - self.invocations.append(key) - return defer.succeed(key * 2) - - def get_cache(self, cache_name, miss_fn): - self.assertEqual(cache_name, "mycache") - cache = mock.Mock(name="mycache") - if self.cache_get_raises_exception: - def ex(key): - raise RuntimeError("cache.get called unexpectedly") - cache.get = ex - else: - cache.get = miss_fn - return cache - - # tests - - @defer.inlineCallbacks - def test_cached(self): - # attach it to the connector - connector = mock.Mock(name="connector") - connector.master.caches.get_cache = self.get_cache - - # build an instance - comp = self.TestConnectorComponent(connector) - - # test it twice (to test an implementation detail) - res1 = yield comp.getThing("foo") - - res2 = yield comp.getThing("bar") - - self.assertEqual((res1, res2, comp.invocations), - ('foofoo', 'barbar', ['foo', 'bar'])) - - @defer.inlineCallbacks - def test_cached_no_cache(self): - # attach it to the connector - connector = mock.Mock(name="connector") - connector.master.caches.get_cache = self.get_cache - self.cache_get_raises_exception = True - - # build an instance - comp = self.TestConnectorComponent(connector) - - yield comp.getThing("foo", no_cache=1) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildrequests.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildrequests.py deleted file mode 100644 index a4b1c001..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildrequests.py +++ /dev/null @@ -1,729 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import datetime -import sqlalchemy as sa -from twisted.trial import unittest -from twisted.internet import task, defer -from buildbot.db import buildrequests -from buildbot.test.util import connector_component, db -from buildbot.test.fake import fakedb -from buildbot.util import UTC, epoch2datetime - -class TestBuildsetsConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - # test that the datetime translations are done correctly by specifying - # the epoch timestamp and datetime objects explicitly. These should - # pass regardless of the local timezone used while running tests! - CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC) - CLAIMED_AT_EPOCH = 266761875 - SUBMITTED_AT = datetime.datetime(1979, 6, 15, 12, 31, 15, tzinfo=UTC) - SUBMITTED_AT_EPOCH = 298297875 - COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC) - COMPLETE_AT_EPOCH = 329920275 - BSID = 567 - BSID2 = 5670 - MASTER_ID = "set in setUp" - OTHER_MASTER_ID = "set in setUp" - - MASTER_NAME = "testmaster" - MASTER_INCARN = "pid123-boot456789" - - def setUp(self): - self.MASTER_ID = fakedb.FakeBuildRequestsComponent.MASTER_ID - self.OTHER_MASTER_ID = self.MASTER_ID + 1111 - d = self.setUpConnectorComponent( - table_names=[ 'patches', 'changes', 'sourcestamp_changes', - 'buildsets', 'buildset_properties', 'buildrequests', - 'objects', 'buildrequest_claims', 'sourcestamps', 'sourcestampsets' ]) - - def finish_setup(_): - self.db.buildrequests = \ - buildrequests.BuildRequestsConnectorComponent(self.db) - self.db.master.getObjectId = lambda : defer.succeed(self.MASTER_ID) - d.addCallback(finish_setup) - - # set up a sourcestamp and buildset for use below - d.addCallback(lambda _ : - self.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234), - fakedb.Object(id=self.MASTER_ID, name="fake master", - class_name="BuildMaster"), - fakedb.Object(id=self.OTHER_MASTER_ID, name="other master", - class_name="BuildMaster"), - fakedb.Buildset(id=self.BSID, sourcestampsetid=234), - ])) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # tests - - def test_getBuildRequest(self): - # ned fakedb.BuildRequestClaim - d = self.insertTestData([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID, buildername="bbb", - complete=1, results=75, priority=7, - submitted_at=self.SUBMITTED_AT_EPOCH, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim( - brid=44, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequest(44)) - def check(brdict): - self.assertEqual(brdict, - dict(brid=44, buildsetid=self.BSID, buildername="bbb", - priority=7, claimed=True, mine=True, complete=True, - results=75, claimed_at=self.CLAIMED_AT, - submitted_at=self.SUBMITTED_AT, - complete_at=self.COMPLETE_AT)) - d.addCallback(check) - return d - - def test_getBuildRequest_missing(self): - d = self.db.buildrequests.getBuildRequest(44) - def check(brdict): - self.assertEqual(brdict, None) - d.addCallback(check) - return d - - def do_test_getBuildRequests_claim_args(self, **kwargs): - expected = kwargs.pop('expected') - d = self.insertTestData([ - # 50: claimed by this master - fakedb.BuildRequest(id=50, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=50, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 51: claimed by another master - fakedb.BuildRequest(id=51, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=51, objectid=self.OTHER_MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 52: unclaimed - fakedb.BuildRequest(id=52, buildsetid=self.BSID), - - # 53: unclaimed but complete (should not appear for claimed=False) - fakedb.BuildRequest(id=53, buildsetid=self.BSID, complete=1), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(**kwargs)) - def check(brlist): - self.assertEqual(sorted([ br['brid'] for br in brlist ]), - sorted(expected)) - d.addCallback(check) - return d - - def test_getBuildRequests_no_claimed_arg(self): - return self.do_test_getBuildRequests_claim_args( - expected=[50, 51, 52, 53]) - - def test_getBuildRequests_claimed_mine(self): - return self.do_test_getBuildRequests_claim_args( - claimed="mine", - expected=[50]) - - def test_getBuildRequests_claimed_true(self): - return self.do_test_getBuildRequests_claim_args( - claimed=True, - expected=[50, 51]) - - def test_getBuildRequests_unclaimed(self): - return self.do_test_getBuildRequests_claim_args( - claimed=False, - expected=[52]) - - def do_test_getBuildRequests_buildername_arg(self, **kwargs): - expected = kwargs.pop('expected') - d = self.insertTestData([ - # 8: 'bb' - fakedb.BuildRequest(id=8, buildsetid=self.BSID, buildername='bb'), - # 9: 'cc' - fakedb.BuildRequest(id=9, buildsetid=self.BSID, buildername='cc'), - # 10: 'cc' - fakedb.BuildRequest(id=10, buildsetid=self.BSID, buildername='cc'), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(**kwargs)) - def check(brlist): - self.assertEqual(sorted([ br['brid'] for br in brlist ]), - sorted(expected)) - d.addCallback(check) - return d - - def test_getBuildRequests_buildername_single(self): - return self.do_test_getBuildRequests_buildername_arg( - buildername='bb', - expected=[8]) - - def test_getBuildRequests_buildername_multiple(self): - return self.do_test_getBuildRequests_buildername_arg( - buildername='cc', - expected=[9,10]) - - def test_getBuildRequests_buildername_none(self): - return self.do_test_getBuildRequests_buildername_arg( - buildername='dd', - expected=[]) - - def do_test_getBuildRequests_complete_arg(self, **kwargs): - expected = kwargs.pop('expected') - d = self.insertTestData([ - # 70: incomplete - fakedb.BuildRequest(id=70, buildsetid=self.BSID, - complete=0, complete_at=None), - # 80: complete - fakedb.BuildRequest(id=80, buildsetid=self.BSID, - complete=1, - complete_at=self.COMPLETE_AT_EPOCH), - # 81: complete but no complete_at - fakedb.BuildRequest(id=81, buildsetid=self.BSID, - complete=1, complete_at=0), - # 82: complete_at set but complete is false, so not complete - fakedb.BuildRequest(id=82, buildsetid=self.BSID, - complete=0, - complete_at=self.COMPLETE_AT_EPOCH), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(**kwargs)) - def check(brlist): - self.assertEqual(sorted([ br['brid'] for br in brlist ]), - sorted(expected)) - d.addCallback(check) - return d - - def test_getBuildRequests_complete_none(self): - return self.do_test_getBuildRequests_complete_arg( - expected=[ 70, 80, 81, 82]) - - def test_getBuildRequests_complete_true(self): - return self.do_test_getBuildRequests_complete_arg( - complete=True, - expected=[ 80, 81 ]) - - def test_getBuildRequests_complete_false(self): - return self.do_test_getBuildRequests_complete_arg( - complete=False, - expected=[ 70, 82 ]) - - def test_getBuildRequests_bsid_arg(self): - d = self.insertTestData([ - # the buildset that we are *not* looking for - fakedb.Buildset(id=self.BSID+1, sourcestampsetid=234), - - fakedb.BuildRequest(id=70, buildsetid=self.BSID, - complete=0, complete_at=None), - fakedb.BuildRequest(id=71, buildsetid=self.BSID+1, - complete=0, complete_at=None), - fakedb.BuildRequest(id=72, buildsetid=self.BSID, - complete=0, complete_at=None), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(bsid=self.BSID)) - def check(brlist): - self.assertEqual(sorted([ br['brid'] for br in brlist ]), - sorted([70, 72])) - d.addCallback(check) - return d - - def test_getBuildRequests_combo(self): - d = self.insertTestData([ - # 44: everything we want - fakedb.BuildRequest(id=44, buildsetid=self.BSID, buildername="bbb", - complete=1, results=92, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 45: different buildername - fakedb.BuildRequest(id=45, buildsetid=self.BSID, buildername="ccc", - complete=1, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim(brid=45, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 46: incomplete - fakedb.BuildRequest(id=46, buildsetid=self.BSID, buildername="bbb", - complete=0, results=92, - complete_at=0), - fakedb.BuildRequestClaim(brid=46, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 47: unclaimed - fakedb.BuildRequest(id=47, buildsetid=self.BSID, buildername="bbb", - complete=1, results=92, - complete_at=self.COMPLETE_AT_EPOCH), - - # 48: claimed by other - fakedb.BuildRequest(id=48, buildsetid=self.BSID, buildername="bbb", - complete=1, results=92, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim(brid=48, objectid=self.OTHER_MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 49: different bsid - fakedb.Buildset(id=self.BSID+1, sourcestampsetid=234), - fakedb.BuildRequest(id=49, buildsetid=self.BSID+1, - buildername="bbb", complete=1, results=92, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim(brid=49, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(buildername="bbb", - claimed="mine", complete=True, bsid=self.BSID)) - def check(brlist): - self.assertEqual([ br['brid'] for br in brlist ], [ 44 ]) - d.addCallback(check) - return d - - def do_test_getBuildRequests_branch_arg(self, **kwargs): - expected = kwargs.pop('expected') - d = self.insertTestData([ - fakedb.BuildRequest(id=70, buildsetid=self.BSID+1), - fakedb.Buildset(id=self.BSID+1, sourcestampsetid=self.BSID+1), - fakedb.SourceStampSet(id=self.BSID+1), - fakedb.SourceStamp(sourcestampsetid=self.BSID+1, - branch='branch_A'), - - fakedb.BuildRequest(id=80, buildsetid=self.BSID+2), - fakedb.Buildset(id=self.BSID+2, sourcestampsetid=self.BSID+2), - fakedb.SourceStampSet(id=self.BSID+2), - fakedb.SourceStamp(sourcestampsetid=self.BSID+2, - repository='repository_A'), - - fakedb.BuildRequest(id=90, buildsetid=self.BSID+3), - fakedb.Buildset(id=self.BSID+3, sourcestampsetid=self.BSID+3), - fakedb.SourceStampSet(id=self.BSID+3), - fakedb.SourceStamp(sourcestampsetid=self.BSID+3, - branch='branch_A', repository='repository_A'), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.getBuildRequests(**kwargs)) - def check(brlist): - self.assertEqual(sorted([ br['brid'] for br in brlist ]), - sorted(expected)) - d.addCallback(check) - return d - - def test_getBuildRequests_branch(self): - return self.do_test_getBuildRequests_branch_arg(branch='branch_A', - expected=[70, 90]) - - def test_getBuildRequests_branch_empty(self): - return self.do_test_getBuildRequests_branch_arg(branch='absent_branch', - expected=[]) - - def test_getBuildRequests_repository(self): - return self.do_test_getBuildRequests_branch_arg( - repository='repository_A', expected=[80, 90]) - - def test_getBuildRequests_repository_empty(self): - return self.do_test_getBuildRequests_branch_arg( - repository='absent_repository', expected=[]) - - def test_getBuildRequests_repository_and_branch(self): - return self.do_test_getBuildRequests_branch_arg( - repository='repository_A', branch='branch_A', expected=[90]) - - def test_getBuildRequests_no_repository_nor_branch(self): - return self.do_test_getBuildRequests_branch_arg(expected=[70, 80, 90]) - - def do_test_claimBuildRequests(self, rows, now, brids, expected=None, - expfailure=None, claimed_at=None): - clock = task.Clock() - clock.advance(now) - - d = self.insertTestData(rows) - d.addCallback(lambda _ : - self.db.buildrequests.claimBuildRequests(brids=brids, - claimed_at=claimed_at, _reactor=clock)) - def check(brlist): - self.assertNotEqual(expected, None, - "unexpected success from claimBuildRequests") - def thd(conn): - reqs_tbl = self.db.model.buildrequests - claims_tbl = self.db.model.buildrequest_claims - q = sa.select([ reqs_tbl.outerjoin(claims_tbl, - reqs_tbl.c.id == claims_tbl.c.brid) ]) - results = conn.execute(q).fetchall() - self.assertEqual( - sorted([ (r.id, r.claimed_at, r.objectid) - for r in results ]), - sorted(expected)) - return self.db.pool.do(thd) - d.addCallback(check) - def fail(f): - if not expfailure: - raise f - f.trap(expfailure) - d.addErrback(fail) - return d - - def test_claimBuildRequests_single(self): - return self.do_test_claimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - ], 1300305712, [ 44 ], - [ (44, 1300305712, self.MASTER_ID) ]) - - def test_claimBuildRequests_single_explicit_claimed_at(self): - return self.do_test_claimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - ], 1300305712, [ 44 ], - [ (44, 14000000, self.MASTER_ID) ], - claimed_at=epoch2datetime(14000000)) - - def test_claimBuildRequests_multiple(self): - return self.do_test_claimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - fakedb.BuildRequest(id=46, buildsetid=self.BSID), - ], 1300305712, [ 44, 46 ], - [ - (44, 1300305712, self.MASTER_ID), - (45, None, None), - (46, 1300305712, self.MASTER_ID), - ]) - - def test_claimBuildRequests_stress(self): - return self.do_test_claimBuildRequests([ - fakedb.BuildRequest(id=id, buildsetid=self.BSID) - for id in xrange(1, 1000) - ], 1300305713, range(1, 1000), - [ - (id, 1300305713, self.MASTER_ID) - for id in xrange(1, 1000) - ]) - - def test_claimBuildRequests_other_master_claim(self): - return self.do_test_claimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, - objectid=self.OTHER_MASTER_ID, - claimed_at=1300103810), - ], 1300305712, [ 44 ], - expfailure=buildrequests.AlreadyClaimedError) - - @db.skip_for_dialect('mysql') - def test_claimBuildRequests_other_master_claim_stress(self): - d = self.do_test_claimBuildRequests( - [ fakedb.BuildRequest(id=id, buildsetid=self.BSID) - for id in range(1, 1000) ] + - [ - fakedb.BuildRequest(id=1000, buildsetid=self.BSID), - # the fly in the ointment.. - fakedb.BuildRequestClaim(brid=1000, - objectid=self.OTHER_MASTER_ID, claimed_at=1300103810), - ], 1300305712, range(1, 1001), - expfailure=buildrequests.AlreadyClaimedError) - def check(_): - # check that [1,1000) were not claimed, and 1000 is still claimed - def thd(conn): - tbl = self.db.model.buildrequest_claims - q = tbl.select() - results = conn.execute(q).fetchall() - self.assertEqual([ (r.brid, r.objectid, r.claimed_at) - for r in results ][:10], - [ (1000, self.OTHER_MASTER_ID, 1300103810) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_claimBuildRequests_sequential(self): - now = 120350934 - clock = task.Clock() - clock.advance(now) - - d = self.insertTestData([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - ]) - d.addCallback(lambda _ : - self.db.buildrequests.claimBuildRequests(brids=[44], - _reactor=clock)) - d.addCallback(lambda _ : - self.db.buildrequests.claimBuildRequests(brids=[45], - _reactor=clock)) - def check(brlist): - def thd(conn): - reqs_tbl = self.db.model.buildrequests - claims_tbl = self.db.model.buildrequest_claims - join = reqs_tbl.outerjoin(claims_tbl, - reqs_tbl.c.id == claims_tbl.c.brid) - q = join.select(claims_tbl.c.claimed_at == None) - results = conn.execute(q).fetchall() - self.assertEqual(results, []) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def do_test_reclaimBuildRequests(self, rows, now, brids, expected=None, - expfailure=None): - clock = task.Clock() - clock.advance(now) - - d = self.insertTestData(rows) - d.addCallback(lambda _ : - self.db.buildrequests.reclaimBuildRequests(brids=brids, - _reactor=clock)) - def check(brlist): - self.assertNotEqual(expected, None, - "unexpected success from claimBuildRequests") - def thd(conn): - reqs_tbl = self.db.model.buildrequests - claims_tbl = self.db.model.buildrequest_claims - q = sa.select([ reqs_tbl.outerjoin(claims_tbl, - reqs_tbl.c.id == claims_tbl.c.brid) ]) - results = conn.execute(q).fetchall() - self.assertEqual( - sorted([ (r.id, r.claimed_at, r.objectid) - for r in results ]), - sorted(expected)) - return self.db.pool.do(thd) - d.addCallback(check) - def fail(f): - if not expfailure: - raise f - f.trap(expfailure) - d.addErrback(fail) - return d - - def test_reclaimBuildRequests(self): - return self.do_test_reclaimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=1300103810), - ], 1300305712, [ 44 ], - # note that the time is updated - [ (44, 1300305712, self.MASTER_ID) ]) - - def test_reclaimBuildRequests_fail(self): - d = self.do_test_reclaimBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=1300103810), - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=45, objectid=self.OTHER_MASTER_ID, - claimed_at=1300103810), - ], 1300305712, [ 44, 45 ], - expfailure=buildrequests.AlreadyClaimedError) - def check(_): - # check that the time wasn't updated on 44, noting that MySQL does - # not support this. - if self.db_engine.dialect.name == 'mysql': - return - def thd(conn): - tbl = self.db.model.buildrequest_claims - q = tbl.select(order_by=tbl.c.brid) - results = conn.execute(q).fetchall() - self.assertEqual([ (r.brid, r.claimed_at, r.objectid) - for r in results ], [ - (44, 1300103810, self.MASTER_ID), - (45, 1300103810, self.OTHER_MASTER_ID), - ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def do_test_completeBuildRequests(self, rows, now, expected=None, - expfailure=None, brids=[44], - complete_at=None): - clock = task.Clock() - clock.advance(now) - - d = self.insertTestData(rows) - d.addCallback(lambda _ : - self.db.buildrequests.completeBuildRequests(brids=brids, - results=7, complete_at=complete_at, - _reactor=clock)) - def check(brlist): - self.assertNotEqual(expected, None, - "unexpected success from completeBuildRequests") - def thd(conn): - tbl = self.db.model.buildrequests - q = sa.select([ tbl.c.id, tbl.c.complete, - tbl.c.results, tbl.c.complete_at ]) - results = conn.execute(q).fetchall() - self.assertEqual(sorted(map(tuple, results)), sorted(expected)) - return self.db.pool.do(thd) - d.addCallback(check) - def fail(f): - if not expfailure: - raise f - f.trap(expfailure) - d.addErrback(fail) - return d - - def test_completeBuildRequests(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=1300103810), - ], 1300305712, - [ (44, 1, 7, 1300305712) ]) - - def test_completeBuildRequests_explicit_time(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=1300103810), - ], 1300305712, - [ (44, 1, 7, 999999) ], - complete_at=epoch2datetime(999999)) - - def test_completeBuildRequests_multiple(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=1300103810), - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=45, objectid=self.OTHER_MASTER_ID, - claimed_at=1300103811), - fakedb.BuildRequest(id=46, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=46, objectid=self.MASTER_ID, - claimed_at=1300103812), - ], 1300305712, - [ (44, 1, 7, 1300305712), - (45, 0, -1, 0), - (46, 1, 7, 1300305712), - ], brids=[44, 46]) - - def test_completeBuildRequests_stress(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=id, buildsetid=self.BSID) - for id in range(1, 280) - ] + [ - fakedb.BuildRequestClaim(brid=id, objectid=self.MASTER_ID, - claimed_at=1300103810) - for id in range(1, 280) - ], 1300305712, - [ (id, 1, 7, 1300305712) - for id in range(1, 280) - ], brids=range(1, 280)) - - def test_completeBuildRequests_multiple_notmine(self): - # note that the requests are completed even though they are not mine! - return self.do_test_completeBuildRequests([ - # two unclaimed requests - fakedb.BuildRequest(id=44, buildsetid=self.BSID), - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - # and one claimed by another master - fakedb.BuildRequest(id=46, buildsetid=self.BSID), - fakedb.BuildRequestClaim(brid=46, objectid=self.OTHER_MASTER_ID, - claimed_at=1300103812), - ], 1300305712, - [ (44, 1, 7, 1300305712), - (45, 1, 7, 1300305712), - (46, 1, 7, 1300305712), ], - brids=[44, 45, 46]) - - def test_completeBuildRequests_already_completed(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=44, buildsetid=self.BSID, - complete=1, complete_at=1300104190), - ], 1300305712, - expfailure=buildrequests.NotClaimedError) - - def test_completeBuildRequests_no_such(self): - return self.do_test_completeBuildRequests([ - fakedb.BuildRequest(id=45, buildsetid=self.BSID), - ], 1300305712, - expfailure=buildrequests.NotClaimedError) - - def do_test_unclaimMethod(self, method, expected): - d = self.insertTestData([ - # 44: a complete build (should not be unclaimed) - fakedb.BuildRequest(id=44, buildsetid=self.BSID, - complete=1, results=92, - complete_at=self.COMPLETE_AT_EPOCH), - fakedb.BuildRequestClaim(brid=44, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 45: incomplete build belonging to this incarnation - fakedb.BuildRequest(id=45, buildsetid=self.BSID, - complete=0, complete_at=0), - fakedb.BuildRequestClaim(brid=45, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 46: incomplete build belonging to another master - fakedb.BuildRequest(id=46, buildsetid=self.BSID, - complete=0, complete_at=0), - fakedb.BuildRequestClaim(brid=46, objectid=self.OTHER_MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH), - - # 47: unclaimed - fakedb.BuildRequest(id=47, buildsetid=self.BSID, - complete=0, complete_at=0), - - # 48: claimed by this master, but recently - fakedb.BuildRequest(id=48, buildsetid=self.BSID, - complete=0, complete_at=0), - fakedb.BuildRequestClaim(brid=48, objectid=self.MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH-50), - - # 49: incomplete old build belonging to another master - fakedb.BuildRequest(id=49, buildsetid=self.BSID, - complete=0, complete_at=0), - fakedb.BuildRequestClaim(brid=49, objectid=self.OTHER_MASTER_ID, - claimed_at=self.CLAIMED_AT_EPOCH - 1000), - ]) - d.addCallback(lambda _ : method()) - def check(brlist): - def thd(conn): - # just select the unclaimed requests - reqs_tbl = self.db.model.buildrequests - claims_tbl = self.db.model.buildrequest_claims - join = reqs_tbl.outerjoin(claims_tbl, - reqs_tbl.c.id == claims_tbl.c.brid) - q = sa.select([ reqs_tbl.c.id ], - from_obj=[ join ], - whereclause=claims_tbl.c.claimed_at == None) - results = conn.execute(q).fetchall() - self.assertEqual(sorted([ r.id for r in results ]), - sorted(expected)) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_unclaimExpiredRequests(self): - clock = task.Clock() - clock.advance(self.CLAIMED_AT_EPOCH) - - meth = self.db.buildrequests.unclaimExpiredRequests - return self.do_test_unclaimMethod( - lambda : meth(100, _reactor=clock), - [47, 49]) - - def test_unclaimBuildRequests(self): - to_unclaim = [ - 44, # completed -> unclaimed anyway - 45, # incomplete -> unclaimed - 46, # from another master -> not unclaimed - 47, # unclaimed -> still unclaimed - 48, # claimed -> unclaimed - 49, # another master -> not unclaimed - 50 # no such buildrequest -> no error - ] - return self.do_test_unclaimMethod( - lambda : self.db.buildrequests.unclaimBuildRequests(to_unclaim), - [44, 45, 47, 48]) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_builds.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_builds.py deleted file mode 100644 index 1773e1d1..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_builds.py +++ /dev/null @@ -1,159 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer, task -from buildbot.db import builds -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb -from buildbot.util import epoch2datetime - -class TestBuildsConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['builds', 'buildrequests', 'buildsets', - 'sourcestamps', 'sourcestampsets', 'patches' ]) - - def finish_setup(_): - self.db.builds = builds.BuildsConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # common sample data - - background_data = [ - fakedb.SourceStampSet(id=27), - fakedb.SourceStamp(id=27, sourcestampsetid=27, revision='abcd'), - fakedb.Buildset(id=20, sourcestampsetid=27), - fakedb.Buildset(id=30, sourcestampsetid=27), - fakedb.BuildRequest(id=41, buildsetid=20, buildername='b1'), - fakedb.BuildRequest(id=42, buildsetid=30, buildername='b1'), - ] - - # tests - - def test_getBuild(self): - d = self.insertTestData(self.background_data + [ - fakedb.Build(id=50, brid=42, number=5, start_time=1304262222), - ]) - d.addCallback(lambda _ : - self.db.builds.getBuild(50)) - def check(bdict): - self.assertEqual(bdict, dict(bid=50, number=5, brid=42, - start_time=epoch2datetime(1304262222), finish_time=None)) - d.addCallback(check) - return d - - def test_getBuild_missing(self): - d = defer.succeed(None) - d.addCallback(lambda _ : - self.db.builds.getBuild(50)) - def check(bdict): - self.assertEqual(bdict, None) - d.addCallback(check) - return d - - def test_getBuildsForRequest(self): - d = self.insertTestData(self.background_data + [ - fakedb.Build(id=50, brid=42, number=5, start_time=1304262222), - fakedb.Build(id=51, brid=41, number=6, start_time=1304262223), - fakedb.Build(id=52, brid=42, number=7, start_time=1304262224, - finish_time=1304262235), - ]) - d.addCallback(lambda _ : - self.db.builds.getBuildsForRequest(42)) - def check(bdicts): - self.assertEqual(sorted(bdicts), sorted([ - dict(bid=50, number=5, brid=42, - start_time=epoch2datetime(1304262222), finish_time=None), - dict(bid=52, number=7, brid=42, - start_time=epoch2datetime(1304262224), - finish_time=epoch2datetime(1304262235)), - ])) - d.addCallback(check) - return d - - def test_addBuild(self): - clock = task.Clock() - clock.advance(1302222222) - d = self.insertTestData(self.background_data) - d.addCallback(lambda _ : - self.db.builds.addBuild(brid=41, number=119, _reactor=clock)) - def check(_): - def thd(conn): - r = conn.execute(self.db.model.builds.select()) - rows = [ (row.brid, row.number, row.start_time, - row.finish_time) for row in r.fetchall() ] - self.assertEqual(rows, - [ (41, 119, 1302222222, None) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_finishBuilds(self): - clock = task.Clock() - clock.advance(1305555555) - - d = self.insertTestData(self.background_data + [ - fakedb.Build(id=50, brid=41, number=5, start_time=1304262222), - fakedb.Build(id=51, brid=42, number=5, start_time=1304262222), - fakedb.Build(id=52, brid=42, number=6, start_time=1304262222), - ]) - d.addCallback(lambda _ : - self.db.builds.finishBuilds([50,51], _reactor=clock)) - def check(_): - def thd(conn): - r = conn.execute(self.db.model.builds.select()) - rows = [ (row.id, row.brid, row.number, row.start_time, - row.finish_time) for row in r.fetchall() ] - self.assertEqual(sorted(rows), [ - (50, 41, 5, 1304262222, 1305555555), - (51, 42, 5, 1304262222, 1305555555), - (52, 42, 6, 1304262222, None), - ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_finishBuilds_big(self): - clock = task.Clock() - clock.advance(1305555555) - - d = self.insertTestData(self.background_data + [ - fakedb.Build(id=nn, brid=41, number=nn, start_time=1304262222) - for nn in xrange(50,200) - ]) - d.addCallback(lambda _ : - self.db.builds.finishBuilds(range(50,200), _reactor=clock)) - def check(_): - def thd(conn): - r = conn.execute(self.db.model.builds.select()) - rows = [ (row.id, row.brid, row.number, row.start_time, - row.finish_time) for row in r.fetchall() ] - self.assertEqual(sorted(rows), [ - (nn, 41, nn, 1304262222, 1305555555) - for nn in xrange(50,200) - ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildsets.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildsets.py deleted file mode 100644 index 714a7ab0..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_buildsets.py +++ /dev/null @@ -1,430 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import datetime -from twisted.trial import unittest -from twisted.internet import defer, task -from buildbot.db import buildsets -from buildbot.util import json, UTC, epoch2datetime -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb - -class TestBuildsetsConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - self.now = 9272359 - self.clock = task.Clock() - self.clock.advance(self.now) - - d = self.setUpConnectorComponent( - table_names=[ 'patches', 'changes', 'sourcestamp_changes', - 'buildsets', 'buildset_properties', 'objects', - 'buildrequests', 'sourcestamps', 'sourcestampsets' ]) - - def finish_setup(_): - self.db.buildsets = buildsets.BuildsetsConnectorComponent(self.db) - d.addCallback(finish_setup) - - # set up a sourcestamp with id 234 for use below - d.addCallback(lambda _ : - self.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234), - ])) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # tests - - def test_addBuildset_simple(self): - d = defer.succeed(None) - d.addCallback(lambda _ : - self.db.buildsets.addBuildset(sourcestampsetid=234, reason='because', - properties={}, builderNames=['bldr'], external_idstring='extid', - _reactor=self.clock)) - def check((bsid, brids)): - def thd(conn): - # we should only have one brid - self.assertEqual(len(brids), 1) - - # should see one buildset row - r = conn.execute(self.db.model.buildsets.select()) - rows = [ (row.id, row.external_idstring, row.reason, - row.sourcestampsetid, row.complete, row.complete_at, - row.submitted_at, row.results) for row in r.fetchall() ] - self.assertEqual(rows, - [ ( bsid, 'extid', 'because', 234, 0, None, self.now, -1) ]) - - # and one buildrequests row - r = conn.execute(self.db.model.buildrequests.select()) - - rows = [ (row.buildsetid, row.id, row.buildername, - row.priority, row.complete, row.results, - row.submitted_at, row.complete_at) - for row in r.fetchall() ] - self.assertEqual(rows, - [ ( bsid, brids['bldr'], 'bldr', 0, 0, - -1, self.now, None) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_addBuildset_bigger(self): - props = dict(prop=(['list'], 'test')) - d = defer.succeed(None) - d.addCallback(lambda _ : - self.db.buildsets.addBuildset(sourcestampsetid=234, reason='because', - properties=props, builderNames=['a', 'b'])) - def check((bsid, brids)): - def thd(conn): - self.assertEqual(len(brids), 2) - - # should see one buildset row - r = conn.execute(self.db.model.buildsets.select()) - rows = [ (row.id, row.external_idstring, row.reason, - row.sourcestampsetid, row.complete, - row.complete_at, row.results) - for row in r.fetchall() ] - self.assertEqual(rows, - [ ( bsid, None, u'because', 234, 0, None, -1) ]) - - # one property row - r = conn.execute(self.db.model.buildset_properties.select()) - rows = [ (row.buildsetid, row.property_name, row.property_value) - for row in r.fetchall() ] - self.assertEqual(rows, - [ ( bsid, 'prop', json.dumps([ ['list'], 'test' ]) ) ]) - - # and two buildrequests rows (and don't re-check the default columns) - r = conn.execute(self.db.model.buildrequests.select()) - rows = [ (row.buildsetid, row.id, row.buildername) - for row in r.fetchall() ] - - # we don't know which of the brids is assigned to which - # buildername, but either one will do - self.assertEqual(sorted(rows), - [ ( bsid, brids['a'], 'a'), (bsid, brids['b'], 'b') ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def do_test_getBuildsetProperties(self, buildsetid, rows, expected): - d = self.insertTestData(rows) - d.addCallback(lambda _ : - self.db.buildsets.getBuildsetProperties(buildsetid)) - def check(props): - self.assertEqual(props, expected) - d.addCallback(check) - return d - - def test_getBuildsetProperties_multiple(self): - return self.do_test_getBuildsetProperties(91, [ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - results=-1, submitted_at=0), - fakedb.BuildsetProperty(buildsetid=91, property_name='prop1', - property_value='["one", "fake1"]'), - fakedb.BuildsetProperty(buildsetid=91, property_name='prop2', - property_value='["two", "fake2"]'), - ], dict(prop1=("one", "fake1"), prop2=("two", "fake2"))) - - def test_getBuildsetProperties_empty(self): - return self.do_test_getBuildsetProperties(91, [ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - results=-1, submitted_at=0), - ], dict()) - - def test_getBuildsetProperties_nosuch(self): - "returns an empty dict even if no such buildset exists" - return self.do_test_getBuildsetProperties(91, [], dict()) - - def test_getBuildset_incomplete_None(self): - d = self.insertTestData([ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - complete_at=None, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn'), - ]) - d.addCallback(lambda _ : - self.db.buildsets.getBuildset(91)) - def check(bsdict): - self.assertEqual(bsdict, dict(external_idstring='extid', - reason='rsn', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=False, complete_at=None, results=-1, - bsid=91)) - d.addCallback(check) - return d - - def test_getBuildset_incomplete_zero(self): - d = self.insertTestData([ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - complete_at=0, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn'), - ]) - d.addCallback(lambda _ : - self.db.buildsets.getBuildset(91)) - def check(bsdict): - self.assertEqual(bsdict, dict(external_idstring='extid', - reason='rsn', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=False, complete_at=None, results=-1, - bsid=91)) - d.addCallback(check) - return d - - def test_getBuildset_complete(self): - d = self.insertTestData([ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=1, - complete_at=298297875, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn'), - ]) - d.addCallback(lambda _ : - self.db.buildsets.getBuildset(91)) - def check(bsdict): - self.assertEqual(bsdict, dict(external_idstring='extid', - reason='rsn', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=True, - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 15, - tzinfo=UTC), - results=-1, - bsid=91)) - d.addCallback(check) - return d - - def test_getBuildset_nosuch(self): - d = self.db.buildsets.getBuildset(91) - def check(bsdict): - self.assertEqual(bsdict, None) - d.addCallback(check) - return d - - def insert_test_getBuildsets_data(self): - return self.insertTestData([ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - complete_at=298297875, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn1'), - fakedb.Buildset(id=92, sourcestampsetid=234, complete=1, - complete_at=298297876, results=7, submitted_at=266761876, - external_idstring='extid', reason='rsn2'), - ]) - - def test_getBuildsets_empty(self): - d = self.db.buildsets.getBuildsets() - def check(bsdictlist): - self.assertEqual(bsdictlist, []) - d.addCallback(check) - return d - - def test_getBuildsets_all(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getBuildsets()) - def check(bsdictlist): - self.assertEqual(sorted(bsdictlist), sorted([ - dict(external_idstring='extid', reason='rsn1', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=False, results=-1, bsid=91), - dict(external_idstring='extid', reason='rsn2', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete=True, results=7, bsid=92), - ])) - d.addCallback(check) - return d - - def test_getBuildsets_complete(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getBuildsets(complete=True)) - def check(bsdictlist): - self.assertEqual(bsdictlist, [ - dict(external_idstring='extid', reason='rsn2', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete=True, results=7, bsid=92), - ]) - d.addCallback(check) - return d - - def test_getBuildsets_incomplete(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getBuildsets(complete=False)) - def check(bsdictlist): - self.assertEqual(bsdictlist, [ - dict(external_idstring='extid', reason='rsn1', sourcestampsetid=234, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=False, results=-1, bsid=91), - ]) - d.addCallback(check) - return d - - def test_completeBuildset(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.completeBuildset(bsid=91, results=6, - _reactor=self.clock)) - def check(_): - def thd(conn): - # should see one buildset row - r = conn.execute(self.db.model.buildsets.select()) - rows = [ (row.id, row.complete, row.complete_at, row.results) - for row in r.fetchall() ] - self.assertEqual(sorted(rows), sorted([ - ( 91, 1, self.now, 6), - ( 92, 1, 298297876, 7) ])) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_completeBuildset_explicit_complete_at(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.completeBuildset(bsid=91, results=6, - complete_at=epoch2datetime(72759))) - def check(_): - def thd(conn): - # should see one buildset row - r = conn.execute(self.db.model.buildsets.select()) - rows = [ (row.id, row.complete, row.complete_at, row.results) - for row in r.fetchall() ] - self.assertEqual(sorted(rows), sorted([ - ( 91, 1, 72759, 6), - ( 92, 1, 298297876, 7) ])) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_completeBuildset_already_completed(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.completeBuildset(bsid=92, results=6, - _reactor=self.clock)) - return self.assertFailure(d, KeyError) - - def test_completeBuildset_missing(self): - d = self.insert_test_getBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.completeBuildset(bsid=93, results=6, - _reactor=self.clock)) - return self.assertFailure(d, KeyError) - - def insert_test_getRecentBuildsets_data(self): - return self.insertTestData([ - fakedb.SourceStamp(id=91, branch='branch_a', repository='repo_a', - sourcestampsetid=91), - fakedb.SourceStampSet(id=91), - - fakedb.Buildset(id=91, sourcestampsetid=91, complete=0, - complete_at=298297875, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn1'), - fakedb.Buildset(id=92, sourcestampsetid=91, complete=1, - complete_at=298297876, results=7, submitted_at=266761876, - external_idstring='extid', reason='rsn2'), - - # buildset unrelated to the change - fakedb.SourceStampSet(id=1), - fakedb.Buildset(id=93, sourcestampsetid=1, complete=1, - complete_at=298297877, results=7, submitted_at=266761877, - external_idstring='extid', reason='rsn2'), - ]) - - def test_getRecentBuildsets_all(self): - d = self.insert_test_getRecentBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getRecentBuildsets(2, branch='branch_a', - repository='repo_a')) - def check(bsdictlist): - self.assertEqual(bsdictlist, [ - dict(external_idstring='extid', reason='rsn1', sourcestampsetid=91, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 15, - tzinfo=UTC), - complete=False, results=-1, bsid=91), - dict(external_idstring='extid', reason='rsn2', sourcestampsetid=91, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete=True, results=7, bsid=92), - ]) - d.addCallback(check) - return d - - def test_getRecentBuildsets_one(self): - d = self.insert_test_getRecentBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getRecentBuildsets(1, branch='branch_a', - repository='repo_a')) - def check(bsdictlist): - self.assertEqual(bsdictlist, [ - dict(external_idstring='extid', reason='rsn2', sourcestampsetid=91, - submitted_at=datetime.datetime(1978, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete_at=datetime.datetime(1979, 6, 15, 12, 31, 16, - tzinfo=UTC), - complete=True, results=7, bsid=92), - ]) - d.addCallback(check) - return d - - def test_getRecentBuildsets_zero(self): - d = self.insert_test_getRecentBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getRecentBuildsets(0, branch='branch_a', - repository='repo_a')) - def check(bsdictlist): - self.assertEqual(bsdictlist, []) - d.addCallback(check) - return d - - def test_getRecentBuildsets_noBranchMatch(self): - d = self.insert_test_getRecentBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getRecentBuildsets(2, branch='bad_branch', - repository='repo_a')) - def check(bsdictlist): - self.assertEqual(bsdictlist, []) - d.addCallback(check) - return d - - def test_getRecentBuildsets_noRepoMatch(self): - d = self.insert_test_getRecentBuildsets_data() - d.addCallback(lambda _ : - self.db.buildsets.getRecentBuildsets(2, branch='branch_a', - repository='bad_repo')) - def check(bsdictlist): - self.assertEqual(bsdictlist, []) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_changes.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_changes.py deleted file mode 100644 index f7427875..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_changes.py +++ /dev/null @@ -1,522 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -import pprint -import sqlalchemy as sa -from twisted.trial import unittest -from twisted.internet import defer, task -from buildbot.changes.changes import Change -from buildbot.db import changes -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb -from buildbot.util import epoch2datetime - -class TestChangesConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['changes', 'change_files', - 'change_properties', 'scheduler_changes', 'objects', - 'sourcestampsets', 'sourcestamps', 'sourcestamp_changes', - 'patches', 'change_users', 'users']) - - def finish_setup(_): - self.db.changes = changes.ChangesConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # common sample data - - change13_rows = [ - fakedb.Change(changeid=13, author="dustin", comments="fix spelling", - is_dir=0, branch="master", revision="deadbeef", - when_timestamp=266738400, revlink=None, category=None, - repository='', codebase='', project=''), - - fakedb.ChangeFile(changeid=13, filename='master/README.txt'), - fakedb.ChangeFile(changeid=13, filename='slave/README.txt'), - - fakedb.ChangeProperty(changeid=13, property_name='notest', - property_value='["no","Change"]'), - ] - - change14_rows = [ - fakedb.Change(changeid=14, author="warner", comments="fix whitespace", - is_dir=0, branch="warnerdb", revision="0e92a098b", - when_timestamp=266738404, revlink='http://warner/0e92a098b', - category='devel', repository='git://warner', codebase='mainapp', - project='Buildbot'), - - fakedb.ChangeFile(changeid=14, filename='master/buildbot/__init__.py'), - ] - - change14_dict = { - 'changeid': 14, - 'author': u'warner', - 'branch': u'warnerdb', - 'category': u'devel', - 'comments': u'fix whitespace', - 'files': [u'master/buildbot/__init__.py'], - 'is_dir': 0, - 'project': u'Buildbot', - 'properties': {}, - 'repository': u'git://warner', - 'codebase': u'mainapp', - 'revision': u'0e92a098b', - 'revlink': u'http://warner/0e92a098b', - 'when_timestamp': epoch2datetime(266738404), - } - - def change14(self): - c = Change(**dict( - category='devel', - isdir=0, - repository=u'git://warner', - codebase=u'mainapp', - who=u'warner', - when=266738404, - comments=u'fix whitespace', - project=u'Buildbot', - branch=u'warnerdb', - revlink=u'http://warner/0e92a098b', - properties={}, - files=[u'master/buildbot/__init__.py'], - revision=u'0e92a098b')) - c.number = 14 - return c - - # assertions - - def assertChangesEqual(self, ca, cb): - ok = True - ok = ok and ca.number == cb.number - ok = ok and ca.who == cb.who - ok = ok and sorted(ca.files) == sorted(cb.files) - ok = ok and ca.comments == cb.comments - ok = ok and bool(ca.isdir) == bool(cb.isdir) - ok = ok and ca.revision == cb.revision - ok = ok and ca.when == cb.when - ok = ok and ca.branch == cb.branch - ok = ok and ca.category == cb.category - ok = ok and ca.revlink == cb.revlink - ok = ok and ca.properties == cb.properties - ok = ok and ca.repository == cb.repository - ok = ok and ca.codebase == cb.codebase - ok = ok and ca.project == cb.project - if not ok: - def printable(c): - return pprint.pformat(c.__dict__) - self.fail("changes do not match; expected\n%s\ngot\n%s" % - (printable(ca), printable(cb))) - - # tests - - def test_getChange(self): - d = self.insertTestData(self.change14_rows) - def get14(_): - return self.db.changes.getChange(14) - d.addCallback(get14) - def check14(chdict): - self.assertEqual(chdict, self.change14_dict) - d.addCallback(check14) - return d - - def test_Change_fromChdict_with_chdict(self): - # test that the chdict getChange returns works with Change.fromChdict - d = Change.fromChdict(mock.Mock(), self.change14_dict) - def check(c): - self.assertChangesEqual(c, self.change14()) - d.addCallback(check) - return d - - def test_getChange_missing(self): - d = defer.succeed(None) - def get14(_): - return self.db.changes.getChange(14) - d.addCallback(get14) - def check14(chdict): - self.failUnless(chdict is None) - d.addCallback(check14) - return d - - def test_getLatestChangeid(self): - d = self.insertTestData(self.change13_rows) - def get(_): - return self.db.changes.getLatestChangeid() - d.addCallback(get) - def check(changeid): - self.assertEqual(changeid, 13) - d.addCallback(check) - return d - - def test_getLatestChangeid_empty(self): - d = defer.succeed(None) - def get(_): - return self.db.changes.getLatestChangeid() - d.addCallback(get) - def check(changeid): - self.assertEqual(changeid, None) - d.addCallback(check) - return d - - def test_addChange(self): - d = self.db.changes.addChange( - author=u'dustin', - files=[u'master/LICENSING.txt', u'slave/LICENSING.txt'], - comments=u'fix spelling', - is_dir=0, - revision=u'2d6caa52', - when_timestamp=epoch2datetime(266738400), - branch=u'master', - category=None, - revlink=None, - properties={u'platform': (u'linux', 'Change')}, - repository=u'', - codebase=u'', - project=u'') - # check all of the columns of the four relevant tables - def check_change(changeid): - def thd(conn): - self.assertEqual(changeid, 1) - r = conn.execute(self.db.model.changes.select()) - r = r.fetchall() - self.assertEqual(len(r), 1) - self.assertEqual(r[0].changeid, changeid) - self.assertEqual(r[0].author, 'dustin') - self.assertEqual(r[0].comments, 'fix spelling') - self.assertFalse(r[0].is_dir) - self.assertEqual(r[0].branch, 'master') - self.assertEqual(r[0].revision, '2d6caa52') - self.assertEqual(r[0].when_timestamp, 266738400) - self.assertEqual(r[0].category, None) - self.assertEqual(r[0].repository, '') - self.assertEqual(r[0].codebase, '') - self.assertEqual(r[0].project, '') - return self.db.pool.do(thd) - d.addCallback(check_change) - def check_change_files(_): - def thd(conn): - query = self.db.model.change_files.select() - query.where(self.db.model.change_files.c.changeid == 1) - query.order_by(self.db.model.change_files.c.filename) - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 2) - self.assertEqual(r[0].filename, 'master/LICENSING.txt') - self.assertEqual(r[1].filename, 'slave/LICENSING.txt') - return self.db.pool.do(thd) - d.addCallback(check_change_files) - def check_change_properties(_): - def thd(conn): - query = self.db.model.change_properties.select() - query.where(self.db.model.change_properties.c.changeid == 1) - query.order_by(self.db.model.change_properties.c.property_name) - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 1) - self.assertEqual(r[0].property_name, 'platform') - self.assertEqual(r[0].property_value, '["linux", "Change"]') - return self.db.pool.do(thd) - d.addCallback(check_change_properties) - def check_change_users(_): - def thd(conn): - query = self.db.model.change_users.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_users) - return d - - def test_addChange_when_timestamp_None(self): - clock = task.Clock() - clock.advance(1239898353) - d = self.db.changes.addChange( - author=u'dustin', - files=[], - comments=u'fix spelling', - is_dir=0, - revision=u'2d6caa52', - when_timestamp=None, - branch=u'master', - category=None, - revlink=None, - properties={}, - repository=u'', - codebase=u'', - project=u'', - _reactor=clock) - # check all of the columns of the four relevant tables - def check_change(changeid): - def thd(conn): - r = conn.execute(self.db.model.changes.select()) - r = r.fetchall() - self.assertEqual(len(r), 1) - self.assertEqual(r[0].changeid, changeid) - self.assertEqual(r[0].when_timestamp, 1239898353) - return self.db.pool.do(thd) - d.addCallback(check_change) - def check_change_files(_): - def thd(conn): - query = self.db.model.change_files.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_files) - def check_change_properties(_): - def thd(conn): - query = self.db.model.change_properties.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_properties) - def check_change_users(_): - def thd(conn): - query = self.db.model.change_users.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_users) - return d - - def test_addChange_with_uid(self): - d = self.insertTestData([ - fakedb.User(uid=1, identifier="one"), - ]) - d.addCallback(lambda _ : - self.db.changes.addChange( - author=u'dustin', - files=[], - comments=u'fix spelling', - is_dir=0, - revision=u'2d6caa52', - when_timestamp=epoch2datetime(1239898353), - branch=u'master', - category=None, - revlink=None, - properties={}, - repository=u'', - codebase=u'', - project=u'', - uid=1)) - # check all of the columns of the five relevant tables - def check_change(changeid): - def thd(conn): - r = conn.execute(self.db.model.changes.select()) - r = r.fetchall() - self.assertEqual(len(r), 1) - self.assertEqual(r[0].changeid, changeid) - self.assertEqual(r[0].when_timestamp, 1239898353) - return self.db.pool.do(thd) - d.addCallback(check_change) - def check_change_files(_): - def thd(conn): - query = self.db.model.change_files.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_files) - def check_change_properties(_): - def thd(conn): - query = self.db.model.change_properties.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check_change_properties) - def check_change_users(_): - def thd(conn): - query = self.db.model.change_users.select() - r = conn.execute(query) - r = r.fetchall() - self.assertEqual(len(r), 1) - self.assertEqual(r[0].changeid, 1) - self.assertEqual(r[0].uid, 1) - return self.db.pool.do(thd) - d.addCallback(check_change_users) - return d - - def test_getChangeUids_missing(self): - d = self.db.changes.getChangeUids(1) - def check(res): - self.assertEqual(res, []) - d.addCallback(check) - return d - - def test_getChangeUids_found(self): - d = self.insertTestData(self.change14_rows + [ - fakedb.User(uid=1), - fakedb.ChangeUser(changeid=14, uid=1), - ]) - d.addCallback(lambda _ : self.db.changes.getChangeUids(14)) - def check(res): - self.assertEqual(res, [1]) - d.addCallback(check) - return d - - def test_getChangeUids_multi(self): - d = self.insertTestData(self.change14_rows + self.change13_rows + [ - fakedb.User(uid=1, identifier="one"), - fakedb.User(uid=2, identifier="two"), - fakedb.User(uid=99, identifier="nooo"), - fakedb.ChangeUser(changeid=14, uid=1), - fakedb.ChangeUser(changeid=14, uid=2), - fakedb.ChangeUser(changeid=13, uid=99), # not selected - ]) - d.addCallback(lambda _ : self.db.changes.getChangeUids(14)) - def check(res): - self.assertEqual(sorted(res), [1, 2]) - d.addCallback(check) - return d - - def test_pruneChanges(self): - d = self.insertTestData([ - fakedb.Object(id=29), - fakedb.SourceStamp(id=234), - - fakedb.Change(changeid=11), - - fakedb.Change(changeid=12), - fakedb.SchedulerChange(objectid=29, changeid=12), - fakedb.SourceStampChange(sourcestampid=234, changeid=12), - ] + - - self.change13_rows + [ - fakedb.SchedulerChange(objectid=29, changeid=13), - ] + - - self.change14_rows + [ - fakedb.SchedulerChange(objectid=29, changeid=14), - - fakedb.Change(changeid=15), - fakedb.SourceStampChange(sourcestampid=234, changeid=15), - ] - ) - - # pruning with a horizon of 2 should delete changes 11, 12 and 13 - d.addCallback(lambda _ : self.db.changes.pruneChanges(2)) - def check(_): - def thd(conn): - results = {} - for tbl_name in ('scheduler_changes', 'sourcestamp_changes', - 'change_files', 'change_properties', - 'changes'): - tbl = self.db.model.metadata.tables[tbl_name] - r = conn.execute(sa.select([tbl.c.changeid])) - results[tbl_name] = sorted([ r[0] for r in r.fetchall() ]) - self.assertEqual(results, { - 'scheduler_changes': [14], - 'sourcestamp_changes': [15], - 'change_files': [14], - 'change_properties': [], - 'changes': [14, 15], - }) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_pruneChanges_lots(self): - d = self.insertTestData([ - fakedb.Change(changeid=n) - for n in xrange(1, 151) - ]) - - d.addCallback(lambda _ : self.db.changes.pruneChanges(1)) - def check(_): - def thd(conn): - results = {} - for tbl_name in ('scheduler_changes', 'sourcestamp_changes', - 'change_files', 'change_properties', - 'changes'): - tbl = self.db.model.metadata.tables[tbl_name] - r = conn.execute(sa.select([tbl.c.changeid])) - results[tbl_name] = len([ r for r in r.fetchall() ]) - self.assertEqual(results, { - 'scheduler_changes': 0, - 'sourcestamp_changes': 0, - 'change_files': 0, - 'change_properties': 0, - 'changes': 1, - }) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_pruneChanges_None(self): - d = self.insertTestData(self.change13_rows) - - d.addCallback(lambda _ : self.db.changes.pruneChanges(None)) - def check(_): - def thd(conn): - tbl = self.db.model.changes - r = conn.execute(tbl.select()) - self.assertEqual([ row.changeid for row in r.fetchall() ], - [ 13 ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_getRecentChanges_subset(self): - d = self.insertTestData([ - fakedb.Change(changeid=8), - fakedb.Change(changeid=9), - fakedb.Change(changeid=10), - fakedb.Change(changeid=11), - fakedb.Change(changeid=12), - ] + self.change13_rows + self.change14_rows) - d.addCallback(lambda _ : - self.db.changes.getRecentChanges(5)) - def check(changes): - changeids = [ c['changeid'] for c in changes ] - self.assertEqual(changeids, [10, 11, 12, 13, 14]) - d.addCallback(check) - return d - - def test_getRecentChanges_empty(self): - d = defer.succeed(None) - d.addCallback(lambda _ : - self.db.changes.getRecentChanges(5)) - def check(changes): - changeids = [ c['changeid'] for c in changes ] - self.assertEqual(changeids, []) - d.addCallback(check) - return d - - def test_getRecentChanges_missing(self): - d = self.insertTestData(self.change13_rows + self.change14_rows) - d.addCallback(lambda _ : - self.db.changes.getRecentChanges(5)) - def check(changes): - # requested 5, but only got 2 - changeids = [ c['changeid'] for c in changes ] - self.assertEqual(changeids, [13, 14]) - # double-check that they have .files, etc. - self.assertEqual(sorted(changes[0]['files']), - sorted(['master/README.txt', 'slave/README.txt'])) - self.assertEqual(changes[0]['properties'], - { 'notest' : ('no', 'Change') }) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_connector.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_connector.py deleted file mode 100644 index 3c3083cd..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_connector.py +++ /dev/null @@ -1,87 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import mock -from twisted.internet import defer -from twisted.trial import unittest -from buildbot.db import connector -from buildbot import config -from buildbot.test.util import db -from buildbot.test.fake import fakemaster - -class DBConnector(db.RealDatabaseMixin, unittest.TestCase): - """ - Basic tests of the DBConnector class - all start with an empty DB - """ - - @defer.inlineCallbacks - def setUp(self): - yield self.setUpRealDatabase(table_names=[ - 'changes', 'change_properties', 'change_files', 'patches', - 'sourcestamps', 'buildset_properties', 'buildsets', - 'sourcestampsets' ]) - - self.master = fakemaster.make_master() - self.master.config = config.MasterConfig() - self.db = connector.DBConnector(self.master, - os.path.abspath('basedir')) - - @defer.inlineCallbacks - def tearDown(self): - if self.db.running: - yield self.db.stopService() - - yield self.tearDownRealDatabase() - - @defer.inlineCallbacks - def startService(self, check_version=False): - self.master.config.db['db_url'] = self.db_url - yield self.db.setup(check_version=check_version) - self.db.startService() - yield self.db.reconfigService(self.master.config) - - - # tests - - def test_doCleanup_service(self): - d = self.startService() - @d.addCallback - def check(_): - self.assertTrue(self.db.cleanup_timer.running) - - def test_doCleanup_unconfigured(self): - self.db.changes.pruneChanges = mock.Mock( - return_value=defer.succeed(None)) - self.db._doCleanup() - self.assertFalse(self.db.changes.pruneChanges.called) - - def test_doCleanup_configured(self): - self.db.changes.pruneChanges = mock.Mock( - return_value=defer.succeed(None)) - d = self.startService() - @d.addCallback - def check(_): - self.db._doCleanup() - self.assertTrue(self.db.changes.pruneChanges.called) - return d - - def test_setup_check_version_bad(self): - d = self.startService(check_version=True) - return self.assertFailure(d, connector.DatabaseNotReadyError) - - def test_setup_check_version_good(self): - self.db.model.is_current = lambda : defer.succeed(True) - return self.startService(check_version=True) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_enginestrategy.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_enginestrategy.py deleted file mode 100644 index d9693979..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_enginestrategy.py +++ /dev/null @@ -1,176 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.python import runtime -from sqlalchemy.engine import url -from sqlalchemy.pool import NullPool -from buildbot.db import enginestrategy - -class BuildbotEngineStrategy_special_cases(unittest.TestCase): - "Test the special case methods, without actually creating a db" - - # used several times below - mysql_kwargs = dict(basedir='my-base-dir', - connect_args=dict(init_command='SET storage_engine=MyISAM'), - pool_recycle=3600) - sqlite_kwargs = dict(basedir='/my-base-dir', poolclass=NullPool) - - def setUp(self): - self.strat = enginestrategy.BuildbotEngineStrategy() - - # utility - - def filter_kwargs(self, kwargs): - # filter out the listeners list to just include the class name - if 'listeners' in kwargs: - kwargs['listeners'] = [ lstnr.__class__.__name__ - for lstnr in kwargs['listeners'] ] - return kwargs - - # tests - - def test_sqlite_pct_sub(self): - u = url.make_url("sqlite:///%(basedir)s/x/state.sqlite") - kwargs = dict(basedir='/my-base-dir') - u, kwargs, max_conns = self.strat.special_case_sqlite(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "sqlite:////my-base-dir/x/state.sqlite", None, - self.sqlite_kwargs ]) - - def test_sqlite_relpath(self): - url_src = "sqlite:///x/state.sqlite" - basedir = "/my-base-dir" - expected_url = "sqlite:////my-base-dir/x/state.sqlite" - - # this looks a whole lot different on windows - if runtime.platformType == 'win32': - url_src = r'sqlite:///X\STATE.SQLITE' - basedir = r'C:\MYBASE~1' - expected_url = r'sqlite:///C:\MYBASE~1\X\STATE.SQLITE' - - exp_kwargs = self.sqlite_kwargs.copy() - exp_kwargs['basedir'] = basedir - - u = url.make_url(url_src) - kwargs = dict(basedir=basedir) - u, kwargs, max_conns = self.strat.special_case_sqlite(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ expected_url, None, exp_kwargs ]) - - def test_sqlite_abspath(self): - u = url.make_url("sqlite:////x/state.sqlite") - kwargs = dict(basedir='/my-base-dir') - u, kwargs, max_conns = self.strat.special_case_sqlite(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "sqlite:////x/state.sqlite", None, self.sqlite_kwargs ]) - - def test_sqlite_memory(self): - u = url.make_url("sqlite://") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_sqlite(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "sqlite://", 1, # only one conn at a time - dict(basedir='my-base-dir', - # note: no poolclass= argument - pool_size=1) ]) # extra in-memory args - - def test_mysql_simple(self): - u = url.make_url("mysql://host/dbname") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql://host/dbname?charset=utf8&use_unicode=True", None, - self.mysql_kwargs ]) - - def test_mysql_userport(self): - u = url.make_url("mysql://user:pass@host:1234/dbname") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql://user:pass@host:1234/dbname?" - "charset=utf8&use_unicode=True", None, self.mysql_kwargs ]) - - def test_mysql_local(self): - u = url.make_url("mysql:///dbname") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&use_unicode=True", None, - self.mysql_kwargs ]) - - def test_mysql_args(self): - u = url.make_url("mysql:///dbname?foo=bar") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&foo=bar&use_unicode=True", - None, self.mysql_kwargs ]) - - def test_mysql_max_idle(self): - u = url.make_url("mysql:///dbname?max_idle=1234") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - exp = self.mysql_kwargs.copy() - exp['pool_recycle'] = 1234 - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&use_unicode=True", None, - exp ]) - - def test_mysql_good_charset(self): - u = url.make_url("mysql:///dbname?charset=utf8") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&use_unicode=True", None, - self.mysql_kwargs ]) - - def test_mysql_bad_charset(self): - u = url.make_url("mysql:///dbname?charset=ebcdic") - kwargs = dict(basedir='my-base-dir') - self.assertRaises(TypeError, - lambda : self.strat.special_case_mysql(u, kwargs)) - - def test_mysql_good_use_unicode(self): - u = url.make_url("mysql:///dbname?use_unicode=True") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&use_unicode=True", None, - self.mysql_kwargs ]) - - def test_mysql_bad_use_unicode(self): - u = url.make_url("mysql:///dbname?use_unicode=maybe") - kwargs = dict(basedir='my-base-dir') - self.assertRaises(TypeError, - lambda : self.strat.special_case_mysql(u, kwargs)) - - def test_mysql_storage_engine(self): - u = url.make_url("mysql:///dbname?storage_engine=foo") - kwargs = dict(basedir='my-base-dir') - u, kwargs, max_conns = self.strat.special_case_mysql(u, kwargs) - exp = self.mysql_kwargs.copy() - exp['connect_args'] = dict(init_command='SET storage_engine=foo') - self.assertEqual([ str(u), max_conns, self.filter_kwargs(kwargs) ], - [ "mysql:///dbname?charset=utf8&use_unicode=True", None, - exp ]) - - -class BuildbotEngineStrategy(unittest.TestCase): - "Test create_engine by creating a sqlite in-memory db" - - def test_create_engine(self): - engine = enginestrategy.create_engine('sqlite://', basedir="/base") - self.assertEqual(engine.scalar("SELECT 13 + 14"), 27) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_011_add_buildrequest_claims.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_011_add_buildrequest_claims.py deleted file mode 100644 index ea895983..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_011_add_buildrequest_claims.py +++ /dev/null @@ -1,107 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.util import migration -import sqlalchemy as sa -from sqlalchemy.engine import reflection - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - self.buildsets = sa.Table('buildsets', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('external_idstring', sa.String(256)), - sa.Column('reason', sa.String(256)), - sa.Column('sourcestampid', sa.Integer, - nullable=False), # NOTE: foreign key omitted - sa.Column('submitted_at', sa.Integer, nullable=False), - sa.Column('complete', sa.SmallInteger, nullable=False, - server_default=sa.DefaultClause("0")), - sa.Column('complete_at', sa.Integer), - sa.Column('results', sa.SmallInteger), - ) - self.buildsets.create(bind=conn) - - self.buildrequests = sa.Table('buildrequests', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('buildsetid', sa.Integer, sa.ForeignKey("buildsets.id"), - nullable=False), - sa.Column('buildername', sa.String(length=256), nullable=False), - sa.Column('priority', sa.Integer, nullable=False, - server_default=sa.DefaultClause("0")), - sa.Column('claimed_at', sa.Integer, - server_default=sa.DefaultClause("0")), - sa.Column('claimed_by_name', sa.String(length=256)), - sa.Column('claimed_by_incarnation', sa.String(length=256)), - sa.Column('complete', sa.Integer, - server_default=sa.DefaultClause("0")), - sa.Column('results', sa.SmallInteger), - sa.Column('submitted_at', sa.Integer, nullable=False), - sa.Column('complete_at', sa.Integer), - ) - self.buildrequests.create(bind=conn) - - idx = sa.Index('buildrequests_buildsetid', - self.buildrequests.c.buildsetid) - idx.create() - - idx = sa.Index('buildrequests_buildername', - self.buildrequests.c.buildername) - idx.create() - - idx = sa.Index('buildrequests_complete', - self.buildrequests.c.complete) - idx.create() - - self.objects = sa.Table("objects", metadata, - sa.Column("id", sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - sa.UniqueConstraint('name', 'class_name', name='object_identity'), - ) - self.objects.create(bind=conn) - - # tests - - def test_migrate(self): - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - # regression test for bug #2158; this is known to be broken on - # sqlite (and fixed in db version 016) but expected to work on - # other engines. - if conn.dialect.name != 'sqlite': - insp = reflection.Inspector.from_engine(conn) - indexes = insp.get_indexes('buildrequests') - self.assertEqual( - sorted([ i['name'] for i in indexes ]), - sorted([ - 'buildrequests_buildername', - 'buildrequests_buildsetid', - 'buildrequests_complete', - ])) - - return self.do_test_migration(10, 11, setup_thd, verify_thd) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_015_remove_bad_master_objectid.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_015_remove_bad_master_objectid.py deleted file mode 100644 index 1ee7be07..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_015_remove_bad_master_objectid.py +++ /dev/null @@ -1,140 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.util import migration -import sqlalchemy as sa - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - self.objects = sa.Table("objects", metadata, - sa.Column("id", sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - sa.UniqueConstraint('name', 'class_name', name='object_identity'), - ) - self.object_state = sa.Table("object_state", metadata, - sa.Column("objectid", sa.Integer, sa.ForeignKey('objects.id'), - nullable=False), - sa.Column("name", sa.String(length=256), nullable=False), - sa.Column("value_json", sa.Text, nullable=False), - sa.UniqueConstraint('objectid', 'name', name='name_per_object'), - ) - self.objects.create(bind=conn) - self.object_state.create(bind=conn) - - def insert_old_obj(self, conn): - conn.execute(self.objects.insert(), - id=21, - name='master', - class_name='buildbot.master.BuildMaster') - conn.execute(self.object_state.insert(), - objectid=21, - name='last_processed_change', - value_json='938') - - def insert_new_objs(self, conn, count): - for id in range(50, 50+count): - conn.execute(self.objects.insert(), - id=id, - name='some_hostname:/base/dir/%d' % id, - class_name='BuildMaster') - # (this id would be referenced from buildrequests, but that table - # doesn't change) - - def assertObjectState_thd(self, conn, exp_objects=[], - exp_object_state=[]): - tbl = self.objects - res = conn.execute(tbl.select(order_by=tbl.c.id)) - got_objects = res.fetchall() - - tbl = self.object_state - res = conn.execute(tbl.select( - order_by=[tbl.c.objectid, tbl.c.name])) - got_object_state = res.fetchall() - - self.assertEqual( - dict(objects=exp_objects, object_state=exp_object_state), - dict(objects=got_objects, object_state=got_object_state)) - - # tests - - def test_no_old_id(self): - def setup_thd(conn): - self.create_tables_thd(conn) - self.insert_new_objs(conn, 2) - - def verify_thd(conn): - self.assertObjectState_thd(conn, [ - (50, 'some_hostname:/base/dir/50', - 'buildbot.master.BuildMaster'), - (51, 'some_hostname:/base/dir/51', - 'buildbot.master.BuildMaster'), - ], []) - - return self.do_test_migration(14, 15, setup_thd, verify_thd) - - def test_no_new_id(self): - def setup_thd(conn): - self.create_tables_thd(conn) - self.insert_old_obj(conn) - - def verify_thd(conn): - self.assertObjectState_thd(conn, [], []) - - return self.do_test_migration(14, 15, setup_thd, verify_thd) - - def test_one_new_id(self): - def setup_thd(conn): - self.create_tables_thd(conn) - self.insert_old_obj(conn) - self.insert_new_objs(conn, 1) - - def verify_thd(conn): - self.assertObjectState_thd(conn, [ - (50, 'some_hostname:/base/dir/50', - 'buildbot.master.BuildMaster'), - ], [ - (50, 'last_processed_change', '938'), - ]) - - return self.do_test_migration(14, 15, setup_thd, verify_thd) - - def test_two_new_ids(self): - def setup_thd(conn): - self.create_tables_thd(conn) - self.insert_old_obj(conn) - self.insert_new_objs(conn, 2) - - def verify_thd(conn): - self.assertObjectState_thd(conn, [ - (50, 'some_hostname:/base/dir/50', - 'buildbot.master.BuildMaster'), - (51, 'some_hostname:/base/dir/51', - 'buildbot.master.BuildMaster'), - ], [ - # last_processed_change is just deleted - ]) - - return self.do_test_migration(14, 15, setup_thd, verify_thd) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_016_restore_buildrequest_indices.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_016_restore_buildrequest_indices.py deleted file mode 100644 index 0cb03645..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_016_restore_buildrequest_indices.py +++ /dev/null @@ -1,81 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.util import migration -import sqlalchemy as sa -from sqlalchemy.engine import reflection - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - self.buildrequests = sa.Table('buildrequests', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('buildsetid', sa.Integer, # foreign key removed - nullable=False), - sa.Column('buildername', sa.String(length=256), nullable=False), - sa.Column('priority', sa.Integer, nullable=False, - server_default=sa.DefaultClause("0")), - sa.Column('complete', sa.Integer, - server_default=sa.DefaultClause("0")), - sa.Column('results', sa.SmallInteger), - sa.Column('submitted_at', sa.Integer, nullable=False), - sa.Column('complete_at', sa.Integer), - ) - self.buildrequests.create(bind=conn) - - # these indices should already exist everywhere but on sqlite - if conn.dialect.name != 'sqlite': - idx = sa.Index('buildrequests_buildsetid', - self.buildrequests.c.buildsetid) - idx.create() - - idx = sa.Index('buildrequests_buildername', - self.buildrequests.c.buildername) - idx.create() - - idx = sa.Index('buildrequests_complete', - self.buildrequests.c.complete) - idx.create() - - # tests - - def test_migrate(self): - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - insp = reflection.Inspector.from_engine(conn) - indexes = insp.get_indexes('buildrequests') - self.assertEqual( - sorted([ i['name'] for i in indexes ]), - sorted([ - 'buildrequests_buildername', - 'buildrequests_buildsetid', - 'buildrequests_complete', - ])) - - - return self.do_test_migration(15, 16, setup_thd, verify_thd) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_017_restore_other_indices.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_017_restore_other_indices.py deleted file mode 100644 index e8dcd6b5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_017_restore_other_indices.py +++ /dev/null @@ -1,124 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.util import migration -import sqlalchemy as sa -from sqlalchemy.engine import reflection - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - self.changes = sa.Table('changes', metadata, - sa.Column('changeid', sa.Integer, primary_key=True), - sa.Column('author', sa.String(256), nullable=False), - sa.Column('comments', sa.String(1024), nullable=False), - sa.Column('is_dir', sa.SmallInteger, nullable=False), - sa.Column('branch', sa.String(256)), - sa.Column('revision', sa.String(256)), - sa.Column('revlink', sa.String(256)), - sa.Column('when_timestamp', sa.Integer, nullable=False), - sa.Column('category', sa.String(256)), - sa.Column('repository', sa.String(length=512), nullable=False, - server_default=''), - sa.Column('project', sa.String(length=512), nullable=False, - server_default=''), - ) - self.changes.create(bind=conn) - - self.schedulers = sa.Table("schedulers", metadata, - sa.Column('schedulerid', sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - ) - self.schedulers.create(bind=conn) - - self.users = sa.Table("users", metadata, - sa.Column("uid", sa.Integer, primary_key=True), - sa.Column("identifier", sa.String(256), nullable=False), - sa.Column("bb_username", sa.String(128)), - sa.Column("bb_password", sa.String(128)), - ) - self.users.create(bind=conn) - - self.objects = sa.Table("objects", metadata, - sa.Column("id", sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - ) - self.objects.create() - - self.object_state = sa.Table("object_state", metadata, - sa.Column("objectid", sa.Integer, sa.ForeignKey('objects.id'), - nullable=False), - sa.Column("name", sa.String(length=256), nullable=False), - sa.Column("value_json", sa.Text, nullable=False), - ) - self.object_state.create() - - # these indices should already exist everywhere but on sqlite - if conn.dialect.name != 'sqlite': - sa.Index('name_and_class', self.schedulers.c.name, - self.schedulers.c.class_name).create() - sa.Index('changes_branch', self.changes.c.branch).create() - sa.Index('changes_revision', self.changes.c.revision).create() - sa.Index('changes_author', self.changes.c.author).create() - sa.Index('changes_category', self.changes.c.category).create() - sa.Index('changes_when_timestamp', - self.changes.c.when_timestamp).create() - - # create this index without the unique attribute - sa.Index('users_identifier', self.users.c.identifier).create() - - # tests - - def test_migrate(self): - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - insp = reflection.Inspector.from_engine(conn) - indexes = (insp.get_indexes('changes') - + insp.get_indexes('schedulers')) - self.assertEqual( - sorted([ i['name'] for i in indexes ]), - sorted([ - 'changes_author', - 'changes_branch', - 'changes_category', - 'changes_revision', - 'changes_when_timestamp', - 'name_and_class', - ])) - indexes = insp.get_indexes('users') - for idx in indexes: - if idx['name'] == 'users_identifier': - self.assertTrue(idx['unique']) - break - else: - self.fail("no users_identifier index") - - return self.do_test_migration(16, 17, setup_thd, verify_thd) - - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_018_add_sourcestampset.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_018_add_sourcestampset.py deleted file mode 100644 index 790bf1ac..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_018_add_sourcestampset.py +++ /dev/null @@ -1,234 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -from sqlalchemy.engine import reflection -from twisted.python import log -from twisted.trial import unittest -from buildbot.test.util import migration - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - self.buildsets = sa.Table('buildsets', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('external_idstring', sa.String(256)), - sa.Column('reason', sa.String(256)), - sa.Column('sourcestampid', sa.Integer, - nullable=False), # NOTE: foreign key omitted - sa.Column('submitted_at', sa.Integer, nullable=False), - sa.Column('complete', sa.SmallInteger, nullable=False, - server_default=sa.DefaultClause("0")), - sa.Column('complete_at', sa.Integer), - sa.Column('results', sa.SmallInteger), - ) - self.buildsets.create(bind=conn) - sa.Index('buildsets_complete', self.buildsets.c.complete).create() - sa.Index('buildsets_submitted_at', self.buildsets.c.submitted_at).create() - - self.patches = sa.Table('patches', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('patchlevel', sa.Integer, nullable=False), - sa.Column('patch_base64', sa.Text, nullable=False), - sa.Column('patch_author', sa.Text, nullable=False), - sa.Column('patch_comment', sa.Text, nullable=False), - sa.Column('subdir', sa.Text), - ) - self.patches.create(bind=conn) - - self.sourcestamps = sa.Table('sourcestamps', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('branch', sa.String(256)), - sa.Column('revision', sa.String(256)), - sa.Column('patchid', sa.Integer, sa.ForeignKey('patches.id')), - sa.Column('repository', sa.String(length=512), nullable=False, server_default=''), - sa.Column('project', sa.String(length=512), nullable=False, server_default=''), - sa.Column('sourcestampid', sa.Integer, sa.ForeignKey('sourcestamps.id')), - ) - self.sourcestamps.create(bind=conn) - - def fill_tables_with_testdata(self, conn, testdata): - for bsid, ssid in testdata: - self.insert_buildset_sourcestamp(conn, bsid, ssid) - - def insert_buildset_sourcestamp(self, conn, bsid, sourcestampid): - conn.execute(self.buildsets.insert(), - id=bsid, - externalid_string='', - reason = 'just', - sourcestampid=sourcestampid, - submitted_at=22417200, - complete = 0, - complete_at=22417200, - results=0) - conn.execute(self.sourcestamps.insert(), - id=sourcestampid, - branch='this_branch', - revision='this_revision', - patchid = None, - repository='repo_a', - project='') - - def assertBuildsetSourceStamp_thd(self, conn, exp_buildsets=[], - exp_sourcestamps=[]): - metadata = sa.MetaData() - metadata.bind = conn - tbl = sa.Table('buildsets', metadata, autoload=True) - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], order_by=tbl.c.id)) - got_buildsets = res.fetchall() - - tbl = sa.Table('sourcestamps', metadata, autoload=True) - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], - order_by=[tbl.c.sourcestampsetid, tbl.c.id])) - got_sourcestamps = res.fetchall() - - self.assertEqual( - dict(buildsets=exp_buildsets, sourcestamps=exp_sourcestamps), - dict(buildsets=got_buildsets, sourcestamps=got_sourcestamps)) - - # tests - - def thd_assertForeignKeys(self, conn, exp, with_constrained_columns=[]): - # MySQL does not reflect or use foreign keys, so we can't check.. - if conn.dialect.name == 'mysql': - return - - insp = reflection.Inspector.from_engine(conn) - fks = orig_fks = insp.get_foreign_keys('buildsets') - - # filter out constraints including all of the given columns - with_constrained_columns = set(with_constrained_columns) - fks = sorted([ fk - for fk in fks - if not with_constrained_columns - set(fk['constrained_columns']) - ]) - - # clean up - for fk in fks: - del fk['name'] # schema dependent - del fk['referred_schema'] # idem - - # finally, assert - if fks != exp: - log.msg("got: %r" % (orig_fks,)) - self.assertEqual(fks, exp) - - def test_1_buildsets(self): - buildsetdata = [(10, 100),(20, 200),(30, 300)] - def setup_thd(conn): - self.create_tables_thd(conn) - self.fill_tables_with_testdata(conn, buildsetdata) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - tbl = sa.Table('buildsets', metadata, autoload=True) - self.assertTrue(hasattr(tbl.c, 'sourcestampsetid')) - - self.thd_assertForeignKeys(conn, [ { - 'constrained_columns':['sourcestampsetid'], - 'referred_table':'sourcestampsets', - 'referred_columns':['id']}, - ], with_constrained_columns=['sourcestampsetid']) - - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], order_by=tbl.c.id)) - got_buildsets = res.fetchall() - self.assertEqual(got_buildsets, buildsetdata) - - return self.do_test_migration(17, 18, setup_thd, verify_thd) - - def test_2_sourcestamp(self): - buildsetdata = [(10, 100),(20, 200),(30, 300)] - sourcestampdata = [ (ssid, ssid) for bsid, ssid in buildsetdata ] - def setup_thd(conn): - self.create_tables_thd(conn) - self.fill_tables_with_testdata(conn, buildsetdata) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - tbl = sa.Table('sourcestamps', metadata, autoload=True) - self.assertTrue(hasattr(tbl.c, 'sourcestampsetid')) - - self.thd_assertForeignKeys(conn, [ { - 'constrained_columns':['sourcestampsetid'], - 'referred_table':'sourcestampsets', - 'referred_columns':['id']}, - ], with_constrained_columns=['sourcestampsetid']) - - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], - order_by=[tbl.c.sourcestampsetid, tbl.c.id])) - got_sourcestamps = res.fetchall() - self.assertEqual(got_sourcestamps, sourcestampdata) - - return self.do_test_migration(17, 18, setup_thd, verify_thd) - - def test_3_sourcestampset(self): - buildsetdata = [(10, 100),(20, 200),(30, 300)] - sourcestampsetdata = [ (ssid,) for bsid, ssid in buildsetdata ] - def setup_thd(conn): - self.create_tables_thd(conn) - self.fill_tables_with_testdata(conn, buildsetdata) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - tbl = sa.Table('sourcestampsets', metadata, autoload=True) - self.assertTrue(hasattr(tbl.c, 'id')) - res = conn.execute(sa.select([tbl.c.id],order_by=[tbl.c.id])) - got_sourcestampsets = res.fetchall() - self.assertEqual(got_sourcestampsets, sourcestampsetdata) - - return self.do_test_migration(17, 18, setup_thd, verify_thd) - - def test_4_integrated_migration(self): - buildsetdata = [(10, 100),(20, 200),(30, 300)] - sourcestampdata = [ (ssid, ssid) for bsid, ssid in buildsetdata ] - sourcestampsetdata = [ (ssid,) for bsid, ssid in buildsetdata ] - def setup_thd(conn): - self.create_tables_thd(conn) - self.fill_tables_with_testdata(conn, buildsetdata) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - # Test for the buildsets - tbl = sa.Table('buildsets', metadata, autoload=True) - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], order_by=tbl.c.id)) - got_buildsets = res.fetchall() - self.assertEqual(got_buildsets, buildsetdata) - - # Test for the sourcestamps - tbl = sa.Table('sourcestamps', metadata, autoload=True) - res = conn.execute(sa.select([tbl.c.id, tbl.c.sourcestampsetid], - order_by=[tbl.c.sourcestampsetid, tbl.c.id])) - got_sourcestamps = res.fetchall() - self.assertEqual(got_sourcestamps, sourcestampdata) - - tbl = sa.Table('sourcestampsets', metadata, autoload=True) - res = conn.execute(sa.select([tbl.c.id],order_by=[tbl.c.id])) - got_sourcestampsets = res.fetchall() - self.assertEqual(got_sourcestampsets, sourcestampsetdata) - - return self.do_test_migration(17, 18, setup_thd, verify_thd) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_019_merge_schedulers_to_objects.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_019_merge_schedulers_to_objects.py deleted file mode 100644 index 452fc743..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_019_merge_schedulers_to_objects.py +++ /dev/null @@ -1,120 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -from twisted.trial import unittest -from buildbot.test.util import migration - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - changes = sa.Table('changes', metadata, - sa.Column('changeid', sa.Integer, primary_key=True), - # the rest is unimportant - ) - changes.create() - - buildsets = sa.Table('buildsets', metadata, - sa.Column('id', sa.Integer, primary_key=True), - # the rest is unimportant - ) - buildsets.create() - - self.schedulers = sa.Table("schedulers", metadata, - sa.Column('schedulerid', sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - ) - self.schedulers.create(bind=conn) - sa.Index('name_and_class', self.schedulers.c.name, - self.schedulers.c.class_name).create() - - self.scheduler_changes = sa.Table('scheduler_changes', metadata, - sa.Column('schedulerid', sa.Integer, - sa.ForeignKey('schedulers.schedulerid')), - sa.Column('changeid', sa.Integer, - sa.ForeignKey('changes.changeid')), - sa.Column('important', sa.SmallInteger), - ) - self.scheduler_changes.create() - sa.Index('scheduler_changes_schedulerid', - self.scheduler_changes.c.schedulerid).create() - sa.Index('scheduler_changes_changeid', - self.scheduler_changes.c.changeid).create() - sa.Index('scheduler_changes_unique', - self.scheduler_changes.c.schedulerid, - self.scheduler_changes.c.changeid, unique=True).create() - - self.scheduler_upstream_buildsets = sa.Table( - 'scheduler_upstream_buildsets', metadata, - sa.Column('buildsetid', sa.Integer, sa.ForeignKey('buildsets.id')), - sa.Column('schedulerid', sa.Integer, - sa.ForeignKey('schedulers.schedulerid')), - ) - self.scheduler_upstream_buildsets.create() - - sa.Index('scheduler_upstream_buildsets_buildsetid', - self.scheduler_upstream_buildsets.c.buildsetid).create() - sa.Index('scheduler_upstream_buildsets_schedulerid', - self.scheduler_upstream_buildsets.c.schedulerid).create() - - self.objects = sa.Table("objects", metadata, - sa.Column("id", sa.Integer, primary_key=True), - sa.Column('name', sa.String(128), nullable=False), - sa.Column('class_name', sa.String(128), nullable=False), - ) - self.objects.create(bind=conn) - - sa.Index('object_identity', self.objects.c.name, - self.objects.c.class_name, unique=True).create() - - # tests - - def test_update(self): - # this upgrade script really just drops a bunch of tables, so - # there's not much to test! - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - - # these tables are gone - for tbl in 'schedulers', 'scheduler_upstream_buildsets': - try: - conn.execute("select * from %s" % tbl) - except: - pass - else: - self.fail("%s table still exists" % tbl) - - # but scheduler_changes is not - s_c_tbl = sa.Table("scheduler_changes", metadata, - autoload=True) - q = sa.select( - [ s_c_tbl.c.objectid, s_c_tbl.c.changeid, s_c_tbl.c.important ]) - self.assertEqual(conn.execute(q).fetchall(), []) - - return self.do_test_migration(18, 19, setup_thd, verify_thd) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_020_remove_change_links.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_020_remove_change_links.py deleted file mode 100644 index fedd3535..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_020_remove_change_links.py +++ /dev/null @@ -1,66 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -from twisted.trial import unittest -from buildbot.test.util import migration - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - changes = sa.Table('changes', metadata, - sa.Column('changeid', sa.Integer, primary_key=True), - # the rest is unimportant - ) - changes.create() - - # Links (URLs) for changes - change_links = sa.Table('change_links', metadata, - sa.Column('changeid', sa.Integer, - sa.ForeignKey('changes.changeid'), nullable=False), - sa.Column('link', sa.String(1024), nullable=False), - ) - change_links.create() - - sa.Index('change_links_changeid', change_links.c.changeid).create() - - # tests - - def test_update(self): - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - - try: - conn.execute("select * from change_links") - except: - pass - else: - self.fail("change_links still exists") - - return self.do_test_migration(19, 20, setup_thd, verify_thd) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_021_fix_postgres_sequences.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_021_fix_postgres_sequences.py deleted file mode 100644 index 5cc3c980..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_021_fix_postgres_sequences.py +++ /dev/null @@ -1,75 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -from twisted.trial import unittest -from buildbot.test.util import migration - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - cols = [ - 'buildrequests.id', - 'builds.id', - 'buildsets.id', - 'changes.changeid', - 'patches.id', - 'sourcestampsets.id', - 'sourcestamps.id', - 'objects.id', - 'users.uid', - ] - - # tests - - def test_update(self): - def setup_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - - # insert a row into each table, giving an explicit id column so - # that the sequence is not advanced correctly, but leave no rows in - # one table to test that corner case - for i, col in enumerate(self.cols): - tbl_name, col_name = col.split('.') - tbl = sa.Table(tbl_name, metadata, - sa.Column(col_name, sa.Integer, primary_key=True)) - tbl.create() - if i > 1: - conn.execute(tbl.insert(), { col_name : i }) - - def verify_thd(conn): - metadata = sa.MetaData() - metadata.bind = conn - - # try inserting *without* an ID, and verify that the resulting ID - # is as expected - for i, col in enumerate(self.cols): - tbl_name, col_name = col.split('.') - tbl = sa.Table(tbl_name, metadata, - sa.Column(col_name, sa.Integer, primary_key=True)) - r = conn.execute(tbl.insert(), {}) - if i > 1: - exp = i+1 - else: - exp = 1 - self.assertEqual(r.inserted_primary_key[0], exp) - - return self.do_test_migration(20, 21, setup_thd, verify_thd) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_022_add_codebase.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_022_add_codebase.py deleted file mode 100644 index 95e154f5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_migrate_versions_022_add_codebase.py +++ /dev/null @@ -1,135 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import datetime -import sqlalchemy as sa -from twisted.trial import unittest -from buildbot.test.util import migration -from buildbot.util import UTC, datetime2epoch - -class Migration(migration.MigrateTestMixin, unittest.TestCase): - - def setUp(self): - return self.setUpMigrateTest() - - def tearDown(self): - return self.tearDownMigrateTest() - - # create tables as they are before migrating to version 019 - def create_tables_thd(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - - self.sourcestamps = sa.Table('sourcestamps', metadata, - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('branch', sa.String(256)), - sa.Column('revision', sa.String(256)), - sa.Column('patchid', sa.Integer), - sa.Column('repository', sa.String(length=512), nullable=False, server_default=''), - sa.Column('project', sa.String(length=512), nullable=False, server_default=''), - sa.Column('sourcestampsetid', sa.Integer), - ) - self.sourcestamps.create(bind=conn) - - self.changes = sa.Table('changes', metadata, - sa.Column('changeid', sa.Integer, primary_key=True), - sa.Column('author', sa.String(256), nullable=False), - sa.Column('comments', sa.String(1024), nullable=False), - sa.Column('is_dir', sa.SmallInteger, nullable=False), - sa.Column('branch', sa.String(256)), - sa.Column('revision', sa.String(256)), - sa.Column('revlink', sa.String(256)), - sa.Column('when_timestamp', sa.Integer, nullable=False), - sa.Column('category', sa.String(256)), - sa.Column('repository', sa.String(length=512), nullable=False, server_default=''), - sa.Column('project', sa.String(length=512), nullable=False, server_default=''), - ) - self.changes.create(bind=conn) - - def reload_tables_after_migration(self, conn): - metadata = sa.MetaData() - metadata.bind = conn - self.sourcestamps = sa.Table('sourcestamps', metadata, autoload=True) - self.changes = sa.Table('changes', metadata, autoload=True) - - def fill_tables_with_testdata(self, conn, testdata): - for ssid, repo, codebase, cid in testdata: - self.insert_sourcestamps_changes(conn, ssid, repo, codebase, cid) - - def insert_sourcestamps_changes(self, conn, sourcestampid, repository, codebase, changeid): - conn.execute(self.sourcestamps.insert(), - id=sourcestampid, - sourcestampsetid=sourcestampid, - branch='this_branch', - revision='this_revision', - patchid = None, - repository=repository, - project='', - codebase=codebase) - - dt_when = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC) - conn.execute(self.changes.insert(), - changeid = changeid, - author = 'develop', - comments = 'no comment', - is_dir = 0, - branch = 'default', - revision = 'FD56A89', - revling = None, - when_timestamp = datetime2epoch(dt_when), - category = None, - repository = repository, - codebase = codebase, - project = '') - - def test_changes_has_codebase(self): - changesdata = [(1000, 'https://svn.com/repo_a', 'repo_a', 1)] - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - self.reload_tables_after_migration(conn) - tbl = self.changes - self.assertTrue(hasattr(tbl.c, 'codebase'), 'Column codebase not found') - - # insert data in the table and new column - self.fill_tables_with_testdata(conn, changesdata) - - res = conn.execute(sa.select([tbl.c.changeid, tbl.c.repository, - tbl.c.codebase, ])) - got_changes = res.fetchall() - self.assertEqual(got_changes, [(1, 'https://svn.com/repo_a', 'repo_a')]) - - return self.do_test_migration(21, 22, setup_thd, verify_thd) - - def test_sourcestamps_has_codebase(self): - changesdata = [(1000, 'https://svn.com/repo_a', 'repo_a', 1)] - def setup_thd(conn): - self.create_tables_thd(conn) - - def verify_thd(conn): - self.reload_tables_after_migration(conn) - tbl = self.sourcestamps - self.assertTrue(hasattr(tbl.c, 'codebase'), 'Column codebase not found') - - # insert data in the table and new column - self.fill_tables_with_testdata(conn, changesdata) - - res = conn.execute(sa.select([tbl.c.id, tbl.c.repository, - tbl.c.codebase,])) - got_sourcestamps = res.fetchall() - self.assertEqual(got_sourcestamps, [(1000, 'https://svn.com/repo_a', 'repo_a')]) - - return self.do_test_migration(21, 22, setup_thd, verify_thd) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_model.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_model.py deleted file mode 100644 index 99af34ef..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_model.py +++ /dev/null @@ -1,58 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.db import model, enginestrategy -from buildbot.test.util import db - -class DBConnector_Basic(db.RealDatabaseMixin, unittest.TestCase): - """ - Basic tests of the DBConnector class - all start with an empty DB - """ - - def setUp(self): - d = self.setUpRealDatabase() - def make_fake_pool(_): - engine = enginestrategy.create_engine(self.db_url, - basedir=os.path.abspath('basedir')) - - # mock out the pool, and set up the model - self.db = mock.Mock() - self.db.pool.do_with_engine = lambda thd : defer.maybeDeferred(thd,engine) - self.db.model = model.Model(self.db) - self.db.start() - d.addCallback(make_fake_pool) - return d - - def tearDown(self): - self.db.stop() - return self.tearDownRealDatabase() - - def test_is_current_empty(self): - d = self.db.model.is_current() - d.addCallback(lambda r : self.assertFalse(r)) - return d - - def test_is_current_full(self): - d = self.db.model.upgrade() - d.addCallback(lambda _ : self.db.model.is_current()) - d.addCallback(lambda r : self.assertTrue(r)) - return d - - # the upgrade method is very well-tested by the integration tests; the - # remainder of the object is just tables. diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_pool.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_pool.py deleted file mode 100644 index 67d6a7e3..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_pool.py +++ /dev/null @@ -1,185 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import time -import sqlalchemy as sa -from twisted.trial import unittest -from twisted.internet import defer, reactor -from buildbot.db import pool -from buildbot.test.util import db - -class Basic(unittest.TestCase): - - # basic tests, just using an in-memory SQL db and one thread - - def setUp(self): - self.engine = sa.create_engine('sqlite://') - self.engine.optimal_thread_pool_size = 1 - self.pool = pool.DBThreadPool(self.engine) - - def tearDown(self): - self.pool.shutdown() - - def test_do(self): - def add(conn, addend1, addend2): - rp = conn.execute("SELECT %d + %d" % (addend1, addend2)) - return rp.scalar() - d = self.pool.do(add, 10, 11) - def check(res): - self.assertEqual(res, 21) - d.addCallback(check) - return d - - def test_do_error(self): - def fail(conn): - rp = conn.execute("EAT COOKIES") - return rp.scalar() - d = self.pool.do(fail) - return self.assertFailure(d, sa.exc.OperationalError) - - def test_do_exception(self): - def raise_something(conn): - raise RuntimeError("oh noes") - d = self.pool.do(raise_something) - return self.assertFailure(d, RuntimeError) - - def test_do_with_engine(self): - def add(engine, addend1, addend2): - rp = engine.execute("SELECT %d + %d" % (addend1, addend2)) - return rp.scalar() - d = self.pool.do_with_engine(add, 10, 11) - def check(res): - self.assertEqual(res, 21) - d.addCallback(check) - return d - - def test_do_with_engine_exception(self): - def fail(engine): - rp = engine.execute("EAT COOKIES") - return rp.scalar() - d = self.pool.do_with_engine(fail) - return self.assertFailure(d, sa.exc.OperationalError) - - def test_persistence_across_invocations(self): - # NOTE: this assumes that both methods are called with the same - # connection; if they run in parallel threads then it is not valid to - # assume that the database engine will have finalized the first - # transaction (and thus created the table) by the time the second - # transaction runs. This is why we set optimal_thread_pool_size in - # setUp. - d = defer.succeed(None) - def create_table(engine): - engine.execute("CREATE TABLE tmp ( a integer )") - d.addCallback( lambda r : self.pool.do_with_engine(create_table)) - def insert_into_table(engine): - engine.execute("INSERT INTO tmp values ( 1 )") - d.addCallback( lambda r : self.pool.do_with_engine(insert_into_table)) - return d - - -class Stress(unittest.TestCase): - - def setUp(self): - setup_engine = sa.create_engine('sqlite:///test.sqlite') - setup_engine.execute("pragma journal_mode = wal") - setup_engine.execute("CREATE TABLE test (a integer, b integer)") - - self.engine = sa.create_engine('sqlite:///test.sqlite') - self.engine.optimal_thread_pool_size = 2 - self.pool = pool.DBThreadPool(self.engine) - - def tearDown(self): - self.pool.shutdown() - os.unlink("test.sqlite") - - @defer.inlineCallbacks - def test_inserts(self): - def write(conn): - trans = conn.begin() - conn.execute("INSERT INTO test VALUES (1, 1)") - time.sleep(31) - trans.commit() - d1 = self.pool.do(write) - - def write2(conn): - trans = conn.begin() - conn.execute("INSERT INTO test VALUES (1, 1)") - trans.commit() - d2 = defer.Deferred() - d2.addCallback(lambda _ : - self.pool.do(write2)) - reactor.callLater(0.1, d2.callback, None) - - yield defer.DeferredList([ d1, d2 ]) - - # don't run this test, since it takes 30s - del test_inserts - - -class BasicWithDebug(Basic): - - # same thing, but with debug=True - - def setUp(self): - pool.debug = True - return Basic.setUp(self) - - def tearDown(self): - pool.debug = False - return Basic.tearDown(self) - - -class Native(unittest.TestCase, db.RealDatabaseMixin): - - # similar tests, but using the BUILDBOT_TEST_DB_URL - - def setUp(self): - d = self.setUpRealDatabase(want_pool=False) - def make_pool(_): - self.pool = pool.DBThreadPool(self.db_engine) - d.addCallback(make_pool) - return d - - def tearDown(self): - # try to delete the 'native_tests' table - meta = sa.MetaData() - native_tests = sa.Table("native_tests", meta) - def thd(conn): - native_tests.drop(bind=self.db_engine, checkfirst=True) - d = self.pool.do(thd) - d.addCallback(lambda _ : self.pool.shutdown()) - d.addCallback(lambda _ : self.tearDownRealDatabase()) - return d - - def test_ddl_and_queries(self): - meta = sa.MetaData() - native_tests = sa.Table("native_tests", meta, - sa.Column('name', sa.String(length=200))) - - # perform a DDL operation and immediately try to access that table; - # this has caused problems in the past, so this is basically a - # regression test. - def ddl(conn): - t = conn.begin() - native_tests.create(bind=conn) - t.commit() - d = self.pool.do(ddl) - def access(conn): - native_tests.insert(bind=conn).execute([ {'name':'foo'} ]) - d.addCallback(lambda _ : - self.pool.do(access)) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_schedulers.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_schedulers.py deleted file mode 100644 index 395fbb79..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_schedulers.py +++ /dev/null @@ -1,161 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.db import schedulers -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb - -class TestSchedulersConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['changes', 'objects', 'scheduler_changes' ]) - - def finish_setup(_): - self.db.schedulers = \ - schedulers.SchedulersConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - def checkScheduler(self, objectid, name, class_name): - def thd(conn): - q = self.db.model.schedulers.select( - whereclause=(self.db.model.schedulers.c.objectid == objectid)) - for row in conn.execute(q): - self.assertEqual([ row.objectid, row.name, row.class_name], - [ objectid, name, class_name]) - return self.db.pool.do(thd) - - # test data - - change3 = fakedb.Change(changeid=3) - change4 = fakedb.Change(changeid=4) - change5 = fakedb.Change(changeid=5) - change6 = fakedb.Change(changeid=6, branch='sql') - - scheduler24 = fakedb.Object(id=24) - - def addClassifications(self, _, objectid, *classifications): - def thd(conn): - q = self.db.model.scheduler_changes.insert() - conn.execute(q, [ - dict(changeid=c[0], objectid=objectid, important=c[1]) - for c in classifications ]) - return self.db.pool.do(thd) - - # tests - def test_classifyChanges(self): - d = self.insertTestData([ self.change3, self.change4, - self.scheduler24 ]) - d.addCallback(lambda _ : - self.db.schedulers.classifyChanges(24, - { 3 : False, 4: True })) - def check(_): - def thd(conn): - sch_chgs_tbl = self.db.model.scheduler_changes - q = sch_chgs_tbl.select(order_by=sch_chgs_tbl.c.changeid) - r = conn.execute(q) - rows = [ (row.objectid, row.changeid, row.important) - for row in r.fetchall() ] - self.assertEqual(rows, [ (24, 3, 0), (24, 4, 1) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_classifyChanges_again(self): - # test reclassifying changes, which may happen during some timing - # conditions - d = self.insertTestData([ - self.change3, - self.scheduler24, - fakedb.SchedulerChange(objectid=24, changeid=3, important=0), - ]) - d.addCallback(lambda _ : - self.db.schedulers.classifyChanges(24, { 3 : True })) - def check(_): - def thd(conn): - sch_chgs_tbl = self.db.model.scheduler_changes - q = sch_chgs_tbl.select(order_by=sch_chgs_tbl.c.changeid) - r = conn.execute(q) - rows = [ (row.objectid, row.changeid, row.important) - for row in r.fetchall() ] - self.assertEqual(rows, [ (24, 3, 1) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_flushChangeClassifications(self): - d = self.insertTestData([ self.change3, self.change4, - self.change5, self.scheduler24 ]) - d.addCallback(self.addClassifications, 24, - (3, 1), (4, 0), (5, 1)) - d.addCallback(lambda _ : - self.db.schedulers.flushChangeClassifications(24)) - def check(_): - def thd(conn): - q = self.db.model.scheduler_changes.select() - rows = conn.execute(q).fetchall() - self.assertEqual(rows, []) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_flushChangeClassifications_less_than(self): - d = self.insertTestData([ self.change3, self.change4, - self.change5, self.scheduler24 ]) - d.addCallback(self.addClassifications, 24, - (3, 1), (4, 0), (5, 1)) - d.addCallback(lambda _ : - self.db.schedulers.flushChangeClassifications(24, less_than=5)) - def check(_): - def thd(conn): - q = self.db.model.scheduler_changes.select() - rows = conn.execute(q).fetchall() - self.assertEqual([ (r.changeid, r.important) for r in rows], - [ (5, 1) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_getChangeClassifications(self): - d = self.insertTestData([ self.change3, self.change4, self.change5, - self.change6, self.scheduler24 ]) - d.addCallback(self.addClassifications, 24, - (3, 1), (4, 0), (5, 1), (6, 1)) - d.addCallback(lambda _ : - self.db.schedulers.getChangeClassifications(24)) - def check(cls): - self.assertEqual(cls, { 3 : True, 4 : False, 5 : True, 6: True }) - d.addCallback(check) - return d - - def test_getChangeClassifications_branch(self): - d = self.insertTestData([ self.change3, self.change4, self.change5, - self.change6, self.scheduler24 ]) - d.addCallback(self.addClassifications, 24, - (3, 1), (4, 0), (5, 1), (6, 1)) - d.addCallback(lambda _ : - self.db.schedulers.getChangeClassifications(24, branch='sql')) - def check(cls): - self.assertEqual(cls, { 6 : True }) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestamps.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestamps.py deleted file mode 100644 index 01346a2c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestamps.py +++ /dev/null @@ -1,212 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.db import sourcestamps -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb - -class TestSourceStampsConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['changes', 'change_files', 'patches', - 'sourcestamp_changes', 'sourcestamps', 'sourcestampsets' ]) - - def finish_setup(_): - self.db.sourcestamps = \ - sourcestamps.SourceStampsConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # tests - - def test_addSourceStamp_simple(self): - # add a sourcestampset for referential integrity - d = self.insertTestData([ - fakedb.SourceStampSet(id=1), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.addSourceStamp(branch = 'production', revision='abdef', - repository='test://repo', codebase='cb', project='stamper', sourcestampsetid=1)) - def check(ssid): - def thd(conn): - # should see one sourcestamp row - ss_tbl = self.db.model.sourcestamps - r = conn.execute(ss_tbl.select()) - rows = [ (row.id, row.branch, row.revision, - row.patchid, row.repository, row.codebase, row.project, row.sourcestampsetid) - for row in r.fetchall() ] - self.assertEqual(rows, - [ ( ssid, 'production', 'abdef', None, 'test://repo', 'cb', 'stamper', 1) ]) - - # .. and no sourcestamp_changes - ssc_tbl = self.db.model.sourcestamp_changes - r = conn.execute(ssc_tbl.select()) - rows = [ 1 for row in r.fetchall() ] - self.assertEqual(rows, []) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_addSourceStamp_changes(self): - # add some sample changes and a sourcestampset for referential integrity - d = self.insertTestData([ - fakedb.SourceStampSet(id=1), - fakedb.Change(changeid=3), - fakedb.Change(changeid=4), - ]) - - d.addCallback(lambda _ : - self.db.sourcestamps.addSourceStamp(branch = 'production', revision='abdef', - repository='test://repo', codebase='cb', project='stamper', sourcestampsetid=1, changeids=[3,4])) - - def check(ssid): - def thd(conn): - # should see one sourcestamp row - ss_tbl = self.db.model.sourcestamps - r = conn.execute(ss_tbl.select()) - rows = [ (row.id, row.branch, row.revision, - row.patchid, row.repository, row.codebase, row.project, row.sourcestampsetid) - for row in r.fetchall() ] - self.assertEqual(rows, - [ ( ssid, 'production', 'abdef', None, 'test://repo', 'cb', 'stamper', 1) ]) - - # .. and two sourcestamp_changes - ssc_tbl = self.db.model.sourcestamp_changes - r = conn.execute(ssc_tbl.select()) - rows = [ (row.sourcestampid, row.changeid) for row in r.fetchall() ] - self.assertEqual(sorted(rows), [ (ssid, 3), (ssid, 4) ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_addSourceStamp_patch(self): - # add a sourcestampset for referential integrity - d = self.insertTestData([ - fakedb.SourceStampSet(id=1), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.addSourceStamp(branch = 'production', revision='abdef', - repository='test://repo', codebase='cb', project='stamper', sourcestampsetid=1, patch_body='my patch', patch_level=3, - patch_subdir='master/', patch_author='me', - patch_comment="comment")) - def check(ssid): - def thd(conn): - # should see one sourcestamp row - ss_tbl = self.db.model.sourcestamps - r = conn.execute(ss_tbl.select()) - rows = [ (row.id, row.branch, row.revision, - row.patchid, row.repository, row.codebase, row.project, row.sourcestampsetid) - for row in r.fetchall() ] - patchid = row.patchid - self.assertNotEqual(patchid, None) - self.assertEqual(rows, - [ ( ssid, 'production', 'abdef', patchid, 'test://repo', 'cb', - 'stamper', 1) ]) - - # .. and a single patch - patches_tbl = self.db.model.patches - r = conn.execute(patches_tbl.select()) - rows = [ (row.id, row.patchlevel, row.patch_base64, row.subdir, - row.patch_author, row.patch_comment) - for row in r.fetchall() ] - self.assertEqual(rows, [(patchid, 3, 'bXkgcGF0Y2g=', 'master/', - 'me', 'comment')]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_getSourceStamp_simple(self): - d = self.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='br', revision='rv', repository='rep', codebase='cb', project='prj'), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.getSourceStamp(234)) - def check(ssdict): - self.assertEqual(ssdict, dict(ssid=234, branch='br', revision='rv', - sourcestampsetid=234, repository='rep', codebase = 'cb', - project='prj', patch_body=None, - patch_level=None, patch_subdir=None, - patch_author=None, patch_comment=None, changeids=set([]))) - d.addCallback(check) - return d - - def test_getSourceStamp_simple_None(self): - "check that NULL branch and revision are handled correctly" - d = self.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch=None, revision=None, - repository='rep', codebase='cb', project='prj'), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.getSourceStamp(234)) - def check(ssdict): - self.assertEqual((ssdict['branch'], ssdict['revision']), - (None, None)) - d.addCallback(check) - return d - - def test_getSourceStamp_changes(self): - d = self.insertTestData([ - fakedb.Change(changeid=16), - fakedb.Change(changeid=19), - fakedb.Change(changeid=20), - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234), - fakedb.SourceStampChange(sourcestampid=234, changeid=16), - fakedb.SourceStampChange(sourcestampid=234, changeid=20), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.getSourceStamp(234)) - def check(ssdict): - self.assertEqual(ssdict['changeids'], set([16,20])) - d.addCallback(check) - return d - - def test_getSourceStamp_patch(self): - d = self.insertTestData([ - fakedb.Patch(id=99, patch_base64='aGVsbG8sIHdvcmxk', - patch_author='bar', patch_comment='foo', subdir='/foo', - patchlevel=3), - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, patchid=99), - ]) - d.addCallback(lambda _ : - self.db.sourcestamps.getSourceStamp(234)) - def check(ssdict): - self.assertEqual(dict((k,v) for k,v in ssdict.iteritems() - if k.startswith('patch_')), - dict(patch_body='hello, world', - patch_level=3, - patch_author='bar', - patch_comment='foo', - patch_subdir='/foo')) - d.addCallback(check) - return d - - def test_getSourceStamp_nosuch(self): - d = self.db.sourcestamps.getSourceStamp(234) - def check(ssdict): - self.assertEqual(ssdict, None) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestampsets.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestampsets.py deleted file mode 100644 index 217b3ed3..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_sourcestampsets.py +++ /dev/null @@ -1,61 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.db import sourcestampsets -from buildbot.test.util import connector_component - -class TestSourceStampSetsConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=[ 'patches', 'buildsets', 'sourcestamps', - 'sourcestampsets' ]) - - def finish_setup(_): - self.db.sourcestampsets = \ - sourcestampsets.SourceStampSetsConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # tests - def test_addSourceStampSet_simple(self): - d = defer.succeed(None) - - d.addCallback(lambda _ : - self.db.sourcestampsets.addSourceStampSet()) - - def check(sourcestampsetid): - def thd(conn): - # should see one sourcestamp row - ssset_tbl = self.db.model.sourcestampsets - r = conn.execute(ssset_tbl.select()) - rows = [ (row.id) - for row in r.fetchall() ] - # Test if returned setid is in database - self.assertEqual(rows, - [ ( sourcestampsetid) ]) - # Test if returned set id starts with - self.assertEqual(sourcestampsetid, 1) - return self.db.pool.do(thd) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_state.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_state.py deleted file mode 100644 index 8002222e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_state.py +++ /dev/null @@ -1,182 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.db import state -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb - -class TestStateConnectorComponent( - connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['objects', 'object_state' ]) - - def finish_setup(_): - self.db.state = \ - state.StateConnectorComponent(self.db) - d.addCallback(finish_setup) - - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - def test_getObjectId_new(self): - d = self.db.state.getObjectId('someobj', 'someclass') - def check(objectid): - self.assertNotEqual(objectid, None) - def thd(conn): - q = self.db.model.objects.select() - rows = conn.execute(q).fetchall() - self.assertEqual( - [ (r.id, r.name, r.class_name) for r in rows ], - [ (objectid, 'someobj', 'someclass') ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_getObjectId_existing(self): - d = self.insertTestData([ - fakedb.Object(id=19, name='someobj', - class_name='someclass') ]) - d.addCallback(lambda _ : - self.db.state.getObjectId('someobj', 'someclass')) - def check(objectid): - self.assertEqual(objectid, 19) - d.addCallback(check) - return d - - - def test_getObjectId_conflict(self): - # set up to insert a row between looking for an existing object - # and adding a new one, triggering the fallback to re-running - # the select. - def hook(conn): - conn.execute(self.db.model.objects.insert(), - id=27, name='someobj', class_name='someclass') - self.db.state._test_timing_hook = hook - - d = self.db.state.getObjectId('someobj', 'someclass') - def check(objectid): - self.assertEqual(objectid, 27) - d.addCallback(check) - return d - - def test_getState_missing(self): - d = self.db.state.getState(10, 'nosuch') - return self.assertFailure(d, KeyError) - - def test_getState_missing_default(self): - d = self.db.state.getState(10, 'nosuch', 'abc') - def check(val): - self.assertEqual(val, 'abc') - d.addCallback(check) - return d - - def test_getState_missing_default_None(self): - d = self.db.state.getState(10, 'nosuch', None) - def check(val): - self.assertEqual(val, None) - d.addCallback(check) - return d - - def test_getState_present(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='x', class_name='y'), - fakedb.ObjectState(objectid=10, name='x', value_json='[1,2]'), - ]) - d.addCallback(lambda _ : - self.db.state.getState(10, 'x')) - def check(val): - self.assertEqual(val, [1,2]) - d.addCallback(check) - return d - - def test_getState_badjson(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='x', class_name='y'), - fakedb.ObjectState(objectid=10, name='x', value_json='ff[1'), - ]) - d.addCallback(lambda _ : - self.db.state.getState(10, 'x')) - return self.assertFailure(d, TypeError) - - def test_setState(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='-', class_name='-'), - ]) - d.addCallback(lambda _ : - self.db.state.setState(10, 'x', [1,2])) - def check(_): - def thd(conn): - q = self.db.model.object_state.select() - rows = conn.execute(q).fetchall() - self.assertEqual( - [ (r.objectid, r.name, r.value_json) for r in rows ], - [ (10, 'x', '[1, 2]') ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_setState_badjson(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='x', class_name='y'), - ]) - d.addCallback(lambda _ : - self.db.state.setState(10, 'x', self)) # self is not JSON-able.. - return self.assertFailure(d, TypeError) - - def test_setState_existing(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='-', class_name='-'), - fakedb.ObjectState(objectid=10, name='x', value_json='99'), - ]) - d.addCallback(lambda _ : - self.db.state.setState(10, 'x', [1,2])) - def check(_): - def thd(conn): - q = self.db.model.object_state.select() - rows = conn.execute(q).fetchall() - self.assertEqual( - [ (r.objectid, r.name, r.value_json) for r in rows ], - [ (10, 'x', '[1, 2]') ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - - def test_setState_conflict(self): - d = self.insertTestData([ - fakedb.Object(id=10, name='-', class_name='-'), - ]) - def hook(conn): - conn.execute(self.db.model.object_state.insert(), - objectid=10, name='x', value_json='22') - self.db.state._test_timing_hook = hook - d.addCallback(lambda _ : - self.db.state.setState(10, 'x', [1,2])) - def check(_): - def thd(conn): - q = self.db.model.object_state.select() - rows = conn.execute(q).fetchall() - self.assertEqual( - [ (r.objectid, r.name, r.value_json) for r in rows ], - [ (10, 'x', '22') ]) - return self.db.pool.do(thd) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_users.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_users.py deleted file mode 100644 index 63e2c0de..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_db_users.py +++ /dev/null @@ -1,473 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sqlalchemy as sa -from twisted.trial import unittest -from buildbot.db import users -from buildbot.test.util import connector_component -from buildbot.test.fake import fakedb - -class TestUsersConnectorComponent(connector_component.ConnectorComponentMixin, - unittest.TestCase): - - def setUp(self): - d = self.setUpConnectorComponent( - table_names=['users', 'users_info', 'changes', 'change_users']) - def finish_setup(_): - self.db.users = users.UsersConnectorComponent(self.db) - d.addCallback(finish_setup) - return d - - def tearDown(self): - return self.tearDownConnectorComponent() - - # sample user data - - user1_rows = [ - fakedb.User(uid=1, identifier='soap'), - fakedb.UserInfo(uid=1, attr_type='IPv9', attr_data='0578cc6.8db024'), - ] - - user2_rows = [ - fakedb.User(uid=2, identifier='lye'), - fakedb.UserInfo(uid=2, attr_type='git', - attr_data='Tyler Durden <tyler@mayhem.net>'), - fakedb.UserInfo(uid=2, attr_type='irc', attr_data='durden') - ] - - user3_rows = [ - fakedb.User(uid=3, identifier='marla', bb_username='marla', - bb_password='cancer') - ] - - user1_dict = { - 'uid': 1, - 'identifier': u'soap', - 'bb_username': None, - 'bb_password': None, - 'IPv9': u'0578cc6.8db024', - } - - user2_dict = { - 'uid': 2, - 'identifier': u'lye', - 'bb_username': None, - 'bb_password': None, - 'irc': u'durden', - 'git': u'Tyler Durden <tyler@mayhem.net>' - } - - user3_dict = { - 'uid': 3, - 'identifier': u'marla', - 'bb_username': u'marla', - 'bb_password': u'cancer', - } - - # tests - - def test_addUser_new(self): - d = self.db.users.findUserByAttr(identifier='soap', - attr_type='subspace_net_handle', - attr_data='Durden0924') - def check_user(uid): - def thd(conn): - users_tbl = self.db.model.users - users_info_tbl = self.db.model.users_info - users = conn.execute(users_tbl.select()).fetchall() - infos = conn.execute(users_info_tbl.select()).fetchall() - self.assertEqual(len(users), 1) - self.assertEqual(users[0].uid, uid) - self.assertEqual(users[0].identifier, 'soap') - self.assertEqual(len(infos), 1) - self.assertEqual(infos[0].uid, uid) - self.assertEqual(infos[0].attr_type, 'subspace_net_handle') - self.assertEqual(infos[0].attr_data, 'Durden0924') - return self.db.pool.do(thd) - d.addCallback(check_user) - return d - - def test_addUser_existing(self): - d = self.insertTestData(self.user1_rows) - d.addCallback(lambda _ : self.db.users.findUserByAttr( - identifier='soapy', - attr_type='IPv9', - attr_data='0578cc6.8db024')) - def check_user(uid): - self.assertEqual(uid, 1) - def thd(conn): - users_tbl = self.db.model.users - users_info_tbl = self.db.model.users_info - users = conn.execute(users_tbl.select()).fetchall() - infos = conn.execute(users_info_tbl.select()).fetchall() - self.assertEqual(len(users), 1) - self.assertEqual(users[0].uid, uid) - self.assertEqual(users[0].identifier, 'soap') # not changed! - self.assertEqual(len(infos), 1) - self.assertEqual(infos[0].uid, uid) - self.assertEqual(infos[0].attr_type, 'IPv9') - self.assertEqual(infos[0].attr_data, '0578cc6.8db024') - return self.db.pool.do(thd) - d.addCallback(check_user) - return d - - def test_findUser_existing(self): - d = self.insertTestData( - self.user1_rows + self.user2_rows + self.user3_rows) - d.addCallback(lambda _ : self.db.users.findUserByAttr( - identifier='lye', - attr_type='git', - attr_data='Tyler Durden <tyler@mayhem.net>')) - def check_user(uid): - self.assertEqual(uid, 2) - def thd(conn): - users_tbl = self.db.model.users - users_info_tbl = self.db.model.users_info - users = conn.execute(users_tbl.select()).fetchall() - infos = conn.execute(users_info_tbl.select()).fetchall() - self.assertEqual(( - sorted([ tuple(u) for u in users]), - sorted([ tuple(i) for i in infos]) - ), ( - [ - (1L, u'soap', None, None), - (2L, u'lye', None, None), - (3L, u'marla', u'marla', u'cancer'), - ], [ - (1L, u'IPv9', u'0578cc6.8db024'), - (2L, u'git', u'Tyler Durden <tyler@mayhem.net>'), - (2L, u'irc', u'durden') - ])) - return self.db.pool.do(thd) - d.addCallback(check_user) - return d - - def test_addUser_race(self): - def race_thd(conn): - # note that this assumes that both inserts can happen "at once". - # This is the case for DB engines that support transactions, but - # not for MySQL. so this test does not detect the potential MySQL - # failure, which will generally result in a spurious failure. - conn.execute(self.db.model.users.insert(), - uid=99, identifier='soap') - conn.execute(self.db.model.users_info.insert(), - uid=99, attr_type='subspace_net_handle', - attr_data='Durden0924') - d = self.db.users.findUserByAttr(identifier='soap', - attr_type='subspace_net_handle', - attr_data='Durden0924', - _race_hook=race_thd) - def check_user(uid): - self.assertEqual(uid, 99) - def thd(conn): - users_tbl = self.db.model.users - users_info_tbl = self.db.model.users_info - users = conn.execute(users_tbl.select()).fetchall() - infos = conn.execute(users_info_tbl.select()).fetchall() - self.assertEqual(len(users), 1) - self.assertEqual(users[0].uid, uid) - self.assertEqual(users[0].identifier, 'soap') - self.assertEqual(len(infos), 1) - self.assertEqual(infos[0].uid, uid) - self.assertEqual(infos[0].attr_type, 'subspace_net_handle') - self.assertEqual(infos[0].attr_data, 'Durden0924') - return self.db.pool.do(thd) - d.addCallback(check_user) - return d - - def test_addUser_existing_identifier(self): - d = self.insertTestData(self.user1_rows) - d.addCallback(lambda _ : self.db.users.findUserByAttr( - identifier='soap', - attr_type='telepathIO(tm)', - attr_data='hmm,lye')) - return self.assertFailure(d, sa.exc.IntegrityError, - sa.exc.ProgrammingError) - - def test_getUser(self): - d = self.insertTestData(self.user1_rows) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict, self.user1_dict) - d.addCallback(check1) - return d - - def test_getUser_bb(self): - d = self.insertTestData(self.user3_rows) - def get3(_): - return self.db.users.getUser(3) - d.addCallback(get3) - def check3(usdict): - self.assertEqual(usdict, self.user3_dict) - d.addCallback(check3) - return d - - def test_getUser_multi_attr(self): - d = self.insertTestData(self.user2_rows) - def get1(_): - return self.db.users.getUser(2) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict, self.user2_dict) - d.addCallback(check1) - return d - - def test_getUser_no_match(self): - d = self.insertTestData(self.user1_rows) - def get3(_): - return self.db.users.getUser(3) - d.addCallback(get3) - def check3(none): - self.assertEqual(none, None) - d.addCallback(check3) - return d - - def test_getUsers_none(self): - d = self.db.users.getUsers() - def check(res): - self.assertEqual(res, []) - d.addCallback(check) - return d - - def test_getUsers(self): - d = self.insertTestData(self.user1_rows) - def get(_): - return self.db.users.getUsers() - d.addCallback(get) - def check(res): - self.assertEqual(res, [dict(uid=1, identifier='soap')]) - d.addCallback(check) - return d - - def test_getUsers_multiple(self): - d = self.insertTestData(self.user1_rows + self.user2_rows) - def get(_): - return self.db.users.getUsers() - d.addCallback(get) - def check(res): - self.assertEqual(res, [dict(uid=1, identifier='soap'), - dict(uid=2, identifier='lye')]) - d.addCallback(check) - return d - - def test_getUserByUsername(self): - d = self.insertTestData(self.user3_rows) - def get3(_): - return self.db.users.getUserByUsername("marla") - d.addCallback(get3) - def check3(res): - self.assertEqual(res, self.user3_dict) - d.addCallback(check3) - return d - - def test_getUserByUsername_no_match(self): - d = self.insertTestData(self.user3_rows) - def get3(_): - return self.db.users.getUserByUsername("tyler") - d.addCallback(get3) - def check3(none): - self.assertEqual(none, None) - d.addCallback(check3) - return d - - def test_updateUser_existing_type(self): - d = self.insertTestData(self.user1_rows) - def update1(_): - return self.db.users.updateUser( - uid=1, attr_type='IPv9', attr_data='abcd.1234') - d.addCallback(update1) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['IPv9'], 'abcd.1234') - self.assertEqual(usdict['identifier'], 'soap') # no change - d.addCallback(check1) - return d - - def test_updateUser_new_type(self): - d = self.insertTestData(self.user1_rows) - def update1(_): - return self.db.users.updateUser( - uid=1, attr_type='IPv4', attr_data='123.134.156.167') - d.addCallback(update1) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['IPv4'], '123.134.156.167') - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - self.assertEqual(usdict['identifier'], 'soap') # no change - d.addCallback(check1) - return d - - def test_updateUser_identifier(self): - d = self.insertTestData(self.user1_rows) - def update1(_): - return self.db.users.updateUser( - uid=1, identifier='lye') - d.addCallback(update1) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['identifier'], 'lye') - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - d.addCallback(check1) - return d - - def test_updateUser_bb(self): - d = self.insertTestData(self.user3_rows) - def update3(_): - return self.db.users.updateUser( - uid=3, bb_username='boss', bb_password='fired') - d.addCallback(update3) - def get3(_): - return self.db.users.getUser(3) - d.addCallback(get3) - def check3(usdict): - self.assertEqual(usdict['bb_username'], 'boss') - self.assertEqual(usdict['bb_password'], 'fired') - self.assertEqual(usdict['identifier'], 'marla') # no change - d.addCallback(check3) - return d - - def test_updateUser_all(self): - d = self.insertTestData(self.user1_rows) - def update1(_): - return self.db.users.updateUser( - uid=1, identifier='lye', bb_username='marla', - bb_password='cancer', attr_type='IPv4', attr_data='123.134.156.167') - d.addCallback(update1) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['identifier'], 'lye') - self.assertEqual(usdict['bb_username'], 'marla') - self.assertEqual(usdict['bb_password'], 'cancer') - self.assertEqual(usdict['IPv4'], '123.134.156.167') - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - d.addCallback(check1) - return d - - def test_updateUser_race(self): - # called from the db thread, this opens a *new* connection (to avoid - # the existing transaction) and executes a conflicting insert in that - # connection. This will cause the insert in the db method to fail, and - # the data in this insert (8.8.8.8) will appear below. - def race_thd(conn): - conn = self.db.pool.engine.connect() - conn.execute(self.db.model.users_info.insert(), - uid=1, attr_type='IPv4', - attr_data='8.8.8.8') - - d = self.insertTestData(self.user1_rows) - def update1(_): - return self.db.users.updateUser( - uid=1, attr_type='IPv4', attr_data='123.134.156.167', - _race_hook=race_thd) - d.addCallback(update1) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['identifier'], 'soap') - self.assertEqual(usdict['IPv4'], '8.8.8.8') - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - d.addCallback(check1) - return d - - def test_update_NoMatch_identifier(self): - d = self.insertTestData(self.user1_rows) - def update3(_): - return self.db.users.updateUser( - uid=3, identifier='abcd') - d.addCallback(update3) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['identifier'], 'soap') # no change - d.addCallback(check1) - return d - - def test_update_NoMatch_attribute(self): - d = self.insertTestData(self.user1_rows) - def update3(_): - return self.db.users.updateUser( - uid=3, attr_type='abcd', attr_data='efgh') - d.addCallback(update3) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - d.addCallback(check1) - return d - - def test_update_NoMatch_bb(self): - d = self.insertTestData(self.user1_rows) - def update3(_): - return self.db.users.updateUser( - uid=3, attr_type='marla', attr_data='cancer') - d.addCallback(update3) - def get1(_): - return self.db.users.getUser(1) - d.addCallback(get1) - def check1(usdict): - self.assertEqual(usdict['IPv9'], '0578cc6.8db024') # no change - d.addCallback(check1) - return d - - def test_removeUser_uid(self): - d = self.insertTestData(self.user1_rows) - def remove1(_): - return self.db.users.removeUser(1) - d.addCallback(remove1) - def check1(_): - def thd(conn): - r = conn.execute(self.db.model.users.select()) - r = r.fetchall() - self.assertEqual(len(r), 0) - return self.db.pool.do(thd) - d.addCallback(check1) - return d - - def test_removeNoMatch(self): - d = self.insertTestData(self.user1_rows) - def check(_): - return self.db.users.removeUser(uid=3) - d.addCallback(check) - return d - - def test_identifierToUid_NoMatch(self): - d = self.db.users.identifierToUid(identifier="soap") - def check(res): - self.assertEqual(res, None) - d.addCallback(check) - return d - - def test_identifierToUid_match(self): - d = self.insertTestData(self.user1_rows) - def ident2uid(_): - return self.db.users.identifierToUid(identifier="soap") - d.addCallback(ident2uid) - def check(res): - self.assertEqual(res, 1) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_master.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_master.py deleted file mode 100644 index c170382e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_master.py +++ /dev/null @@ -1,567 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import mock -import signal -from twisted.internet import defer, reactor, task -from twisted.trial import unittest -from twisted.python import log -from buildbot import master, monkeypatches, config -from buildbot.util import subscription -from buildbot.db import connector -from buildbot.test.util import dirs, compat, misc, logging -from buildbot.test.fake import fakedb -from buildbot.util import epoch2datetime -from buildbot.changes import changes -from buildbot.process.users import users - -class Subscriptions(dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - basedir = os.path.abspath('basedir') - d = self.setUpDirs(basedir) - def set_master(_): - self.master = master.BuildMaster(basedir) - self.master.config.db['db_poll_interval'] = None - d.addCallback(set_master) - return d - - def tearDown(self): - return self.tearDownDirs() - - def test_change_subscription(self): - changeid = 918 - chdict = { - 'changeid': 14, - 'author': u'warner', - 'branch': u'warnerdb', - 'category': u'devel', - 'comments': u'fix whitespace', - 'files': [u'master/buildbot/__init__.py'], - 'is_dir': 0, - 'project': u'Buildbot', - 'properties': {}, - 'repository': u'git://warner', - 'revision': u'0e92a098b', - 'revlink': u'http://warner/0e92a098b', - 'when_timestamp': epoch2datetime(266738404), - } - newchange = mock.Mock(name='newchange') - - # patch out everything we're about to call - self.master.db = mock.Mock() - self.master.db.changes.addChange.return_value = \ - defer.succeed(changeid) - self.master.db.changes.getChange.return_value = \ - defer.succeed(chdict) - self.patch(changes.Change, 'fromChdict', - classmethod(lambda cls, master, chdict : - defer.succeed(newchange))) - - cb = mock.Mock() - sub = self.master.subscribeToChanges(cb) - self.assertIsInstance(sub, subscription.Subscription) - - d = self.master.addChange() - def check(change): - # master called the right thing in the db component, including with - # appropriate default values - self.master.db.changes.addChange.assert_called_with(author=None, - files=None, comments=None, is_dir=0, - revision=None, when_timestamp=None, branch=None, codebase='', - category=None, revlink='', properties={}, repository='', project='', uid=None) - - self.master.db.changes.getChange.assert_called_with(changeid) - # addChange returned the right value - self.failUnless(change is newchange) # fromChdict's return value - # and the notification sub was called correctly - cb.assert_called_with(newchange) - d.addCallback(check) - return d - - def do_test_addChange_args(self, args=(), kwargs={}, exp_db_kwargs={}): - # add default arguments - default_db_kwargs = dict(files=None, comments=None, author=None, - is_dir=0, revision=None, when_timestamp=None, - branch=None, category=None, revlink='', properties={}, - repository='', codebase='', project='', uid=None) - k = default_db_kwargs - k.update(exp_db_kwargs) - exp_db_kwargs = k - - self.master.db = mock.Mock() - got = [] - def db_addChange(*args, **kwargs): - got[:] = args, kwargs - # use an exception as a quick way to bail out of the remainder - # of the addChange method - return defer.fail(RuntimeError) - self.master.db.changes.addChange = db_addChange - - d = self.master.addChange(*args, **kwargs) - d.addCallback(lambda _ : self.fail("should not succeed")) - def check(f): - self.assertEqual(got, [(), exp_db_kwargs]) - d.addErrback(check) - return d - - def test_addChange_args_author(self): - # who should come through as author - return self.do_test_addChange_args( - kwargs=dict(who='me'), - exp_db_kwargs=dict(author='me')) - - def test_addChange_args_isdir(self): - # isdir should come through as is_dir - return self.do_test_addChange_args( - kwargs=dict(isdir=1), - exp_db_kwargs=dict(is_dir=1)) - - def test_addChange_args_when(self): - # when should come through as when_timestamp, as a datetime - return self.do_test_addChange_args( - kwargs=dict(when=892293875), - exp_db_kwargs=dict(when_timestamp=epoch2datetime(892293875))) - - def test_addChange_args_properties(self): - # properties should be qualified with a source - return self.do_test_addChange_args( - kwargs=dict(properties={ 'a' : 'b' }), - exp_db_kwargs=dict(properties={ 'a' : ('b', 'Change') })) - - def test_addChange_args_properties_tuple(self): - # properties should be qualified with a source, even if they - # already look like they have a source - return self.do_test_addChange_args( - kwargs=dict(properties={ 'a' : ('b', 'Change') }), - exp_db_kwargs=dict(properties={ - 'a' : (('b', 'Change'), 'Change') })) - - def test_addChange_args_positional(self): - # master.addChange can take author, files, comments as positional - # arguments - return self.do_test_addChange_args( - args=('me', ['a'], 'com'), - exp_db_kwargs=dict(author='me', files=['a'], comments='com')) - - def do_test_createUserObjects_args(self, args=(), kwargs={}, exp_args=()): - got = [] - def fake_createUserObject(*args, **kwargs): - got[:] = args, kwargs - # use an exception as a quick way to bail out of the remainder - # of the createUserObject method - return defer.fail(RuntimeError) - - self.patch(users, 'createUserObject', fake_createUserObject) - - d = self.master.addChange(*args, **kwargs) - d.addCallback(lambda _ : self.fail("should not succeed")) - def check(f): - self.assertEqual(got, [exp_args, {}]) - d.addErrback(check) - return d - - def test_addChange_createUserObject_args(self): - # who should come through as author - return self.do_test_createUserObjects_args( - kwargs=dict(who='me', src='git'), - exp_args=(self.master, 'me', 'git')) - - def test_buildset_subscription(self): - self.master.db = mock.Mock() - self.master.db.buildsets.addBuildset.return_value = \ - defer.succeed((938593, dict(a=19,b=20))) - - cb = mock.Mock() - sub = self.master.subscribeToBuildsets(cb) - self.assertIsInstance(sub, subscription.Subscription) - - d = self.master.addBuildset(ssid=999) - def check((bsid,brids)): - # master called the right thing in the db component - self.master.db.buildsets.addBuildset.assert_called_with(ssid=999) - # addBuildset returned the right value - self.assertEqual((bsid,brids), (938593, dict(a=19,b=20))) - # and the notification sub was called correctly - cb.assert_called_with(bsid=938593, ssid=999) - d.addCallback(check) - return d - - def test_buildset_completion_subscription(self): - self.master.db = mock.Mock() - - cb = mock.Mock() - sub = self.master.subscribeToBuildsetCompletions(cb) - self.assertIsInstance(sub, subscription.Subscription) - - self.master._buildsetComplete(938593, 999) - # assert the notification sub was called correctly - cb.assert_called_with(938593, 999) - -class StartupAndReconfig(dirs.DirsMixin, logging.LoggingMixin, unittest.TestCase): - - def setUp(self): - self.setUpLogging() - self.basedir = os.path.abspath('basedir') - d = self.setUpDirs(self.basedir) - @d.addCallback - def make_master(_): - # don't create child services - self.patch(master.BuildMaster, 'create_child_services', - lambda self : None) - - # patch out a few other annoying things the master likes to do - self.patch(monkeypatches, 'patch_all', lambda : None) - self.patch(signal, 'signal', lambda sig, hdlr : None) - self.patch(master, 'Status', lambda master : mock.Mock()) # XXX temporary - self.patch(config.MasterConfig, 'loadConfig', - classmethod(lambda cls, b, f : cls())) - - self.master = master.BuildMaster(self.basedir) - self.db = self.master.db = fakedb.FakeDBConnector(self) - - return d - - def tearDown(self): - return self.tearDownDirs() - - def make_reactor(self): - r = mock.Mock() - r.callWhenRunning = reactor.callWhenRunning - return r - - def patch_loadConfig_fail(self): - @classmethod - def loadConfig(cls, b, f): - config.error('oh noes') - self.patch(config.MasterConfig, 'loadConfig', loadConfig) - - - # tests - - def test_startup_bad_config(self): - reactor = self.make_reactor() - self.patch_loadConfig_fail() - - d = self.master.startService(_reactor=reactor) - - @d.addCallback - def check(_): - reactor.stop.assert_called() - self.assertLogged("oh noes") - return d - - def test_startup_db_not_ready(self): - reactor = self.make_reactor() - def db_setup(): - log.msg("GOT HERE") - raise connector.DatabaseNotReadyError() - self.db.setup = db_setup - - d = self.master.startService(_reactor=reactor) - - @d.addCallback - def check(_): - reactor.stop.assert_called() - self.assertLogged("GOT HERE") - return d - - @compat.usesFlushLoggedErrors - def test_startup_error(self): - reactor = self.make_reactor() - def db_setup(): - raise RuntimeError("oh noes") - self.db.setup = db_setup - - d = self.master.startService(_reactor=reactor) - - @d.addCallback - def check(_): - reactor.stop.assert_called() - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - return d - - def test_startup_ok(self): - reactor = self.make_reactor() - - d = self.master.startService(_reactor=reactor) - d.addCallback(lambda _ : self.master.stopService()) - - @d.addCallback - def check(_): - self.failIf(reactor.stop.called) - self.assertLogged("BuildMaster is running") - return d - - def test_reconfig(self): - reactor = self.make_reactor() - self.master.reconfigService = mock.Mock( - side_effect=lambda n : defer.succeed(None)) - - d = self.master.startService(_reactor=reactor) - d.addCallback(lambda _ : self.master.reconfig()) - d.addCallback(lambda _ : self.master.stopService()) - - @d.addCallback - def check(_): - self.master.reconfigService.assert_called() - return d - - @defer.inlineCallbacks - def test_reconfig_bad_config(self): - reactor = self.make_reactor() - self.master.reconfigService = mock.Mock( - side_effect=lambda n : defer.succeed(None)) - - yield self.master.startService(_reactor=reactor) - - # reset, since startService called reconfigService - self.master.reconfigService.reset_mock() - - # reconfig, with a failure - self.patch_loadConfig_fail() - yield self.master.reconfig() - - self.master.stopService() - - self.assertLogged("reconfig aborted without") - self.failIf(self.master.reconfigService.called) - - @defer.inlineCallbacks - def test_reconfigService_db_url_changed(self): - old = self.master.config = config.MasterConfig() - old.db['db_url'] = 'aaaa' - yield self.master.reconfigService(old) - - new = config.MasterConfig() - new.db['db_url'] = 'bbbb' - - self.assertRaises(config.ConfigErrors, lambda : - self.master.reconfigService(new)) - - def test_reconfigService_start_polling(self): - loopingcall = mock.Mock() - self.patch(task, 'LoopingCall', lambda fn : loopingcall) - - self.master.config = config.MasterConfig() - new = config.MasterConfig() - new.db['db_poll_interval'] = 120 - - d = self.master.reconfigService(new) - @d.addCallback - def check(_): - loopingcall.start.assert_called_with(120, now=False) - return d - - @defer.inlineCallbacks - def test_reconfigService_stop_polling(self): - db_loop = self.master.db_loop = mock.Mock() - - old = self.master.config = config.MasterConfig() - old.db['db_poll_interval'] = 120 - yield self.master.reconfigService(old) - - new = config.MasterConfig() - new.db['db_poll_interval'] = None - yield self.master.reconfigService(new) - - db_loop.stop.assert_called() - self.assertEqual(self.master.db_loop, None) - - -class Polling(dirs.DirsMixin, misc.PatcherMixin, unittest.TestCase): - - def setUp(self): - self.gotten_changes = [] - self.gotten_buildset_additions = [] - self.gotten_buildset_completions = [] - self.gotten_buildrequest_additions = [] - - - basedir = os.path.abspath('basedir') - - # patch out os.uname so that we get a consistent hostname - self.patch_os_uname(lambda : [ 0, 'testhost.localdomain' ]) - self.master_name = "testhost.localdomain:%s" % (basedir,) - - d = self.setUpDirs(basedir) - def set_master(_): - self.master = master.BuildMaster(basedir) - - self.db = self.master.db = fakedb.FakeDBConnector(self) - - self.master.config.db['db_poll_interval'] = 10 - - # overridesubscription callbacks - self.master._change_subs = sub = mock.Mock() - sub.deliver = self.deliverChange - self.master._new_buildset_subs = sub = mock.Mock() - sub.deliver = self.deliverBuildsetAddition - self.master._complete_buildset_subs = sub = mock.Mock() - sub.deliver = self.deliverBuildsetCompletion - self.master._new_buildrequest_subs = sub = mock.Mock() - sub.deliver = self.deliverBuildRequestAddition - - d.addCallback(set_master) - return d - - def tearDown(self): - return self.tearDownDirs() - - def deliverChange(self, change): - self.gotten_changes.append(change) - - def deliverBuildsetAddition(self, **kwargs): - self.gotten_buildset_additions.append(kwargs) - - def deliverBuildsetCompletion(self, bsid, result): - self.gotten_buildset_completions.append((bsid, result)) - - def deliverBuildRequestAddition(self, notif): - self.gotten_buildrequest_additions.append(notif) - - # tests - - def test_pollDatabaseChanges_empty(self): - self.db.insertTestData([ - fakedb.Object(id=22, name=self.master_name, - class_name='buildbot.master.BuildMaster'), - ]) - d = self.master.pollDatabaseChanges() - def check(_): - self.assertEqual(self.gotten_changes, []) - self.assertEqual(self.gotten_buildset_additions, []) - self.assertEqual(self.gotten_buildset_completions, []) - self.db.state.assertState(22, last_processed_change=0) - d.addCallback(check) - return d - - def test_pollDatabaseChanges_catchup(self): - # with no existing state, it should catch up to the most recent change, - # but not process anything - self.db.insertTestData([ - fakedb.Object(id=22, name=self.master_name, - class_name='buildbot.master.BuildMaster'), - fakedb.Change(changeid=10), - fakedb.Change(changeid=11), - ]) - d = self.master.pollDatabaseChanges() - def check(_): - self.assertEqual(self.gotten_changes, []) - self.assertEqual(self.gotten_buildset_additions, []) - self.assertEqual(self.gotten_buildset_completions, []) - self.db.state.assertState(22, last_processed_change=11) - d.addCallback(check) - return d - - def test_pollDatabaseChanges_multiple(self): - self.db.insertTestData([ - fakedb.Object(id=53, name=self.master_name, - class_name='buildbot.master.BuildMaster'), - fakedb.ObjectState(objectid=53, name='last_processed_change', - value_json='10'), - fakedb.Change(changeid=10), - fakedb.Change(changeid=11), - fakedb.Change(changeid=12), - ]) - d = self.master.pollDatabaseChanges() - def check(_): - self.assertEqual([ ch.number for ch in self.gotten_changes], - [ 11, 12 ]) # note 10 was already seen - self.assertEqual(self.gotten_buildset_additions, []) - self.assertEqual(self.gotten_buildset_completions, []) - self.db.state.assertState(53, last_processed_change=12) - d.addCallback(check) - return d - - def test_pollDatabaseChanges_nothing_new(self): - self.db.insertTestData([ - fakedb.Object(id=53, name='master', - class_name='buildbot.master.BuildMaster'), - fakedb.ObjectState(objectid=53, name='last_processed_change', - value_json='10'), - fakedb.Change(changeid=10), - ]) - d = self.master.pollDatabaseChanges() - def check(_): - self.assertEqual(self.gotten_changes, []) - self.assertEqual(self.gotten_buildset_additions, []) - self.assertEqual(self.gotten_buildset_completions, []) - self.db.state.assertState(53, last_processed_change=10) - d.addCallback(check) - return d - - def test_pollDatabaseBuildRequests_empty(self): - d = self.master.pollDatabaseBuildRequests() - def check(_): - self.assertEqual(self.gotten_buildrequest_additions, []) - d.addCallback(check) - return d - - def test_pollDatabaseBuildRequests_new(self): - self.db.insertTestData([ - fakedb.SourceStampSet(id=127), - fakedb.SourceStamp(id=127, sourcestampsetid=127), - fakedb.Buildset(id=99, sourcestampsetid=127), - fakedb.BuildRequest(id=19, buildsetid=99, buildername='9teen'), - fakedb.BuildRequest(id=20, buildsetid=99, buildername='twenty') - ]) - d = self.master.pollDatabaseBuildRequests() - def check(_): - self.assertEqual(sorted(self.gotten_buildrequest_additions), - sorted([dict(bsid=99, brid=19, buildername='9teen'), - dict(bsid=99, brid=20, buildername='twenty')])) - d.addCallback(check) - return d - - def test_pollDatabaseBuildRequests_incremental(self): - d = defer.succeed(None) - def insert1(_): - self.db.insertTestData([ - fakedb.SourceStampSet(id=127), - fakedb.SourceStamp(id=127, sourcestampsetid=127), - fakedb.Buildset(id=99, sourcestampsetid=127), - fakedb.BuildRequest(id=11, buildsetid=9, buildername='eleventy'), - ]) - d.addCallback(insert1) - d.addCallback(lambda _ : self.master.pollDatabaseBuildRequests()) - def insert2_and_claim(_): - self.gotten_buildrequest_additions.append('MARK') - self.db.insertTestData([ - fakedb.BuildRequest(id=20, buildsetid=9, - buildername='twenty'), - ]) - self.db.buildrequests.fakeClaimBuildRequest(11) - d.addCallback(insert2_and_claim) - d.addCallback(lambda _ : self.master.pollDatabaseBuildRequests()) - def unclaim(_): - self.gotten_buildrequest_additions.append('MARK') - self.db.buildrequests.fakeUnclaimBuildRequest(11) - # note that at this point brid 20 is still unclaimed, but we do - # not get a new notification about it - d.addCallback(unclaim) - d.addCallback(lambda _ : self.master.pollDatabaseBuildRequests()) - def check(_): - self.assertEqual(self.gotten_buildrequest_additions, [ - dict(bsid=9, brid=11, buildername='eleventy'), - 'MARK', - dict(bsid=9, brid=20, buildername='twenty'), - 'MARK', - dict(bsid=9, brid=11, buildername='eleventy'), - ]) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_pbmanager.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_pbmanager.py deleted file mode 100644 index 032c8ff9..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_pbmanager.py +++ /dev/null @@ -1,98 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -# Test clean shutdown functionality of the master -import mock -from twisted.trial import unittest -from twisted.internet import defer -from twisted.spread import pb -from twisted.cred import credentials -from buildbot import pbmanager - -class TestPBManager(unittest.TestCase): - - def setUp(self): - self.pbm = pbmanager.PBManager() - self.pbm.startService() - self.connections = [] - - def tearDown(self): - return self.pbm.stopService() - - def perspectiveFactory(self, mind, username): - persp = mock.Mock() - persp.is_my_persp = True - persp.attached = lambda mind : defer.succeed(None) - self.connections.append(username) - return defer.succeed(persp) - - def test_repr(self): - reg = self.pbm.register('tcp:0:interface=127.0.0.1', "x", "y", self.perspectiveFactory) - self.assertEqual(`self.pbm.dispatchers['tcp:0:interface=127.0.0.1']`, - '<pbmanager.Dispatcher for x on tcp:0:interface=127.0.0.1>') - self.assertEqual(`reg`, '<pbmanager.Registration for x on tcp:0:interface=127.0.0.1>') - - def test_register_unregister(self): - portstr = "tcp:0:interface=127.0.0.1" - reg = self.pbm.register(portstr, "boris", "pass", self.perspectiveFactory) - - # make sure things look right - self.assertIn(portstr, self.pbm.dispatchers) - disp = self.pbm.dispatchers[portstr] - self.assertIn('boris', disp.users) - - # we can't actually connect to it, as that requires finding the - # dynamically allocated port number which is buried out of reach; - # however, we can try the requestAvatar and requestAvatarId methods. - - d = disp.requestAvatarId(credentials.UsernamePassword('boris', 'pass')) - def check_avatarid(username): - self.assertEqual(username, 'boris') - d.addCallback(check_avatarid) - d.addCallback(lambda _ : - disp.requestAvatar('boris', mock.Mock(), pb.IPerspective)) - def check_avatar((iface, persp, detach_fn)): - self.failUnless(persp.is_my_persp) - self.assertIn('boris', self.connections) - d.addCallback(check_avatar) - - d.addCallback(lambda _ : reg.unregister()) - return d - - def test_double_register_unregister(self): - portstr = "tcp:0:interface=127.0.0.1" - reg1 = self.pbm.register(portstr, "boris", "pass", None) - reg2 = self.pbm.register(portstr, "ivona", "pass", None) - - # make sure things look right - self.assertEqual(len(self.pbm.dispatchers), 1) - self.assertIn(portstr, self.pbm.dispatchers) - disp = self.pbm.dispatchers[portstr] - self.assertIn('boris', disp.users) - self.assertIn('ivona', disp.users) - - d = reg1.unregister() - def check_boris_gone(_): - self.assertEqual(len(self.pbm.dispatchers), 1) - self.assertIn(portstr, self.pbm.dispatchers) - disp = self.pbm.dispatchers[portstr] - self.assertNotIn('boris', disp.users) - self.assertIn('ivona', disp.users) - d.addCallback(check_boris_gone) - d.addCallback(lambda _ : reg2.unregister()) - def check_dispatcher_gone(_): - self.assertEqual(len(self.pbm.dispatchers), 0) - d.addCallback(check_dispatcher_gone) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_BotMaster.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_BotMaster.py deleted file mode 100644 index ff45c907..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_BotMaster.py +++ /dev/null @@ -1,259 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from zope.interface import implements -from twisted.trial import unittest -from twisted.internet import defer -from twisted.application import service -from buildbot.process.botmaster import BotMaster -from buildbot.process import factory -from buildbot import config, interfaces -from buildbot.test.fake import fakemaster - -class TestCleanShutdown(unittest.TestCase): - def setUp(self): - self.botmaster = BotMaster(mock.Mock()) - self.reactor = mock.Mock() - self.botmaster.startService() - - def assertReactorStopped(self, _=None): - self.assertTrue(self.reactor.stop.called) - - def assertReactorNotStopped(self, _=None): - self.assertFalse(self.reactor.stop.called) - - def makeFakeBuild(self): - self.fake_builder = builder = mock.Mock() - build = mock.Mock() - builder.builder_status.getCurrentBuilds.return_value = [build] - - self.build_deferred = defer.Deferred() - build.waitUntilFinished.return_value = self.build_deferred - - self.botmaster.builders = mock.Mock() - self.botmaster.builders.values.return_value = [builder] - - def finishFakeBuild(self): - self.fake_builder.builder_status.getCurrentBuilds.return_value = [] - self.build_deferred.callback(None) - - # tests - - def test_shutdown_idle(self): - """Test that the master shuts down when it's idle""" - self.botmaster.cleanShutdown(_reactor=self.reactor) - self.assertReactorStopped() - - def test_shutdown_busy(self): - """Test that the master shuts down after builds finish""" - self.makeFakeBuild() - - self.botmaster.cleanShutdown(_reactor=self.reactor) - - # check that we haven't stopped yet, since there's a running build - self.assertReactorNotStopped() - - # try to shut it down again, just to check that this does not fail - self.botmaster.cleanShutdown(_reactor=self.reactor) - - # Now we cause the build to finish - self.finishFakeBuild() - - # And now we should be stopped - self.assertReactorStopped() - - def test_shutdown_cancel_not_shutting_down(self): - """Test that calling cancelCleanShutdown when none is in progress - works""" - # this just shouldn't fail.. - self.botmaster.cancelCleanShutdown() - - def test_shutdown_cancel(self): - """Test that we can cancel a shutdown""" - self.makeFakeBuild() - - self.botmaster.cleanShutdown(_reactor=self.reactor) - - # Next we check that we haven't stopped yet, since there's a running - # build. - self.assertReactorNotStopped() - - # but the BuildRequestDistributor should not be running - self.assertFalse(self.botmaster.brd.running) - - # Cancel the shutdown - self.botmaster.cancelCleanShutdown() - - # Now we cause the build to finish - self.finishFakeBuild() - - # We should still be running! - self.assertReactorNotStopped() - - # and the BuildRequestDistributor should be, as well - self.assertTrue(self.botmaster.brd.running) - - -class FakeBuildSlave(config.ReconfigurableServiceMixin, service.Service): - - implements(interfaces.IBuildSlave) - - reconfig_count = 0 - - def __init__(self, slavename): - self.slavename = slavename - - def reconfigService(self, new_config): - self.reconfig_count += 1 - return defer.succeed(None) - - -class FakeBuildSlave2(FakeBuildSlave): - pass - - -class TestBotMaster(unittest.TestCase): - - def setUp(self): - self.master = fakemaster.make_master() - self.botmaster = BotMaster(self.master) - self.new_config = mock.Mock() - self.botmaster.startService() - - def tearDown(self): - return self.botmaster.stopService() - - def test_reconfigService(self): - # check that reconfigServiceSlaves and reconfigServiceBuilders are - # both called; they will be tested invidually below - self.patch(self.botmaster, 'reconfigServiceBuilders', - mock.Mock(side_effect=lambda c : defer.succeed(None))) - self.patch(self.botmaster, 'reconfigServiceSlaves', - mock.Mock(side_effect=lambda c : defer.succeed(None))) - self.patch(self.botmaster, 'maybeStartBuildsForAllBuilders', - mock.Mock()) - - old_config, new_config = mock.Mock(), mock.Mock() - d = self.botmaster.reconfigService(new_config) - @d.addCallback - def check(_): - self.botmaster.reconfigServiceBuilders.assert_called_with( - new_config) - self.botmaster.reconfigServiceSlaves.assert_called_with( - new_config) - self.assertTrue( - self.botmaster.maybeStartBuildsForAllBuilders.called) - return d - - @defer.inlineCallbacks - def test_reconfigServiceSlaves_add_remove(self): - sl = FakeBuildSlave('sl1') - self.new_config.slaves = [ sl ] - - yield self.botmaster.reconfigServiceSlaves(self.new_config) - - self.assertIdentical(sl.parent, self.botmaster) - self.assertEqual(self.botmaster.slaves, { 'sl1' : sl }) - - self.new_config.slaves = [ ] - - yield self.botmaster.reconfigServiceSlaves(self.new_config) - - self.assertIdentical(sl.parent, None) - self.assertIdentical(sl.master, None) - - @defer.inlineCallbacks - def test_reconfigServiceSlaves_reconfig(self): - sl = FakeBuildSlave('sl1') - self.botmaster.slaves = dict(sl1=sl) - sl.setServiceParent(self.botmaster) - sl.master = self.master - sl.botmaster = self.botmaster - - sl_new = FakeBuildSlave('sl1') - self.new_config.slaves = [ sl_new ] - - yield self.botmaster.reconfigServiceSlaves(self.new_config) - - # sl was not replaced.. - self.assertIdentical(self.botmaster.slaves['sl1'], sl) - - @defer.inlineCallbacks - def test_reconfigServiceSlaves_class_changes(self): - sl = FakeBuildSlave('sl1') - self.botmaster.slaves = dict(sl1=sl) - sl.setServiceParent(self.botmaster) - sl.master = self.master - sl.botmaster = self.botmaster - - sl_new = FakeBuildSlave2('sl1') - self.new_config.slaves = [ sl_new ] - - yield self.botmaster.reconfigServiceSlaves(self.new_config) - - # sl *was* replaced (different class) - self.assertIdentical(self.botmaster.slaves['sl1'], sl_new) - - @defer.inlineCallbacks - def test_reconfigServiceBuilders_add_remove(self): - bc = config.BuilderConfig(name='bldr', factory=factory.BuildFactory(), - slavename='f') - self.new_config.builders = [ bc ] - - yield self.botmaster.reconfigServiceBuilders(self.new_config) - - bldr = self.botmaster.builders['bldr'] - self.assertIdentical(bldr.parent, self.botmaster) - self.assertIdentical(bldr.master, self.master) - self.assertEqual(self.botmaster.builderNames, [ 'bldr' ]) - - self.new_config.builders = [ ] - - yield self.botmaster.reconfigServiceBuilders(self.new_config) - - self.assertIdentical(bldr.parent, None) - self.assertIdentical(bldr.master, None) - self.assertEqual(self.botmaster.builders, {}) - self.assertEqual(self.botmaster.builderNames, []) - - def test_maybeStartBuildsForBuilder(self): - brd = self.botmaster.brd = mock.Mock() - - self.botmaster.maybeStartBuildsForBuilder('frank') - - brd.maybeStartBuildsOn.assert_called_once_with(['frank']) - - def test_maybeStartBuildsForSlave(self): - brd = self.botmaster.brd = mock.Mock() - b1 = mock.Mock(name='frank') - b1.name = 'frank' - b2 = mock.Mock(name='larry') - b2.name = 'larry' - self.botmaster.getBuildersForSlave = mock.Mock(return_value=[b1, b2]) - - self.botmaster.maybeStartBuildsForSlave('centos') - - self.botmaster.getBuildersForSlave.assert_called_once_with('centos') - brd.maybeStartBuildsOn.assert_called_once_with(['frank', 'larry']) - - def test_maybeStartBuildsForAll(self): - brd = self.botmaster.brd = mock.Mock() - self.botmaster.builderNames = ['frank', 'larry'] - - self.botmaster.maybeStartBuildsForAllBuilders() - - brd.maybeStartBuildsOn.assert_called_once_with(['frank', 'larry']) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_DuplicateSlaveArbitrator.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_DuplicateSlaveArbitrator.py deleted file mode 100644 index 34e5af1e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_botmaster_DuplicateSlaveArbitrator.py +++ /dev/null @@ -1,213 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.python import failure, log -from twisted.trial import unittest -from twisted.internet import defer, reactor, task -from twisted.spread import pb -from buildbot.test.util import compat -from buildbot.process import botmaster -from buildbot.util.eventual import eventually - -# TODO: should do this with more of the Twisted machinery intact - maybe in a -# separate integration test? - -class FakeAbstractBuildSlave(object): - - def __init__(self, slave, name, isConnected=True, reactor=reactor): - self.slavename = name - self.slave = slave - self.isConnectedResult = isConnected - self.reactor = reactor - self.call_on_detach = lambda : None - - # set up for loseConnection to cause the slave to detach, but not - # immediately - def tport_loseConnection(): - self.isConnectedResult = False - self.call_on_detach() - self.call_on_detach = None - self.slave.broker.transport.loseConnection = (lambda : - eventually(tport_loseConnection)) - - def subscribeToDetach(self, callback): - self.call_on_detach = callback - - def isConnected(self): - return self.isConnectedResult - - -class FakeRemoteBuildSlave(object): - - def __init__(self, name, callRemoteFailure=False, - callRemoteException=False, - callRemoteHang=0, - reactor=reactor): - self.name = name - self.callRemoteFailure = callRemoteFailure - self.callRemoteException = callRemoteException - self.callRemoteHang = callRemoteHang - self.reactor = reactor - - self.broker = mock.Mock() - self.broker.transport.getPeer = lambda : "<peer %s>" % name - - def _makePingResult(self): - if self.callRemoteException: - exc = self.callRemoteException() - log.msg(" -> exception %r" % (exc,)) - raise exc - if self.callRemoteFailure: - f = defer.fail(self.callRemoteFailure()) - log.msg(" -> failure %r" % (f,)) - return f - return defer.succeed(None) - - def callRemote(self, meth, *args, **kwargs): - assert meth == "print" - log.msg("%r.callRemote('print', %r)" % (self, args[0],)) - # if we're asked to hang, then set up to fire the deferred later - if self.callRemoteHang: - log.msg(" -> hang for %d s" % (self.callRemoteHang,)) - d = defer.Deferred() - self.reactor.callLater(self.callRemoteHang, d.callback, None) - def hangdone(_): - log.msg("%r.callRemote hang finished" % (self,)) - return self._makePingResult() - d.addCallback(hangdone) - self.callRemote_d = d - # otherwise, return a fired deferred - else: - self.callRemote_d = self._makePingResult() - return self.callRemote_d - - def __repr__(self): - return "<FakeRemoteBuildSlave %s>" % (self.name,) - - -class DuplicateSlaveArbitrator(unittest.TestCase): - - def makeDeadReferenceError(self): - return pb.DeadReferenceError("Calling Stale Broker (fake exception)") - - def makeRuntimeError(self): - return RuntimeError("oh noes!") - - def makePBConnectionLostFailure(self): - return failure.Failure(pb.PBConnectionLost("gone")) - - def test_old_slave_present(self): - old_remote = FakeRemoteBuildSlave("old") - new_remote = FakeRemoteBuildSlave("new") - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave") - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - self.fail("shouldn't get here") - def failed(f): - f.trap(RuntimeError) # expected error - d.addCallbacks(got_persp, failed) - return d - - def test_old_slave_absent_deadref_exc(self): - old_remote = FakeRemoteBuildSlave("old", - callRemoteException=self.makeDeadReferenceError) - new_remote = FakeRemoteBuildSlave("new") - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave") - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - self.assertIdentical(bs, buildslave) - d.addCallback(got_persp) - return d - - def test_old_slave_absent_connlost_failure(self): - old_remote = FakeRemoteBuildSlave("old", - callRemoteFailure=self.makePBConnectionLostFailure) - new_remote = FakeRemoteBuildSlave("new") - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave") - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - self.assertIdentical(bs, buildslave) - d.addCallback(got_persp) - return d - - @compat.usesFlushLoggedErrors - def test_old_slave_absent_unexpected_exc(self): - old_remote = FakeRemoteBuildSlave("old", - callRemoteException=self.makeRuntimeError) - new_remote = FakeRemoteBuildSlave("new") - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave") - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - # getPerspective has returned successfully: - self.assertIdentical(bs, buildslave) - # and the unexpected RuntimeError was logged: - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - d.addCallback(got_persp) - return d - - def do_test_old_slave_absent_timeout(self, callRemoteException=None): - clock = task.Clock() - PING_TIMEOUT = botmaster.DuplicateSlaveArbitrator.PING_TIMEOUT - - old_remote = FakeRemoteBuildSlave("old", reactor=clock, - callRemoteHang=PING_TIMEOUT+1, - callRemoteException=callRemoteException) - new_remote = FakeRemoteBuildSlave("new") - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave", - reactor=clock) - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - arb._reactor = clock - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - self.assertIdentical(bs, buildslave) - d.addCallback(got_persp) - - # show the passage of time for 2s more than the PING_TIMEOUT, to allow - # the old callRemote to return eventually - clock.pump([.1] * 10 * (PING_TIMEOUT+4)) - - # check that the timed-out call eventually returned (and was ignored, - # even if there was an exception) - self.failUnless(old_remote.callRemote_d.called) - - return d - - def test_old_slave_absent_timeout(self): - return self.do_test_old_slave_absent_timeout() - - def test_old_slave_absent_timeout_exc(self): - return self.do_test_old_slave_absent_timeout( - callRemoteException=self.makeRuntimeError) - - @compat.usesFlushLoggedErrors - def test_new_slave_ping_error(self): - old_remote = FakeRemoteBuildSlave("old") - new_remote = FakeRemoteBuildSlave("new", - callRemoteException=self.makeRuntimeError) - buildslave = FakeAbstractBuildSlave(old_remote, name="testslave") - arb = botmaster.DuplicateSlaveArbitrator(buildslave) - d = arb.getPerspective(new_remote, "testslave") - def got_persp(bs): - self.fail("shouldn't get here") - def failed(f): - pass #f.trap(RuntimeError) # expected error - d.addCallbacks(got_persp, failed) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_build.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_build.py deleted file mode 100644 index 784ea172..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_build.py +++ /dev/null @@ -1,823 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from zope.interface import implements -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import interfaces -from buildbot.process.build import Build -from buildbot.process.properties import Properties -from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, RETRY, EXCEPTION -from buildbot.locks import SlaveLock -from buildbot.process.buildstep import LoggingBuildStep -from buildbot.test.fake.fakemaster import FakeBotMaster -from buildbot import config - -from mock import Mock - -class FakeChange: - properties = Properties() - def __init__(self, number = None): - self.number = number - self.who = "me" - -class FakeSource: - def __init__(self): - self.sourcestampsetid = None - self.changes = [] - self.branch = None - self.revision = None - self.repository = '' - self.codebase = '' - self.project = '' - self.patch_info = None - self.patch = None - - def getRepository(self): - return self.repository - -class FakeRequest: - def __init__(self): - self.sources = [] - self.reason = "Because" - self.properties = Properties() - - def mergeSourceStampsWith(self, others): - return self.sources - - def mergeReasons(self, others): - return self.reason - -class FakeBuildStep: - def __init__(self): - self.haltOnFailure = False - self.flunkOnWarnings = False - self.flunkOnFailure = True - self.warnOnWarnings = True - self.warnOnFailure = False - self.alwaysRun = False - self.name = 'fake' - -class FakeMaster: - def __init__(self): - self.locks = {} - self.parent = Mock() - self.config = config.MasterConfig() - - def getLockByID(self, lockid): - if not lockid in self.locks: - self.locks[lockid] = lockid.lockClass(lockid) - return self.locks[lockid] - -class FakeBuildStatus(Mock): - implements(interfaces.IProperties) - -class FakeBuilderStatus: - implements(interfaces.IBuilderStatus) - -class FakeStepFactory(object): - """Fake step factory that just returns a fixed step object.""" - implements(interfaces.IBuildStepFactory) - def __init__(self, step): - self.step = step - - def buildStep(self): - return self.step - -class TestBuild(unittest.TestCase): - - def setUp(self): - r = FakeRequest() - r.sources = [FakeSource()] - r.sources[0].changes = [FakeChange()] - r.sources[0].revision = "12345" - - self.request = r - self.master = FakeMaster() - - self.master.botmaster = FakeBotMaster(master=self.master) - - self.builder = self.createBuilder() - self.build = Build([r]) - self.build.setBuilder(self.builder) - - def createBuilder(self): - bldr = Mock() - bldr.botmaster = self.master.botmaster - return bldr - - def testRunSuccessfulBuild(self): - b = self.build - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - b.setStepFactories([FakeStepFactory(step)]) - - slavebuilder = Mock() - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assertEqual(b.result, SUCCESS) - self.assert_( ('startStep', (slavebuilder.remote,), {}) - in step.method_calls) - - def testStopBuild(self): - b = self.build - - step = Mock() - step.return_value = step - b.setStepFactories([FakeStepFactory(step)]) - - slavebuilder = Mock() - - def startStep(*args, **kw): - # Now interrupt the build - b.stopBuild("stop it") - return defer.Deferred() - step.startStep = startStep - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assertEqual(b.result, EXCEPTION) - - self.assert_( ('interrupt', ('stop it',), {}) in step.method_calls) - - def testAlwaysRunStepStopBuild(self): - """Test that steps marked with alwaysRun=True still get run even if - the build is stopped.""" - - # Create a build with 2 steps, the first one will get interrupted, and - # the second one is marked with alwaysRun=True - b = self.build - - step1 = Mock() - step1.return_value = step1 - step1.alwaysRun = False - step2 = Mock() - step2.return_value = step2 - step2.alwaysRun = True - b.setStepFactories([ - FakeStepFactory(step1), - FakeStepFactory(step2), - ]) - - slavebuilder = Mock() - - def startStep1(*args, **kw): - # Now interrupt the build - b.stopBuild("stop it") - return defer.succeed( SUCCESS ) - step1.startStep = startStep1 - step1.stepDone.return_value = False - - step2Started = [False] - def startStep2(*args, **kw): - step2Started[0] = True - return defer.succeed( SUCCESS ) - step2.startStep = startStep2 - step1.stepDone.return_value = False - - d = b.startBuild(FakeBuildStatus(), None, slavebuilder) - def check(ign): - self.assertEqual(b.result, EXCEPTION) - self.assert_( ('interrupt', ('stop it',), {}) in step1.method_calls) - self.assert_(step2Started[0]) - d.addCallback(check) - return d - - def testBuildcanStartWithSlavebuilder(self): - b = self.build - - slavebuilder1 = Mock() - slavebuilder2 = Mock() - - l = SlaveLock('lock') - counting_access = l.access('counting') - real_lock = b.builder.botmaster.getLockByID(l) - - # no locks, so both these pass (call twice to verify there's no state/memory) - lock_list = [(real_lock, counting_access)] - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - - slave_lock_1 = real_lock.getLock(slavebuilder1.slave) - slave_lock_2 = real_lock.getLock(slavebuilder2.slave) - - # then have slavebuilder2 claim its lock: - slave_lock_2.claim(slavebuilder2, counting_access) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertFalse(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - self.assertFalse(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - slave_lock_2.release(slavebuilder2, counting_access) - - # then have slavebuilder1 claim its lock: - slave_lock_1.claim(slavebuilder1, counting_access) - self.assertFalse(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertFalse(Build.canStartWithSlavebuilder(lock_list, slavebuilder1)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - self.assertTrue(Build.canStartWithSlavebuilder(lock_list, slavebuilder2)) - slave_lock_1.release(slavebuilder1, counting_access) - - - def testBuildLocksAcquired(self): - b = self.build - - slavebuilder = Mock() - - l = SlaveLock('lock') - claimCount = [0] - lock_access = l.access('counting') - l.access = lambda mode: lock_access - real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder.slave) - def claim(owner, access): - claimCount[0] += 1 - return real_lock.old_claim(owner, access) - real_lock.old_claim = real_lock.claim - real_lock.claim = claim - b.setLocks([lock_access]) - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - b.setStepFactories([FakeStepFactory(step)]) - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assertEqual(b.result, SUCCESS) - self.assert_( ('startStep', (slavebuilder.remote,), {}) - in step.method_calls) - self.assertEquals(claimCount[0], 1) - - def testBuildLocksOrder(self): - """Test that locks are acquired in FIFO order; specifically that - counting locks cannot jump ahead of exclusive locks""" - eBuild = self.build - - cBuilder = self.createBuilder() - cBuild = Build([self.request]) - cBuild.setBuilder(cBuilder) - - eSlavebuilder = Mock() - cSlavebuilder = Mock() - - slave = eSlavebuilder.slave - cSlavebuilder.slave = slave - - l = SlaveLock('lock', 2) - claimLog = [] - realLock = self.master.botmaster.getLockByID(l).getLock(slave) - def claim(owner, access): - claimLog.append(owner) - return realLock.oldClaim(owner, access) - realLock.oldClaim = realLock.claim - realLock.claim = claim - - eBuild.setLocks([l.access('exclusive')]) - cBuild.setLocks([l.access('counting')]) - - fakeBuild = Mock() - fakeBuildAccess = l.access('counting') - realLock.claim(fakeBuild, fakeBuildAccess) - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - eBuild.setStepFactories([FakeStepFactory(step)]) - cBuild.setStepFactories([FakeStepFactory(step)]) - - e = eBuild.startBuild(FakeBuildStatus(), None, eSlavebuilder) - c = cBuild.startBuild(FakeBuildStatus(), None, cSlavebuilder) - d = defer.DeferredList([e, c]) - - realLock.release(fakeBuild, fakeBuildAccess) - - def check(ign): - self.assertEqual(eBuild.result, SUCCESS) - self.assertEqual(cBuild.result, SUCCESS) - self.assertEquals(claimLog, [fakeBuild, eBuild, cBuild]) - - d.addCallback(check) - return d - - def testBuildWaitingForLocks(self): - b = self.build - - slavebuilder = Mock() - - l = SlaveLock('lock') - claimCount = [0] - lock_access = l.access('counting') - l.access = lambda mode: lock_access - real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder.slave) - def claim(owner, access): - claimCount[0] += 1 - return real_lock.old_claim(owner, access) - real_lock.old_claim = real_lock.claim - real_lock.claim = claim - b.setLocks([lock_access]) - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - b.setStepFactories([FakeStepFactory(step)]) - - real_lock.claim(Mock(), l.access('counting')) - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assert_( ('startStep', (slavebuilder.remote,), {}) - not in step.method_calls) - self.assertEquals(claimCount[0], 1) - self.assert_(b.currentStep is None) - self.assert_(b._acquiringLock is not None) - - def testStopBuildWaitingForLocks(self): - b = self.build - - slavebuilder = Mock() - - l = SlaveLock('lock') - lock_access = l.access('counting') - l.access = lambda mode: lock_access - real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder) - b.setLocks([lock_access]) - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - step.alwaysRun = False - b.setStepFactories([FakeStepFactory(step)]) - - real_lock.claim(Mock(), l.access('counting')) - - def acquireLocks(res=None): - retval = Build.acquireLocks(b, res) - b.stopBuild('stop it') - return retval - b.acquireLocks = acquireLocks - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assert_( ('startStep', (slavebuilder.remote,), {}) - not in step.method_calls) - self.assert_(b.currentStep is None) - self.assertEqual(b.result, EXCEPTION) - self.assert_( ('interrupt', ('stop it',), {}) not in step.method_calls) - - def testStopBuildWaitingForLocks_lostRemote(self): - b = self.build - - slavebuilder = Mock() - - l = SlaveLock('lock') - lock_access = l.access('counting') - l.access = lambda mode: lock_access - real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder) - b.setLocks([lock_access]) - - step = Mock() - step.return_value = step - step.startStep.return_value = SUCCESS - step.alwaysRun = False - b.setStepFactories([FakeStepFactory(step)]) - - real_lock.claim(Mock(), l.access('counting')) - - def acquireLocks(res=None): - retval = Build.acquireLocks(b, res) - b.lostRemote() - return retval - b.acquireLocks = acquireLocks - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assert_( ('startStep', (slavebuilder.remote,), {}) - not in step.method_calls) - self.assert_(b.currentStep is None) - self.assertEqual(b.result, RETRY) - self.assert_( ('interrupt', ('stop it',), {}) not in step.method_calls) - self.build.build_status.setText.assert_called_with(["retry", "lost", "remote"]) - self.build.build_status.setResults.assert_called_with(RETRY) - - def testStopBuildWaitingForStepLocks(self): - b = self.build - - slavebuilder = Mock() - - l = SlaveLock('lock') - lock_access = l.access('counting') - l.access = lambda mode: lock_access - real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder) - - step = LoggingBuildStep(locks=[lock_access]) - b.setStepFactories([FakeStepFactory(step)]) - - real_lock.claim(Mock(), l.access('counting')) - - gotLocks = [False] - - def acquireLocks(res=None): - gotLocks[0] = True - retval = LoggingBuildStep.acquireLocks(step, res) - self.assert_(b.currentStep is step) - b.stopBuild('stop it') - return retval - step.acquireLocks = acquireLocks - step.setStepStatus = Mock() - step.step_status = Mock() - step.step_status.addLog().chunkSize = 10 - step.step_status.getLogs.return_value = [] - - b.startBuild(FakeBuildStatus(), None, slavebuilder) - - self.assertEqual(gotLocks, [True]) - self.assert_(('stepStarted', (), {}) in step.step_status.method_calls) - self.assertEqual(b.result, EXCEPTION) - - def testStepDone(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - terminate = b.stepDone(SUCCESS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, SUCCESS) - - def testStepDoneHaltOnFailure(self): - b = self.build - b.results = [] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.haltOnFailure = True - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, True) - self.assertEqual(b.result, FAILURE) - - def testStepDoneHaltOnFailureNoFlunkOnFailure(self): - b = self.build - b.results = [] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.flunkOnFailure = False - step.haltOnFailure = True - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, True) - self.assertEqual(b.result, SUCCESS) - - def testStepDoneFlunkOnWarningsFlunkOnFailure(self): - b = self.build - b.results = [] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.flunkOnFailure = True - step.flunkOnWarnings = True - b.stepDone(WARNINGS, step) - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneNoWarnOnWarnings(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.warnOnWarnings = False - terminate = b.stepDone(WARNINGS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, SUCCESS) - - def testStepDoneWarnings(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - terminate = b.stepDone(WARNINGS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, WARNINGS) - - def testStepDoneFail(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneFailOverridesWarnings(self): - b = self.build - b.results = [SUCCESS, WARNINGS] - b.result = WARNINGS - b.remote = Mock() - step = FakeBuildStep() - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneWarnOnFailure(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.warnOnFailure = True - step.flunkOnFailure = False - terminate = b.stepDone(FAILURE, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, WARNINGS) - - def testStepDoneFlunkOnWarnings(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.flunkOnWarnings = True - terminate = b.stepDone(WARNINGS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneHaltOnFailureFlunkOnWarnings(self): - b = self.build - b.results = [SUCCESS] - b.result = SUCCESS - b.remote = Mock() - step = FakeBuildStep() - step.flunkOnWarnings = True - self.haltOnFailure = True - terminate = b.stepDone(WARNINGS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneWarningsDontOverrideFailure(self): - b = self.build - b.results = [FAILURE] - b.result = FAILURE - b.remote = Mock() - step = FakeBuildStep() - terminate = b.stepDone(WARNINGS, step) - self.assertEqual(terminate, False) - self.assertEqual(b.result, FAILURE) - - def testStepDoneRetryOverridesAnythingElse(self): - b = self.build - b.results = [RETRY] - b.result = RETRY - b.remote = Mock() - step = FakeBuildStep() - step.alwaysRun = True - b.stepDone(WARNINGS, step) - b.stepDone(FAILURE, step) - b.stepDone(SUCCESS, step) - terminate = b.stepDone(EXCEPTION, step) - self.assertEqual(terminate, True) - self.assertEqual(b.result, RETRY) - -class TestMultipleSourceStamps(unittest.TestCase): - - def setUp(self): - r = FakeRequest() - s1 = FakeSource() - s1.repository = "repoA" - s1.codebase = "A" - s1.changes = [FakeChange(10), FakeChange(11)] - s1.revision = "12345" - s2 = FakeSource() - s2.repository = "repoB" - s2.codebase = "B" - s2.changes = [FakeChange(12),FakeChange(13)] - s2.revision = "67890" - s3 = FakeSource() - s3.repository = "repoC" - # no codebase defined - s3.changes = [FakeChange(14),FakeChange(15)] - s3.revision = "111213" - r.sources.extend([s1,s2,s3]) - - self.build = Build([r]) - - def test_buildReturnSourceStamp(self): - """ - Test that a build returns the correct sourcestamp - """ - source1 = self.build.getSourceStamp("A") - source2 = self.build.getSourceStamp("B") - - self.assertEqual( [source1.repository, source1.revision], ["repoA", "12345"]) - self.assertEqual( [source2.repository, source2.revision], ["repoB", "67890"]) - - def test_buildReturnSourceStamp_empty_codebase(self): - """ - Test that a build returns the correct sourcestamp if codebase is empty - """ - codebase = '' - source3 = self.build.getSourceStamp(codebase) - self.assertTrue(source3 is not None) - self.assertEqual( [source3.repository, source3.revision], ["repoC", "111213"]) - - -class TestBuildBlameList(unittest.TestCase): - - def setUp(self): - self.sourceByMe = FakeSource() - self.sourceByMe.repository = "repoA" - self.sourceByMe.codebase = "A" - self.sourceByMe.changes = [FakeChange(10), FakeChange(11)] - self.sourceByMe.changes[0].who = "me" - self.sourceByMe.changes[1].who = "me" - - self.sourceByHim = FakeSource() - self.sourceByHim.repository = "repoB" - self.sourceByHim.codebase = "B" - self.sourceByHim.changes = [FakeChange(12), FakeChange(13)] - self.sourceByHim.changes[0].who = "him" - self.sourceByHim.changes[1].who = "him" - - self.patchSource = FakeSource() - self.patchSource.repository = "repoB" - self.patchSource.codebase = "B" - self.patchSource.changes = [] - self.patchSource.revision = "67890" - self.patchSource.patch_info = ("jeff", "jeff's new feature") - - def test_blamelist_for_changes(self): - r = FakeRequest() - r.sources.extend([self.sourceByMe, self.sourceByHim]) - build = Build([r]) - blamelist = build.blamelist() - self.assertEqual(blamelist, ['him', 'me']) - - def test_blamelist_for_patch(self): - r = FakeRequest() - r.sources.extend([self.patchSource]) - build = Build([r]) - blamelist = build.blamelist() - self.assertEqual(blamelist, ['jeff']) - -class TestSetupProperties_MultipleSources(unittest.TestCase): - """ - Test that the property values, based on the available requests, are - initialized properly - """ - def setUp(self): - self.props = {} - r = FakeRequest() - r.sources = [] - r.sources.append(FakeSource()) - r.sources[0].changes = [FakeChange()] - r.sources[0].repository = "http://svn-repo-A" - r.sources[0].codebase = "A" - r.sources[0].branch = "develop" - r.sources[0].revision = "12345" - r.sources.append(FakeSource()) - r.sources[1].changes = [FakeChange()] - r.sources[1].repository = "http://svn-repo-B" - r.sources[1].codebase = "B" - r.sources[1].revision = "34567" - self.build = Build([r]) - self.build.setStepFactories([]) - self.builder = Mock() - self.build.setBuilder(self.builder) - self.build.build_status = FakeBuildStatus() - # record properties that will be set - self.build.build_status.setProperty = self.setProperty - - def setProperty(self, n,v,s, runtime = False): - if s not in self.props: - self.props[s] = {} - if not self.props[s]: - self.props[s] = {} - self.props[s][n] = v - - def test_sourcestamp_properties_not_set(self): - self.build.setupProperties() - self.assertTrue("codebase" not in self.props["Build"]) - self.assertTrue("revision" not in self.props["Build"]) - self.assertTrue("branch" not in self.props["Build"]) - self.assertTrue("project" not in self.props["Build"]) - self.assertTrue("repository" not in self.props["Build"]) - -class TestSetupProperties_SingleSource(unittest.TestCase): - """ - Test that the property values, based on the available requests, are - initialized properly - """ - def setUp(self): - self.props = {} - r = FakeRequest() - r.sources = [] - r.sources.append(FakeSource()) - r.sources[0].changes = [FakeChange()] - r.sources[0].repository = "http://svn-repo-A" - r.sources[0].codebase = "A" - r.sources[0].branch = "develop" - r.sources[0].revision = "12345" - self.build = Build([r]) - self.build.setStepFactories([]) - self.builder = Mock() - self.build.setBuilder(self.builder) - self.build.build_status = FakeBuildStatus() - # record properties that will be set - self.build.build_status.setProperty = self.setProperty - - def setProperty(self, n,v,s, runtime = False): - if s not in self.props: - self.props[s] = {} - if not self.props[s]: - self.props[s] = {} - self.props[s][n] = v - - def test_properties_codebase(self): - self.build.setupProperties() - codebase = self.props["Build"]["codebase"] - self.assertEqual(codebase, "A") - - def test_properties_repository(self): - self.build.setupProperties() - repository = self.props["Build"]["repository"] - self.assertEqual(repository, "http://svn-repo-A") - - def test_properties_revision(self): - self.build.setupProperties() - revision = self.props["Build"]["revision"] - self.assertEqual(revision, "12345") - - def test_properties_branch(self): - self.build.setupProperties() - branch = self.props["Build"]["branch"] - self.assertEqual(branch, "develop") - - def test_property_project(self): - self.build.setupProperties() - project = self.props["Build"]["project"] - self.assertEqual(project, '') - -class TestBuildProperties(unittest.TestCase): - """ - Test that a Build has the necessary L{IProperties} methods, and that they - properly delegate to the C{build_status} attribute - so really just a test - of the L{IProperties} adapter. - """ - - def setUp(self): - r = FakeRequest() - r.sources = [FakeSource()] - r.sources[0].changes = [FakeChange()] - r.sources[0].revision = "12345" - self.build = Build([r]) - self.build.setStepFactories([]) - self.builder = Mock() - self.build.setBuilder(self.builder) - self.build_status = FakeBuildStatus() - self.build.startBuild(self.build_status, None, Mock()) - - def test_getProperty(self): - self.build.getProperty('x') - self.build_status.getProperty.assert_called_with('x', None) - - def test_getProperty_default(self): - self.build.getProperty('x', 'nox') - self.build_status.getProperty.assert_called_with('x', 'nox') - - def test_setProperty(self): - self.build.setProperty('n', 'v', 's') - self.build_status.setProperty.assert_called_with('n', 'v', 's', - runtime=True) - - def test_hasProperty(self): - self.build_status.hasProperty.return_value = True - self.assertTrue(self.build.hasProperty('p')) - self.build_status.hasProperty.assert_called_with('p') - - def test_has_key(self): - self.build_status.has_key.return_value = True - self.assertTrue(self.build.has_key('p')) - # has_key calls through to hasProperty - self.build_status.hasProperty.assert_called_with('p') - - def test_render(self): - self.build.render("xyz") - self.build_status.render.assert_called_with("xyz") diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_builder.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_builder.py deleted file mode 100644 index 462b5694..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_builder.py +++ /dev/null @@ -1,427 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -import random -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import config -from buildbot.test.fake import fakedb, fakemaster -from buildbot.process import builder, factory -from buildbot.util import epoch2datetime - -class BuilderMixin(object): - def makeBuilder(self, name="bldr", patch_random=False, **config_kwargs): - """Set up C{self.bldr}""" - self.factory = factory.BuildFactory() - self.master = fakemaster.make_master() - # only include the necessary required config, plus user-requested - config_args = dict(name=name, slavename="slv", builddir="bdir", - slavebuilddir="sbdir", factory=self.factory) - config_args.update(config_kwargs) - self.builder_config = config.BuilderConfig(**config_args) - self.bldr = builder.Builder(self.builder_config.name, _addServices=False) - self.master.db = self.db = fakedb.FakeDBConnector(self) - self.bldr.master = self.master - self.bldr.botmaster = self.master.botmaster - - # patch into the _startBuildsFor method - self.builds_started = [] - def _startBuildFor(slavebuilder, buildrequests): - self.builds_started.append((slavebuilder, buildrequests)) - return defer.succeed(True) - self.bldr._startBuildFor = _startBuildFor - - if patch_random: - # patch 'random.choice' to always take the slave that sorts - # last, based on its name - self.patch(random, "choice", - lambda lst : sorted(lst, key=lambda m : m.name)[-1]) - - self.bldr.startService() - - mastercfg = config.MasterConfig() - mastercfg.builders = [ self.builder_config ] - return self.bldr.reconfigService(mastercfg) - -class TestBuilderBuildCreation(BuilderMixin, unittest.TestCase): - - def setUp(self): - # a collection of rows that would otherwise clutter up every test - self.base_rows = [ - fakedb.SourceStampSet(id=21), - fakedb.SourceStamp(id=21, sourcestampsetid=21), - fakedb.Buildset(id=11, reason='because', sourcestampsetid=21), - ] - - def makeBuilder(self, patch_random=False, startBuildsForSucceeds=True, **config_kwargs): - d = BuilderMixin.makeBuilder(self, patch_random=patch_random, **config_kwargs) - @d.addCallback - def patch_startBuildsFor(_): - # patch into the _startBuildsFor method - self.builds_started = [] - def _startBuildFor(slavebuilder, buildrequests): - self.builds_started.append((slavebuilder, buildrequests)) - return defer.succeed(startBuildsForSucceeds) - self.bldr._startBuildFor = _startBuildFor - return d - - def assertBuildsStarted(self, exp): - # munge builds_started into a list of (slave, [brids]) - builds_started = [ - (sl.name, [ br.id for br in buildreqs ]) - for (sl, buildreqs) in self.builds_started ] - self.assertEqual(sorted(builds_started), sorted(exp)) - - def setSlaveBuilders(self, slavebuilders): - """C{slaves} maps name : available""" - self.bldr.slaves = [] - for name, avail in slavebuilders.iteritems(): - sb = mock.Mock(spec=['isAvailable'], name=name) - sb.name = name - sb.isAvailable.return_value = avail - self.bldr.slaves.append(sb) - - # services - - @defer.inlineCallbacks - def test_maybeStartBuild_builder_stopped(self): - yield self.makeBuilder() - - # this will cause an exception if maybeStartBuild tries to start - self.bldr.slaves = None - - # so we just hope this does not fail - yield self.bldr.stopService() - started = yield self.bldr.maybeStartBuild(None, []) - self.assertEquals(started, False) - - - # maybeStartBuild - - def _makeMocks(self): - slave = mock.Mock() - slave.name = 'slave' - buildrequest = mock.Mock() - buildrequest.id = 10 - buildrequests = [buildrequest] - return slave, buildrequests - - @defer.inlineCallbacks - def test_maybeStartBuild(self): - yield self.makeBuilder() - - slave, buildrequests = self._makeMocks() - - started = yield self.bldr.maybeStartBuild(slave, buildrequests) - self.assertEqual(started, True) - self.assertBuildsStarted([('slave', [10])]) - - @defer.inlineCallbacks - def test_maybeStartBuild_failsToStart(self): - yield self.makeBuilder(startBuildsForSucceeds=False) - - slave, buildrequests = self._makeMocks() - - started = yield self.bldr.maybeStartBuild(slave, buildrequests) - self.assertEqual(started, False) - self.assertBuildsStarted([('slave', [10])]) - - @defer.inlineCallbacks - def do_test_getMergeRequestsFn(self, builder_param=None, - global_param=None, expected=0): - cble = lambda : None - builder_param = builder_param == 'callable' and cble or builder_param - global_param = global_param == 'callable' and cble or global_param - - # omit the constructor parameter if None was given - if builder_param is None: - yield self.makeBuilder() - else: - yield self.makeBuilder(mergeRequests=builder_param) - - self.master.config.mergeRequests = global_param - - fn = self.bldr.getMergeRequestsFn() - - if fn == builder.Builder._defaultMergeRequestFn: - fn = "default" - elif fn is cble: - fn = 'callable' - self.assertEqual(fn, expected) - - def test_getMergeRequestsFn_defaults(self): - self.do_test_getMergeRequestsFn(None, None, "default") - - def test_getMergeRequestsFn_global_True(self): - self.do_test_getMergeRequestsFn(None, True, "default") - - def test_getMergeRequestsFn_global_False(self): - self.do_test_getMergeRequestsFn(None, False, None) - - def test_getMergeRequestsFn_global_function(self): - self.do_test_getMergeRequestsFn(None, 'callable', 'callable') - - def test_getMergeRequestsFn_builder_True(self): - self.do_test_getMergeRequestsFn(True, False, "default") - - def test_getMergeRequestsFn_builder_False(self): - self.do_test_getMergeRequestsFn(False, True, None) - - def test_getMergeRequestsFn_builder_function(self): - self.do_test_getMergeRequestsFn('callable', None, 'callable') - - - # other methods - - @defer.inlineCallbacks - def test_reclaimAllBuilds_empty(self): - yield self.makeBuilder() - - # just to be sure this doesn't crash - yield self.bldr.reclaimAllBuilds() - - @defer.inlineCallbacks - def test_reclaimAllBuilds(self): - yield self.makeBuilder() - - claims = [] - def fakeClaimBRs(*args): - claims.append(args) - return defer.succeed(None) - self.bldr.master.db.buildrequests.claimBuildRequests = fakeClaimBRs - self.bldr.master.db.buildrequests.reclaimBuildRequests = fakeClaimBRs - - def mkbld(brids): - bld = mock.Mock(name='Build') - bld.requests = [] - for brid in brids: - br = mock.Mock(name='BuildRequest %d' % brid) - br.id = brid - bld.requests.append(br) - return bld - - old = mkbld([15]) # keep a reference to the "old" build - self.bldr.old_building[old] = None - self.bldr.building.append(mkbld([10,11,12])) - - yield self.bldr.reclaimAllBuilds() - - self.assertEqual(claims, [ (set([10,11,12,15]),) ]) - - @defer.inlineCallbacks - def test_canStartBuild(self): - yield self.makeBuilder() - - # by default, it returns True - startable = yield self.bldr.canStartBuild('slave', 100) - self.assertEqual(startable, True) - - startable = yield self.bldr.canStartBuild('slave', 101) - self.assertEqual(startable, True) - - # set a configurable one - record = [] - def canStartBuild(bldr, slave, breq): - record.append((bldr, slave, breq)) - return (slave,breq)==('slave',100) - self.bldr.config.canStartBuild = canStartBuild - - startable = yield self.bldr.canStartBuild('slave', 100) - self.assertEqual(startable, True) - self.assertEqual(record, [(self.bldr, 'slave', 100)]) - - startable = yield self.bldr.canStartBuild('slave', 101) - self.assertEqual(startable, False) - self.assertEqual(record, [(self.bldr, 'slave', 100), (self.bldr, 'slave', 101)]) - - # set a configurable one to return Deferred - record = [] - def canStartBuild_deferred(bldr, slave, breq): - record.append((bldr, slave, breq)) - return (slave,breq)==('slave',100) - return defer.succeed((slave,breq)==('slave',100)) - self.bldr.config.canStartBuild = canStartBuild_deferred - - startable = yield self.bldr.canStartBuild('slave', 100) - self.assertEqual(startable, True) - self.assertEqual(record, [(self.bldr, 'slave', 100)]) - - startable = yield self.bldr.canStartBuild('slave', 101) - self.assertEqual(startable, False) - self.assertEqual(record, [(self.bldr, 'slave', 100), (self.bldr, 'slave', 101)]) - - @defer.inlineCallbacks - def test_enforceChosenSlave(self): - """enforceChosenSlave rejects and accepts builds""" - yield self.makeBuilder() - - self.bldr.config.canStartBuild = builder.enforceChosenSlave - - slave = mock.Mock() - slave.slave.slavename = 'slave5' - - breq = mock.Mock() - - # no buildslave requested - breq.properties = {} - result = yield self.bldr.canStartBuild(slave, breq) - self.assertIdentical(True, result) - - # buildslave requested as the right one - breq.properties = { 'slavename': 'slave5' } - result = yield self.bldr.canStartBuild(slave, breq) - self.assertIdentical(True, result) - - # buildslave requested as the wrong one - breq.properties = { 'slavename': 'slave4' } - result = yield self.bldr.canStartBuild(slave, breq) - self.assertIdentical(False, result) - - # buildslave set to non string value gets skipped - breq.properties = { 'slavename': 0 } - result = yield self.bldr.canStartBuild(slave, breq) - self.assertIdentical(True, result) - - - - -class TestGetOldestRequestTime(BuilderMixin, unittest.TestCase): - - def setUp(self): - # a collection of rows that would otherwise clutter up every test - master_id = fakedb.FakeBuildRequestsComponent.MASTER_ID - self.base_rows = [ - fakedb.SourceStampSet(id=21), - fakedb.SourceStamp(id=21, sourcestampsetid=21), - fakedb.Buildset(id=11, reason='because', sourcestampsetid=21), - fakedb.BuildRequest(id=111, submitted_at=1000, - buildername='bldr1', buildsetid=11), - fakedb.BuildRequest(id=222, submitted_at=2000, - buildername='bldr1', buildsetid=11), - fakedb.BuildRequestClaim(brid=222, objectid=master_id, - claimed_at=2001), - fakedb.BuildRequest(id=333, submitted_at=3000, - buildername='bldr1', buildsetid=11), - fakedb.BuildRequest(id=444, submitted_at=2500, - buildername='bldr2', buildsetid=11), - fakedb.BuildRequestClaim(brid=444, objectid=master_id, - claimed_at=2501), - ] - - def test_gort_unclaimed(self): - d = self.makeBuilder(name='bldr1') - d.addCallback(lambda _ : self.db.insertTestData(self.base_rows)) - d.addCallback(lambda _ : self.bldr.getOldestRequestTime()) - def check(rqtime): - self.assertEqual(rqtime, epoch2datetime(1000)) - d.addCallback(check) - return d - - def test_gort_all_claimed(self): - d = self.makeBuilder(name='bldr2') - d.addCallback(lambda _ : self.db.insertTestData(self.base_rows)) - d.addCallback(lambda _ : self.bldr.getOldestRequestTime()) - def check(rqtime): - self.assertEqual(rqtime, None) - d.addCallback(check) - return d - -class TestRebuild(BuilderMixin, unittest.TestCase): - - def makeBuilder(self, name, sourcestamps): - d = BuilderMixin.makeBuilder(self, name=name) - @d.addCallback - def setupBstatus(_): - self.bstatus = mock.Mock() - bstatus_properties = mock.Mock() - bstatus_properties.properties = {} - self.bstatus.getProperties.return_value = bstatus_properties - self.bstatus.getSourceStamps.return_value = sourcestamps - self.master.addBuildset = addBuildset = mock.Mock() - addBuildset.return_value = (1, [100]) - return d - - @defer.inlineCallbacks - def do_test_rebuild(self, - sourcestampsetid, - nr_of_sourcestamps): - - # Store combinations of sourcestampId and sourcestampSetId - self.sslist = {} - self.ssseq = 1 - def addSourceStampToDatabase(master, sourcestampsetid): - self.sslist[self.ssseq] = sourcestampsetid - self.ssseq += 1 - return defer.succeed(sourcestampsetid) - def getSourceStampSetId(master): - return addSourceStampToDatabase(master, sourcestampsetid = sourcestampsetid) - - sslist = [] - for x in range(nr_of_sourcestamps): - ssx = mock.Mock() - ssx.addSourceStampToDatabase = addSourceStampToDatabase - ssx.getSourceStampSetId = getSourceStampSetId - sslist.append(ssx) - - yield self.makeBuilder(name='bldr1', sourcestamps = sslist) - control = mock.Mock(spec=['master']) - control.master = self.master - self.bldrctrl = builder.BuilderControl(self.bldr, control) - - yield self.bldrctrl.rebuildBuild(self.bstatus, reason = 'unit test', extraProperties = {}) - - @defer.inlineCallbacks - def test_rebuild_with_no_sourcestamps(self): - yield self.do_test_rebuild(101, 0) - self.assertEqual(self.sslist, {}) - - @defer.inlineCallbacks - def test_rebuild_with_single_sourcestamp(self): - yield self.do_test_rebuild(101, 1) - self.assertEqual(self.sslist, {1:101}) - self.master.addBuildset.assert_called_with(builderNames=['bldr1'], - sourcestampsetid=101, - reason = 'unit test', - properties = {}) - - - @defer.inlineCallbacks - def test_rebuild_with_multiple_sourcestamp(self): - yield self.do_test_rebuild(101, 3) - self.assertEqual(self.sslist, {1:101, 2:101, 3:101}) - self.master.addBuildset.assert_called_with(builderNames=['bldr1'], - sourcestampsetid=101, - reason = 'unit test', - properties = {}) - - -class TestReconfig(BuilderMixin, unittest.TestCase): - """Tests that a reconfig properly updates all attributes""" - - @defer.inlineCallbacks - def test_reconfig(self): - yield self.makeBuilder(description="Old", category="OldCat") - self.builder_config.description = "New" - self.builder_config.category = "NewCat" - - mastercfg = config.MasterConfig() - mastercfg.builders = [ self.builder_config ] - yield self.bldr.reconfigService(mastercfg) - self.assertEqual( - dict(description=self.bldr.builder_status.getDescription(), - category=self.bldr.builder_status.getCategory()), - dict(description="New", - category="NewCat")) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequest.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequest.py deleted file mode 100644 index 632be205..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequest.py +++ /dev/null @@ -1,346 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.fake import fakedb, fakemaster -from buildbot.process import buildrequest - -class FakeSource: - def __init__(self, mergeable = True): - self.codebase = '' - self.mergeable = mergeable - self.changes = [] - - def canBeMergedWith(self, other): - return self.mergeable - -class TestBuildRequest(unittest.TestCase): - - def test_fromBrdict(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://...', project='world-domination'), - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='trunk', - revision='9284', repository='svn://...', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=234, changeid=13), - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=234), - fakedb.BuildsetProperty(buildsetid=539, property_name='x', - property_value='[1, "X"]'), - fakedb.BuildsetProperty(buildsetid=539, property_name='y', - property_value='[2, "Y"]'), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='bldr', - priority=13, submitted_at=1200000000), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - def check(br): - # check enough of the source stamp to verify it found the changes - self.assertEqual(br.source.ssid, 234) - self.assertEqual([ ch.number for ch in br.source.changes], [13]) - - self.assertEqual(br.reason, 'triggered') - - self.assertEqual(br.properties.getProperty('x'), 1) - self.assertEqual(br.properties.getProperty('y'), 2) - self.assertEqual(br.submittedAt, 1200000000) - self.assertEqual(br.buildername, 'bldr') - self.assertEqual(br.priority, 13) - self.assertEqual(br.id, 288) - self.assertEqual(br.bsid, 539) - d.addCallback(check) - return d - - def test_fromBrdict_submittedAt_NULL(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='trunk', - revision='9284', repository='svn://...', - project='world-domination'), - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=234), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='bldr', - priority=13, submitted_at=None), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - def check(br): - # remaining fields assumed to be checked in test_fromBrdict - self.assertEqual(br.submittedAt, None) - d.addCallback(check) - return d - - def test_fromBrdict_no_sourcestamps(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStampSet(id=234), - # Sourcestampset has no sourcestamps - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=234), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='not important', - priority=0, submitted_at=None), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict: - buildrequest.BuildRequest.fromBrdict(master, brdict)) - return self.assertFailure(d, AssertionError) - - def test_fromBrdict_multiple_sourcestamps(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStampSet(id=234), - - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://a..', codebase='A', - project='world-domination'), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='trunk', - revision='9283', repository='svn://a..', - codebase='A', project='world-domination'), - fakedb.SourceStampChange(sourcestampid=234, changeid=13), - - fakedb.Change(changeid=14, branch='trunk', revision='9284', - repository='svn://b..', codebase='B', - project='world-domination'), - fakedb.SourceStamp(id=235, sourcestampsetid=234, branch='trunk', - revision='9284', repository='svn://b..', - codebase='B', project='world-domination'), - fakedb.SourceStampChange(sourcestampid=235, changeid=14), - - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=234), - fakedb.BuildsetProperty(buildsetid=539, property_name='x', - property_value='[1, "X"]'), - fakedb.BuildsetProperty(buildsetid=539, property_name='y', - property_value='[2, "Y"]'), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='bldr', - priority=13, submitted_at=1200000000), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - def check(br): - # check enough of the source stamp to verify it found the changes - - # Test the single-sourcestamp interface - self.assertEqual(br.source.ssid, 234) - - # Test the multiple sourcestamp interface - self.assertEqual(br.sources['A'].ssid, 234) - self.assertEqual(br.sources['B'].ssid, 235) - - self.assertEqual([ ch.number for ch in br.sources['A'].changes], [13]) - self.assertEqual([ ch.number for ch in br.sources['B'].changes], [14]) - - self.assertEqual(br.reason, 'triggered') - - self.assertEqual(br.properties.getProperty('x'), 1) - self.assertEqual(br.properties.getProperty('y'), 2) - self.assertEqual(br.submittedAt, 1200000000) - self.assertEqual(br.buildername, 'bldr') - self.assertEqual(br.priority, 13) - self.assertEqual(br.id, 288) - self.assertEqual(br.bsid, 539) - d.addCallback(check) - return d - - def test_mergeSourceStampsWith_common_codebases(self): - """ This testcase has two buildrequests - Request Change Codebase Revision Comment - ---------------------------------------------------------------------- - 288 13 A 9283 - 289 15 A 9284 - 288 14 B 9200 - 289 16 B 9201 - -------------------------------- - After merged in Build: - Source1 has rev 9284 and contains changes 13 and 15 from repository svn://a - Source2 has rev 9201 and contains changes 14 and 16 from repository svn://b - """ - brs=[] # list of buildrequests - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStampSet(id=2340), - - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://a..', codebase='A', - project='world-domination'), - fakedb.SourceStamp(id=234, sourcestampsetid=2340, branch='trunk', - revision='9283', repository='svn://a..', codebase='A', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=234, changeid=13), - - fakedb.Change(changeid=14, branch='trunk', revision='9200', - repository='svn://b..', codebase='A', - project='world-domination'), - fakedb.SourceStamp(id=235, sourcestampsetid=2340, branch='trunk', - revision='9200', repository='svn://b..', codebase='B', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=235, changeid=14), - - fakedb.SourceStampSet(id=2360), - - fakedb.Change(changeid=15, branch='trunk', revision='9284', - repository='svn://a..', codebase='A', - project='world-domination'), - fakedb.SourceStamp(id=236, sourcestampsetid=2360, branch='trunk', - revision='9284', repository='svn://a..', codebase='A', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=236, changeid=15), - - fakedb.Change(changeid=16, branch='trunk', revision='9201', - repository='svn://b..', codebase='B', - project='world-domination'), - fakedb.SourceStamp(id=237, sourcestampsetid=2360, branch='trunk', - revision='9201', repository='svn://b..', codebase='B', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=237, changeid=16), - - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=2340), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='bldr'), - - fakedb.Buildset(id=540, reason='triggered', sourcestampsetid=2360), - fakedb.BuildRequest(id=289, buildsetid=540, buildername='bldr'), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - d.addCallback(lambda br : brs.append(br)) - d.addCallback(lambda _ : - master.db.buildrequests.getBuildRequest(289)) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - d.addCallback(lambda br : brs.append(br)) - def check(_): - sources = brs[0].mergeSourceStampsWith(brs[1:]) - - source1 = source2 = None - for source in sources: - if source.codebase == 'A': - source1 = source - if source.codebase == 'B': - source2 = source - - self.assertFalse(source1 == None) - self.assertEqual(source1.revision,'9284') - - self.assertFalse(source2 == None) - self.assertEqual(source2.revision,'9201') - - self.assertEqual([c.number for c in source1.changes], [13,15]) - self.assertEqual([c.number for c in source2.changes], [14,16]) - - d.addCallback(check) - return d - - def test_canBeMergedWith_different_codebases_raises_error(self): - """ This testcase has two buildrequests - Request Change Codebase Revision Comment - ---------------------------------------------------------------------- - 288 17 C 1800 request 1 has repo not in request 2 - 289 18 D 2100 request 2 has repo not in request 1 - -------------------------------- - Merge cannot be performd and raises error: - Merging requests requires both requests to have the same codebases - """ - brs=[] # list of buildrequests - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStampSet(id=2340), - - fakedb.Change(changeid=17, branch='trunk', revision='1800', - repository='svn://c..', codebase='C', - project='world-domination'), - fakedb.SourceStamp(id=238, sourcestampsetid=2340, branch='trunk', - revision='1800', repository='svn://c..', - codebase='C', project='world-domination'), - fakedb.SourceStampChange(sourcestampid=238, changeid=17), - - fakedb.SourceStampSet(id=2360), - - fakedb.Change(changeid=18, branch='trunk', revision='2100', - repository='svn://d..', codebase='D', - project='world-domination'), - fakedb.SourceStamp(id=239, sourcestampsetid=2360, branch='trunk', - revision='2100', repository='svn://d..', - codebase='D', project='world-domination'), - fakedb.SourceStampChange(sourcestampid=239, changeid=18), - - fakedb.Buildset(id=539, reason='triggered', sourcestampsetid=2340), - fakedb.BuildRequest(id=288, buildsetid=539, buildername='bldr'), - - fakedb.Buildset(id=540, reason='triggered', sourcestampsetid=2360), - fakedb.BuildRequest(id=289, buildsetid=540, buildername='bldr'), - ]) - # use getBuildRequest to minimize the risk from changes to the format - # of the brdict - d = master.db.buildrequests.getBuildRequest(288) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - d.addCallback(lambda br : brs.append(br)) - d.addCallback(lambda _ : - master.db.buildrequests.getBuildRequest(289)) - d.addCallback(lambda brdict : - buildrequest.BuildRequest.fromBrdict(master, brdict)) - d.addCallback(lambda br : brs.append(br)) - def check(_): - self.assertEqual(brs[0].canBeMergedWith(brs[1]), False) - - d.addCallback(check) - return d - - def test_build_can_be_merged_with_mergables_same_codebases(self): - r1 = buildrequest.BuildRequest() - r1.sources = {"A": FakeSource()} - r2 = buildrequest.BuildRequest() - r2.sources = {"A": FakeSource()} - mergeable = r1.canBeMergedWith(r2) - self.assertTrue(mergeable, "Both request should be able to merge") - - def test_build_can_be_merged_with_non_mergable_same_codebases(self): - r1 = buildrequest.BuildRequest() - r1.sources = {"A": FakeSource(mergeable = False)} - r2 = buildrequest.BuildRequest() - r2.sources = {"A": FakeSource(mergeable = False)} - mergeable = r1.canBeMergedWith(r2) - self.assertFalse(mergeable, "Both request should not be able to merge") - - def test_build_can_be_merged_with_non_mergables_different_codebases(self): - r1 = buildrequest.BuildRequest() - r1.sources = {"A": FakeSource(mergeable = False)} - r2 = buildrequest.BuildRequest() - r2.sources = {"B": FakeSource(mergeable = False)} - mergeable = r1.canBeMergedWith(r2) - self.assertFalse(mergeable, "Request containing different codebases " + - "should never be able to merge") - - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequestdistributor_BuildRequestDistributor.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequestdistributor_BuildRequestDistributor.py deleted file mode 100644 index e27e6f1d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildrequestdistributor_BuildRequestDistributor.py +++ /dev/null @@ -1,1031 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer, reactor -from twisted.python import failure -from buildbot.test.util import compat -from buildbot.test.fake import fakedb, fakemaster -from buildbot.process import buildrequestdistributor -from buildbot.util import epoch2datetime -from buildbot.util.eventual import fireEventually -from buildbot.db import buildrequests - -def nth_slave(n): - def pick_nth_by_name(lst): - slaves = lst[:] - slaves.sort(cmp=lambda a,b: cmp(a.name, b.name)) - return slaves[n] - return pick_nth_by_name - -class SkipSlavesThatCantGetLock(buildrequestdistributor.BasicBuildChooser): - """This class disables the 'rejectedSlaves' feature""" - def __init__(self, *args, **kwargs): - buildrequestdistributor.BasicBuildChooser.__init__(self, *args, **kwargs) - self.rejectedSlaves = None # disable this feature - -class Test(unittest.TestCase): - - def setUp(self): - self.botmaster = mock.Mock(name='botmaster') - self.botmaster.builders = {} - def prioritizeBuilders(master, builders): - # simple sort-by-name by default - return sorted(builders, lambda b1,b2 : cmp(b1.name, b2.name)) - self.master = self.botmaster.master = mock.Mock(name='master') - self.master.config.prioritizeBuilders = prioritizeBuilders - self.master.db = fakedb.FakeDBConnector(self) - self.brd = buildrequestdistributor.BuildRequestDistributor(self.botmaster) - self.brd.startService() - - # TODO: this is a terrible way to detect the "end" of the test - - # it regularly completes too early after a simple modification of - # a test. Is there a better way? - self.quiet_deferred = defer.Deferred() - def _quiet(): - if self.quiet_deferred: - d, self.quiet_deferred = self.quiet_deferred, None - d.callback(None) - else: - self.fail("loop has already gone quiet once") - self.brd._quiet = _quiet - - self.builders = {} - - def tearDown(self): - if self.brd.running: - return self.brd.stopService() - - def checkAllCleanedUp(self): - # check that the BRD didnt end with a stuck lock or in the 'active' state (which would mean - # it ended without unwinding correctly) - self.assertEqual(self.brd.pending_builders_lock.locked, False) - self.assertEqual(self.brd.activity_lock.locked, False) - self.assertEqual(self.brd.active, False) - - def useMock_maybeStartBuildsOnBuilder(self): - # sets up a mock "maybeStartBuildsOnBuilder" so we can track - # how the method gets invoked - - # keep track of the calls to brd.maybeStartBuildsOnBuilder - self.maybeStartBuildsOnBuilder_calls = [] - - def maybeStartBuildsOnBuilder(bldr): - self.assertIdentical(self.builders[bldr.name], bldr) - self.maybeStartBuildsOnBuilder_calls.append(bldr.name) - return fireEventually() - self.brd._maybeStartBuildsOnBuilder = maybeStartBuildsOnBuilder - - def addBuilders(self, names): - self.startedBuilds = [] - - for name in names: - bldr = mock.Mock(name=name) - bldr.name = name - self.botmaster.builders[name] = bldr - self.builders[name] = bldr - - def maybeStartBuild(*args): - self.startedBuilds.append((name, args)) - d = defer.Deferred() - reactor.callLater(0, d.callback, None) - return d - bldr.maybeStartBuild = maybeStartBuild - bldr.canStartWithSlavebuilder = lambda _: True - - bldr.slaves = [] - bldr.getAvailableSlaves = lambda : [ s for s in bldr.slaves if s.isAvailable ] - - def removeBuilder(self, name): - del self.builders[name] - del self.botmaster.builders[name] - - # tests - - def test_maybeStartBuildsOn_simple(self): - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(['bldr1']) - self.brd.maybeStartBuildsOn(['bldr1']) - def check(_): - self.assertEqual(self.maybeStartBuildsOnBuilder_calls, ['bldr1']) - self.checkAllCleanedUp() - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - def test_maybeStartBuildsOn_parallel(self): - # test 15 "parallel" invocations of maybeStartBuildsOn, with a - # _sortBuilders that takes a while. This is a regression test for bug - # #1979. - builders = ['bldr%02d' % i for i in xrange(15) ] - - def slow_sorter(master, bldrs): - bldrs.sort(lambda b1, b2 : cmp(b1.name, b2.name)) - d = defer.Deferred() - reactor.callLater(0, d.callback, bldrs) - def done(_): - return _ - d.addCallback(done) - return d - self.master.config.prioritizeBuilders = slow_sorter - - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(builders) - for bldr in builders: - self.brd.maybeStartBuildsOn([bldr]) - def check(_): - self.assertEqual(self.maybeStartBuildsOnBuilder_calls, builders) - self.checkAllCleanedUp() - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - @compat.usesFlushLoggedErrors - def test_maybeStartBuildsOn_exception(self): - self.addBuilders(['bldr1']) - - def _maybeStartBuildsOnBuilder(n): - # fail slowly, so that the activity loop doesn't go quiet too soon - d = defer.Deferred() - reactor.callLater(0, - d.errback, failure.Failure(RuntimeError("oh noes"))) - return d - self.brd._maybeStartBuildsOnBuilder = _maybeStartBuildsOnBuilder - - self.brd.maybeStartBuildsOn(['bldr1']) - def check(_): - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - self.checkAllCleanedUp() - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - def test_maybeStartBuildsOn_collapsing(self): - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(['bldr1', 'bldr2', 'bldr3']) - self.brd.maybeStartBuildsOn(['bldr3']) - self.brd.maybeStartBuildsOn(['bldr2', 'bldr1']) - self.brd.maybeStartBuildsOn(['bldr4']) # should be ignored - self.brd.maybeStartBuildsOn(['bldr2']) # already queued - ignored - self.brd.maybeStartBuildsOn(['bldr3', 'bldr2']) - def check(_): - # bldr3 gets invoked twice, since it's considered to have started - # already when the first call to maybeStartBuildsOn returns - self.assertEqual(self.maybeStartBuildsOnBuilder_calls, - ['bldr3', 'bldr1', 'bldr2', 'bldr3']) - self.checkAllCleanedUp() - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - def test_maybeStartBuildsOn_builders_missing(self): - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(['bldr1', 'bldr2', 'bldr3']) - self.brd.maybeStartBuildsOn(['bldr1', 'bldr2', 'bldr3']) - # bldr1 is already run, so surreptitiously remove the other - # two - nothing should crash, but the builders should not run - self.removeBuilder('bldr2') - self.removeBuilder('bldr3') - def check(_): - self.assertEqual(self.maybeStartBuildsOnBuilder_calls, ['bldr1']) - self.checkAllCleanedUp() - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - def do_test_sortBuilders(self, prioritizeBuilders, oldestRequestTimes, - expected, returnDeferred=False): - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(oldestRequestTimes.keys()) - self.master.config.prioritizeBuilders = prioritizeBuilders - - def mklambda(t): # work around variable-binding issues - if returnDeferred: - return lambda : defer.succeed(t) - else: - return lambda : t - - for n, t in oldestRequestTimes.iteritems(): - if t is not None: - t = epoch2datetime(t) - self.builders[n].getOldestRequestTime = mklambda(t) - - d = self.brd._sortBuilders(oldestRequestTimes.keys()) - def check(result): - self.assertEqual(result, expected) - self.checkAllCleanedUp() - d.addCallback(check) - return d - - def test_sortBuilders_default_sync(self): - return self.do_test_sortBuilders(None, # use the default sort - dict(bldr1=777, bldr2=999, bldr3=888), - ['bldr1', 'bldr3', 'bldr2']) - - def test_sortBuilders_default_asyn(self): - return self.do_test_sortBuilders(None, # use the default sort - dict(bldr1=777, bldr2=999, bldr3=888), - ['bldr1', 'bldr3', 'bldr2'], - returnDeferred=True) - - def test_sortBuilders_default_None(self): - return self.do_test_sortBuilders(None, # use the default sort - dict(bldr1=777, bldr2=None, bldr3=888), - ['bldr1', 'bldr3', 'bldr2']) - - def test_sortBuilders_custom(self): - def prioritizeBuilders(master, builders): - self.assertIdentical(master, self.master) - return sorted(builders, key=lambda b : b.name) - - return self.do_test_sortBuilders(prioritizeBuilders, - dict(bldr1=1, bldr2=1, bldr3=1), - ['bldr1', 'bldr2', 'bldr3']) - - def test_sortBuilders_custom_async(self): - def prioritizeBuilders(master, builders): - self.assertIdentical(master, self.master) - return defer.succeed(sorted(builders, key=lambda b : b.name)) - - return self.do_test_sortBuilders(prioritizeBuilders, - dict(bldr1=1, bldr2=1, bldr3=1), - ['bldr1', 'bldr2', 'bldr3']) - - @compat.usesFlushLoggedErrors - def test_sortBuilders_custom_exception(self): - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(['x', 'y']) - def fail(m, b): - raise RuntimeError("oh noes") - self.master.config.prioritizeBuilders = fail - - # expect to get the builders back in the same order in the event of an - # exception - d = self.brd._sortBuilders(['y', 'x']) - def check(result): - self.assertEqual(result, ['y', 'x']) - - # and expect the exception to be logged - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - d.addCallback(check) - return d - - def test_stopService(self): - # check that stopService waits for a builder run to complete, but does not - # allow a subsequent run to start - self.useMock_maybeStartBuildsOnBuilder() - self.addBuilders(['A', 'B']) - - oldMSBOB = self.brd._maybeStartBuildsOnBuilder - def maybeStartBuildsOnBuilder(bldr): - d = oldMSBOB(bldr) - - stop_d = self.brd.stopService() - stop_d.addCallback(lambda _ : - self.maybeStartBuildsOnBuilder_calls.append('(stopped)')) - - d.addCallback(lambda _ : - self.maybeStartBuildsOnBuilder_calls.append('finished')) - return d - self.brd._maybeStartBuildsOnBuilder = maybeStartBuildsOnBuilder - - # start both builds; A should start and complete *before* the service stops, - # and B should not run. - self.brd.maybeStartBuildsOn(['A', 'B']) - - def check(_): - self.assertEqual(self.maybeStartBuildsOnBuilder_calls, - ['A', 'finished', '(stopped)']) - self.quiet_deferred.addCallback(check) - return self.quiet_deferred - - -class TestMaybeStartBuilds(unittest.TestCase): - - def setUp(self): - self.botmaster = mock.Mock(name='botmaster') - self.botmaster.builders = {} - self.master = self.botmaster.master = mock.Mock(name='master') - self.master.db = fakedb.FakeDBConnector(self) - class getCache(object): - def get_cache(self): - return self - def get(self, name): - return - self.master.caches = fakemaster.FakeCaches() - self.brd = buildrequestdistributor.BuildRequestDistributor(self.botmaster) - self.brd.startService() - - self.startedBuilds = [] - - # TODO: this is a terrible way to detect the "end" of the test - - # it regularly completes too early after a simple modification of - # a test. Is there a better way? - self.quiet_deferred = defer.Deferred() - def _quiet(): - if self.quiet_deferred: - d, self.quiet_deferred = self.quiet_deferred, None - d.callback(None) - else: - self.fail("loop has already gone quiet once") - self.brd._quiet = _quiet - - self.bldr = self.createBuilder('A') - - # a collection of rows that would otherwise clutter up every test - self.base_rows = [ - fakedb.SourceStampSet(id=21), - fakedb.SourceStamp(id=21, sourcestampsetid=21), - fakedb.Buildset(id=11, reason='because', sourcestampsetid=21), - ] - - - def tearDown(self): - if self.brd.running: - return self.brd.stopService() - - def createBuilder(self, name): - bldr = mock.Mock(name=name) - bldr.name = name - self.botmaster.builders[name] = bldr - - def maybeStartBuild(slave, builds): - self.startedBuilds.append((slave.name, builds)) - return defer.succeed(True) - - bldr.maybeStartBuild = maybeStartBuild - bldr.canStartWithSlavebuilder = lambda _: True - bldr.getMergeRequestsFn = lambda : False - - bldr.slaves = [] - bldr.getAvailableSlaves = lambda : [ s for s in bldr.slaves if s.isAvailable() ] - bldr.config.nextSlave = None - bldr.config.nextBuild = None - - def canStartBuild(*args): - can = bldr.config.canStartBuild - return not can or can(*args) - bldr.canStartBuild = canStartBuild - - return bldr - - def addSlaves(self, slavebuilders): - """C{slaves} maps name : available""" - for name, avail in slavebuilders.iteritems(): - sb = mock.Mock(spec=['isAvailable'], name=name) - sb.name = name - sb.isAvailable.return_value = avail - self.bldr.slaves.append(sb) - - def assertBuildsStarted(self, exp): - # munge builds_started into (slave, [brids]) - builds_started = [ - (slave, [br.id for br in breqs]) - for (slave, breqs) in self.startedBuilds ] - self.assertEqual(sorted(builds_started), sorted(exp)) - - # _maybeStartBuildsOnBuilder - - @defer.inlineCallbacks - def do_test_maybeStartBuildsOnBuilder(self, rows=[], exp_claims=[], exp_builds=[]): - yield self.master.db.insertTestData(rows) - - yield self.brd._maybeStartBuildsOnBuilder(self.bldr) - - self.master.db.buildrequests.assertMyClaims(exp_claims) - self.assertBuildsStarted(exp_builds) - - @defer.inlineCallbacks - def test_no_buildreqests(self): - self.addSlaves({'test-slave11':1}) - yield self.do_test_maybeStartBuildsOnBuilder(exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_no_slavebuilders(self): - rows = [ - fakedb.BuildRequest(id=11, buildsetid=10, buildername="bldr"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_limited_by_slaves(self): - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10], exp_builds=[('test-slave1', [10])]) - - @defer.inlineCallbacks - def test_sorted_by_submit_time(self): - self.master.config.mergeRequests = False - - # same as "limited_by_slaves" but with rows swapped - self.addSlaves({'test-slave1':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10], exp_builds=[('test-slave1', [10])]) - - @defer.inlineCallbacks - def test_limited_by_available_slaves(self): - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':0, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10], exp_builds=[('test-slave2', [10])]) - - @defer.inlineCallbacks - def test_slow_db(self): - # test what happens if the "getBuildRequests" fetch takes a "long time" - - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1}) - - # wrap to simulate a "long" db access - old_getBuildRequests = self.master.db.buildrequests.getBuildRequests - def longGetBuildRequests(*args, **kwargs): - res_d = old_getBuildRequests(*args, **kwargs) - long_d = defer.Deferred() - long_d.addCallback(lambda _: res_d) - reactor.callLater(0, long_d.callback, None) - return long_d - self.master.db.buildrequests.getBuildRequests = longGetBuildRequests - - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10], exp_builds=[('test-slave1', [10])]) - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def test_limited_by_canStartBuild(self): - """Set the 'canStartBuild' value in the config to something - that limits the possible options.""" - - self.master.config.mergeRequests = False - - slaves_attempted = [] - def _canStartWithSlavebuilder(slavebuilder): - slaves_attempted.append(slavebuilder.name) - return True - self.bldr.canStartWithSlavebuilder = _canStartWithSlavebuilder - - pairs_tested = [] - def _canStartBuild(slave, breq): - result = (slave.name, breq.id) - pairs_tested.append(result) - allowed = [ - ("test-slave1", 10), - ("test-slave3", 11), - ] - return result in allowed - self.bldr.config.canStartBuild = _canStartBuild - - self.addSlaves({'test-slave1':1, 'test-slave2':1, 'test-slave3':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - fakedb.BuildRequest(id=12, buildsetid=11, buildername="A", - submitted_at=140000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10, 11], exp_builds=[('test-slave1', [10]), ('test-slave3', [11])]) - - self.assertEqual(slaves_attempted, ['test-slave3', 'test-slave2', 'test-slave1']) - - # we expect brids in order (10-11-12), - # with each searched in reverse order of slaves (3-2-1) available (due to nth_slave(-1)) - self.assertEqual(pairs_tested, [ - ('test-slave3', 10), - ('test-slave2', 10), - ('test-slave1', 10), - ('test-slave3', 11), - ('test-slave2', 12)]) - - @mock.patch('random.choice', nth_slave(-1)) - @mock.patch('buildbot.process.buildrequestdistributor.BuildRequestDistributor.BuildChooser', SkipSlavesThatCantGetLock) - @defer.inlineCallbacks - def test_limited_by_canStartBuild_deferreds(self): - """Another variant that: - * returns Defered types, - * use 'canStartWithSlavebuilder' to reject one of the slaves - * patch using SkipSlavesThatCantGetLock to disable the 'rejectedSlaves' feature""" - - self.master.config.mergeRequests = False - - slaves_attempted = [] - def _canStartWithSlavebuilder(slavebuilder): - slaves_attempted.append(slavebuilder.name) - allowed = slavebuilder.name in ['test-slave2', 'test-slave1'] - return defer.succeed(allowed) # a defered here! - self.bldr.canStartWithSlavebuilder = _canStartWithSlavebuilder - - pairs_tested = [] - def _canStartBuild(slave, breq): - result = (slave.name, breq.id) - pairs_tested.append(result) - allowed = [ - ("test-slave1", 10), - ("test-slave3", 11), - ] - return defer.succeed(result in allowed) - self.bldr.config.canStartBuild = _canStartBuild - - self.addSlaves({'test-slave1':1, 'test-slave2':1, 'test-slave3':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - fakedb.BuildRequest(id=12, buildsetid=11, buildername="A", - submitted_at=140000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10], exp_builds=[('test-slave1', [10])]) - - self.assertEqual(slaves_attempted, ['test-slave3', 'test-slave2', 'test-slave1']) - - # we expect brids in order (10-11-12), - # with slave3 skipped, and slave2 unable to pair - self.assertEqual(pairs_tested, [ - ('test-slave2', 10), - ('test-slave1', 10), - ('test-slave2', 11), - ('test-slave2', 12)]) - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def test_limited_by_canStartWithSlavebuilder(self): - self.master.config.mergeRequests = False - - slaves_attempted = [] - def _canStartWithSlavebuilder(slavebuilder): - slaves_attempted.append(slavebuilder.name) - return (slavebuilder.name == 'test-slave3') - self.bldr.canStartWithSlavebuilder = _canStartWithSlavebuilder - self.addSlaves({'test-slave1':0, 'test-slave2':1, 'test-slave3':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10, 11], exp_builds=[('test-slave3', [10]), ('test-slave2', [11])]) - - self.assertEqual(slaves_attempted, ['test-slave3', 'test-slave2']) - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def test_unlimited(self): - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[10, 11], - exp_builds=[('test-slave2', [10]), ('test-slave1', [11])]) - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def test_bldr_maybeStartBuild_fails_always(self): - # the builder fails to start the build; we'll see that the build - # was requested, but the brids will get reclaimed - def maybeStartBuild(slave, builds): - self.startedBuilds.append((slave.name, builds)) - return defer.succeed(False) - self.bldr.maybeStartBuild = maybeStartBuild - - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], # reclaimed so none taken! - exp_builds=[('test-slave2', [10]), ('test-slave1', [11])]) - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def test_bldr_maybeStartBuild_fails_once(self): - # the builder fails to start the build; we'll see that the build - # was requested, but the brids will get reclaimed - def maybeStartBuild(slave, builds, _fail=[False]): - self.startedBuilds.append((slave.name, builds)) - ret = _fail[0] - _fail[0] = True - return defer.succeed(ret) - self.bldr.maybeStartBuild = maybeStartBuild - - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - - yield self.master.db.insertTestData(rows) - - # first time around, only #11 stays claimed - yield self.brd._maybeStartBuildsOnBuilder(self.bldr) - self.master.db.buildrequests.assertMyClaims([11]) # reclaimed so none taken! - self.assertBuildsStarted([('test-slave2', [10]), ('test-slave1', [11])]) - - # second time around the #10 will pass, adding another request and it is claimed - yield self.brd._maybeStartBuildsOnBuilder(self.bldr) - self.master.db.buildrequests.assertMyClaims([10, 11]) - self.assertBuildsStarted([('test-slave2', [10]), ('test-slave1', [11]), ('test-slave2', [10])]) - - - @mock.patch('random.choice', nth_slave(1)) - @defer.inlineCallbacks - def test_limited_by_requests(self): - self.master.config.mergeRequests = False - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[11], exp_builds=[('test-slave2', [11])]) - - - @defer.inlineCallbacks - def test_nextSlave_None(self): - self.bldr.config.nextSlave = lambda _1,_2 : defer.succeed(None) - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_nextSlave_bogus(self): - self.bldr.config.nextSlave = lambda _1,_2 : defer.succeed(mock.Mock()) - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_nextSlave_fails(self): - def nextSlaveRaises(*args): - raise RuntimeError("xx") - self.bldr.config.nextSlave = nextSlaveRaises - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - - @defer.inlineCallbacks - def test_nextBuild_None(self): - self.bldr.config.nextBuild = lambda _1,_2 : defer.succeed(None) - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_nextBuild_bogus(self): - self.bldr.config.nextBuild = lambda _1,_2 : mock.Mock() - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - @defer.inlineCallbacks - def test_nextBuild_fails(self): - def nextBuildRaises(*args): - raise RuntimeError("xx") - self.bldr.config.nextBuild = nextBuildRaises - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) - - - # check concurrency edge cases - - @mock.patch('random.choice', nth_slave(0)) - @defer.inlineCallbacks - def test_claim_race(self): - # fake a race condition on the buildrequests table - old_claimBuildRequests = self.master.db.buildrequests.claimBuildRequests - def claimBuildRequests(brids): - # first, ensure this only happens the first time - self.master.db.buildrequests.claimBuildRequests = old_claimBuildRequests - # claim brid 10 for some other master - assert 10 in brids - self.master.db.buildrequests.fakeClaimBuildRequest(10, 136000, - objectid=9999) # some other objectid - # ..and fail - return defer.fail(buildrequests.AlreadyClaimedError()) - self.master.db.buildrequests.claimBuildRequests = claimBuildRequests - - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=10, buildsetid=11, buildername="A", - submitted_at=130000), # will turn out to be claimed! - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A", - submitted_at=135000), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[11], exp_builds=[('test-slave1', [11])]) - - - # nextSlave - - @defer.inlineCallbacks - def do_test_nextSlave(self, nextSlave, exp_choice=None): - for i in range(4): - self.addSlaves({'sb%d'%i: 1}) - - self.bldr.config.nextSlave = nextSlave - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="A"), - ] - - if exp_choice is None: - exp_claims = [] - exp_builds = [] - else: - exp_claims = [11] - exp_builds = [('sb%d'%exp_choice, [11])] - - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=exp_claims, exp_builds=exp_builds) - - @mock.patch('random.choice', nth_slave(2)) - def test_nextSlave_default(self): - return self.do_test_nextSlave(None, exp_choice=2) - - def test_nextSlave_simple(self): - def nextSlave(bldr, lst): - self.assertIdentical(bldr, self.bldr) - return lst[1] - return self.do_test_nextSlave(nextSlave, exp_choice=1) - - def test_nextSlave_deferred(self): - def nextSlave(bldr, lst): - self.assertIdentical(bldr, self.bldr) - return defer.succeed(lst[1]) - return self.do_test_nextSlave(nextSlave, exp_choice=1) - - def test_nextSlave_exception(self): - def nextSlave(bldr, lst): - raise RuntimeError("") - return self.do_test_nextSlave(nextSlave) - - def test_nextSlave_failure(self): - def nextSlave(bldr, lst): - return defer.fail(failure.Failure(RuntimeError())) - return self.do_test_nextSlave(nextSlave) - - # _nextBuild - - @mock.patch('random.choice', nth_slave(-1)) - @defer.inlineCallbacks - def do_test_nextBuild(self, nextBuild, exp_choice=None): - self.bldr.config.nextBuild = nextBuild - self.master.config.mergeRequests = False - - rows = self.base_rows[:] - for i in range(4): - rows.append(fakedb.Buildset(id=100+i, reason='because', sourcestampsetid=21)) - rows.append(fakedb.BuildRequest(id=10+i, buildsetid=100+i, buildername="A")) - self.addSlaves({'test-slave%d'%i:1}) - - exp_claims = [] - exp_builds = [] - if exp_choice is not None: - slave = 3 - for choice in exp_choice: - exp_claims.append(choice) - exp_builds.append(('test-slave%d'%slave, [choice])) - slave = slave - 1 - - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=sorted(exp_claims), exp_builds=exp_builds) - - def test_nextBuild_default(self): - "default chooses the first in the list, which should be the earliest" - return self.do_test_nextBuild(None, exp_choice=[10, 11, 12, 13]) - - def test_nextBuild_simple(self): - def nextBuild(bldr, lst): - self.assertIdentical(bldr, self.bldr) - return lst[-1] - return self.do_test_nextBuild(nextBuild, exp_choice=[13, 12, 11, 10]) - - def test_nextBuild_deferred(self): - def nextBuild(bldr, lst): - self.assertIdentical(bldr, self.bldr) - return defer.succeed(lst[-1]) - return self.do_test_nextBuild(nextBuild, exp_choice=[13, 12, 11, 10]) - - def test_nextBuild_exception(self): - def nextBuild(bldr, lst): - raise RuntimeError("") - return self.do_test_nextBuild(nextBuild) - - def test_nextBuild_failure(self): - def nextBuild(bldr, lst): - return defer.fail(failure.Failure(RuntimeError())) - return self.do_test_nextBuild(nextBuild) - - - # merge tests - - @defer.inlineCallbacks - def test_merge_ordering(self): - # (patch_random=True) - self.bldr.getMergeRequestsFn = lambda : lambda _, req1, req2: req1.canBeMergedWith(req2) - - self.addSlaves({'test-slave1':1}) - - # based on the build in bug #2249 - rows = [ - fakedb.SourceStampSet(id=1976), - fakedb.SourceStamp(id=1976, sourcestampsetid=1976), - fakedb.Buildset(id=1980, reason='scheduler', sourcestampsetid=1976, - submitted_at=1332024020.67792), - fakedb.BuildRequest(id=42880, buildsetid=1980, - submitted_at=1332024020.67792, buildername="A"), - - fakedb.SourceStampSet(id=1977), - fakedb.SourceStamp(id=1977, sourcestampsetid=1977), - fakedb.Buildset(id=1981, reason='scheduler', sourcestampsetid=1977, - submitted_at=1332025495.19141), - fakedb.BuildRequest(id=42922, buildsetid=1981, - buildername="A", submitted_at=1332025495.19141), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[42880, 42922], - exp_builds=[('test-slave1', [42880, 42922])]) - - @mock.patch('random.choice', nth_slave(0)) - @defer.inlineCallbacks - def test_mergeRequests(self): - # set up all of the data required for a BuildRequest object - rows = [ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234), - fakedb.Buildset(id=30, sourcestampsetid=234, reason='foo', - submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=19, buildsetid=30, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=20, buildsetid=30, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=21, buildsetid=30, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - ] - - self.addSlaves({'test-slave1':1, 'test-slave2': 1}) - - def mergeRequests_fn(builder, breq, other): - # merge evens with evens, odds with odds - self.assertIdentical(builder, self.bldr) - return breq.id % 2 == other.id % 2 - self.bldr.getMergeRequestsFn = lambda : mergeRequests_fn - - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[19, 20, 21], - exp_builds=[ - ('test-slave1', [19, 21]), - ('test-slave2', [20]) - ]) - - - @mock.patch('random.choice', nth_slave(0)) - @defer.inlineCallbacks - def test_mergeRequest_no_other_request(self): - """ Test if builder test for codebases in requests """ - # set up all of the data required for a BuildRequest object - rows = [ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, codebase='A'), - fakedb.Change(changeid=14, codebase='A'), - fakedb.SourceStampChange(sourcestampid=234, changeid=14), - fakedb.Buildset(id=30, sourcestampsetid=234, reason='foo', - submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=19, buildsetid=30, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - ] - - self.addSlaves({'test-slave1':1, 'test-slave2': 1}) - - def mergeRequests_fn(builder, breq, other): - # Allow all requests - self.fail("Should never be called") - return True - self.bldr.getMergeRequestsFn = lambda : mergeRequests_fn - - # check if the request remains the same - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[19], - exp_builds=[ - ('test-slave1', [19]), - ]) - - @mock.patch('random.choice', nth_slave(0)) - @defer.inlineCallbacks - def test_mergeRequests_no_merging(self): - """ Test if builder test for codebases in requests """ - # set up all of the data required for a BuildRequest object - rows = [ - fakedb.SourceStampSet(id=234), - fakedb.SourceStamp(id=234, sourcestampsetid=234, codebase='C'), - fakedb.Buildset(id=30, sourcestampsetid=234, reason='foo', - submitted_at=1300305712, results=-1), - fakedb.SourceStampSet(id=235), - fakedb.SourceStamp(id=235, sourcestampsetid=235, codebase='C'), - fakedb.Buildset(id=31, sourcestampsetid=235, reason='foo', - submitted_at=1300305712, results=-1), - fakedb.SourceStampSet(id=236), - fakedb.SourceStamp(id=236, sourcestampsetid=236, codebase='C'), - fakedb.Buildset(id=32, sourcestampsetid=236, reason='foo', - submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=19, buildsetid=30, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=20, buildsetid=31, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - fakedb.BuildRequest(id=21, buildsetid=32, buildername='A', - priority=13, submitted_at=1300305712, results=-1), - ] - - self.addSlaves({'test-slave1':1, 'test-slave2': 1}) - - def mergeRequests_fn(builder, breq, other): - # Fail all merge attempts - return False - self.bldr.getMergeRequestsFn = lambda : mergeRequests_fn - - # check if all are merged - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[19, 20], - exp_builds=[ - ('test-slave1', [19]), - ('test-slave2', [20]), - ]) - - @defer.inlineCallbacks - def test_mergeRequests_fails(self): - def mergeRequests_fn(*args): - raise RuntimeError("xx") - self.bldr.getMergeRequestsFn = lambda : mergeRequests_fn - - self.addSlaves({'test-slave1':1, 'test-slave2':1}) - rows = self.base_rows + [ - fakedb.BuildRequest(id=11, buildsetid=11, buildername="bldr"), - ] - yield self.do_test_maybeStartBuildsOnBuilder(rows=rows, - exp_claims=[], exp_builds=[]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildstep.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildstep.py deleted file mode 100644 index 62dff108..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_buildstep.py +++ /dev/null @@ -1,272 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import re -import mock -from twisted.trial import unittest -from twisted.internet import defer -from twisted.python import log -from buildbot.process import buildstep -from buildbot.process.buildstep import regex_log_evaluator -from buildbot.status.results import FAILURE, SUCCESS, WARNINGS, EXCEPTION -from buildbot.test.fake import fakebuild, remotecommand -from buildbot.test.util import config, steps, compat -from buildbot.util.eventual import eventually - -class FakeLogFile: - def __init__(self, text): - self.text = text - - def getText(self): - return self.text - -class FakeStepStatus: - pass - -class TestRegexLogEvaluator(unittest.TestCase): - - def makeRemoteCommand(self, rc, stdout, stderr=''): - cmd = remotecommand.FakeRemoteCommand('cmd', {}) - cmd.fakeLogData(self, 'stdio', stdout=stdout, stderr=stderr) - cmd.rc = rc - return cmd - - def test_find_worse_status(self): - cmd = self.makeRemoteCommand(0, 'This is a big step') - step_status = FakeStepStatus() - r = [(re.compile("This is"), WARNINGS)] - new_status = regex_log_evaluator(cmd, step_status, r) - self.assertEqual(new_status, WARNINGS, - "regex_log_evaluator returned %d, expected %d" - % (new_status, WARNINGS)) - - def test_multiple_regexes(self): - cmd = self.makeRemoteCommand(0, "Normal stdout text\nan error") - step_status = FakeStepStatus() - r = [(re.compile("Normal stdout"), SUCCESS), - (re.compile("error"), FAILURE)] - new_status = regex_log_evaluator(cmd, step_status, r) - self.assertEqual(new_status, FAILURE, - "regex_log_evaluator returned %d, expected %d" - % (new_status, FAILURE)) - - def test_exception_not_in_stdout(self): - cmd = self.makeRemoteCommand(0, - "Completely normal output", "exception output") - step_status = FakeStepStatus() - r = [(re.compile("exception"), EXCEPTION)] - new_status = regex_log_evaluator(cmd, step_status, r) - self.assertEqual(new_status, EXCEPTION, - "regex_log_evaluator returned %d, expected %d" - % (new_status, EXCEPTION)) - - def test_pass_a_string(self): - cmd = self.makeRemoteCommand(0, "Output", "Some weird stuff on stderr") - step_status = FakeStepStatus() - r = [("weird stuff", WARNINGS)] - new_status = regex_log_evaluator(cmd, step_status, r) - self.assertEqual(new_status, WARNINGS, - "regex_log_evaluator returned %d, expected %d" - % (new_status, WARNINGS)) - - -class TestBuildStep(steps.BuildStepMixin, config.ConfigErrorsMixin, unittest.TestCase): - - class FakeBuildStep(buildstep.BuildStep): - def start(self): - eventually(self.finished, 0) - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - # support - - def _setupWaterfallTest(self, hideStepIf, expect, expectedResult=SUCCESS): - self.setupStep(TestBuildStep.FakeBuildStep(hideStepIf=hideStepIf)) - self.expectOutcome(result=expectedResult, status_text=["generic"]) - self.expectHidden(expect) - - # tests - - def test_nameIsntString(self): - """ - When BuildStep is passed a name that isn't a string, it reports - a config error. - """ - self.assertRaisesConfigError("BuildStep name must be a string", - lambda: buildstep.BuildStep(name=5)) - - def test_unexpectedKeywordArgument(self): - """ - When BuildStep is passed an unknown keyword argument, it reports - a config error. - """ - self.assertRaisesConfigError("__init__ got unexpected keyword argument(s) ['oogaBooga']", - lambda: buildstep.BuildStep(oogaBooga=5)) - - - def test_getProperty(self): - bs = buildstep.BuildStep() - bs.build = fakebuild.FakeBuild() - props = bs.build.build_status.properties = mock.Mock() - bs.getProperty("xyz", 'b') - props.getProperty.assert_called_with("xyz", 'b') - bs.getProperty("xyz") - props.getProperty.assert_called_with("xyz", None) - - def test_setProperty(self): - bs = buildstep.BuildStep() - bs.build = fakebuild.FakeBuild() - props = bs.build.build_status.properties = mock.Mock() - bs.setProperty("x", "y", "t") - props.setProperty.assert_called_with("x", "y", "t", runtime=True) - bs.setProperty("x", "abc", "test", runtime=True) - props.setProperty.assert_called_with("x", "abc", "test", runtime=True) - - def test_hideStepIf_False(self): - self._setupWaterfallTest(False, False) - return self.runStep() - - def test_hideStepIf_True(self): - self._setupWaterfallTest(True, True) - return self.runStep() - - def test_hideStepIf_Callable_False(self): - called = [False] - def shouldHide(result, step): - called[0] = True - self.assertTrue(step is self.step) - self.assertEquals(result, SUCCESS) - return False - - self._setupWaterfallTest(shouldHide, False) - - d = self.runStep() - d.addCallback(lambda _ : self.assertTrue(called[0])) - return d - - def test_hideStepIf_Callable_True(self): - called = [False] - def shouldHide(result, step): - called[0] = True - self.assertTrue(step is self.step) - self.assertEquals(result, SUCCESS) - return True - - self._setupWaterfallTest(shouldHide, True) - - d = self.runStep() - d.addCallback(lambda _ : self.assertTrue(called[0])) - return d - - def test_hideStepIf_fails(self): - # 0/0 causes DivideByZeroError, which should be flagged as an exception - self._setupWaterfallTest(lambda : 0/0, False, expectedResult=EXCEPTION) - return self.runStep() - - @compat.usesFlushLoggedErrors - def test_hideStepIf_Callable_Exception(self): - called = [False] - def shouldHide(result, step): - called[0] = True - self.assertTrue(step is self.step) - self.assertEquals(result, EXCEPTION) - return True - - def createException(*args, **kwargs): - raise RuntimeError() - - self.setupStep(self.FakeBuildStep(hideStepIf=shouldHide, - doStepIf=createException)) - self.expectOutcome(result=EXCEPTION, - status_text=['generic', 'exception']) - self.expectHidden(True) - - d = self.runStep() - d.addErrback(log.err) - d.addCallback(lambda _ : - self.assertEqual(len(self.flushLoggedErrors(defer.FirstError)), 1)) - d.addCallback(lambda _: - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)) - d.addCallback(lambda _ : self.assertTrue(called[0])) - return d - - -class TestLoggingBuildStep(unittest.TestCase): - - def makeRemoteCommand(self, rc, stdout, stderr=''): - cmd = remotecommand.FakeRemoteCommand('cmd', {}) - cmd.fakeLogData(self, 'stdio', stdout=stdout, stderr=stderr) - cmd.rc = rc - return cmd - - def test_evaluateCommand_success(self): - cmd = self.makeRemoteCommand(0, "Log text", "Log text") - lbs = buildstep.LoggingBuildStep() - status = lbs.evaluateCommand(cmd) - self.assertEqual(status, SUCCESS, "evaluateCommand returned %d, should've returned %d" % (status, SUCCESS)) - - def test_evaluateCommand_failed(self): - cmd = self.makeRemoteCommand(23, "Log text", "") - lbs = buildstep.LoggingBuildStep() - status = lbs.evaluateCommand(cmd) - self.assertEqual(status, FAILURE, "evaluateCommand returned %d, should've returned %d" % (status, FAILURE)) - - def test_evaluateCommand_log_eval_func(self): - cmd = self.makeRemoteCommand(0, "Log text") - def eval(cmd, step_status): - return WARNINGS - lbs = buildstep.LoggingBuildStep(log_eval_func=eval) - status = lbs.evaluateCommand(cmd) - self.assertEqual(status, WARNINGS, "evaluateCommand didn't call log_eval_func or overrode its results") - - -class FailingCustomStep(buildstep.LoggingBuildStep): - - def __init__(self, exception=buildstep.BuildStepFailed, *args, **kwargs): - buildstep.LoggingBuildStep.__init__(self, *args, **kwargs) - self.exception = exception - - @defer.inlineCallbacks - def start(self): - yield defer.succeed(None) - raise self.exception() - - -class TestCustomStepExecution(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_step_raining_buildstepfailed_in_start(self): - self.setupStep(FailingCustomStep()) - self.expectOutcome(result=FAILURE, status_text=["generic"]) - return self.runStep() - - def test_step_raising_exception_in_start(self): - self.setupStep(FailingCustomStep(exception=ValueError)) - self.expectOutcome(result=EXCEPTION, status_text=["generic", "exception"]) - d = self.runStep() - @d.addCallback - def cb(_): - self.assertEqual(len(self.flushLoggedErrors(ValueError)), 1) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_cache.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_cache.py deleted file mode 100644 index 508d14a4..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_cache.py +++ /dev/null @@ -1,53 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from buildbot.process import cache - -class CacheManager(unittest.TestCase): - - def setUp(self): - self.caches = cache.CacheManager() - - def make_config(self, **kwargs): - cfg = mock.Mock() - cfg.caches = kwargs - return cfg - - def test_get_cache_idempotency(self): - foo_cache = self.caches.get_cache("foo", None) - bar_cache = self.caches.get_cache("bar", None) - foo_cache2 = self.caches.get_cache("foo", None) - self.assertIdentical(foo_cache, foo_cache2) - self.assertNotIdentical(foo_cache, bar_cache) - - def test_reconfigService(self): - # load config with one cache loaded and the other not - foo_cache = self.caches.get_cache("foo", None) - d = self.caches.reconfigService( - self.make_config(foo=5, bar=6, bing=11)) - @d.addCallback - def check(_): - bar_cache = self.caches.get_cache("bar", None) - self.assertEqual((foo_cache.max_size, bar_cache.max_size), - (5, 6)) - - def test_get_metrics(self): - self.caches.get_cache("foo", None) - self.assertIn('foo', self.caches.get_metrics()) - metric = self.caches.get_metrics()['foo'] - for k in 'hits', 'refhits', 'misses', 'max_size': - self.assertIn(k, metric) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_debug.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_debug.py deleted file mode 100644 index 1170ca66..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_debug.py +++ /dev/null @@ -1,146 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from twisted.application import service -from buildbot.process import debug -from buildbot import config - -class FakeManhole(service.Service): - pass - -class TestDebugServices(unittest.TestCase): - - def setUp(self): - self.master = mock.Mock(name='master') - self.config = config.MasterConfig() - - @defer.inlineCallbacks - def test_reconfigService_debug(self): - # mock out PBManager - self.master.pbmanager = pbmanager = mock.Mock() - registration = mock.Mock(name='registration') - registration.unregister = mock.Mock(name='unregister', - side_effect=lambda : defer.succeed(None)) - pbmanager.register.return_value = registration - - ds = debug.DebugServices(self.master) - ds.startService() - - # start off with no debug password - self.config.slavePortnum = '9824' - self.config.debugPassword = None - yield ds.reconfigService(self.config) - - self.assertFalse(pbmanager.register.called) - - # set the password, and see it register - self.config.debugPassword = 'seeeekrit' - yield ds.reconfigService(self.config) - - self.assertTrue(pbmanager.register.called) - self.assertEqual(pbmanager.register.call_args[0][:3], - ('9824', 'debug', 'seeeekrit')) - factory = pbmanager.register.call_args[0][3] - self.assertIsInstance(factory(mock.Mock(), mock.Mock()), - debug.DebugPerspective) - - # change the password, and see it re-register - self.config.debugPassword = 'lies' - pbmanager.register.reset_mock() - yield ds.reconfigService(self.config) - - self.assertTrue(registration.unregister.called) - self.assertTrue(pbmanager.register.called) - self.assertEqual(pbmanager.register.call_args[0][:3], - ('9824', 'debug', 'lies')) - - # remove the password, and see it unregister - self.config.debugPassword = None - pbmanager.register.reset_mock() - registration.unregister.reset_mock() - yield ds.reconfigService(self.config) - - self.assertTrue(registration.unregister.called) - self.assertFalse(pbmanager.register.called) - - # re-register to test stopService - self.config.debugPassword = 'confusion' - pbmanager.register.reset_mock() - yield ds.reconfigService(self.config) - - # stop the service, and see that it unregisters - pbmanager.register.reset_mock() - registration.unregister.reset_mock() - yield ds.stopService() - - self.assertTrue(registration.unregister.called) - - @defer.inlineCallbacks - def test_reconfigService_manhole(self): - master = mock.Mock(name='master') - ds = debug.DebugServices(master) - ds.startService() - - # start off with no manhole - yield ds.reconfigService(self.config) - - # set a manhole, fire it up - self.config.manhole = manhole = FakeManhole() - yield ds.reconfigService(self.config) - - self.assertTrue(manhole.running) - self.assertIdentical(manhole.master, master) - - # unset it, see it stop - self.config.manhole = None - yield ds.reconfigService(self.config) - - self.assertFalse(manhole.running) - self.assertIdentical(manhole.master, None) - - # re-start to test stopService - self.config.manhole = manhole - yield ds.reconfigService(self.config) - - # stop the service, and see that it unregisters - yield ds.stopService() - - self.assertFalse(manhole.running) - self.assertIdentical(manhole.master, None) - - -class TestDebugPerspective(unittest.TestCase): - - def setUp(self): - self.master = mock.Mock() - self.persp = debug.DebugPerspective(self.master) - - def test_attached(self): - self.assertIdentical(self.persp.attached(mock.Mock()), self.persp) - - def test_detached(self): - self.persp.detached(mock.Mock()) # just shouldn't crash - - def test_perspective_reload(self): - d = defer.maybeDeferred(lambda : self.persp.perspective_reload()) - def check(_): - self.master.reconfig.assert_called_with() - d.addCallback(check) - return d - - # remaining methods require IControl adapters or other weird stuff.. TODO diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_factory.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_factory.py deleted file mode 100644 index 2724f924..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_factory.py +++ /dev/null @@ -1,81 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest - -from buildbot.process.factory import BuildFactory, s -from buildbot.process.buildstep import BuildStep, _BuildStepFactory - -class TestBuildFactory(unittest.TestCase): - - def test_init(self): - step = BuildStep() - factory = BuildFactory([step]) - self.assertEqual(factory.steps, [_BuildStepFactory(BuildStep)]) - - def test_addStep(self): - step = BuildStep() - factory = BuildFactory() - factory.addStep(step) - self.assertEqual(factory.steps, [_BuildStepFactory(BuildStep)]) - - def test_addStep_deprecated_withArguments(self): - """ - Passing keyword arguments to L{BuildFactory.addStep} is deprecated, - but pass the arguments to the first argument, to construct a step. - """ - factory = BuildFactory() - factory.addStep(BuildStep, name='test') - self.assertEqual(factory.steps, [_BuildStepFactory(BuildStep, name='test')]) - warnings = self.flushWarnings([self.test_addStep_deprecated_withArguments]) - self.assertEqual(len(warnings), 1) - self.assertEqual(warnings[0]['category'], DeprecationWarning) - - def test_addStep_deprecated(self): - """ - Passing keyword arguments to L{BuildFactory.addStep} is deprecated, - but pass the arguments to the first argument, to construct a step. - """ - factory = BuildFactory() - factory.addStep(BuildStep) - self.assertEqual(factory.steps, [_BuildStepFactory(BuildStep)]) - warnings = self.flushWarnings([self.test_addStep_deprecated]) - self.assertEqual(len(warnings), 1) - self.assertEqual(warnings[0]['category'], DeprecationWarning) - - def test_s(self): - """ - L{s} is deprecated, but pass keyword arguments to the first argument, - to construct a step. - """ - stepFactory = s(BuildStep, name='test') - self.assertEqual(stepFactory, _BuildStepFactory(BuildStep, name='test')) - warnings = self.flushWarnings([self.test_s]) - self.assertEqual(len(warnings), 1) - self.assertEqual(warnings[0]['category'], DeprecationWarning) - - def test_addStep_notAStep(self): - factory = BuildFactory() - # This fails because object isn't adaptable to IBuildStepFactory - self.assertRaises(TypeError, factory.addStep, object()) - - def test_addStep_ArgumentsInTheWrongPlace(self): - factory = BuildFactory() - self.assertRaises(TypeError, factory.addStep, BuildStep(), name="name") - - def test_addSteps(self): - factory = BuildFactory() - factory.addSteps([BuildStep(), BuildStep()]) - self.assertEqual(factory.steps, [_BuildStepFactory(BuildStep), _BuildStepFactory(BuildStep)]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_metrics.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_metrics.py deleted file mode 100644 index 49d90011..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_metrics.py +++ /dev/null @@ -1,233 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import gc, sys -from twisted.trial import unittest -from twisted.internet import task -from buildbot.process import metrics -from buildbot.test.fake import fakemaster - -class TestMetricBase(unittest.TestCase): - def setUp(self): - self.clock = task.Clock() - self.observer = metrics.MetricLogObserver() - self.observer.parent = self.master = fakemaster.make_master() - self.master.config.db['db_poll_interval'] = 60 - self.master.config.metrics = dict(log_interval=0, periodic_interval=0) - self.observer._reactor = self.clock - self.observer.startService() - self.observer.reconfigService(self.master.config) - - def tearDown(self): - if self.observer.running: - self.observer.stopService() - -class TestMetricCountEvent(TestMetricBase): - def testIncrement(self): - metrics.MetricCountEvent.log('num_widgets', 1) - report = self.observer.asDict() - self.assertEquals(report['counters']['num_widgets'], 1) - - metrics.MetricCountEvent.log('num_widgets', 1) - report = self.observer.asDict() - self.assertEquals(report['counters']['num_widgets'], 2) - - def testDecrement(self): - metrics.MetricCountEvent.log('num_widgets', 1) - report = self.observer.asDict() - self.assertEquals(report['counters']['num_widgets'], 1) - - metrics.MetricCountEvent.log('num_widgets', -1) - report = self.observer.asDict() - self.assertEquals(report['counters']['num_widgets'], 0) - - def testAbsolute(self): - metrics.MetricCountEvent.log('num_widgets', 10, absolute=True) - report = self.observer.asDict() - self.assertEquals(report['counters']['num_widgets'], 10) - - def testCountMethod(self): - @metrics.countMethod('foo_called') - def foo(): - return "foo!" - - for i in range(10): - foo() - report = self.observer.asDict() - self.assertEquals(report['counters']['foo_called'], 10) - -class TestMetricTimeEvent(TestMetricBase): - def testManualEvent(self): - metrics.MetricTimeEvent.log('foo_time', 0.001) - report = self.observer.asDict() - self.assertEquals(report['timers']['foo_time'], 0.001) - - def testTimer(self): - clock = task.Clock() - t = metrics.Timer('foo_time') - t._reactor = clock - t.start() - - clock.advance(5) - t.stop() - - report = self.observer.asDict() - self.assertEquals(report['timers']['foo_time'], 5) - - def testStartStopDecorators(self): - clock = task.Clock() - t = metrics.Timer('foo_time') - t._reactor = clock - - @t.startTimer - def foo(): - clock.advance(5) - return "foo!" - - @t.stopTimer - def bar(): - clock.advance(5) - return "bar!" - - foo() - bar() - report = self.observer.asDict() - self.assertEquals(report['timers']['foo_time'], 10) - - def testTimeMethod(self): - clock = task.Clock() - @metrics.timeMethod('foo_time', _reactor=clock) - def foo(): - clock.advance(5) - return "foo!" - foo() - report = self.observer.asDict() - self.assertEquals(report['timers']['foo_time'], 5) - - def testAverages(self): - data = range(10) - for i in data: - metrics.MetricTimeEvent.log('foo_time', i) - report = self.observer.asDict() - self.assertEquals(report['timers']['foo_time'], sum(data)/float(len(data))) - -class TestPeriodicChecks(TestMetricBase): - def testPeriodicCheck(self): - # fake out that there's no garbage (since we can't rely on Python - # not having any garbage while running tests) - self.patch(gc, 'garbage', []) - - clock = task.Clock() - metrics.periodicCheck(_reactor=clock) - clock.pump([0.1, 0.1, 0.1]) - - # We should have 0 reactor delay since we're using a fake clock - report = self.observer.asDict() - self.assertEquals(report['timers']['reactorDelay'], 0) - self.assertEquals(report['counters']['gc.garbage'], 0) - self.assertEquals(report['alarms']['gc.garbage'][0], 'OK') - - def testUncollectable(self): - # make some fake garbage - self.patch(gc, 'garbage', [ 1, 2 ]) - - clock = task.Clock() - metrics.periodicCheck(_reactor=clock) - clock.pump([0.1, 0.1, 0.1]) - - # We should have 0 reactor delay since we're using a fake clock - report = self.observer.asDict() - self.assertEquals(report['timers']['reactorDelay'], 0) - self.assertEquals(report['counters']['gc.garbage'], 2) - self.assertEquals(report['alarms']['gc.garbage'][0], 'WARN') - - def testGetRSS(self): - self.assert_(metrics._get_rss() > 0) - if sys.platform != 'linux2': - testGetRSS.skip = "only available on linux2 platforms" - -class TestReconfig(TestMetricBase): - def testReconfig(self): - observer = self.observer - new_config = self.master.config - - # starts up without running tasks - self.assertEquals(observer.log_task, None) - self.assertEquals(observer.periodic_task, None) - - # enable log_interval - new_config.metrics = dict(log_interval=10, periodic_interval=0) - observer.reconfigService(new_config) - self.assert_(observer.log_task) - self.assertEquals(observer.periodic_task, None) - - # disable that and enable periodic_interval - new_config.metrics = dict(periodic_interval=10, log_interval=0) - observer.reconfigService(new_config) - self.assert_(observer.periodic_task) - self.assertEquals(observer.log_task, None) - - # Make the periodic check run - self.clock.pump([0.1]) - - # disable the whole listener - new_config.metrics = None - observer.reconfigService(new_config) - self.assertFalse(observer.enabled) - self.assertEquals(observer.log_task, None) - self.assertEquals(observer.periodic_task, None) - - # disable both - new_config.metrics = dict(periodic_interval=0, log_interval=0) - observer.reconfigService(new_config) - self.assertEquals(observer.log_task, None) - self.assertEquals(observer.periodic_task, None) - - # enable both - new_config.metrics = dict(periodic_interval=10, log_interval=10) - observer.reconfigService(new_config) - self.assert_(observer.log_task) - self.assert_(observer.periodic_task) - - # (service will be stopped by tearDown) - -class _LogObserver: - def __init__(self): - self.events = [] - - def gotEvent(self, event): - self.events.append(event) - -class TestReports(unittest.TestCase): - def testMetricCountReport(self): - handler = metrics.MetricCountHandler(None) - handler.handle({}, metrics.MetricCountEvent('num_foo', 1)) - - self.assertEquals("Counter num_foo: 1", handler.report()) - self.assertEquals({"counters": {"num_foo": 1}}, handler.asDict()) - - def testMetricTimeReport(self): - handler = metrics.MetricTimeHandler(None) - handler.handle({}, metrics.MetricTimeEvent('time_foo', 1)) - - self.assertEquals("Timer time_foo: 1", handler.report()) - self.assertEquals({"timers": {"time_foo": 1}}, handler.asDict()) - - def testMetricAlarmReport(self): - handler = metrics.MetricAlarmHandler(None) - handler.handle({}, metrics.MetricAlarmEvent('alarm_foo', msg='Uh oh', level=metrics.ALARM_WARN)) - - self.assertEquals("WARN alarm_foo: Uh oh", handler.report()) - self.assertEquals({"alarms": {"alarm_foo": ("WARN", "Uh oh")}}, handler.asDict()) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_properties.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_properties.py deleted file mode 100644 index 040bedad..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_properties.py +++ /dev/null @@ -1,1407 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from zope.interface import implements -from twisted.internet import defer -from twisted.trial import unittest -from twisted.python import components -from buildbot.process.properties import Properties, WithProperties -from buildbot.process.properties import Interpolate -from buildbot.process.properties import _Lazy, _SourceStampDict, _Lookup -from buildbot.process.properties import Property, PropertiesMixin, renderer -from buildbot.interfaces import IRenderable, IProperties -from buildbot.test.fake.fakebuild import FakeBuild -from buildbot.test.util.config import ConfigErrorsMixin -from buildbot.test.util.properties import ConstantRenderable -from buildbot.test.util import compat - -class FakeSource: - def __init__(self): - self.branch = None - self.codebase = '' - self.project = '' - self.repository = '' - self.revision = None - - def asDict(self): - ds = {} - ds['branch'] = self.branch - ds['codebase'] = self.codebase - ds['project'] = self.project - ds['repository'] = self.repository - ds['revision'] = self.revision - return ds - -class DeferredRenderable: - implements (IRenderable) - def __init__(self): - self.d = defer.Deferred() - def getRenderingFor(self, build): - return self.d - def callback(self, value): - self.d.callback(value) - -class TestPropertyMap(unittest.TestCase): - """ - Test the behavior of PropertyMap, using the external interace - provided by WithProperties. - """ - - def setUp(self): - self.props = Properties( - prop_str='a-string', - prop_none=None, - prop_list=['a', 'b'], - prop_zero=0, - prop_one=1, - prop_false=False, - prop_true=True, - prop_empty='', - ) - self.build = FakeBuild(self.props) - - def doTestSimpleWithProperties(self, fmtstring, expect, **kwargs): - d = self.build.render(WithProperties(fmtstring, **kwargs)) - d.addCallback(self.failUnlessEqual, "%s" % expect) - return d - - def testSimpleStr(self): - return self.doTestSimpleWithProperties('%(prop_str)s', 'a-string') - - def testSimpleNone(self): - # None is special-cased to become an empty string - return self.doTestSimpleWithProperties('%(prop_none)s', '') - - def testSimpleList(self): - return self.doTestSimpleWithProperties('%(prop_list)s', ['a', 'b']) - - def testSimpleZero(self): - return self.doTestSimpleWithProperties('%(prop_zero)s', 0) - - def testSimpleOne(self): - return self.doTestSimpleWithProperties('%(prop_one)s', 1) - - def testSimpleFalse(self): - return self.doTestSimpleWithProperties('%(prop_false)s', False) - - def testSimpleTrue(self): - return self.doTestSimpleWithProperties('%(prop_true)s', True) - - def testSimpleEmpty(self): - return self.doTestSimpleWithProperties('%(prop_empty)s', '') - - def testSimpleUnset(self): - d = self.build.render(WithProperties('%(prop_nosuch)s')) - return self.assertFailure(d, KeyError) - - - def testColonMinusSet(self): - return self.doTestSimpleWithProperties('%(prop_str:-missing)s', 'a-string') - - def testColonMinusNone(self): - # None is special-cased here, too - return self.doTestSimpleWithProperties('%(prop_none:-missing)s', '') - - def testColonMinusZero(self): - return self.doTestSimpleWithProperties('%(prop_zero:-missing)s', 0) - - def testColonMinusOne(self): - return self.doTestSimpleWithProperties('%(prop_one:-missing)s', 1) - - def testColonMinusFalse(self): - return self.doTestSimpleWithProperties('%(prop_false:-missing)s', False) - - def testColonMinusTrue(self): - return self.doTestSimpleWithProperties('%(prop_true:-missing)s', True) - - def testColonMinusEmpty(self): - return self.doTestSimpleWithProperties('%(prop_empty:-missing)s', '') - - def testColonMinusUnset(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:-missing)s', 'missing') - - - def testColonTildeSet(self): - return self.doTestSimpleWithProperties('%(prop_str:~missing)s', 'a-string') - - def testColonTildeNone(self): - # None is special-cased *differently* for ~: - return self.doTestSimpleWithProperties('%(prop_none:~missing)s', 'missing') - - def testColonTildeZero(self): - return self.doTestSimpleWithProperties('%(prop_zero:~missing)s', 'missing') - - def testColonTildeOne(self): - return self.doTestSimpleWithProperties('%(prop_one:~missing)s', 1) - - def testColonTildeFalse(self): - return self.doTestSimpleWithProperties('%(prop_false:~missing)s', 'missing') - - def testColonTildeTrue(self): - return self.doTestSimpleWithProperties('%(prop_true:~missing)s', True) - - def testColonTildeEmpty(self): - return self.doTestSimpleWithProperties('%(prop_empty:~missing)s', 'missing') - - def testColonTildeUnset(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:~missing)s', 'missing') - - - def testColonPlusSet(self): - return self.doTestSimpleWithProperties('%(prop_str:+present)s', 'present') - - def testColonPlusNone(self): - return self.doTestSimpleWithProperties('%(prop_none:+present)s', 'present') - - def testColonPlusZero(self): - return self.doTestSimpleWithProperties('%(prop_zero:+present)s', 'present') - - def testColonPlusOne(self): - return self.doTestSimpleWithProperties('%(prop_one:+present)s', 'present') - - def testColonPlusFalse(self): - return self.doTestSimpleWithProperties('%(prop_false:+present)s', 'present') - - def testColonPlusTrue(self): - return self.doTestSimpleWithProperties('%(prop_true:+present)s', 'present') - - def testColonPlusEmpty(self): - return self.doTestSimpleWithProperties('%(prop_empty:+present)s', 'present') - - def testColonPlusUnset(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:+present)s', '') - - def testClearTempValues(self): - d = self.doTestSimpleWithProperties('', '', - prop_temp=lambda b: 'present') - d.addCallback(lambda _: - self.doTestSimpleWithProperties('%(prop_temp:+present)s', '')) - return d - - def testTempValue(self): - self.doTestSimpleWithProperties('%(prop_temp)s', 'present', - prop_temp=lambda b: 'present') - - def testTempValueOverrides(self): - return self.doTestSimpleWithProperties('%(prop_one)s', 2, - prop_one=lambda b: 2) - - def testTempValueColonMinusSet(self): - return self.doTestSimpleWithProperties('%(prop_one:-missing)s', 2, - prop_one=lambda b: 2) - - def testTempValueColonMinusUnset(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:-missing)s', 'temp', - prop_nosuch=lambda b: 'temp') - - def testTempValueColonTildeTrueSet(self): - return self.doTestSimpleWithProperties('%(prop_false:~nontrue)s', 'temp', - prop_false=lambda b: 'temp') - - def testTempValueColonTildeTrueUnset(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:~nontrue)s', 'temp', - prop_nosuch=lambda b: 'temp') - - def testTempValueColonTildeFalseFalse(self): - return self.doTestSimpleWithProperties('%(prop_false:~nontrue)s', 'nontrue', - prop_false=lambda b: False) - - def testTempValueColonTildeTrueFalse(self): - return self.doTestSimpleWithProperties('%(prop_true:~nontrue)s', True, - prop_true=lambda b: False) - - def testTempValueColonTildeNoneFalse(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:~nontrue)s', 'nontrue', - prop_nosuch=lambda b: False) - - - def testTempValueColonTildeFalseZero(self): - return self.doTestSimpleWithProperties('%(prop_false:~nontrue)s', 'nontrue', - prop_false=lambda b: 0) - - def testTempValueColonTildeTrueZero(self): - return self.doTestSimpleWithProperties('%(prop_true:~nontrue)s', True, - prop_true=lambda b: 0) - - def testTempValueColonTildeNoneZero(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:~nontrue)s', 'nontrue', - prop_nosuch=lambda b: 0) - - def testTempValueColonTildeFalseBlank(self): - return self.doTestSimpleWithProperties('%(prop_false:~nontrue)s', 'nontrue', - prop_false=lambda b: '') - - def testTempValueColonTildeTrueBlank(self): - return self.doTestSimpleWithProperties('%(prop_true:~nontrue)s', True, - prop_true=lambda b: '') - - def testTempValueColonTildeNoneBlank(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:~nontrue)s', 'nontrue', - prop_nosuch=lambda b: '') - - def testTempValuePlusSetSet(self): - return self.doTestSimpleWithProperties('%(prop_one:+set)s', 'set', - prop_one=lambda b: 2) - - def testTempValuePlusUnsetSet(self): - return self.doTestSimpleWithProperties('%(prop_nosuch:+set)s', 'set', - prop_nosuch=lambda b: 1) - - -class TestInterpolateConfigure(unittest.TestCase, ConfigErrorsMixin): - """ - Test that Interpolate reports erros in the interpolation string - at configure time. - """ - - def test_invalid_args_and_kwargs(self): - self.assertRaisesConfigError("Interpolate takes either positional", - lambda : Interpolate("%s %(foo)s", 1, foo=2)) - - def test_invalid_selector(self): - self.assertRaisesConfigError("invalid Interpolate selector 'garbage'", - lambda: Interpolate("%(garbage:test)s")) - - def test_no_selector(self): - self.assertRaisesConfigError("invalid Interpolate substitution without selector 'garbage'", - lambda: Interpolate("%(garbage)s")) - - def test_invalid_default_type(self): - self.assertRaisesConfigError("invalid Interpolate default type '@'", - lambda: Interpolate("%(prop:some_prop:@wacky)s")) - - def test_nested_invalid_selector(self): - self.assertRaisesConfigError("invalid Interpolate selector 'garbage'", - lambda: Interpolate("%(prop:some_prop:~%(garbage:test)s)s")) - - def test_colon_ternary_missing_delimeter(self): - self.assertRaisesConfigError("invalid Interpolate ternary expression 'one' with delimiter ':'", - lambda: Interpolate("echo '%(prop:P:?:one)s'")) - - def test_colon_ternary_paren_delimiter(self): - self.assertRaisesConfigError("invalid Interpolate ternary expression 'one(:)' with delimiter ':'", - lambda: Interpolate("echo '%(prop:P:?:one(:))s'")) - - def test_colon_ternary_hash_bad_delimeter(self): - self.assertRaisesConfigError("invalid Interpolate ternary expression 'one' with delimiter '|'", - lambda: Interpolate("echo '%(prop:P:#?|one)s'")) - - def test_prop_invalid_character(self): - self.assertRaisesConfigError("Property name must be alphanumeric for prop Interpolation 'a+a'", - lambda: Interpolate("echo '%(prop:a+a)s'")) - - def test_kw_invalid_character(self): - self.assertRaisesConfigError("Keyword must be alphanumeric for kw Interpolation 'a+a'", - lambda: Interpolate("echo '%(kw:a+a)s'")) - - def test_src_codebase_invalid_character(self): - self.assertRaisesConfigError("Codebase must be alphanumeric for src Interpolation 'a+a:a'", - lambda: Interpolate("echo '%(src:a+a:a)s'")) - - def test_src_attr_invalid_character(self): - self.assertRaisesConfigError("Attribute must be alphanumeric for src Interpolation 'a:a+a'", - lambda: Interpolate("echo '%(src:a:a+a)s'")) - - def test_src_missing_attr(self): - self.assertRaisesConfigError("Must specify both codebase and attr", - lambda: Interpolate("echo '%(src:a)s'")) - - -class TestInterpolatePositional(unittest.TestCase): - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - def test_string(self): - command = Interpolate("test %s", "one fish") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "test one fish") - - def test_twoString(self): - command = Interpolate("test %s, %s", "one fish", "two fish") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "test one fish, two fish") - - def test_deferred(self): - renderable = DeferredRenderable() - command = Interpolate("echo '%s'", renderable) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'red fish'") - renderable.callback("red fish") - return d - - def test_renderable(self): - self.props.setProperty("buildername", "blue fish", "test") - command = Interpolate("echo '%s'", Property("buildername")) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'blue fish'") - return d - - - -class TestInterpolateProperties(unittest.TestCase): - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - def test_properties(self): - self.props.setProperty("buildername", "winbld", "test") - command = Interpolate("echo buildby-%(prop:buildername)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-winbld") - return d - - def test_properties_newline(self): - self.props.setProperty("buildername", "winbld", "test") - command = Interpolate("aa\n%(prop:buildername)s\nbb") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "aa\nwinbld\nbb") - return d - - def test_property_not_set(self): - command = Interpolate("echo buildby-%(prop:buildername)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-") - return d - - def test_property_colon_minus(self): - command = Interpolate("echo buildby-%(prop:buildername:-blddef)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-blddef") - return d - - def test_property_colon_tilde_true(self): - self.props.setProperty("buildername", "winbld", "test") - command = Interpolate("echo buildby-%(prop:buildername:~blddef)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-winbld") - return d - - def test_property_colon_tilde_false(self): - self.props.setProperty("buildername", "", "test") - command = Interpolate("echo buildby-%(prop:buildername:~blddef)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-blddef") - return d - - def test_property_colon_plus(self): - self.props.setProperty("project", "proj1", "test") - command = Interpolate("echo %(prop:project:+projectdefined)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo projectdefined") - return d - - def test_nested_property(self): - self.props.setProperty("project", "so long!", "test") - command = Interpolate("echo '%(prop:missing:~%(prop:project)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'so long!'") - return d - - def test_property_substitute_recursively(self): - self.props.setProperty("project", "proj1", "test") - command = Interpolate("echo '%(prop:no_such:-%(prop:project)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'proj1'") - return d - - def test_property_colon_ternary_present(self): - self.props.setProperty("project", "proj1", "test") - command = Interpolate("echo %(prop:project:?:defined:missing)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo defined") - return d - - def test_property_colon_ternary_missing(self): - command = Interpolate("echo %(prop:project:?|defined|missing)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo missing") - return d - - def test_property_colon_ternary_hash_true(self): - self.props.setProperty("project", "winbld", "test") - command = Interpolate("echo buildby-%(prop:project:#?:T:F)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-T") - return d - - def test_property_colon_ternary_hash_false(self): - self.props.setProperty("project", "", "test") - command = Interpolate("echo buildby-%(prop:project:#?|T|F)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo buildby-F") - return d - - def test_property_colon_ternary_substitute_recursively_true(self): - self.props.setProperty("P", "present", "test") - self.props.setProperty("one", "proj1", "test") - self.props.setProperty("two", "proj2", "test") - command = Interpolate("echo '%(prop:P:?|%(prop:one)s|%(prop:two)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'proj1'") - return d - - def test_property_colon_ternary_substitute_recursively_false(self): - self.props.setProperty("one", "proj1", "test") - self.props.setProperty("two", "proj2", "test") - command = Interpolate("echo '%(prop:P:?|%(prop:one)s|%(prop:two)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'proj2'") - return d - - def test_property_colon_ternary_substitute_recursively_delimited_true(self): - self.props.setProperty("P", "present", "test") - self.props.setProperty("one", "proj1", "test") - self.props.setProperty("two", "proj2", "test") - command = Interpolate("echo '%(prop:P:?|%(prop:one:?|true|false)s|%(prop:two:?|false|true)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'true'") - return d - - def test_property_colon_ternary_substitute_recursively_delimited_false(self): - self.props.setProperty("one", "proj1", "test") - self.props.setProperty("two", "proj2", "test") - command = Interpolate("echo '%(prop:P:?|%(prop:one:?|true|false)s|%(prop:two:?|false|true)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'false'") - return d - - -class TestInterpolateSrc(unittest.TestCase): - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - sa = FakeSource() - sb = FakeSource() - sc = FakeSource() - - sa.repository = 'cvs://A..' - sa.codebase = 'cbA' - sa.project = "Project" - self.build.sources['cbA'] = sa - - sb.repository = 'cvs://B..' - sb.codebase = 'cbB' - sb.project = "Project" - self.build.sources['cbB'] = sb - - sc.repository = 'cvs://C..' - sc.codebase = 'cbC' - sc.project = None - self.build.sources['cbC'] = sc - - def test_src(self): - command = Interpolate("echo %(src:cbB:repository)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B..") - return d - - def test_src_src(self): - command = Interpolate("echo %(src:cbB:repository)s %(src:cbB:project)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B.. Project") - return d - - def test_src_attr_empty(self): - command = Interpolate("echo %(src:cbC:project)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ") - return d - - def test_src_attr_codebase_notfound(self): - command = Interpolate("echo %(src:unknown_codebase:project)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ") - return d - - def test_src_colon_plus_false(self): - command = Interpolate("echo '%(src:cbD:project:+defaultrepo)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ''") - return d - - def test_src_colon_plus_true(self): - command = Interpolate("echo '%(src:cbB:project:+defaultrepo)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'defaultrepo'") - return d - - def test_src_colon_minus(self): - command = Interpolate("echo %(src:cbB:nonattr:-defaultrepo)s") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo defaultrepo") - return d - - def test_src_colon_minus_false(self): - command = Interpolate("echo '%(src:cbC:project:-noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ''") - return d - - def test_src_colon_minus_true(self): - command = Interpolate("echo '%(src:cbB:project:-noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'Project'") - return d - - def test_src_colon_minus_codebase_notfound(self): - command = Interpolate("echo '%(src:unknown_codebase:project:-noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'noproject'") - return d - - def test_src_colon_tilde_true(self): - command = Interpolate("echo '%(src:cbB:project:~noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'Project'") - return d - - def test_src_colon_tilde_false(self): - command = Interpolate("echo '%(src:cbC:project:~noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'noproject'") - return d - - def test_src_colon_tilde_false_src_as_replacement(self): - command = Interpolate("echo '%(src:cbC:project:~%(src:cbA:project)s)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'Project'") - return d - - def test_src_colon_tilde_codebase_notfound(self): - command = Interpolate("echo '%(src:unknown_codebase:project:~noproject)s'") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'noproject'") - return d - - -class TestInterpolateKwargs(unittest.TestCase): - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - sa = FakeSource() - - sa.repository = 'cvs://A..' - sa.codebase = 'cbA' - sa.project = None - sa.branch = "default" - self.build.sources['cbA'] = sa - - def test_kwarg(self): - command = Interpolate("echo %(kw:repository)s", repository = "cvs://A..") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://A..") - return d - - def test_kwarg_kwarg(self): - command = Interpolate("echo %(kw:repository)s %(kw:branch)s", - repository = "cvs://A..", branch = "default") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://A.. default") - return d - - def test_kwarg_not_mapped(self): - command = Interpolate("echo %(kw:repository)s", project = "projectA") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ") - return d - - def test_kwarg_colon_minus_not_available(self): - command = Interpolate("echo %(kw:repository)s", project = "projectA") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ") - return d - - def test_kwarg_colon_minus_not_available_default(self): - command = Interpolate("echo %(kw:repository:-cvs://A..)s", project = "projectA") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://A..") - return d - - def test_kwarg_colon_minus_available(self): - command = Interpolate("echo %(kw:repository:-cvs://A..)s", repository = "cvs://B..") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B..") - return d - - def test_kwarg_colon_tilde_true(self): - command = Interpolate("echo %(kw:repository:~cvs://B..)s", repository = "cvs://A..") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://A..") - return d - - def test_kwarg_colon_tilde_false(self): - command = Interpolate("echo %(kw:repository:~cvs://B..)s", repository = "") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B..") - return d - - def test_kwarg_colon_tilde_none(self): - command = Interpolate("echo %(kw:repository:~cvs://B..)s", repository = None) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B..") - return d - - def test_kwarg_colon_plus_false(self): - command = Interpolate("echo %(kw:repository:+cvs://B..)s", project = "project") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo ") - return d - - def test_kwarg_colon_plus_true(self): - command = Interpolate("echo %(kw:repository:+cvs://B..)s", repository = None) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo cvs://B..") - return d - - def test_kwargs_colon_minus_false_src_as_replacement(self): - command = Interpolate("echo '%(kw:text:-%(src:cbA:branch)s)s'", notext='ddd') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'default'") - return d - - def test_kwargs_renderable(self): - command = Interpolate("echo '%(kw:test)s'", test = ConstantRenderable('testing')) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'testing'") - return d - - def test_kwargs_deferred(self): - renderable = DeferredRenderable() - command = Interpolate("echo '%(kw:test)s'", test = renderable) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'testing'") - renderable.callback('testing') - return d - - def test_kwarg_deferred(self): - renderable = DeferredRenderable() - command = Interpolate("echo '%(kw:project)s'", project=renderable) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'testing'") - renderable.callback('testing') - return d - - def test_nested_kwarg_deferred(self): - renderable = DeferredRenderable() - command = Interpolate("echo '%(kw:missing:~%(kw:fishy)s)s'", missing=renderable, fishy="so long!") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "echo 'so long!'") - renderable.callback(False) - return d - -class TestWithProperties(unittest.TestCase): - - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - def testInvalidParams(self): - self.assertRaises(ValueError, lambda : - WithProperties("%s %(foo)s", 1, foo=2)) - - def testBasic(self): - # test basic substitution with WithProperties - self.props.setProperty("revision", "47", "test") - command = WithProperties("build-%s.tar.gz", "revision") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "build-47.tar.gz") - return d - - def testDict(self): - # test dict-style substitution with WithProperties - self.props.setProperty("other", "foo", "test") - command = WithProperties("build-%(other)s.tar.gz") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "build-foo.tar.gz") - return d - - def testDictColonMinus(self): - # test dict-style substitution with WithProperties - self.props.setProperty("prop1", "foo", "test") - command = WithProperties("build-%(prop1:-empty)s-%(prop2:-empty)s.tar.gz") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "build-foo-empty.tar.gz") - return d - - def testDictColonPlus(self): - # test dict-style substitution with WithProperties - self.props.setProperty("prop1", "foo", "test") - command = WithProperties("build-%(prop1:+exists)s-%(prop2:+exists)s.tar.gz") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "build-exists-.tar.gz") - return d - - def testEmpty(self): - # None should render as '' - self.props.setProperty("empty", None, "test") - command = WithProperties("build-%(empty)s.tar.gz") - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - "build-.tar.gz") - return d - - def testRecursiveList(self): - self.props.setProperty("x", 10, "test") - self.props.setProperty("y", 20, "test") - command = [ WithProperties("%(x)s %(y)s"), "and", - WithProperties("%(y)s %(x)s") ] - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - ["10 20", "and", "20 10"]) - return d - - def testRecursiveTuple(self): - self.props.setProperty("x", 10, "test") - self.props.setProperty("y", 20, "test") - command = ( WithProperties("%(x)s %(y)s"), "and", - WithProperties("%(y)s %(x)s") ) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - ("10 20", "and", "20 10")) - return d - - def testRecursiveDict(self): - self.props.setProperty("x", 10, "test") - self.props.setProperty("y", 20, "test") - command = { WithProperties("%(x)s %(y)s") : - WithProperties("%(y)s %(x)s") } - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, - {"10 20" : "20 10"}) - return d - - def testLambdaSubst(self): - command = WithProperties('%(foo)s', foo=lambda _: 'bar') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, 'bar') - return d - - def testLambdaHasattr(self): - command = WithProperties('%(foo)s', - foo=lambda b : b.hasProperty('x') and 'x' or 'y') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, 'y') - return d - - def testLambdaOverride(self): - self.props.setProperty('x', 10, 'test') - command = WithProperties('%(x)s', x=lambda _: 20) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, '20') - return d - - def testLambdaCallable(self): - self.assertRaises(ValueError, lambda: WithProperties('%(foo)s', foo='bar')) - - def testLambdaUseExisting(self): - self.props.setProperty('x', 10, 'test') - self.props.setProperty('y', 20, 'test') - command = WithProperties('%(z)s', z=lambda props: props.getProperty('x') + props.getProperty('y')) - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, '30') - return d - - def testColon(self): - self.props.setProperty('some:property', 10, 'test') - command = WithProperties('%(some:property:-with-default)s') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, '10') - return d - - def testColon_default(self): - command = WithProperties('%(some:property:-with-default)s') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, 'with-default') - return d - - def testColon_colon(self): - command = WithProperties('%(some:property:-with:default)s') - d = self.build.render(command) - d.addCallback(self.failUnlessEqual, 'with:default') - return d - -class TestProperties(unittest.TestCase): - def setUp(self): - self.props = Properties() - - def testDictBehavior(self): - # note that dictionary-like behavior is deprecated and not exposed to - # users! - self.props.setProperty("do-tests", 1, "scheduler") - self.props.setProperty("do-install", 2, "scheduler") - - self.assert_(self.props.has_key('do-tests')) - self.failUnlessEqual(self.props['do-tests'], 1) - self.failUnlessEqual(self.props['do-install'], 2) - self.assertRaises(KeyError, lambda : self.props['do-nothing']) - self.failUnlessEqual(self.props.getProperty('do-install'), 2) - self.assertIn('do-tests', self.props) - self.assertNotIn('missing-do-tests', self.props) - - def testAsList(self): - self.props.setProperty("happiness", 7, "builder") - self.props.setProperty("flames", True, "tester") - - self.assertEqual(sorted(self.props.asList()), - [ ('flames', True, 'tester'), ('happiness', 7, 'builder') ]) - - def testAsDict(self): - self.props.setProperty("msi_filename", "product.msi", 'packager') - self.props.setProperty("dmg_filename", "product.dmg", 'packager') - - self.assertEqual(self.props.asDict(), - dict(msi_filename=('product.msi', 'packager'), dmg_filename=('product.dmg', 'packager'))) - - def testUpdate(self): - self.props.setProperty("x", 24, "old") - newprops = { 'a' : 1, 'b' : 2 } - self.props.update(newprops, "new") - - self.failUnlessEqual(self.props.getProperty('x'), 24) - self.failUnlessEqual(self.props.getPropertySource('x'), 'old') - self.failUnlessEqual(self.props.getProperty('a'), 1) - self.failUnlessEqual(self.props.getPropertySource('a'), 'new') - - def testUpdateRuntime(self): - self.props.setProperty("x", 24, "old") - newprops = { 'a' : 1, 'b' : 2 } - self.props.update(newprops, "new", runtime=True) - - self.failUnlessEqual(self.props.getProperty('x'), 24) - self.failUnlessEqual(self.props.getPropertySource('x'), 'old') - self.failUnlessEqual(self.props.getProperty('a'), 1) - self.failUnlessEqual(self.props.getPropertySource('a'), 'new') - self.assertEqual(self.props.runtime, set(['a', 'b'])) - - def testUpdateFromProperties(self): - self.props.setProperty("a", 94, "old") - self.props.setProperty("x", 24, "old") - newprops = Properties() - newprops.setProperty('a', 1, "new") - newprops.setProperty('b', 2, "new") - self.props.updateFromProperties(newprops) - - self.failUnlessEqual(self.props.getProperty('x'), 24) - self.failUnlessEqual(self.props.getPropertySource('x'), 'old') - self.failUnlessEqual(self.props.getProperty('a'), 1) - self.failUnlessEqual(self.props.getPropertySource('a'), 'new') - - def testUpdateFromPropertiesNoRuntime(self): - self.props.setProperty("a", 94, "old") - self.props.setProperty("b", 84, "old") - self.props.setProperty("x", 24, "old") - newprops = Properties() - newprops.setProperty('a', 1, "new", runtime=True) - newprops.setProperty('b', 2, "new", runtime=False) - newprops.setProperty('c', 3, "new", runtime=True) - newprops.setProperty('d', 3, "new", runtime=False) - self.props.updateFromPropertiesNoRuntime(newprops) - - self.failUnlessEqual(self.props.getProperty('a'), 94) - self.failUnlessEqual(self.props.getPropertySource('a'), 'old') - self.failUnlessEqual(self.props.getProperty('b'), 2) - self.failUnlessEqual(self.props.getPropertySource('b'), 'new') - self.failUnlessEqual(self.props.getProperty('c'), None) # not updated - self.failUnlessEqual(self.props.getProperty('d'), 3) - self.failUnlessEqual(self.props.getPropertySource('d'), 'new') - self.failUnlessEqual(self.props.getProperty('x'), 24) - self.failUnlessEqual(self.props.getPropertySource('x'), 'old') - - @compat.usesFlushWarnings - def test_setProperty_notJsonable(self): - self.props.setProperty("project", ConstantRenderable('testing'), "test") - self.props.setProperty("project", object, "test") - self.assertEqual(len(self.flushWarnings([self.test_setProperty_notJsonable])), 2) - - # IProperties methods - - def test_getProperty(self): - self.props.properties['p1'] = (['p', 1], 'test') - self.assertEqual(self.props.getProperty('p1'), ['p', 1]) - - def test_getProperty_default_None(self): - self.assertEqual(self.props.getProperty('p1'), None) - - def test_getProperty_default(self): - self.assertEqual(self.props.getProperty('p1', 2), 2) - - def test_hasProperty_false(self): - self.assertFalse(self.props.hasProperty('x')) - - def test_hasProperty_true(self): - self.props.properties['x'] = (False, 'test') - self.assertTrue(self.props.hasProperty('x')) - - def test_has_key_false(self): - self.assertFalse(self.props.has_key('x')) - - def test_setProperty(self): - self.props.setProperty('x', 'y', 'test') - self.assertEqual(self.props.properties['x'], ('y', 'test')) - self.assertNotIn('x', self.props.runtime) - - def test_setProperty_runtime(self): - self.props.setProperty('x', 'y', 'test', runtime=True) - self.assertEqual(self.props.properties['x'], ('y', 'test')) - self.assertIn('x', self.props.runtime) - - def test_setProperty_no_source(self): - self.assertRaises(TypeError, lambda : - self.props.setProperty('x', 'y')) - - def test_getProperties(self): - self.assertIdentical(self.props.getProperties(), self.props) - - def test_getBuild(self): - self.assertIdentical(self.props.getBuild(), self.props.build) - - def test_render(self): - class Renderable(object): - implements(IRenderable) - def getRenderingFor(self, props): - return props.getProperty('x') + 'z' - self.props.setProperty('x', 'y', 'test') - d = self.props.render(Renderable()) - d.addCallback(self.assertEqual, 'yz') - return d - - -class MyPropertiesThing(PropertiesMixin): - set_runtime_properties = True - -def adaptMyProperties(mp): - return mp.properties - -components.registerAdapter(adaptMyProperties, MyPropertiesThing, IProperties) - - -class TestPropertiesMixin(unittest.TestCase): - - def setUp(self): - self.mp = MyPropertiesThing() - self.mp.properties = mock.Mock() - - def test_getProperty(self): - self.mp.getProperty('abc') - self.mp.properties.getProperty.assert_called_with('abc', None) - - def xtest_getProperty_default(self): - self.mp.getProperty('abc', 'def') - self.mp.properties.getProperty.assert_called_with('abc', 'def') - - def test_hasProperty(self): - self.mp.properties.hasProperty.return_value = True - self.assertTrue(self.mp.hasProperty('abc')) - self.mp.properties.hasProperty.assert_called_with('abc') - - def test_has_key(self): - self.mp.properties.hasProperty.return_value = True - self.assertTrue(self.mp.has_key('abc')) - self.mp.properties.hasProperty.assert_called_with('abc') - - def test_setProperty(self): - self.mp.setProperty('abc', 'def', 'src') - self.mp.properties.setProperty.assert_called_with('abc', 'def', 'src', - runtime=True) - - def test_setProperty_no_source(self): - # this compatibility is maintained for old code - self.mp.setProperty('abc', 'def') - self.mp.properties.setProperty.assert_called_with('abc', 'def', - 'Unknown', runtime=True) - - def test_render(self): - self.mp.render([1,2]) - self.mp.properties.render.assert_called_with([1,2]) - -class TestProperty(unittest.TestCase): - - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - def testIntProperty(self): - self.props.setProperty("do-tests", 1, "scheduler") - value = Property("do-tests") - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - 1) - return d - - def testStringProperty(self): - self.props.setProperty("do-tests", "string", "scheduler") - value = Property("do-tests") - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - "string") - return d - - def testMissingProperty(self): - value = Property("do-tests") - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - None) - return d - - def testDefaultValue(self): - value = Property("do-tests", default="Hello!") - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - "Hello!") - return d - - def testDefaultValueNested(self): - self.props.setProperty("xxx", 'yyy', "scheduler") - value = Property("do-tests", - default=WithProperties("a-%(xxx)s-b")) - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - "a-yyy-b") - return d - - def testIgnoreDefaultValue(self): - self.props.setProperty("do-tests", "string", "scheduler") - value = Property("do-tests", default="Hello!") - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - "string") - return d - - def testIgnoreFalseValue(self): - self.props.setProperty("do-tests-string", "", "scheduler") - self.props.setProperty("do-tests-int", 0, "scheduler") - self.props.setProperty("do-tests-list", [], "scheduler") - self.props.setProperty("do-tests-None", None, "scheduler") - - value = [ Property("do-tests-string", default="Hello!"), - Property("do-tests-int", default="Hello!"), - Property("do-tests-list", default="Hello!"), - Property("do-tests-None", default="Hello!") ] - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - ["Hello!"] * 4) - return d - - def testDefaultWhenFalse(self): - self.props.setProperty("do-tests-string", "", "scheduler") - self.props.setProperty("do-tests-int", 0, "scheduler") - self.props.setProperty("do-tests-list", [], "scheduler") - self.props.setProperty("do-tests-None", None, "scheduler") - - value = [ Property("do-tests-string", default="Hello!", defaultWhenFalse=False), - Property("do-tests-int", default="Hello!", defaultWhenFalse=False), - Property("do-tests-list", default="Hello!", defaultWhenFalse=False), - Property("do-tests-None", default="Hello!", defaultWhenFalse=False) ] - - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - ["", 0, [], None]) - return d - - def testDeferredDefault(self): - default = DeferredRenderable() - value = Property("no-such-property", default) - d = self.build.render(value) - d.addCallback(self.failUnlessEqual, - "default-value") - default.callback("default-value") - return d - - -class TestRenderalbeAdapters(unittest.TestCase): - """ - Tests for list, tuple and dict renderers. - """ - - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - - def test_list_deferred(self): - r1 = DeferredRenderable() - r2 = DeferredRenderable() - d = self.build.render([r1, r2]) - d.addCallback(self.failUnlessEqual, - ["lispy", "lists"]) - r2.callback("lists") - r1.callback("lispy") - return d - - - def test_tuple_deferred(self): - r1 = DeferredRenderable() - r2 = DeferredRenderable() - d = self.build.render((r1, r2)) - d.addCallback(self.failUnlessEqual, - ("totally", "tupled")) - r2.callback("tupled") - r1.callback("totally") - return d - - - def test_dict(self): - r1 = DeferredRenderable() - r2 = DeferredRenderable() - k1 = DeferredRenderable() - k2 = DeferredRenderable() - d = self.build.render({k1: r1, k2: r2}) - d.addCallback(self.failUnlessEqual, - {"lock": "load", "dict": "lookup"}) - k1.callback("lock") - r1.callback("load") - k2.callback("dict") - r2.callback("lookup") - return d - -class Renderer(unittest.TestCase): - - def setUp(self): - self.props = Properties() - self.build = FakeBuild(self.props) - - - def test_renderer(self): - self.props.setProperty("x", "X", "test") - d = self.build.render( - renderer(lambda p : 'x%sx' % p.getProperty('x'))) - d.addCallback(self.failUnlessEqual, 'xXx') - return d - - def test_renderer_called(self): - # it's tempting to try to call the decorated function. Don't do that. - # It's not a function anymore. - d = defer.maybeDeferred(lambda : - self.build.render(renderer(lambda p : 'x')('y'))) - self.failUnlessFailure(d, TypeError) - return d - - def test_renderer_decorator(self): - self.props.setProperty("x", "X", "test") - @renderer - def rend(p): - return 'x%sx' % p.getProperty('x') - d = self.build.render(rend) - d.addCallback(self.failUnlessEqual, 'xXx') - return d - - def test_renderer_deferred(self): - self.props.setProperty("x", "X", "test") - d = self.build.render( - renderer(lambda p : defer.succeed('y%sy' % p.getProperty('x')))) - d.addCallback(self.failUnlessEqual, 'yXy') - return d - - def test_renderer_fails(self): - d = self.build.render( - renderer(lambda p : defer.fail(RuntimeError("oops")))) - self.failUnlessFailure(d, RuntimeError) - return d - -class Compare(unittest.TestCase): - - def test_WithProperties_lambda(self): - self.failIfEqual(WithProperties("%(key)s", key=lambda p:'val'), WithProperties("%(key)s", key=lambda p:'val')) - def rend(p): - return "val" - self.failUnlessEqual( - WithProperties("%(key)s", key=rend), - WithProperties("%(key)s", key=rend)) - self.failIfEqual( - WithProperties("%(key)s", key=rend), - WithProperties("%(key)s", otherkey=rend)) - - def test_WithProperties_positional(self): - self.failIfEqual( - WithProperties("%s", 'key'), - WithProperties("%s", 'otherkey')) - self.failUnlessEqual( - WithProperties("%s", 'key'), - WithProperties("%s", 'key')) - self.failIfEqual( - WithProperties("%s", 'key'), - WithProperties("k%s", 'key')) - - def test_Interpolate_constant(self): - self.failIfEqual( - Interpolate('some text here'), - Interpolate('and other text there')) - self.failUnlessEqual( - Interpolate('some text here'), - Interpolate('some text here')) - - def test_Interpolate_positional(self): - self.failIfEqual( - Interpolate('%s %s', "test", "text"), - Interpolate('%s %s', "other", "text")) - self.failUnlessEqual( - Interpolate('%s %s', "test", "text"), - Interpolate('%s %s', "test", "text")) - - def test_Interpolate_kwarg(self): - self.failIfEqual( - Interpolate("%(kw:test)s", test=object(), other=2), - Interpolate("%(kw:test)s", test=object(), other=2)) - self.failUnlessEqual( - Interpolate('testing: %(kw:test)s', test="test", other=3), - Interpolate('testing: %(kw:test)s', test="test", other=3)) - - def test_renderer(self): - self.failIfEqual( - renderer(lambda p:'val'), - renderer(lambda p:'val')) - def rend(p): - return "val" - self.failUnlessEqual( - renderer(rend), - renderer(rend)) - - def test_Lookup_simple(self): - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'other'), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test'), - _Lookup({'test': 5, 'other': 6}, 'test')) - - def test_Lookup_default(self): - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', default='default'), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test', default='default'), - _Lookup({'test': 5, 'other': 6}, 'test', default='default')) - - def test_Lookup_defaultWhenFalse(self): - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=False), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=False), - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=True)) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=True), - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=True)) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test'), - _Lookup({'test': 5, 'other': 6}, 'test', defaultWhenFalse=True)) - - def test_Lookup_hasKey(self): - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', hasKey=None), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', hasKey='has-key'), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', hasKey='has-key'), - _Lookup({'test': 5, 'other': 6}, 'test', hasKey='other-key')) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test', hasKey='has-key'), - _Lookup({'test': 5, 'other': 6}, 'test', hasKey='has-key')) - - def test_Lookup_elideNoneAs(self): - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs=None), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs=''), - _Lookup({'test': 5, 'other': 6}, 'test')) - self.failIfEqual( - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs='got None'), - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs='')) - self.failUnlessEqual( - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs='got None'), - _Lookup({'test': 5, 'other': 6}, 'test', elideNoneAs='got None')) - - def test_Lazy(self): - self.failIfEqual( - _Lazy(5), - _Lazy(6)) - self.failUnlessEqual( - _Lazy(5), - _Lazy(5)) - - def test_SourceStampDict(self): - self.failIfEqual( - _SourceStampDict('binary'), - _SourceStampDict('library')) - self.failUnlessEqual( - _SourceStampDict('binary'), - _SourceStampDict('binary')) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manager.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manager.py deleted file mode 100644 index 031f9677..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manager.py +++ /dev/null @@ -1,51 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.process.users import manager, manual -from buildbot import config - -class FakeUserManager(manual.UsersBase): - pass - -class TestUserManager(unittest.TestCase): - def setUp(self): - self.master = mock.Mock() - self.umm = manager.UserManagerManager(self.master) - self.umm.startService() - - self.config = config.MasterConfig() - - def tearDown(self): - self.umm.stopService() - - @defer.inlineCallbacks - def test_reconfigService(self): - # add a user manager - um1 = FakeUserManager() - self.config.user_managers = [ um1 ] - - yield self.umm.reconfigService(self.config) - - self.assertTrue(um1.running) - self.assertIdentical(um1.master, self.master) - - # and back to nothing - self.config.user_managers = [ ] - yield self.umm.reconfigService(self.config) - - self.assertIdentical(um1.master, None) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manual.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manual.py deleted file mode 100644 index 9b330051..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_manual.py +++ /dev/null @@ -1,304 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -# this class is known to contain cruft and will be looked at later, so -# no current implementation utilizes it aside from scripts.runner. - -import mock -from twisted.trial import unittest -from twisted.internet import defer - -from buildbot.test.fake import fakedb -from buildbot.process.users import manual - -class ManualUsersMixin(object): - """ - This class fakes out the master/db components to test the manual - user managers located in process.users.manual. - """ - - class FakeMaster(object): - - def __init__(self): - self.db = fakedb.FakeDBConnector(self) - self.slavePortnum = "tcp:9989" - self.caches = mock.Mock(name="caches") - self.caches.get_cache = self.get_cache - - def get_cache(self, cache_name, miss_fn): - c = mock.Mock(name=cache_name) - c.get = miss_fn - return c - - def setUpManualUsers(self): - self.master = self.FakeMaster() - -class TestUsersBase(unittest.TestCase): - """ - Not really sure what there is to test, aside from _setUpManualUsers getting - self.master set. - """ - pass - -class TestCommandlineUserManagerPerspective(unittest.TestCase, ManualUsersMixin): - - def setUp(self): - self.setUpManualUsers() - - def call_perspective_commandline(self, *args): - persp = manual.CommandlineUserManagerPerspective(self.master) - return persp.perspective_commandline(*args) - - def test_perspective_commandline_add(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', 'git': 'x'}]) - def check_get(_): - d = self.master.db.users.getUser(1) - def real_check(usdict): - self.assertEqual(usdict, dict(uid=1, - identifier='x', - bb_username=None, - bb_password=None, - git='x')) - d.addCallback(real_check) - return d - d.addCallback(check_get) - return d - - def test_perspective_commandline_update(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', 'svn':'x'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline( - 'update', None, None, None, - [{'identifier':'x', 'svn':'y'}])) - def check(_): - d = self.master.db.users.getUser(1) - def real_check(usdict): - self.assertEqual(usdict, dict(uid=1, - identifier='x', - bb_username=None, - bb_password=None, - svn='y')) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_update_bb(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', - 'svn':'x'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline( - 'update', 'bb_user', - 'hashed_bb_pass', None, - [{'identifier':'x'}])) - def check(_): - d = self.master.db.users.getUser(1) - def real_check(usdict): - self.assertEqual(usdict, dict(uid=1, - identifier='x', - bb_username='bb_user', - bb_password='hashed_bb_pass', - svn='x')) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_update_both(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', - 'svn':'x'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline( - 'update', 'bb_user', - 'hashed_bb_pass', None, - [{'identifier':'x', - 'svn':'y'}])) - def check(_): - d = self.master.db.users.getUser(1) - def real_check(usdict): - self.assertEqual(usdict, dict(uid=1, - identifier='x', - bb_username='bb_user', - bb_password='hashed_bb_pass', - svn='y')) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_remove(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'h@c', - 'git': 'hi <h@c>'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline('remove', None, - None, ['x'], None)) - def check(_): - d = self.master.db.users.getUser('x') - def real_check(res): - self.assertEqual(res, None) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_get(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', - 'svn':'x'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline('get', None, None, - ['x'], None)) - def check(_): - d = self.master.db.users.getUser(1) - def real_check(res): - self.assertEqual(res, dict(uid=1, - identifier='x', - bb_username=None, - bb_password=None, - svn='x')) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_get_multiple_attrs(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier': 'x', - 'svn': 'x', - 'git': 'x@c'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline('get', None, None, - ['x'], None)) - def check(_): - d = self.master.db.users.getUser(1) - def real_check(res): - self.assertEqual(res, dict(uid=1, - identifier='x', - bb_username=None, - bb_password=None, - svn='x', - git='x@c')) - d.addCallback(real_check) - return d - d.addCallback(check) - return d - - def test_perspective_commandline_add_format(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', 'svn':'x'}]) - def check(result): - exp_format = "user(s) added:\nidentifier: x\nuid: 1\n\n" - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - - def test_perspective_commandline_update_format(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x', 'svn':'x'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline('update', None, None, None, - [{'identifier':'x', - 'svn':'y'}])) - def check(result): - exp_format = 'user(s) updated:\nidentifier: x\n' - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - - def test_perspective_commandline_remove_format(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'h@c', - 'git': 'hi <h@c>'}]) - d.addCallback(lambda _ : self.call_perspective_commandline('remove', - None, None, - ['h@c'], - None)) - def check(result): - exp_format = "user(s) removed:\nidentifier: h@c\n" - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - - def test_perspective_commandline_get_format(self): - d = self.call_perspective_commandline('add', None, None, None, - [{'identifier':'x@y', 'git': 'x <x@y>'}]) - d.addCallback(lambda _ : - self.call_perspective_commandline('get', None, None, - ['x@y'], None)) - def check(result): - exp_format = 'user(s) found:\ngit: x <x@y>\nidentifier: x@y\n' \ - 'bb_username: None\nuid: 1\n\n' - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - - def test_perspective_commandline_remove_no_match_format(self): - d = self.call_perspective_commandline('remove', None, None, ['x'], None) - def check(result): - exp_format = "user(s) removed:\n" - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - - def test_perspective_commandline_get_no_match_format(self): - d = self.call_perspective_commandline('get', None, None, ['x'], None) - def check(result): - exp_format = "user(s) found:\nno match found\n" - self.assertEqual(result, exp_format) - d.addCallback(check) - return d - -class TestCommandlineUserManager(unittest.TestCase, ManualUsersMixin): - - def setUp(self): - self.setUpManualUsers() - self.manual_component = manual.CommandlineUserManager(username="user", - passwd="userpw", - port="9990") - self.manual_component.master = self.master - - def test_no_userpass(self): - d = defer.maybeDeferred(lambda : manual.CommandlineUserManager()) - return self.assertFailure(d, AssertionError) - - def test_no_port(self): - d = defer.maybeDeferred(lambda : manual.CommandlineUserManager(username="x", - passwd="y")) - return self.assertFailure(d, AssertionError) - - def test_service(self): - # patch out the pbmanager's 'register' command both to be sure - # the registration is correct and to get a copy of the factory - registration = mock.Mock() - registration.unregister = lambda : defer.succeed(None) - self.master.pbmanager = mock.Mock() - def register(portstr, user, passwd, factory): - self.assertEqual([portstr, user, passwd], - ['9990', 'user', 'userpw']) - self.got_factory = factory - return registration - self.master.pbmanager.register = register - - self.manual_component.startService() - - persp = self.got_factory(mock.Mock(), 'user') - self.failUnless(isinstance(persp, manual.CommandlineUserManagerPerspective)) - - return self.manual_component.stopService() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_users.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_users.py deleted file mode 100644 index 3c3b7bb8..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_process_users_users.py +++ /dev/null @@ -1,152 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest - -from buildbot.process.users import users -from buildbot.test.fake import fakedb - -class UsersTests(unittest.TestCase): - - def setUp(self): - self.master = mock.Mock() - self.master.db = self.db = fakedb.FakeDBConnector(self) - self.test_sha = users.encrypt("cancer") - - def test_createUserObject_no_src(self): - d = users.createUserObject(self.master, "Tyler Durden", None) - def check(_): - self.assertEqual(self.db.users.users, {}) - self.assertEqual(self.db.users.users_info, {}) - d.addCallback(check) - return d - - def test_createUserObject_unrecognized_src(self): - d = users.createUserObject(self.master, "Tyler Durden", 'blah') - def check(_): - self.assertEqual(self.db.users.users, {}) - self.assertEqual(self.db.users.users_info, {}) - d.addCallback(check) - return d - - def test_createUserObject_git(self): - d = users.createUserObject(self.master, - "Tyler Durden <tyler@mayhem.net>", 'git') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='Tyler Durden <tyler@mayhem.net>', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="git", - attr_data="Tyler Durden <tyler@mayhem.net>")]}) - d.addCallback(check) - return d - - def test_createUserObject_svn(self): - d = users.createUserObject(self.master, "tdurden", 'svn') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='tdurden', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="svn", - attr_data="tdurden")]}) - d.addCallback(check) - return d - - def test_createUserObject_hg(self): - d = users.createUserObject(self.master, - "Tyler Durden <tyler@mayhem.net>", 'hg') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='Tyler Durden <tyler@mayhem.net>', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="hg", - attr_data="Tyler Durden <tyler@mayhem.net>")]}) - d.addCallback(check) - return d - - def test_createUserObject_cvs(self): - d = users.createUserObject(self.master, "tdurden", 'cvs') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='tdurden', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="cvs", - attr_data="tdurden")]}) - d.addCallback(check) - return d - - def test_createUserObject_darcs(self): - d = users.createUserObject(self.master, "tyler@mayhem.net", 'darcs') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='tyler@mayhem.net', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="darcs", - attr_data="tyler@mayhem.net")]}) - d.addCallback(check) - return d - - def test_createUserObject_bzr(self): - d = users.createUserObject(self.master, "Tyler Durden", 'bzr') - def check(_): - self.assertEqual(self.db.users.users, - { 1: dict(identifier='Tyler Durden', - bb_username=None, bb_password=None) }) - self.assertEqual(self.db.users.users_info, - { 1: [dict(attr_type="bzr", - attr_data="Tyler Durden")]}) - d.addCallback(check) - return d - - def test_getUserContact_found(self): - self.db.insertTestData([fakedb.User(uid=1, identifier='tdurden'), - fakedb.UserInfo(uid=1, attr_type='svn', - attr_data='tdurden'), - fakedb.UserInfo(uid=1, attr_type='email', - attr_data='tyler@mayhem.net')]) - d = users.getUserContact(self.master, contact_types=['email'], uid=1) - def check(contact): - self.assertEqual(contact, 'tyler@mayhem.net') - d.addCallback(check) - return d - - def test_getUserContact_key_not_found(self): - self.db.insertTestData([fakedb.User(uid=1, identifier='tdurden'), - fakedb.UserInfo(uid=1, attr_type='svn', - attr_data='tdurden'), - fakedb.UserInfo(uid=1, attr_type='email', - attr_data='tyler@mayhem.net')]) - d = users.getUserContact(self.master, contact_types=['blargh'], uid=1) - def check(contact): - self.assertEqual(contact, None) - d.addCallback(check) - return d - - def test_getUserContact_uid_not_found(self): - d = users.getUserContact(self.master, contact_types=['email'], uid=1) - def check(contact): - self.assertEqual(contact, None) - d.addCallback(check) - return d - - def test_check_passwd(self): - res = users.check_passwd("cancer", self.test_sha) - self.assertEqual(res, True) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_revlinks.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_revlinks.py deleted file mode 100644 index 70c53404..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_revlinks.py +++ /dev/null @@ -1,82 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.revlinks import RevlinkMatch, GithubRevlink, SourceforgeGitRevlink, GitwebMatch - -class TestGithubRevlink(unittest.TestCase): - revision = 'b6874701b54e0043a78882b020afc86033133f91' - url = 'https://github.com/buildbot/buildbot/commit/b6874701b54e0043a78882b020afc86033133f91' - def testHTTPS(self): - self.assertEqual(GithubRevlink(self.revision, 'https://github.com/buildbot/buildbot.git'), - self.url) - - def testGIT(self): - self.assertEqual(GithubRevlink(self.revision, 'git://github.com/buildbot/buildbot.git'), - self.url) - - def testSSH(self): - self.assertEqual(GithubRevlink(self.revision, 'git@github.com:buildbot/buildbot.git'), - self.url) - - def testSSHuri(self): - self.assertEqual(GithubRevlink(self.revision, 'ssh://git@github.com/buildbot/buildbot.git'), - self.url) - -class TestSourceforgeGitRevlink(unittest.TestCase): - revision = 'b99c89a2842d386accea8072ae5bb6e24aa7cf29' - url = 'http://gemrb.git.sourceforge.net/git/gitweb.cgi?p=gemrb/gemrb;a=commit;h=b99c89a2842d386accea8072ae5bb6e24aa7cf29' - - def testGIT(self): - self.assertEqual(SourceforgeGitRevlink(self.revision, 'git://gemrb.git.sourceforge.net/gitroot/gemrb/gemrb'), - self.url) - - def testSSH(self): - self.assertEqual(SourceforgeGitRevlink(self.revision, 'somebody@gemrb.git.sourceforge.net:gitroot/gemrb/gemrb'), - self.url) - - def testSSHuri(self): - self.assertEqual(SourceforgeGitRevlink(self.revision, 'ssh://somebody@gemrb.git.sourceforge.net/gitroot/gemrb/gemrb'), - self.url) - -class TestRevlinkMatch(unittest.TestCase): - def testNotmuch(self): - revision = 'f717d2ece1836c863f9cc02abd1ff2539307cd1d' - matcher = RevlinkMatch(['git://notmuchmail.org/git/(.*)'], - r'http://git.notmuchmail.org/git/\1/commit/%s') - self.assertEquals(matcher(revision, 'git://notmuchmail.org/git/notmuch'), - 'http://git.notmuchmail.org/git/notmuch/commit/f717d2ece1836c863f9cc02abd1ff2539307cd1d') - - def testSingleString(self): - revision = 'rev' - matcher = RevlinkMatch('test', 'out%s') - self.assertEquals(matcher(revision, 'test'), 'outrev') - - def testSingleUnicode(self): - revision = 'rev' - matcher = RevlinkMatch(u'test', 'out%s') - self.assertEquals(matcher(revision, 'test'), 'outrev') - - def testTwoCaptureGroups(self): - revision = 'rev' - matcher = RevlinkMatch('([A-Z]*)Z([0-9]*)', r'\2-\1-%s') - self.assertEquals(matcher(revision, 'ABCZ43'), '43-ABC-rev') - -class TestGitwebMatch(unittest.TestCase): - def testOrgmode(self): - revision = '490d6ace10e0cfe74bab21c59e4b7bd6aa3c59b8' - matcher = GitwebMatch('git://orgmode.org/(?P<repo>.*)', 'http://orgmode.org/w/') - self.assertEquals(matcher(revision, 'git://orgmode.org/org-mode.git'), - 'http://orgmode.org/w/?p=org-mode.git;a=commit;h=490d6ace10e0cfe74bab21c59e4b7bd6aa3c59b8') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_base.py deleted file mode 100644 index 7eaa003d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_base.py +++ /dev/null @@ -1,523 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sys -import mock -import twisted -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import config -from buildbot.schedulers import base -from buildbot.process import properties -from buildbot.test.util import scheduler -from buildbot.test.fake import fakedb - -class BaseScheduler(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 19 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, name='testsched', builderNames=['a', 'b'], - properties={}, codebases = {'':{}}): - sched = self.attachScheduler( - base.BaseScheduler(name=name, builderNames=builderNames, - properties=properties, codebases=codebases), - self.OBJECTID) - - return sched - - # tests - - def test_constructor_builderNames(self): - self.assertRaises(config.ConfigErrors, - lambda : self.makeScheduler(builderNames='xxx')) - - def test_constructor_builderNames_unicode(self): - self.makeScheduler(builderNames=[u'a']) - - def test_constructor_codebases_valid(self): - codebases = {"codebase1": {"repository":"", "branch":"", "revision":""}} - self.makeScheduler(codebases = codebases) - - def test_constructor_codebases_invalid(self): - # scheduler only accepts codebases with at least repository set - codebases = {"codebase1": {"dictionary":"", "that":"", "fails":""}} - self.assertRaises(config.ConfigErrors, - lambda : self.makeScheduler(codebases = codebases)) - - def test_listBuilderNames(self): - sched = self.makeScheduler(builderNames=['x', 'y']) - self.assertEqual(sched.listBuilderNames(), ['x', 'y']) - - def test_getPendingBuildTimes(self): - sched = self.makeScheduler() - self.assertEqual(sched.getPendingBuildTimes(), []) - - def test_addBuildsetForLatest_defaults(self): - sched = self.makeScheduler(name='testy', builderNames=['x'], - properties=dict(a='b')) - d = sched.addBuildsetForLatest(reason='because') - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='because', brids=brids, - external_idstring=None, - properties=[ ('a', ('b', 'Scheduler')), - ('scheduler', ('testy', 'Scheduler')), ], - sourcestampsetid=100), - {'': - dict(branch=None, revision=None, repository='', codebase='', - project='', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_startConsumingChanges_fileIsImportant_check(self): - sched = self.makeScheduler() - self.assertRaises(AssertionError, - lambda : sched.startConsumingChanges(fileIsImportant="maybe")) - - def do_test_change_consumption(self, kwargs, change, expected_result): - # (expected_result should be True (important), False (unimportant), or - # None (ignore the change)) - sched = self.makeScheduler() - sched.startService() - - change_received = [ None ] - def gotChange(got_change, got_important): - self.assertEqual(got_change, change) - change_received[0] = got_important - return defer.succeed(None) - sched.gotChange = gotChange - - d = sched.startConsumingChanges(**kwargs) - def test(_): - # check that it registered a callback - callbacks = self.master.getSubscriptionCallbacks() - self.assertNotEqual(callbacks['changes'], None) - - # invoke the callback with the change, and check the result - callbacks['changes'](change) - self.assertEqual(change_received[0], expected_result) - d.addCallback(test) - d.addCallback(lambda _ : sched.stopService()) - return d - - def test_change_consumption_defaults(self): - # all changes are important by default - return self.do_test_change_consumption( - dict(), - self.makeFakeChange(), - True) - - def test_change_consumption_fileIsImportant_True(self): - return self.do_test_change_consumption( - dict(fileIsImportant=lambda c : True), - self.makeFakeChange(), - True) - - def test_change_consumption_fileIsImportant_False(self): - return self.do_test_change_consumption( - dict(fileIsImportant=lambda c : False), - self.makeFakeChange(), - False) - - def test_change_consumption_fileIsImportant_exception(self): - d = self.do_test_change_consumption( - dict(fileIsImportant=lambda c : 1/0), - self.makeFakeChange(), - None) - def check_err(_): - self.assertEqual(1, len(self.flushLoggedErrors(ZeroDivisionError))) - d.addCallback(check_err) - return d - if twisted.version.major <= 9 and sys.version_info[:2] >= (2,7): - test_change_consumption_fileIsImportant_exception.skip = \ - "flushLoggedErrors does not work correctly on 9.0.0 and earlier with Python-2.7" - - def test_change_consumption_change_filter_True(self): - cf = mock.Mock() - cf.filter_change = lambda c : True - return self.do_test_change_consumption( - dict(change_filter=cf), - self.makeFakeChange(), - True) - - def test_change_consumption_change_filter_False(self): - cf = mock.Mock() - cf.filter_change = lambda c : False - return self.do_test_change_consumption( - dict(change_filter=cf), - self.makeFakeChange(), - None) - - def test_change_consumption_fileIsImportant_False_onlyImportant(self): - return self.do_test_change_consumption( - dict(fileIsImportant=lambda c : False, onlyImportant=True), - self.makeFakeChange(), - None) - - def test_change_consumption_fileIsImportant_True_onlyImportant(self): - return self.do_test_change_consumption( - dict(fileIsImportant=lambda c : True, onlyImportant=True), - self.makeFakeChange(), - True) - - def test_addBuilsetForLatest_args(self): - sched = self.makeScheduler(name='xyz', builderNames=['y', 'z']) - d = sched.addBuildsetForLatest(reason='cuz', branch='default', - project='myp', repository='hgmo', - external_idstring='try_1234') - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='cuz', brids=brids, - external_idstring='try_1234', - properties=[('scheduler', ('xyz', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='default', revision=None, repository='hgmo', - codebase='', project='myp', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForLatest_properties(self): - props = properties.Properties(xxx="yyy") - sched = self.makeScheduler(name='xyz', builderNames=['y', 'z']) - d = sched.addBuildsetForLatest(reason='cuz', branch='default', - project='myp', repository='hgmo', - external_idstring='try_1234', properties=props) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='cuz', brids=brids, - external_idstring='try_1234', - properties=[ - ('scheduler', ('xyz', 'Scheduler')), - ('xxx', ('yyy', 'TEST')), - ], - sourcestampsetid=100), - {'': - dict(branch='default', revision=None, repository='hgmo', - codebase='', project='myp', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForLatest_builderNames(self): - sched = self.makeScheduler(name='xyz', builderNames=['y', 'z']) - d = sched.addBuildsetForLatest(reason='cuz', branch='default', - builderNames=['a', 'b']) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='cuz', brids=brids, - external_idstring=None, - properties=[('scheduler', ('xyz', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='default', revision=None, repository='', - codebase='', project='', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_one_change(self): - sched = self.makeScheduler(name='n', builderNames=['b']) - self.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://...', codebase='', - project='world-domination'), - ]) - d = sched.addBuildsetForChanges(reason='power', changeids=[13]) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='power', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='svn://...', codebase='', - changeids=set([13]), project='world-domination', - revision='9283', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_properties(self): - props = properties.Properties(xxx="yyy") - sched = self.makeScheduler(name='n', builderNames=['c']) - self.db.insertTestData([ - fakedb.Change(changeid=14, branch='default', revision='123:abc', - repository='', project='', codebase=''), - ]) - d = sched.addBuildsetForChanges(reason='downstream', changeids=[14], - properties=props) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='downstream', brids=brids, - external_idstring=None, - properties=[ - ('scheduler', ('n', 'Scheduler')), - ('xxx', ('yyy', 'TEST')), - ], - sourcestampsetid=100), - {'': - dict(branch='default', revision='123:abc', repository='', - project='', changeids=set([14]), sourcestampsetid=100, - codebase='') - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_one_change_builderNames(self): - sched = self.makeScheduler(name='n', builderNames=['b']) - self.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - codebase='', repository='svn://...', - project='world-domination'), - ]) - d = sched.addBuildsetForChanges(reason='power', changeids=[13], - builderNames=['p']) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='power', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='svn://...', codebase='', - changeids=set([13]), project='world-domination', - revision='9283', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_multiple_changes_no_codebaseGenerator(self): - # This is a test for backwards compatibility - # Changes from different repositories come together in one build - sched = self.makeScheduler(name='n', builderNames=['b', 'c']) - # No codebaseGenerator means all changes have codebase == '' - self.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://A..', project='knitting', - codebase=''), - fakedb.Change(changeid=14, branch='devel', revision='9284', - repository='svn://B..', project='making-tea', - codebase=''), - fakedb.Change(changeid=15, branch='trunk', revision='9285', - repository='svn://C..', project='world-domination', - codebase=''), - ]) - - # note that the changeids are given out of order here; it should still - # use the most recent - d = sched.addBuildsetForChanges(reason='power', changeids=[14, 15, 13]) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='power', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='svn://C..', codebase='', - changeids=set([13,14,15]), project='world-domination', - revision='9285', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_multiple_changes_single_codebase(self): - sched = self.makeScheduler(name='n', builderNames=['b', 'c']) - self.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://...', project='knitting', - codebase=''), - fakedb.Change(changeid=14, branch='devel', revision='9284', - repository='svn://...', project='making-tea', - codebase=''), - fakedb.Change(changeid=15, branch='trunk', revision='9285', - repository='svn://...', project='world-domination', - codebase=''), - ]) - - # note that the changeids are given out of order here; it should still - # use the most recent - d = sched.addBuildsetForChanges(reason='power', changeids=[14, 15, 13]) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='power', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='svn://...', codebase='', - changeids=set([13,14,15]), project='world-domination', - revision='9285', sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_addBuildsetForChanges_codebases_set_multiple_changed_codebases(self): - codebases = { 'cbA':dict( - repository='svn://A..', - branch='stable', - revision='13579'), - 'cbB':dict( - repository='svn://B..', - branch='stable', - revision='24680'), - 'cbC':dict( - repository='svn://C..', - branch='stable', - revision='12345'), - 'cbD':dict( - repository='svn://D..')} - # Scheduler gets codebases that can be used to create extra sourcestamps - # for repositories that have no changes - sched = self.makeScheduler(name='n', builderNames=['b', 'c'], - codebases=codebases) - self.db.insertTestData([ - fakedb.Change(changeid=12, branch='trunk', revision='9282', - repository='svn://A..', project='playing', - codebase='cbA'), - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://A..', project='knitting', - codebase='cbA'), - fakedb.Change(changeid=14, branch='develop', revision='9284', - repository='svn://A..', project='making-tea', - codebase='cbA'), - fakedb.Change(changeid=15, branch='trunk', revision='8085', - repository='svn://B..', project='boxing', - codebase='cbB'), - fakedb.Change(changeid=16, branch='develop', revision='8086', - repository='svn://B..', project='playing soccer', - codebase='cbB'), - fakedb.Change(changeid=17, branch='develop', revision='8087', - repository='svn://B..', project='swimming', - codebase='cbB'), - ]) - - # note that the changeids are given out of order here; it should still - # use the most recent for each codebase - d = sched.addBuildsetForChanges(reason='power', changeids=[14, 12, 17, 16, 13, 15]) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='power', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=100), - {'cbA': - dict(branch='develop', repository='svn://A..', codebase='cbA', - changeids=set([12,13,14]), project='making-tea', - revision='9284', sourcestampsetid=100), - 'cbB': - dict(branch='develop', repository='svn://B..', codebase='cbB', - changeids=set([15,16,17]), project='swimming', - revision='8087', sourcestampsetid=100), - 'cbC': - dict(branch='stable', repository='svn://C..', codebase='cbC', - project='', revision='12345', sourcestampsetid=100), - 'cbD': - dict(branch=None, repository='svn://D..', codebase='cbD', - project='', revision=None, sourcestampsetid=100), - }) - d.addCallback(check) - return d - - def test_addBuildsetForSourceStamp(self): - sched = self.makeScheduler(name='n', builderNames=['b']) - d = self.db.insertTestData([ - fakedb.SourceStampSet(id=1091), - fakedb.SourceStamp(id=91, sourcestampsetid=1091, branch='fixins', - revision='abc', patchid=None, repository='r', - project='p'), - ]) - d.addCallback(lambda _ : - sched.addBuildsetForSourceStamp(reason='whynot', setid=1091)) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='whynot', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=1091), - {'': - dict(branch='fixins', revision='abc', repository='r', - project='p', codebase='', sourcestampsetid=1091) - }) - d.addCallback(check) - return d - - def test_addBuildsetForSourceStamp_properties(self): - props = properties.Properties(xxx="yyy") - sched = self.makeScheduler(name='n', builderNames=['b']) - d = self.db.insertTestData([ - fakedb.SourceStampSet(id=1091), - fakedb.SourceStamp(id=91, sourcestampsetid=1091, branch='fixins', - revision='abc', patchid=None, repository='r', codebase='cb', - project='p'), - ]) - d.addCallback(lambda _ : - sched.addBuildsetForSourceStamp(reason='whynot', setid=1091, - properties=props)) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='whynot', brids=brids, - external_idstring=None, - properties=[ - ('scheduler', ('n', 'Scheduler')), - ('xxx', ('yyy', 'TEST')), - ], - sourcestampsetid=1091), - {'cb': - dict(branch='fixins', revision='abc', repository='r', - codebase='cb', project='p', sourcestampsetid=1091) - }) - d.addCallback(check) - return d - - def test_addBuildsetForSourceStamp_builderNames(self): - sched = self.makeScheduler(name='n', builderNames=['k']) - d = self.db.insertTestData([ - fakedb.SourceStampSet(id=1091), - fakedb.SourceStamp(id=91, sourcestampsetid=1091, branch='fixins', - revision='abc', patchid=None, repository='r', codebase='cb', - project='p'), - ]) - d.addCallback(lambda _ : - sched.addBuildsetForSourceStamp(reason='whynot', setid = 1091, - builderNames=['a', 'b'])) - def check((bsid,brids)): - self.db.buildsets.assertBuildset(bsid, - dict(reason='whynot', brids=brids, - external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - sourcestampsetid=1091), - {'cb': - dict(branch='fixins', revision='abc', repository='r', - codebase='cb', project='p', sourcestampsetid=1091) - }) - d.addCallback(check) - return d - - def test_findNewSchedulerInstance(self): - sched = self.makeScheduler(name='n', builderNames=['k']) - new_sched = self.makeScheduler(name='n', builderNames=['l']) - distractor = self.makeScheduler(name='x', builderNames=['l']) - config = mock.Mock() - config.schedulers = dict(dist=distractor, n=new_sched) - self.assertIdentical(sched.findNewSchedulerInstance(config), new_sched) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_basic.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_basic.py deleted file mode 100644 index db8e848e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_basic.py +++ /dev/null @@ -1,452 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer, task -from buildbot import config -from buildbot.test.fake import fakedb -from buildbot.schedulers import basic -from buildbot.test.util import scheduler - -class CommonStuffMixin(object): - - def makeScheduler(self, klass, **kwargs_override): - kwargs = dict(name="tsched", treeStableTimer=60, - builderNames=['tbuild']) - kwargs.update(kwargs_override) - sched = self.attachScheduler(klass(**kwargs), self.OBJECTID) - - # add a Clock to help checking timing issues - self.clock = sched._reactor = task.Clock() - - # keep track of builds in self.events - self.events = [] - def addBuildsetForChanges(reason='', external_idstring=None, changeids=[]): - self.assertEqual(external_idstring, None) - self.assertEqual(reason, 'scheduler') # basic schedulers all use this - self.events.append('B%s@%d' % (`changeids`.replace(' ',''), - self.clock.seconds())) - return defer.succeed(None) - sched.addBuildsetForChanges = addBuildsetForChanges - - # see self.assertConsumingChanges - self.consumingChanges = None - def startConsumingChanges(**kwargs): - self.consumingChanges = kwargs - return defer.succeed(None) - sched.startConsumingChanges = startConsumingChanges - - return sched - - def assertConsumingChanges(self, **kwargs): - self.assertEqual(self.consumingChanges, kwargs) - -class BaseBasicScheduler(CommonStuffMixin, - scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 244 - - # a custom subclass since we're testing the base class. This basically - # re-implements SingleBranchScheduler, but with more asserts - class Subclass(basic.BaseBasicScheduler): - timer_started = False - def getChangeFilter(self, *args, **kwargs): - return kwargs.get('change_filter') - - def getTimerNameForChange(self, change): - self.timer_started = True - return "xxx" - - def getChangeClassificationsForTimer(self, objectid, timer_name): - assert timer_name == "xxx" - assert objectid == BaseBasicScheduler.OBJECTID - return self.master.db.schedulers.getChangeClassifications(objectid) - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - # tests - - def test_constructor_positional_exception(self): - self.assertRaises(config.ConfigErrors, - lambda : self.Subclass("tsched", "master", 60)) - - def test_startService_no_treeStableTimer(self): - cf = mock.Mock('cf') - fII = mock.Mock('fII') - sched = self.makeScheduler(self.Subclass, treeStableTimer=None, change_filter=cf, - fileIsImportant=fII) - - self.db.schedulers.fakeClassifications(self.OBJECTID, { 20 : True }) - - d = sched.startService(_returnDeferred=True) - - # check that the scheduler has started to consume changes, and the - # classifications *have* been flushed, since they will not be used - def check(_): - self.assertConsumingChanges(fileIsImportant=fII, change_filter=cf, - onlyImportant=False) - self.db.schedulers.assertClassifications(self.OBJECTID, {}) - d.addCallback(check) - d.addCallback(lambda _ : sched.stopService()) - return d - - def test_subclass_fileIsImportant(self): - class Subclass(self.Subclass): - def fileIsImportant(self, change): - return False - sched = self.makeScheduler(Subclass, onlyImportant=True) - self.failUnlessEqual(Subclass.fileIsImportant.__get__(sched), sched.fileIsImportant) - - def test_startService_treeStableTimer(self): - cf = mock.Mock() - sched = self.makeScheduler(self.Subclass, treeStableTimer=10, change_filter=cf) - - self.db.schedulers.fakeClassifications(self.OBJECTID, { 20 : True }) - self.master.db.insertTestData([ - fakedb.Change(changeid=20), - fakedb.SchedulerChange(objectid=self.OBJECTID, - changeid=20, important=1) - ]) - - d = sched.startService(_returnDeferred=True) - - # check that the scheduler has started to consume changes, and no - # classifications have been flushed. Furthermore, the existing - # classification should have been acted on, so the timer should be - # running - def check(_): - self.assertConsumingChanges(fileIsImportant=None, change_filter=cf, - onlyImportant=False) - self.db.schedulers.assertClassifications(self.OBJECTID, { 20 : True }) - self.assertTrue(sched.timer_started) - self.assertEqual(sched.getPendingBuildTimes(), [ 10 ]) - self.clock.advance(10) - self.assertEqual(sched.getPendingBuildTimes(), []) - d.addCallback(check) - d.addCallback(lambda _ : sched.stopService()) - return d - - def test_gotChange_no_treeStableTimer_unimportant(self): - sched = self.makeScheduler(self.Subclass, treeStableTimer=None, branch='master') - - sched.startService() - - d = sched.gotChange(self.makeFakeChange(branch='master', number=13), False) - def check(_): - self.assertEqual(self.events, []) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_no_treeStableTimer_important(self): - sched = self.makeScheduler(self.Subclass, treeStableTimer=None, branch='master') - - sched.startService() - - d = sched.gotChange(self.makeFakeChange(branch='master', number=13), True) - def check(_): - self.assertEqual(self.events, [ 'B[13]@0' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_treeStableTimer_unimportant(self): - sched = self.makeScheduler(self.Subclass, treeStableTimer=10, branch='master') - - sched.startService() - - d = sched.gotChange(self.makeFakeChange(branch='master', number=13), False) - def check(_): - self.assertEqual(self.events, []) - d.addCallback(check) - d.addCallback(lambda _ : self.clock.advance(10)) - d.addCallback(check) # should still be empty - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_treeStableTimer_important(self): - sched = self.makeScheduler(self.Subclass, treeStableTimer=10, branch='master') - - sched.startService() - - d = sched.gotChange(self.makeFakeChange(branch='master', number=13), True) - d.addCallback(lambda _ : self.clock.advance(10)) - def check(_): - self.assertEqual(self.events, [ 'B[13]@10' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - @defer.inlineCallbacks - def test_gotChange_treeStableTimer_sequence(self): - sched = self.makeScheduler(self.Subclass, treeStableTimer=9, branch='master') - self.master.db.insertTestData([ - fakedb.Change(changeid=1, branch='master', when_timestamp=1110), - fakedb.ChangeFile(changeid=1, filename='readme.txt'), - fakedb.Change(changeid=2, branch='master', when_timestamp=2220), - fakedb.ChangeFile(changeid=2, filename='readme.txt'), - fakedb.Change(changeid=3, branch='master', when_timestamp=3330), - fakedb.ChangeFile(changeid=3, filename='readme.txt'), - fakedb.Change(changeid=4, branch='master', when_timestamp=4440), - fakedb.ChangeFile(changeid=4, filename='readme.txt'), - ]) - sched.startService() - - self.clock.advance(2220) - - # this important change arrives at 2220, so the stable timer will last - # until 2229 - yield sched.gotChange( - self.makeFakeChange(branch='master', number=1, when=2220), - True) - self.assertEqual(self.events, []) - self.assertEqual(sched.getPendingBuildTimes(), [2229]) - self.db.schedulers.assertClassifications(self.OBJECTID, { 1 : True }) - - # but another (unimportant) change arrives before then - self.clock.advance(6) # to 2226 - self.assertEqual(self.events, []) - - yield sched.gotChange( - self.makeFakeChange(branch='master', number=2, when=2226), - False) - self.assertEqual(self.events, []) - self.assertEqual(sched.getPendingBuildTimes(), [2235]) - self.db.schedulers.assertClassifications(self.OBJECTID, { 1 : True, 2 : False }) - - self.clock.advance(3) # to 2229 - self.assertEqual(self.events, []) - - self.clock.advance(3) # to 2232 - self.assertEqual(self.events, []) - - # another important change arrives at 2232 - yield sched.gotChange( - self.makeFakeChange(branch='master', number=3, when=2232), - True) - self.assertEqual(self.events, []) - self.assertEqual(sched.getPendingBuildTimes(), [2241]) - self.db.schedulers.assertClassifications(self.OBJECTID, { 1 : True, 2 : False, 3 : True }) - - self.clock.advance(3) # to 2235 - self.assertEqual(self.events, []) - - # finally, time to start the build! - self.clock.advance(6) # to 2241 - self.assertEqual(self.events, [ 'B[1,2,3]@2241' ]) - self.assertEqual(sched.getPendingBuildTimes(), []) - self.db.schedulers.assertClassifications(self.OBJECTID, { }) - - yield sched.stopService() - - -class SingleBranchScheduler(CommonStuffMixin, - scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 245 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def test_constructor_branch_mandatory(self): - self.assertRaises(config.ConfigErrors, - lambda : basic.SingleBranchScheduler(name="tsched", treeStableTimer=60)) - - def test_constructor_no_branch_but_filter(self): - # this shouldn't fail - basic.SingleBranchScheduler(name="tsched", treeStableTimer=60, - builderNames=['a','b'], change_filter=mock.Mock()) - - def test_constructor_branches_forbidden(self): - self.assertRaises(config.ConfigErrors, - lambda : basic.SingleBranchScheduler(name="tsched", treeStableTimer=60, branches='x')) - - def test_gotChange_treeStableTimer_important(self): - # this looks suspiciously like the same test above, because SingleBranchScheduler - # is about the same as the test subclass used above - sched = self.makeScheduler(basic.SingleBranchScheduler, - treeStableTimer=10, branch='master') - - sched.startService() - - d = sched.gotChange(self.makeFakeChange(branch='master', number=13), True) - d.addCallback(lambda _ : self.clock.advance(10)) - def check(_): - self.assertEqual(self.events, [ 'B[13]@10' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - -class AnyBranchScheduler(CommonStuffMixin, - scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 246 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def test_constructor_branch_forbidden(self): - self.assertRaises(config.ConfigErrors, - lambda : basic.SingleBranchScheduler(name="tsched", treeStableTimer=60, branch='x')) - - def test_gotChange_treeStableTimer_multiple_branches(self): - """Two changes with different branches get different treeStableTimers""" - sched = self.makeScheduler(basic.AnyBranchScheduler, - treeStableTimer=10, branches=['master', 'devel', 'boring']) - - sched.startService() - - def mkch(**kwargs): - ch = self.makeFakeChange(**kwargs) - self.db.changes.fakeAddChangeInstance(ch) - return ch - - d = defer.succeed(None) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', number=13), True)) - d.addCallback(lambda _ : - self.assertEqual(sched.getPendingBuildTimes(), [10])) - d.addCallback(lambda _ : - self.clock.advance(1)) # time is now 1 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', number=14), False)) - d.addCallback(lambda _ : - self.assertEqual(sched.getPendingBuildTimes(), [11])) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='boring', number=15), False)) - d.addCallback(lambda _ : - self.clock.pump([1]*4)) # time is now 5 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='devel', number=16), True)) - d.addCallback(lambda _ : - self.assertEqual(sorted(sched.getPendingBuildTimes()), [11,15])) - d.addCallback(lambda _ : - self.clock.pump([1]*10)) # time is now 15 - def check(_): - self.assertEqual(self.events, [ 'B[13,14]@11', 'B[16]@15' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_treeStableTimer_multiple_repositories(self): - """Two repositories, even with the same branch name, have different treeStableTimers""" - sched = self.makeScheduler(basic.AnyBranchScheduler, - treeStableTimer=10, branches=['master']) - - sched.startService() - - def mkch(**kwargs): - ch = self.makeFakeChange(**kwargs) - self.db.changes.fakeAddChangeInstance(ch) - return ch - - d = defer.succeed(None) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', repository="repo", number=13), True)) - d.addCallback(lambda _ : - self.clock.advance(1)) # time is now 1 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', repository="repo", number=14), False)) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', repository="other_repo", number=15), False)) - d.addCallback(lambda _ : - self.clock.pump([1]*4)) # time is now 5 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', repository="other_repo", number=17), True)) - d.addCallback(lambda _ : - self.clock.pump([1]*10)) # time is now 15 - def check(_): - self.assertEqual(self.events, [ 'B[13,14]@11', 'B[15,17]@15' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_treeStableTimer_multiple_projects(self): - """Two projects, even with the same branch name, have different treeStableTimers""" - sched = self.makeScheduler(basic.AnyBranchScheduler, - treeStableTimer=10, branches=['master']) - - sched.startService() - - def mkch(**kwargs): - ch = self.makeFakeChange(**kwargs) - self.db.changes.fakeAddChangeInstance(ch) - return ch - - d = defer.succeed(None) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', project="proj", number=13), True)) - d.addCallback(lambda _ : - self.clock.advance(1)) # time is now 1 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', project="proj", number=14), False)) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', project="other_proj", number=15), False)) - d.addCallback(lambda _ : - self.clock.pump([1]*4)) # time is now 5 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', project="other_proj", number=17), True)) - d.addCallback(lambda _ : - self.clock.pump([1]*10)) # time is now 15 - def check(_): - self.assertEqual(self.events, [ 'B[13,14]@11', 'B[15,17]@15' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) - - def test_gotChange_treeStableTimer_multiple_codebases(self): - """Two codebases, even with the same branch name, have different treeStableTimers""" - sched = self.makeScheduler(basic.AnyBranchScheduler, - treeStableTimer=10, branches=['master']) - - sched.startService() - - def mkch(**kwargs): - ch = self.makeFakeChange(**kwargs) - self.db.changes.fakeAddChangeInstance(ch) - return ch - - d = defer.succeed(None) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', codebase="base", number=13), True)) - d.addCallback(lambda _ : - self.clock.advance(1)) # time is now 1 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', codebase="base", number=14), False)) - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', codebase="other_base", number=15), False)) - d.addCallback(lambda _ : - self.clock.pump([1]*4)) # time is now 5 - d.addCallback(lambda _ : - sched.gotChange(mkch(branch='master', codebase="other_base", number=17), True)) - d.addCallback(lambda _ : - self.clock.pump([1]*10)) # time is now 15 - def check(_): - self.assertEqual(self.events, [ 'B[13,14]@11', 'B[15,17]@15' ]) - d.addCallback(check) - - d.addCallback(lambda _ : sched.stopService()) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_dependent.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_dependent.py deleted file mode 100644 index 0af082a6..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_dependent.py +++ /dev/null @@ -1,153 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import config -from buildbot.schedulers import dependent, base -from buildbot.status.results import SUCCESS, WARNINGS, FAILURE -from buildbot.test.util import scheduler -from buildbot.test.fake import fakedb - -class Dependent(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 33 - UPSTREAM_NAME = 'uppy' - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, upstream=None): - # build a fake upstream scheduler - class Upstream(base.BaseScheduler): - def __init__(self, name): - self.name = name - if not upstream: - upstream = Upstream(self.UPSTREAM_NAME) - - sched = dependent.Dependent(name='n', builderNames=['b'], - upstream=upstream) - self.attachScheduler(sched, self.OBJECTID) - return sched - - def assertBuildsetSubscriptions(self, bsids=None): - self.db.state.assertState(self.OBJECTID, - upstream_bsids=bsids) - - # tests - - # NOTE: these tests take advantage of the fact that all of the fake - # scheduler operations are synchronous, and thus do not return a Deferred. - # The Deferred from trigger() is completely processed before this test - # method returns. - - def test_constructor_string_arg(self): - self.assertRaises(config.ConfigErrors, - lambda : self.makeScheduler(upstream='foo')) - - def test_startService(self): - sched = self.makeScheduler() - sched.startService() - - callbacks = self.master.getSubscriptionCallbacks() - self.assertNotEqual(callbacks['buildsets'], None) - self.assertNotEqual(callbacks['buildset_completion'], None) - - d = sched.stopService() - def check(_): - callbacks = self.master.getSubscriptionCallbacks() - self.assertEqual(callbacks['buildsets'], None) - self.assertEqual(callbacks['buildset_completion'], None) - d.addCallback(check) - return d - - def do_test(self, scheduler_name, expect_subscription, - result, expect_buildset): - sched = self.makeScheduler() - sched.startService() - callbacks = self.master.getSubscriptionCallbacks() - - # pretend we saw a buildset with a matching name - self.db.insertTestData([ - fakedb.SourceStamp(id=93, sourcestampsetid=1093, revision='555', - branch='master', project='proj', repository='repo', - codebase = 'cb'), - fakedb.Buildset(id=44, sourcestampsetid=1093), - ]) - callbacks['buildsets'](bsid=44, - properties=dict(scheduler=(scheduler_name, 'Scheduler'))) - - # check whether scheduler is subscribed to that buildset - if expect_subscription: - self.assertBuildsetSubscriptions([44]) - else: - self.assertBuildsetSubscriptions([]) - - # pretend that the buildset is finished - self.db.buildsets.fakeBuildsetCompletion(bsid=44, result=result) - callbacks['buildset_completion'](44, result) - - # and check whether a buildset was added in response - if expect_buildset: - self.db.buildsets.assertBuildsets(2) - bsids = self.db.buildsets.allBuildsetIds() - bsids.remove(44) - self.db.buildsets.assertBuildset(bsids[0], - dict(external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - reason='downstream', sourcestampsetid = 1093), - {'cb': - dict(revision='555', branch='master', project='proj', - repository='repo', codebase='cb', - sourcestampsetid = 1093) - }) - else: - self.db.buildsets.assertBuildsets(1) # only the one we added above - - def test_related_buildset_SUCCESS(self): - return self.do_test(self.UPSTREAM_NAME, True, SUCCESS, True) - - def test_related_buildset_WARNINGS(self): - return self.do_test(self.UPSTREAM_NAME, True, WARNINGS, True) - - def test_related_buildset_FAILURE(self): - return self.do_test(self.UPSTREAM_NAME, True, FAILURE, False) - - def test_unrelated_buildset(self): - return self.do_test('unrelated', False, SUCCESS, False) - - @defer.inlineCallbacks - def test_getUpstreamBuildsets_missing(self): - sched = self.makeScheduler() - - # insert some state, with more bsids than exist - self.db.insertTestData([ - fakedb.SourceStampSet(id=99), - fakedb.Buildset(id=11, sourcestampsetid=99), - fakedb.Buildset(id=13, sourcestampsetid=99), - fakedb.Object(id=self.OBJECTID), - fakedb.ObjectState(objectid=self.OBJECTID, - name='upstream_bsids', value_json='[11,12,13]'), - ]) - - # check return value (missing 12) - self.assertEqual((yield sched._getUpstreamBuildsets()), - [(11, 99, False, -1), (13, 99, False, -1)]) - - # and check that it wrote the correct value back to the state - self.db.state.assertState(self.OBJECTID, upstream_bsids=[11, 13]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_forcesched.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_forcesched.py deleted file mode 100644 index 12476224..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_forcesched.py +++ /dev/null @@ -1,506 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer -from buildbot import config -from buildbot.schedulers.forcesched import ForceScheduler, StringParameter -from buildbot.schedulers.forcesched import IntParameter, FixedParameter -from buildbot.schedulers.forcesched import BooleanParameter, UserNameParameter -from buildbot.schedulers.forcesched import ChoiceStringParameter, ValidationError -from buildbot.schedulers.forcesched import NestedParameter, AnyPropertyParameter -from buildbot.schedulers.forcesched import CodebaseParameter, BaseParameter -from buildbot.test.util import scheduler -from buildbot.test.util.config import ConfigErrorsMixin - -class TestForceScheduler(scheduler.SchedulerMixin, ConfigErrorsMixin, unittest.TestCase): - - OBJECTID = 19 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, name='testsched', builderNames=['a', 'b'], - **kw): - sched = self.attachScheduler( - ForceScheduler(name=name, builderNames=builderNames,**kw), - self.OBJECTID) - sched.master.config = config.MasterConfig() - - self.assertEquals(sched.name, name) - - return sched - - # tests - - def test_compare_branch(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[]), - ForceScheduler(name="testched", builderNames=[], - branch=FixedParameter("branch","fishing/pole"))) - - - def test_compare_reason(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - reason=FixedParameter("reason","no fish for you!")), - ForceScheduler(name="testched", builderNames=[], - reason=FixedParameter("reason","thanks for the fish!"))) - - - def test_compare_revision(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - revision=FixedParameter("revision","fish-v1")), - ForceScheduler(name="testched", builderNames=[], - revision=FixedParameter("revision","fish-v2"))) - - - def test_compare_repository(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - repository=FixedParameter("repository","git://pond.org/fisher.git")), - ForceScheduler(name="testched", builderNames=[], - repository=FixedParameter("repository","svn://ocean.com/trawler/"))) - - - def test_compare_project(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - project=FixedParameter("project","fisher")), - ForceScheduler(name="testched", builderNames=[], - project=FixedParameter("project","trawler"))) - - - def test_compare_username(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[]), - ForceScheduler(name="testched", builderNames=[], - project=FixedParameter("username","The Fisher King <avallach@atlantis.al>"))) - - - def test_compare_properties(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - properties=[]), - ForceScheduler(name="testched", builderNames=[], - properties=[FixedParameter("prop","thanks for the fish!")])) - - def test_compare_codebases(self): - self.assertNotEqual( - ForceScheduler(name="testched", builderNames=[], - codebases=['bar']), - ForceScheduler(name="testched", builderNames=[], - codebases=['foo'])) - - - @defer.inlineCallbacks - def test_basicForce(self): - sched = self.makeScheduler() - - res = yield sched.force('user', builderNames=['a'], branch='a', reason='because',revision='c', - repository='d', project='p', - property1_name='p1',property1_value='e', - property2_name='p2',property2_value='f', - property3_name='p3',property3_value='g', - property4_name='p4',property4_value='h' - ) - bsid,brids = res - - # only one builder forced, so there should only be one brid - self.assertEqual(len(brids), 1) - - self.db.buildsets.assertBuildset\ - (bsid, - dict(reason="A build was forced by 'user': because", - brids=brids, - external_idstring=None, - properties=[ ('owner', ('user', 'Force Build Form')), - ('p1', ('e', 'Force Build Form')), - ('p2', ('f', 'Force Build Form')), - ('p3', ('g', 'Force Build Form')), - ('p4', ('h', 'Force Build Form')), - ('reason', ('because', 'Force Build Form')), - ('scheduler', ('testsched', 'Scheduler')), - ], - sourcestampsetid=100), - {'': - dict(branch='a', revision='c', repository='d', codebase='', - project='p', sourcestampsetid=100) - }) - - @defer.inlineCallbacks - def test_force_allBuilders(self): - sched = self.makeScheduler() - - res = yield sched.force('user', branch='a', reason='because',revision='c', - repository='d', project='p', - ) - bsid,brids = res - - self.assertEqual(len(brids), 2) - - self.db.buildsets.assertBuildset\ - (bsid, - dict(reason="A build was forced by 'user': because", - brids=brids, - builders = ['a', 'b'], - external_idstring=None, - properties=[ ('owner', ('user', 'Force Build Form')), - ('reason', ('because', 'Force Build Form')), - ('scheduler', ('testsched', 'Scheduler')), - ], - sourcestampsetid=100), - {'': - dict(branch='a', revision='c', repository='d', codebase='', - project='p', sourcestampsetid=100) - }) - - @defer.inlineCallbacks - def test_force_someBuilders(self): - sched = self.makeScheduler(builderNames=['a','b','c']) - - res = yield sched.force('user', builderNames=['a','b'], - branch='a', reason='because',revision='c', - repository='d', project='p', - ) - bsid,brids = res - - self.assertEqual(len(brids), 2) - - self.db.buildsets.assertBuildset\ - (bsid, - dict(reason="A build was forced by 'user': because", - brids=brids, - builders = ['a', 'b'], - external_idstring=None, - properties=[ ('owner', ('user', 'Force Build Form')), - ('reason', ('because', 'Force Build Form')), - ('scheduler', ('testsched', 'Scheduler')), - ], - sourcestampsetid=100), - {'': - dict(branch='a', revision='c', repository='d', codebase='', - project='p', sourcestampsetid=100) - }) - - def test_bad_codebases(self): - # cant specify both codebases and branch/revision/project/repository: - self.assertRaisesConfigError("ForceScheduler: Must either specify 'codebases' or the 'branch/revision/repository/project' parameters:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=['foo'], branch=StringParameter('name'))) - self.assertRaisesConfigError("ForceScheduler: Must either specify 'codebases' or the 'branch/revision/repository/project' parameters:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=['foo'], revision=StringParameter('name'))) - self.assertRaisesConfigError("ForceScheduler: Must either specify 'codebases' or the 'branch/revision/repository/project' parameters:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=['foo'], project=StringParameter('name'))) - self.assertRaisesConfigError("ForceScheduler: Must either specify 'codebases' or the 'branch/revision/repository/project' parameters:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=['foo'], repository=StringParameter('name'))) - - # codebases must be a list of either string or BaseParameter types - self.assertRaisesConfigError("ForceScheduler: 'codebases' must be a list of strings or CodebaseParameter objects:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=[123],)) - self.assertRaisesConfigError("ForceScheduler: 'codebases' must be a list of strings or CodebaseParameter objects:", - lambda: ForceScheduler(name='foo', builderNames=['bar'], - codebases=[IntParameter('foo')],)) - - # codebases cannot be empty - self.assertRaisesConfigError("ForceScheduler: 'codebases' cannot be empty; use CodebaseParameter(codebase='', hide=True) if needed:", - lambda: ForceScheduler(name='foo', - builderNames=['bar'], - codebases=[])) - - @defer.inlineCallbacks - def test_good_codebases(self): - sched = self.makeScheduler(codebases=['foo', CodebaseParameter('bar')]) - res = yield sched.force('user', builderNames=['a'], reason='because', - foo_branch='a', foo_revision='c', foo_repository='d', foo_project='p', - bar_branch='a2', bar_revision='c2', bar_repository='d2', bar_project='p2', - property1_name='p1',property1_value='e', - property2_name='p2',property2_value='f', - property3_name='p3',property3_value='g', - property4_name='p4',property4_value='h' - ) - - bsid,brids = res - self.db.buildsets.assertBuildset\ - (bsid, - dict(reason="A build was forced by 'user': because", - brids=brids, - external_idstring=None, - properties=[ ('owner', ('user', 'Force Build Form')), - ('p1', ('e', 'Force Build Form')), - ('p2', ('f', 'Force Build Form')), - ('p3', ('g', 'Force Build Form')), - ('p4', ('h', 'Force Build Form')), - ('reason', ('because', 'Force Build Form')), - ('scheduler', ('testsched', 'Scheduler')), - ], - sourcestampsetid=100), - {'foo': dict(codebase='foo', sourcestampsetid=100, - branch='a', revision='c', repository='d', project='p', ), - 'bar': dict(codebase='bar', sourcestampsetid=100, - branch='a2', revision='c2', repository='d2', project='p2', ), - }) - - # value = the value to be sent with the parameter (ignored if req is set) - # expect = the expected result (can be an exception type) - # klass = the parameter class type - # req = use this request instead of the auto-generated one based on value - @defer.inlineCallbacks - def do_ParameterTest(self, - expect, - klass, - expectKind=None, # None=one prop, Exception=exception, dict=many props - owner='user', - value=None, req=None, - **kwargs): - - name = kwargs.setdefault('name', 'p1') - - # construct one if needed - if isinstance(klass, type): - prop = klass(**kwargs) - else: - prop = klass - - self.assertEqual(prop.name, name) - self.assertEqual(prop.label, kwargs.get('label', prop.name)) - - sched = self.makeScheduler(properties=[prop]) - - if not req: - req = {name:value, 'reason':'because'} - try: - bsid, brids = yield sched.force(owner, builderNames=['a'], **req) - except Exception,e: - if expectKind is not Exception: - # an exception is not expected - raise - if not isinstance(e, expect): - # the exception is the wrong kind - raise - defer.returnValue(None) # success - - expect_props = [ - ('owner', ('user', 'Force Build Form')), - ('reason', ('because', 'Force Build Form')), - ('scheduler', ('testsched', 'Scheduler')), - ] - - if expectKind is None: - expect_props.append((name, (expect, 'Force Build Form'))) - elif expectKind is dict: - for k,v in expect.iteritems(): - expect_props.append((k, (v, 'Force Build Form'))) - else: - self.fail("expectKind is wrong type!") - - self.db.buildsets.assertBuildset\ - (bsid, - dict(reason="A build was forced by 'user': because", - brids=brids, - external_idstring=None, - properties=sorted(expect_props), - sourcestampsetid=100), - {"": - dict(branch="", revision="", repository="", codebase='', - project="", sourcestampsetid=100) - }) - - def test_StringParameter(self): - self.do_ParameterTest(value="testedvalue", expect="testedvalue", - klass=StringParameter) - - def test_IntParameter(self): - self.do_ParameterTest(value="123", expect=123, klass=IntParameter) - - - def test_FixedParameter(self): - self.do_ParameterTest(value="123", expect="321", klass=FixedParameter, - default="321") - - - def test_BooleanParameter_True(self): - req = dict(p1=True,reason='because') - self.do_ParameterTest(value="123", expect=True, klass=BooleanParameter, - req=req) - - - def test_BooleanParameter_False(self): - req = dict(p2=True,reason='because') - self.do_ParameterTest(value="123", expect=False, - klass=BooleanParameter, req=req) - - - def test_UserNameParameter(self): - email = "test <test@buildbot.net>" - self.do_ParameterTest(value=email, expect=email, - klass=UserNameParameter(), - name="username", label="Your name:") - - - def test_UserNameParameterError(self): - for value in ["test","test@buildbot.net","<test@buildbot.net>"]: - self.do_ParameterTest(value=value, - expect=ValidationError, - expectKind=Exception, - klass=UserNameParameter(debug=False), - name="username", label="Your name:") - - - def test_ChoiceParameter(self): - self.do_ParameterTest(value='t1', expect='t1', - klass=ChoiceStringParameter, choices=['t1','t2']) - - - def test_ChoiceParameterError(self): - self.do_ParameterTest(value='t3', - expect=ValidationError, - expectKind=Exception, - klass=ChoiceStringParameter, choices=['t1','t2'], - debug=False) - - def test_ChoiceParameterError_notStrict(self): - self.do_ParameterTest(value='t1', expect='t1', - strict=False, - klass=ChoiceStringParameter, choices=['t1','t2']) - - - def test_ChoiceParameterMultiple(self): - self.do_ParameterTest(value=['t1','t2'], expect=['t1','t2'], - klass=ChoiceStringParameter,choices=['t1','t2'], multiple=True) - - - def test_ChoiceParameterMultipleError(self): - self.do_ParameterTest(value=['t1','t3'], - expect=ValidationError, - expectKind=Exception, - klass=ChoiceStringParameter, choices=['t1','t2'], - multiple=True, debug=False) - - - def test_NestedParameter(self): - fields = [ - IntParameter(name="foo") - ] - self.do_ParameterTest(req=dict(p1_foo='123', reason="because"), - expect=dict(foo=123), - klass=NestedParameter, fields=fields) - - def test_NestedNestedParameter(self): - fields = [ - NestedParameter(name="inner", fields=[ - StringParameter(name='str'), - AnyPropertyParameter(name='any') - ]), - IntParameter(name="foo") - ] - self.do_ParameterTest(req=dict(p1_foo='123', - p1_inner_str="bar", - p1_inner_any_name="hello", - p1_inner_any_value="world", - reason="because"), - expect=dict(foo=123, inner=dict(str="bar", hello="world")), - klass=NestedParameter, fields=fields) - - def test_NestedParameter_nullname(self): - # same as above except "p1" and "any" are skipped - fields = [ - NestedParameter(name="inner", fields=[ - StringParameter(name='str'), - AnyPropertyParameter(name='') - ]), - IntParameter(name="foo"), - NestedParameter(name='bar', fields=[ - NestedParameter(name='', fields=[AnyPropertyParameter(name='a')]), - NestedParameter(name='', fields=[AnyPropertyParameter(name='b')]) - ]) - ] - self.do_ParameterTest(req=dict(foo='123', - inner_str="bar", - inner_name="hello", - inner_value="world", - reason="because", - bar_a_name="a", - bar_a_value="7", - bar_b_name="b", - bar_b_value="8"), - expect=dict(foo=123, - inner=dict(str="bar", hello="world"), - bar={'a':'7', 'b':'8'}), - expectKind=dict, - klass=NestedParameter, fields=fields, name='') - - def test_bad_reason(self): - self.assertRaisesConfigError("ForceScheduler reason must be a StringParameter", - lambda: ForceScheduler(name='testsched', builderNames=[], - codebases=['bar'], reason="foo")) - - def test_bad_username(self): - self.assertRaisesConfigError("ForceScheduler username must be a StringParameter", - lambda: ForceScheduler(name='testsched', builderNames=[], - codebases=['bar'], username="foo")) - - def test_notstring_name(self): - self.assertRaisesConfigError("ForceScheduler name must be a unicode string:", - lambda: ForceScheduler(name=1234, builderNames=[], - codebases=['bar'], username="foo")) - - def test_emptystring_name(self): - self.assertRaisesConfigError("ForceScheduler name must not be empty:", - lambda: ForceScheduler(name='', builderNames=[], - codebases=['bar'], username="foo")) - - def test_integer_builderNames(self): - self.assertRaisesConfigError("ForceScheduler builderNames must be a list of strings:", - lambda: ForceScheduler(name='testsched', builderNames=1234, - codebases=['bar'], username="foo")) - - def test_listofints_builderNames(self): - self.assertRaisesConfigError("ForceScheduler builderNames must be a list of strings:", - lambda: ForceScheduler(name='testsched', builderNames=[1234], - codebases=['bar'], username="foo")) - - def test_listofmixed_builderNames(self): - self.assertRaisesConfigError("ForceScheduler builderNames must be a list of strings:", - lambda: ForceScheduler(name='testsched', - builderNames=['test', 1234], - codebases=['bar'], username="foo")) - - def test_integer_properties(self): - self.assertRaisesConfigError("ForceScheduler properties must be a list of BaseParameters:", - lambda: ForceScheduler(name='testsched', builderNames=[], - codebases=['bar'], username="foo", - properties=1234)) - - def test_listofints_properties(self): - self.assertRaisesConfigError("ForceScheduler properties must be a list of BaseParameters:", - lambda: ForceScheduler(name='testsched', builderNames=[], - codebases=['bar'], username="foo", - properties=[1234, 2345])) - - def test_listofmixed_properties(self): - self.assertRaisesConfigError("ForceScheduler properties must be a list of BaseParameters:", - lambda: ForceScheduler(name='testsched', builderNames=[], - codebases=['bar'], username="foo", - properties=[BaseParameter(name="test",), - 4567])) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_manager.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_manager.py deleted file mode 100644 index 0c79730b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_manager.py +++ /dev/null @@ -1,168 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.schedulers import manager, base -from buildbot import config - -class SchedulerManager(unittest.TestCase): - - def setUp(self): - self.next_objectid = 13 - self.objectids = {} - - self.master = mock.Mock() - def getObjectId(sched_name, class_name): - k = (sched_name, class_name) - try: - rv = self.objectids[k] - except: - rv = self.objectids[k] = self.next_objectid - self.next_objectid += 1 - return defer.succeed(rv) - self.master.db.state.getObjectId = getObjectId - - self.new_config = mock.Mock() - - self.sm = manager.SchedulerManager(self.master) - self.sm.startService() - - def tearDown(self): - if self.sm.running: - return self.sm.stopService() - - class Sched(base.BaseScheduler): - - # changing sch.attr should make a scheduler look "updated" - compare_attrs = base.BaseScheduler.compare_attrs + ( 'attr', ) - already_started = False - reconfig_count = 0 - - def startService(self): - assert not self.already_started - assert self.master is not None - assert self.objectid is not None - self.already_started = True - base.BaseScheduler.startService(self) - - def stopService(self): - d = base.BaseScheduler.stopService(self) - def still_set(_): - assert self.master is not None - assert self.objectid is not None - d.addCallback(still_set) - return d - - class ReconfigSched(config.ReconfigurableServiceMixin, Sched): - - def reconfigService(self, new_config): - self.reconfig_count += 1 - new_sched = self.findNewSchedulerInstance(new_config) - self.attr = new_sched.attr - return config.ReconfigurableServiceMixin.reconfigService(self, - new_config) - - class ReconfigSched2(ReconfigSched): - pass - - def makeSched(self, cls, name, attr='alpha'): - sch = cls(name=name, builderNames=['x'], properties={}) - sch.attr = attr - return sch - - # tests - - @defer.inlineCallbacks - def test_reconfigService_add_and_change_and_remove(self): - sch1 = self.makeSched(self.ReconfigSched, 'sch1', attr='alpha') - self.new_config.schedulers = dict(sch1=sch1) - - yield self.sm.reconfigService(self.new_config) - - self.assertIdentical(sch1.parent, self.sm) - self.assertIdentical(sch1.master, self.master) - self.assertEqual(sch1.reconfig_count, 1) - - sch1_new = self.makeSched(self.ReconfigSched, 'sch1', attr='beta') - sch2 = self.makeSched(self.ReconfigSched, 'sch2', attr='alpha') - self.new_config.schedulers = dict(sch1=sch1_new, sch2=sch2) - - yield self.sm.reconfigService(self.new_config) - - # sch1 is still the active scheduler, and has been reconfig'd, - # and has the correct attribute - self.assertIdentical(sch1.parent, self.sm) - self.assertIdentical(sch1.master, self.master) - self.assertEqual(sch1.attr, 'beta') - self.assertEqual(sch1.reconfig_count, 2) - self.assertIdentical(sch1_new.parent, None) - self.assertIdentical(sch1_new.master, None) - - self.assertIdentical(sch2.parent, self.sm) - self.assertIdentical(sch2.master, self.master) - - self.new_config.schedulers = {} - - yield self.sm.reconfigService(self.new_config) - - self.assertIdentical(sch1.parent, None) - self.assertIdentical(sch1.master, None) - - @defer.inlineCallbacks - def test_reconfigService_class_name_change(self): - sch1 = self.makeSched(self.ReconfigSched, 'sch1') - self.new_config.schedulers = dict(sch1=sch1) - - yield self.sm.reconfigService(self.new_config) - - self.assertIdentical(sch1.parent, self.sm) - self.assertIdentical(sch1.master, self.master) - self.assertEqual(sch1.reconfig_count, 1) - - sch1_new = self.makeSched(self.ReconfigSched2, 'sch1') - self.new_config.schedulers = dict(sch1=sch1_new) - - yield self.sm.reconfigService(self.new_config) - - # sch1 had its class name change, so sch1_new is now the active - # instance - self.assertIdentical(sch1_new.parent, self.sm) - self.assertIdentical(sch1_new.master, self.master) - - @defer.inlineCallbacks - def test_reconfigService_add_and_change_and_remove_no_reconfig(self): - sch1 = self.makeSched(self.Sched, 'sch1', attr='alpha') - self.new_config.schedulers = dict(sch1=sch1) - - yield self.sm.reconfigService(self.new_config) - - self.assertIdentical(sch1.parent, self.sm) - self.assertIdentical(sch1.master, self.master) - - sch1_new = self.makeSched(self.Sched, 'sch1', attr='beta') - sch2 = self.makeSched(self.Sched, 'sch2', attr='alpha') - self.new_config.schedulers = dict(sch1=sch1_new, sch2=sch2) - - yield self.sm.reconfigService(self.new_config) - - # sch1 is not longer active, and sch1_new is - self.assertIdentical(sch1.parent, None) - self.assertIdentical(sch1.master, None) - self.assertIdentical(sch1_new.parent, self.sm) - self.assertIdentical(sch1_new.master, self.master) - self.assertIdentical(sch2.parent, self.sm) - self.assertIdentical(sch2.master, self.master) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Nightly.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Nightly.py deleted file mode 100644 index 34d6c3cb..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Nightly.py +++ /dev/null @@ -1,208 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import time -import mock -from twisted.trial import unittest -from twisted.internet import defer, task -from twisted.python import log -from buildbot.schedulers import timed -from buildbot.test.util import scheduler -from buildbot.changes import filter -from buildbot import config - -class Nightly(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 132 - - # not all timezones are even multiples of 1h from GMT. This variable - # holds the number of seconds ahead of the hour for the current timezone. - # This is then added to the clock before each test is run (to get to 0 - # minutes past the hour) and subtracted before the time offset is reported. - localtime_offset = time.timezone % 3600 - - def makeScheduler(self, firstBuildDuration=0, **kwargs): - sched = self.attachScheduler(timed.Nightly(**kwargs), - self.OBJECTID) - - # add a Clock to help checking timing issues - self.clock = sched._reactor = task.Clock() - self.clock.advance(self.localtime_offset) # get to 0 min past the hour - - # keep track of builds in self.events - self.events = [] - def addBuildsetForLatest(reason='', external_idstring='', - branch=None, repository='', project=''): - self.assertIn('scheduler named', reason) - isFirst = (self.events == []) - self.events.append('B(%s)@%d' % (branch, - # show the offset as seconds past the GMT hour - self.clock.seconds() - self.localtime_offset)) - if isFirst and firstBuildDuration: - d = defer.Deferred() - self.clock.callLater(firstBuildDuration, d.callback, None) - return d - else: - return defer.succeed(None) - sched.addBuildsetForLatest = addBuildsetForLatest - - def addBuildsetForChanges(reason='', external_idstring='', changeids=[]): - self.events.append('B%s@%d' % (`changeids`.replace(' ',''), - # show the offset as seconds past the GMT hour - self.clock.seconds() - self.localtime_offset)) - return defer.succeed(None) - sched.addBuildsetForChanges = addBuildsetForChanges - - # see self.assertConsumingChanges - self.consumingChanges = None - def startConsumingChanges(**kwargs): - self.consumingChanges = kwargs - return defer.succeed(None) - sched.startConsumingChanges = startConsumingChanges - - return sched - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def assertConsumingChanges(self, **kwargs): - self.assertEqual(self.consumingChanges, kwargs) - - ## Tests - - def test_constructor_change_filter(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - branch=None, change_filter=filter.ChangeFilter(category_re="fo+o")) - assert sched.change_filter - - def test_constructor_no_branch(self): - self.assertRaises(config.ConfigErrors, - lambda : self.makeScheduler(name='test', builderNames=['test'], - change_filter=filter.ChangeFilter(category_re="fo+o"))) - - ## end-to-end tests: let's see the scheduler in action - - def test_iterations_simple(self): - # note that Nightly works in local time, but the task.Clock() always - # starts at midnight UTC, so be careful not to use times that are - # timezone dependent -- stick to minutes-past-the-half-hour, as some - # timezones are multiples of 30 minutes off from UTC - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], branch=None, - minute=[10, 20, 21, 40, 50, 51]) - - # add a change classification - self.db.schedulers.fakeClassifications(self.OBJECTID, { 19 : True }) - - sched.startService() - - # check that the classification has been flushed, since this - # invocation has not requested onlyIfChanged - self.db.schedulers.assertClassifications(self.OBJECTID, {}) - - self.clock.advance(0) # let it get set up - while self.clock.seconds() < self.localtime_offset + 30*60: - self.clock.advance(60) - self.assertEqual(self.events, [ 'B(None)@600', 'B(None)@1200', 'B(None)@1260' ]) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=1260 + self.localtime_offset) - - d = sched.stopService() - return d - - def test_iterations_simple_with_branch(self): - # see timezone warning above - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - branch='master', minute=[5, 35]) - - sched.startService() - - self.clock.advance(0) - while self.clock.seconds() < self.localtime_offset + 10*60: - self.clock.advance(60) - self.assertEqual(self.events, [ 'B(master)@300' ]) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=300 + self.localtime_offset) - - d = sched.stopService() - return d - - def do_test_iterations_onlyIfChanged(self, *changes_at): - fII = mock.Mock(name='fII') - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], branch=None, - minute=[5, 25, 45], onlyIfChanged=True, - fileIsImportant=fII) - - sched.startService() - - # check that the scheduler has started to consume changes - self.assertConsumingChanges(fileIsImportant=fII, change_filter=None, - onlyImportant=False) - - # manually run the clock forward through a half-hour, allowing any - # excitement to take place - changes_at = list(changes_at) - self.clock.advance(0) # let it trigger the first build - while self.clock.seconds() < self.localtime_offset + 30*60: - # inject any new changes.. - while (changes_at and - self.clock.seconds() >= - self.localtime_offset + changes_at[0][0]): - when, newchange, important = changes_at.pop(0) - self.sched.gotChange(newchange, important).addErrback(log.err) - # and advance the clock by a minute - self.clock.advance(60) - - def test_iterations_onlyIfChanged_no_changes(self): - self.do_test_iterations_onlyIfChanged() - self.assertEqual(self.events, []) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=1500 + self.localtime_offset) - return self.sched.stopService() - - def test_iterations_onlyIfChanged_unimp_changes(self): - self.do_test_iterations_onlyIfChanged( - (60, mock.Mock(), False), - (600, mock.Mock(), False)) - self.assertEqual(self.events, []) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=1500 + self.localtime_offset) - return self.sched.stopService() - - def test_iterations_onlyIfChanged_off_branch_changes(self): - self.do_test_iterations_onlyIfChanged( - (60, self.makeFakeChange(branch='testing'), True), - (1700, self.makeFakeChange(branch='staging'), True)) - self.assertEqual(self.events, []) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=1500 + self.localtime_offset) - return self.sched.stopService() - - def test_iterations_onlyIfChanged_mixed_changes(self): - self.do_test_iterations_onlyIfChanged( - (120, self.makeFakeChange(number=3, branch=None), False), - (130, self.makeFakeChange(number=4, branch='offbranch'), True), - (1200, self.makeFakeChange(number=5, branch=None), True), - (1201, self.makeFakeChange(number=6, branch=None), False), - (1202, self.makeFakeChange(number=7, branch='offbranch'), True)) - # note that the changeid list includes the unimportant changes, but not the - # off-branch changes, and note that no build took place at 300s, as no important - # changes had yet arrived - self.assertEqual(self.events, [ 'B[3,5,6]@1500' ]) - self.db.state.assertStateByClass('test', 'Nightly', - last_build=1500 + self.localtime_offset) - return self.sched.stopService() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyBase.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyBase.py deleted file mode 100644 index 4d799aed..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyBase.py +++ /dev/null @@ -1,206 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sys -import time -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.schedulers import timed -from buildbot.test.util import scheduler -from buildbot.test.util import config - -class NightlyBase(scheduler.SchedulerMixin, unittest.TestCase): - """detailed getNextBuildTime tests""" - - OBJECTID = 133 - - def makeScheduler(self, firstBuildDuration=0, **kwargs): - return self.attachScheduler(timed.NightlyBase(**kwargs), - self.OBJECTID) - - @defer.inlineCallbacks - def do_getNextBuildTime_test(self, sched, *expectations): - for lastActuated, expected in expectations: - # convert from tuples to epoch time (in local timezone) - lastActuated_ep, expected_ep = [ - time.mktime(t + (0,) * (8 - len(t)) + (-1,)) - for t in (lastActuated, expected) ] - got_ep = yield sched.getNextBuildTime(lastActuated_ep) - self.assertEqual(got_ep, expected_ep, - "%s -> %s != %s" % (lastActuated, time.localtime(got_ep), - expected)) - - def test_getNextBuildTime_hourly(self): - sched = self.makeScheduler(name='test', builderNames=['test']) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 4, 0, 0)), - ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 4, 0, 0)), - ((2011, 1, 1, 3, 15, 1), (2011, 1, 1, 4, 0, 0)), - ((2011, 1, 1, 3, 59, 1), (2011, 1, 1, 4, 0, 0)), - ((2011, 1, 1, 3, 59, 59), (2011, 1, 1, 4, 0, 0)), - ((2011, 1, 1, 23, 22, 22), (2011, 1, 2, 0, 0, 0)), - ((2011, 1, 1, 23, 59, 0), (2011, 1, 2, 0, 0, 0)), - ) - - def test_getNextBuildTime_minutes_single(self): - # basically the same as .._hourly - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=4) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 3, 4, 0)), - ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 4, 4, 0)), - ) - - def test_getNextBuildTime_minutes_multiple(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[4, 34]) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 0, 0), (2011, 1, 1, 3, 4, 0)), - ((2011, 1, 1, 3, 15, 0), (2011, 1, 1, 3, 34, 0)), - ((2011, 1, 1, 3, 34, 0), (2011, 1, 1, 4, 4, 0)), - ((2011, 1, 1, 3, 59, 1), (2011, 1, 1, 4, 4, 0)), - ) - - def test_getNextBuildTime_minutes_star(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute='*') - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 11, 30), (2011, 1, 1, 3, 12, 0)), - ((2011, 1, 1, 3, 12, 0), (2011, 1, 1, 3, 13, 0)), - ((2011, 1, 1, 3, 59, 0), (2011, 1, 1, 4, 0, 0)), - ) - - def test_getNextBuildTime_hours_single(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - hour=4) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 0), (2011, 1, 1, 4, 0)), - ((2011, 1, 1, 13, 0), (2011, 1, 2, 4, 0)), - ) - - def test_getNextBuildTime_hours_multiple(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - hour=[7, 19]) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 0), (2011, 1, 1, 7, 0)), - ((2011, 1, 1, 7, 1), (2011, 1, 1, 19, 0)), - ((2011, 1, 1, 18, 59), (2011, 1, 1, 19, 0)), - ((2011, 1, 1, 19, 59), (2011, 1, 2, 7, 0)), - ) - - def test_getNextBuildTime_hours_minutes(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - hour=13, minute=19) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 1, 3, 11), (2011, 1, 1, 13, 19)), - ((2011, 1, 1, 13, 19), (2011, 1, 2, 13, 19)), - ((2011, 1, 1, 23, 59), (2011, 1, 2, 13, 19)), - ) - - def test_getNextBuildTime_month_single(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - month=3) - return self.do_getNextBuildTime_test(sched, - ((2011, 2, 27, 3, 11), (2011, 3, 1, 0, 0)), - ((2011, 3, 1, 1, 11), (2011, 3, 1, 2, 0)), # still hourly! - ) - - def test_getNextBuildTime_month_multiple(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - month=[4, 6]) - return self.do_getNextBuildTime_test(sched, - ((2011, 3, 30, 3, 11), (2011, 4, 1, 0, 0)), - ((2011, 4, 1, 1, 11), (2011, 4, 1, 2, 0)), # still hourly! - ((2011, 5, 29, 3, 11), (2011, 6, 1, 0, 0)), - ) - - def test_getNextBuildTime_month_dayOfMonth(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - month=[3, 6], dayOfMonth=[15]) - return self.do_getNextBuildTime_test(sched, - ((2011, 2, 12, 3, 11), (2011, 3, 15, 0, 0)), - ((2011, 3, 12, 3, 11), (2011, 3, 15, 0, 0)), - ) - - def test_getNextBuildTime_dayOfMonth_single(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfMonth=10) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 9, 3, 0), (2011, 1, 10, 0, 0)), - ((2011, 1, 10, 3, 0), (2011, 1, 10, 4, 0)), # still hourly! - ((2011, 1, 30, 3, 0), (2011, 2, 10, 0, 0)), - ((2011, 12, 30, 11, 0), (2012, 1, 10, 0, 0)), - ) - - def test_getNextBuildTime_dayOfMonth_multiple(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfMonth=[10, 20, 30]) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 9, 22, 0), (2011, 1, 10, 0, 0)), - ((2011, 1, 19, 22, 0), (2011, 1, 20, 0, 0)), - ((2011, 1, 29, 22, 0), (2011, 1, 30, 0, 0)), - ((2011, 2, 29, 22, 0), (2011, 3, 10, 0, 0)), # no Feb 30! - ) - - def test_getNextBuildTime_dayOfMonth_hours_minutes(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfMonth=15, hour=20, minute=30) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 13, 22, 19), (2011, 1, 15, 20, 30)), - ((2011, 1, 15, 19, 19), (2011, 1, 15, 20, 30)), - ((2011, 1, 15, 20, 29), (2011, 1, 15, 20, 30)), - ) - - def test_getNextBuildTime_dayOfWeek_single(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfWeek=1) # Tuesday (2011-1-1 was a Saturday) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 3, 22, 19), (2011, 1, 4, 0, 0)), - ((2011, 1, 4, 19, 19), (2011, 1, 4, 20, 0)), # still hourly! - ) - - def test_getNextBuildTime_dayOfWeek_multiple_hours(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfWeek=[1,3], hour=1) # Tuesday, Thursday (2011-1-1 was a Saturday) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 3, 22, 19), (2011, 1, 4, 1, 0)), - ((2011, 1, 4, 22, 19), (2011, 1, 6, 1, 0)), - ) - - def test_getNextBuildTime_dayOfWeek_dayOfMonth(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - dayOfWeek=[1,4], dayOfMonth=5, hour=1) - return self.do_getNextBuildTime_test(sched, - ((2011, 1, 3, 22, 19), (2011, 1, 4, 1, 0)), # Tues - ((2011, 1, 4, 22, 19), (2011, 1, 5, 1, 0)), # 5th - ((2011, 1, 5, 22, 19), (2011, 1, 7, 1, 0)), # Thurs - ) - -class NightlyCroniterImport(config.ConfigErrorsMixin, unittest.TestCase): - - def setUp(self): - self.savedModules = sys.modules.copy() - - def tearDown(self): - sys.modules.clear() - sys.modules.update(self.savedModules) - - def test_error_without_dateutil(self): - del sys.modules['buildbot.schedulers.timed'] - del sys.modules['buildbot.util'] - sys.modules["dateutil.relativedelta"] = None - from buildbot.schedulers.timed import NightlyBase - self.assertRaisesConfigError("python-dateutil", - lambda: NightlyBase(name='name', builderNames=[])) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyTriggerable.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyTriggerable.py deleted file mode 100644 index 68b7416e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_NightlyTriggerable.py +++ /dev/null @@ -1,309 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import task -from buildbot.process import properties -from buildbot.schedulers import timed -from buildbot.test.fake import fakedb -from buildbot.test.util import scheduler - -class NightlyTriggerable(scheduler.SchedulerMixin, unittest.TestCase): - - SCHEDULERID = 1327 - - def makeScheduler(self, firstBuildDuration=0, **kwargs): - sched = self.attachScheduler(timed.NightlyTriggerable(**kwargs), - self.SCHEDULERID) - - # add a Clock to help checking timing issues - self.clock = sched._reactor = task.Clock() - - return sched - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - - def test_timer_noBuilds(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5]) - - sched.startService() - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildsets(0) - - - def test_timer_oneTrigger(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - - sched.startService() - - sched.trigger({'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, set_props=None) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev', sourcestampsetid=100) - }) - - - def test_timer_twoTriggers(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - - sched.startService() - - sched.trigger({ 'cb': - dict(revision='myrev1', branch='br', project='p', repository='r') - } , set_props=None) - sched.trigger({ 'cb': - dict(revision='myrev2', branch='br', project='p', repository='r') - } , set_props=None) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev2', sourcestampsetid=100) - }) - - - def test_timer_oneTrigger_then_noBuild(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - - sched.startService() - - sched.trigger({ 'cb': - dict(revision='myrev', branch='br', project='p', repository='r') - } , set_props=None) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev', sourcestampsetid=100) - }) - - self.db.buildsets.flushBuildsets() - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildsets(0) - - - def test_timer_oneTriggers_then_oneTrigger(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - - sched.startService() - - sched.trigger({ 'cb': - dict(revision='myrev1', branch='br', project='p', repository='r') - } , set_props=None) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev1', sourcestampsetid=100) - }) - self.db.buildsets.flushBuildsets() - - sched.trigger({ 'cb': - dict(revision='myrev2', branch='br', project='p', repository='r') - } , set_props=None) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=101), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev2', sourcestampsetid=101) - }) - - def test_savedTrigger(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - self.db.insertTestData([ - fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), - fakedb.ObjectState(objectid=self.SCHEDULERID, name='lastTrigger', - value_json='[ {"cb": {"project": "p", "repository": "r", "branch": "br", "revision": "myrev"}} , {} ]'), - ]) - - sched.startService() - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev', sourcestampsetid=100) - }) - - def test_saveTrigger(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - self.db.insertTestData([ - fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), - ]) - - sched.startService() - - d = sched.trigger({'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, set_props=None) - - @d.addCallback - def cb(_): - self.db.state.assertState(self.SCHEDULERID, lastTrigger=[{'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, {}]) - - return d - - def test_saveTrigger_noTrigger(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - self.db.insertTestData([ - fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), - ]) - - sched.startService() - - d = sched.trigger({'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, set_props=None) - - self.clock.advance(60*60) # Run for 1h - - @d.addCallback - def cb(_): - self.db.state.assertState(self.SCHEDULERID, lastTrigger=None) - - return d - - def test_triggerProperties(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - self.db.insertTestData([ - fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), - ]) - - sched.startService() - - sched.trigger({'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, properties.Properties(testprop='test')) - - self.db.state.assertState(self.SCHEDULERID, lastTrigger=[{'cb': - dict(revision='myrev', - branch='br', project='p', repository='r'), - }, {'testprop': ['test', 'TEST']}]) - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ('testprop', ('test', 'TEST')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev', sourcestampsetid=100) - }) - - def test_savedProperties(self): - sched = self.makeScheduler(name='test', builderNames=['test'], - minute=[5], codebases={'cb':{'repository':'annoying'}}) - self.db.insertTestData([ - fakedb.Object(id=self.SCHEDULERID, name='test', class_name='NightlyTriggerable'), - fakedb.ObjectState(objectid=self.SCHEDULERID, name='lastTrigger', - value_json='[ {"cb": {"project": "p", "repository": "r", "branch": "br", "revision": "myrev"}} , {"testprop": ["test", "TEST"]} ]'), - ]) - - sched.startService() - - self.clock.advance(60*60) # Run for 1h - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('scheduler', ('test', 'Scheduler')), - ('testprop', ('test', 'TEST')), - ], - reason="The NightlyTriggerable scheduler named 'test' triggered this build", - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev', sourcestampsetid=100) - }) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Periodic.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Periodic.py deleted file mode 100644 index 5139a96a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Periodic.py +++ /dev/null @@ -1,173 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import task, defer -from buildbot.schedulers import timed -from buildbot import config - -class Periodic(unittest.TestCase): - - def makeScheduler(self, firstBuildDuration=0, exp_branch=None, **kwargs): - self.sched = sched = timed.Periodic(**kwargs) - - # add a Clock to help checking timing issues - self.clock = sched._reactor = task.Clock() - - # keep track of builds in self.events - self.events = [] - def addBuildsetForLatest(reason=None, branch=None): - self.assertIn('Periodic scheduler named', reason) - self.assertEqual(branch, exp_branch) - isFirst = (self.events == []) - self.events.append('B@%d' % self.clock.seconds()) - if isFirst and firstBuildDuration: - d = defer.Deferred() - self.clock.callLater(firstBuildDuration, d.callback, None) - return d - else: - return defer.succeed(None) - sched.addBuildsetForLatest = addBuildsetForLatest - - # handle state locally - self.state = {} - - def getState(k, default): - return defer.succeed(self.state.get(k, default)) - sched.getState = getState - - def setState(k, v): - self.state[k] = v - return defer.succeed(None) - sched.setState = setState - - return sched - - # tests - - def test_constructor_invalid(self): - self.assertRaises(config.ConfigErrors, - lambda : timed.Periodic(name='test', builderNames=[ 'test' ], - periodicBuildTimer=-2)) - - def test_iterations_simple(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13) - - sched.startService() - self.clock.advance(0) # let it trigger the first build - while self.clock.seconds() < 30: - self.clock.advance(1) - self.assertEqual(self.events, [ 'B@0', 'B@13', 'B@26' ]) - self.assertEqual(self.state.get('last_build'), 26) - - d = sched.stopService() - return d - - def test_iterations_simple_branch(self): - sched = self.makeScheduler(exp_branch='newfeature', - name='test', builderNames=[ 'test' ], - periodicBuildTimer=13, branch='newfeature') - - sched.startService() - self.clock.advance(0) # let it trigger the first build - while self.clock.seconds() < 30: - self.clock.advance(1) - self.assertEqual(self.events, [ 'B@0', 'B@13', 'B@26' ]) - self.assertEqual(self.state.get('last_build'), 26) - - d = sched.stopService() - return d - - def test_iterations_long(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=10, - firstBuildDuration=15) # takes a while to start a build - - sched.startService() - self.clock.advance(0) # let it trigger the first (longer) build - while self.clock.seconds() < 40: - self.clock.advance(1) - self.assertEqual(self.events, [ 'B@0', 'B@15', 'B@25', 'B@35' ]) - self.assertEqual(self.state.get('last_build'), 35) - - d = sched.stopService() - return d - - def test_iterations_stop_while_starting_build(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13, - firstBuildDuration=6) # takes a while to start a build - - sched.startService() - self.clock.advance(0) # let it trigger the first (longer) build - self.clock.advance(3) # get partway into that build - - d = sched.stopService() # begin stopping the service - d.addCallback(lambda _ : self.events.append('STOP@%d' % self.clock.seconds())) - - # run the clock out - while self.clock.seconds() < 40: - self.clock.advance(1) - - # note that the stopService completes after the first build completes, and no - # subsequent builds occur - self.assertEqual(self.events, [ 'B@0', 'STOP@6' ]) - self.assertEqual(self.state.get('last_build'), 0) - - return d - - def test_iterations_with_initial_state(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13) - self.state['last_build'] = self.clock.seconds() - 7 # so next build should start in 6s - - sched.startService() - self.clock.advance(0) # let it trigger the first build - while self.clock.seconds() < 30: - self.clock.advance(1) - self.assertEqual(self.events, [ 'B@6', 'B@19' ]) - self.assertEqual(self.state.get('last_build'), 19) - - d = sched.stopService() - return d - - def test_getNextBuildTime_None(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13) - # given None, build right away - d = sched.getNextBuildTime(None) - d.addCallback(lambda t : self.assertEqual(t, 0)) - return d - - def test_getNextBuildTime_given(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13) - # given a time, add the periodicBuildTimer to it - d = sched.getNextBuildTime(20) - d.addCallback(lambda t : self.assertEqual(t, 33)) - return d - - def test_getPendingBuildTimes(self): - sched = self.makeScheduler(name='test', builderNames=[ 'test' ], - periodicBuildTimer=13) - self.state['last_build'] = self.clock.seconds() - 10 # so next build should start in 3s - - sched.startService() - self.clock.advance(0) # let it schedule the first build - self.assertEqual(sched.getPendingBuildTimes(), [ 3.0 ]) - - d = sched.stopService() - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Timed.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Timed.py deleted file mode 100644 index 54ecd70d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_timed_Timed.py +++ /dev/null @@ -1,62 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import task, defer -from buildbot.schedulers import timed -from buildbot.test.util import scheduler - -class Timed(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 928754 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - class Subclass(timed.Timed): - def getNextBuildTime(self, lastActuation): - self.got_lastActuation = lastActuation - return defer.succeed((lastActuation or 1000) + 60) - def startBuild(self): - self.started_build = True - return defer.succeed(None) - - def makeScheduler(self, firstBuildDuration=0, **kwargs): - sched = self.attachScheduler(self.Subclass(**kwargs), self.OBJECTID) - self.clock = sched._reactor = task.Clock() - return sched - - # tests - - # note that most of the heavy-lifting for testing this class is handled by - # the subclasses' tests, as that's the more natural place for it - - def test_getPendingBuildTimes(self): - sched = self.makeScheduler(name='test', builderNames=['foo']) - - sched.startService() - - self.assertEqual(sched.got_lastActuation, None) - self.assertEqual(sched.getPendingBuildTimes(), [ 1060 ]) - - self.clock.advance(1065) - self.assertTrue(sched.started_build) - self.assertEqual(sched.getPendingBuildTimes(), [ 1120 ]) - - d = sched.stopService() - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_triggerable.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_triggerable.py deleted file mode 100644 index eb225b5b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_triggerable.py +++ /dev/null @@ -1,211 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.schedulers import triggerable -from buildbot.process import properties -from buildbot.test.util import scheduler - -class Triggerable(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 33 - - def setUp(self): - self.setUpScheduler() - self.subscription = None - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, **kwargs): - sched = self.attachScheduler( - triggerable.Triggerable(name='n', builderNames=['b'], **kwargs), - self.OBJECTID) - - return sched - - # tests - - # NOTE: these tests take advantage of the fact that all of the fake - # scheduler operations are synchronous, and thus do not return a Deferred. - # The Deferred from trigger() is completely processed before this test - # method returns. - - def test_trigger(self): - sched = self.makeScheduler(codebases = {'cb':{'repository':'r'}}) - # no subscription should be in place yet - callbacks = self.master.getSubscriptionCallbacks() - self.assertEqual(callbacks['buildset_completion'], None) - - # trigger the scheduler, exercising properties while we're at it - set_props = properties.Properties() - set_props.setProperty('pr', 'op', 'test') - ss = {'revision':'myrev', - 'branch':'br', - 'project':'p', - 'repository':'r', - 'codebase':'cb' } - d = sched.trigger({'cb': ss}, set_props=set_props) - - bsid = self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[ - ('pr', ('op', 'test')), - ('scheduler', ('n', 'Scheduler')), - ], - reason='Triggerable(n)', - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', - codebase='cb', revision='myrev', sourcestampsetid=100) - }) - # set up a boolean so that we can know when the deferred fires - self.fired = False - def fired((result, brids)): - self.assertEqual(result, 13) # 13 comes from the result below - self.assertEqual(brids, self.db.buildsets.allBuildRequests(bsid)) - self.fired = True - d.addCallback(fired) - - # check that the scheduler has subscribed to buildset changes, but - # not fired yet - callbacks = self.master.getSubscriptionCallbacks() - self.assertNotEqual(callbacks['buildset_completion'], None) - self.assertFalse(self.fired) - - # pretend a non-matching buildset is complete - callbacks['buildset_completion'](bsid+27, 3) - - # scheduler should not have reacted - callbacks = self.master.getSubscriptionCallbacks() - self.assertNotEqual(callbacks['buildset_completion'], None) - self.assertFalse(self.fired) - - # pretend the matching buildset is complete - callbacks['buildset_completion'](bsid, 13) - - # scheduler should have reacted - callbacks = self.master.getSubscriptionCallbacks() - self.assertEqual(callbacks['buildset_completion'], None) - self.assertTrue(self.fired) - - def test_trigger_overlapping(self): - sched = self.makeScheduler(codebases = {'cb':{'repository':'r'}}) - - # no subscription should be in place yet - callbacks = self.master.getSubscriptionCallbacks() - self.assertEqual(callbacks['buildset_completion'], None) - - # define sourcestamp - ss = {'revision':'myrev1', - 'branch':'br', - 'project':'p', - 'repository':'r', - 'codebase':'cb' } - # trigger the scheduler the first time - d = sched.trigger({'cb':ss}) - bsid1 = self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - reason='Triggerable(n)', - sourcestampsetid=100), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev1', sourcestampsetid=100)}) - d.addCallback(lambda (res, brids) : self.assertEqual(res, 11) - and self.assertEqual(brids, self.db.buildsets.allBuildRequests(bsid1))) - - # define sourcestamp - ss = {'revision':'myrev2', - 'branch':'br', - 'project':'p', - 'repository':'r', - 'codebase':'cb' } - # and the second time - d = sched.trigger({'cb':ss}) - bsid2 = self.db.buildsets.assertBuildset(bsid1+1, # assumes bsid's are sequential - dict(external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - reason='Triggerable(n)', sourcestampsetid=101), - {'cb': - dict(branch='br', project='p', repository='r', codebase='cb', - revision='myrev2', sourcestampsetid=101)}) - d.addCallback(lambda (res, brids) : self.assertEqual(res, 22) - and self.assertEqual(brids, self.db.buildsets.allBuildRequests(bsid2))) - - # check that the scheduler has subscribed to buildset changes - callbacks = self.master.getSubscriptionCallbacks() - self.assertNotEqual(callbacks['buildset_completion'], None) - - # let a few buildsets complete - callbacks['buildset_completion'](bsid2+27, 3) - callbacks['buildset_completion'](bsid2, 22) - callbacks['buildset_completion'](bsid2+7, 3) - callbacks['buildset_completion'](bsid1, 11) - - # both should have triggered with appropriate results, and the - # subscription should be cancelled - callbacks = self.master.getSubscriptionCallbacks() - self.assertEqual(callbacks['buildset_completion'], None) - - def test_trigger_with_unknown_sourcestamp(self): - # Test a scheduler with 2 repositories. - # Trigger the scheduler with a sourcestamp that is unknown to the scheduler - # Expected Result: - # sourcestamp 1 for repository 1 based on configured sourcestamp - # sourcestamp 2 for repository 2 based on configured sourcestamp - sched = self.makeScheduler( - codebases = {'cb':{'repository':'r', 'branch': 'branchX'}, - 'cb2':{'repository':'r2', 'branch': 'branchX'},}) - - ss = {'repository': 'r3', 'codebase': 'cb3', 'revision': 'fixrev3', - 'branch': 'default', 'project': 'p' } - sched.trigger(sourcestamps = {'cb3': ss}) - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - reason='Triggerable(n)', - sourcestampsetid=100), - {'cb': - dict(branch='branchX', project='', repository='r', codebase='cb', - revision=None, sourcestampsetid=100), - 'cb2': - dict(branch='branchX', project='', repository='r2', codebase='cb2', - revision=None, sourcestampsetid=100),}) - - def test_trigger_without_sourcestamps(self): - # Test a scheduler with 2 repositories. - # Trigger the scheduler without a sourcestamp - # Expected Result: - # sourcestamp 1 for repository 1 based on configured sourcestamp - # sourcestamp 2 for repository 2 based on configured sourcestamp - sched = self.makeScheduler( - codebases = {'cb':{'repository':'r', 'branch': 'branchX'}, - 'cb2':{'repository':'r2', 'branch': 'branchX'},}) - - sched.trigger(sourcestamps = None) - - self.db.buildsets.assertBuildset('?', - dict(external_idstring=None, - properties=[('scheduler', ('n', 'Scheduler'))], - reason='Triggerable(n)', - sourcestampsetid=100), - {'cb': - dict(branch='branchX', project='', repository='r', codebase='cb', - revision=None, sourcestampsetid=100), - 'cb2': - dict(branch='branchX', project='', repository='r2', codebase='cb2', - revision=None, sourcestampsetid=100),})
\ No newline at end of file diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_trysched.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_trysched.py deleted file mode 100644 index 1aaa5b34..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_schedulers_trysched.py +++ /dev/null @@ -1,727 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import mock -import os -import shutil -import cStringIO as StringIO -import sys - -import twisted -from twisted.internet import defer -from twisted.trial import unittest -from twisted.protocols import basic -from buildbot.schedulers import trysched -from buildbot.test.util import dirs -from buildbot.test.util import scheduler -from buildbot.util import json - - -class TryBase(unittest.TestCase): - - def test_filterBuilderList_ok(self): - sched = trysched.TryBase( - name='tsched', builderNames=['a', 'b', 'c'], properties={}) - self.assertEqual(sched.filterBuilderList(['b', 'c']), ['b', 'c']) - - def test_filterBuilderList_bad(self): - sched = trysched.TryBase( - name='tsched', builderNames=['a', 'b'], properties={}) - self.assertEqual(sched.filterBuilderList(['b', 'c']), []) - - def test_filterBuilderList_empty(self): - sched = trysched.TryBase( - name='tsched', builderNames=['a', 'b'], properties={}) - self.assertEqual(sched.filterBuilderList([]), ['a', 'b']) - - -class JobdirService(dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.jobdir = 'jobdir' - self.newdir = os.path.join(self.jobdir, 'new') - self.curdir = os.path.join(self.jobdir, 'cur') - self.tmpdir = os.path.join(self.jobdir, 'tmp') - self.setUpDirs(self.jobdir, self.newdir, self.curdir, self.tmpdir) - - def tearDown(self): - self.tearDownDirs() - - def test_messageReceived(self): - svc = trysched.JobdirService(self.jobdir) - - # creat some new data to process - jobdata = os.path.join(self.newdir, 'jobdata') - with open(jobdata, "w") as f: - f.write('JOBDATA') - - # stub out svc.parent.handleJobFile and .jobdir - def handleJobFile(filename, f): - self.assertEqual(filename, 'jobdata') - self.assertEqual(f.read(), 'JOBDATA') - svc.parent = mock.Mock() - svc.parent.handleJobFile = handleJobFile - svc.parent.jobdir = self.jobdir - - # run it - svc.messageReceived('jobdata') - - -class Try_Jobdir(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 23 - - def setUp(self): - self.setUpScheduler() - self.jobdir = None - - def tearDown(self): - self.tearDownScheduler() - if self.jobdir: - shutil.rmtree(self.jobdir) - - # tests - - def do_test_startService(self, jobdir, exp_jobdir): - # set up jobdir - self.jobdir = os.path.abspath('jobdir') - if os.path.exists(self.jobdir): - shutil.rmtree(self.jobdir) - os.mkdir(self.jobdir) - - # build scheduler - kwargs = dict(name="tsched", builderNames=['a'], jobdir=self.jobdir) - sched = self.attachScheduler( - trysched.Try_Jobdir(**kwargs), self.OBJECTID) - - # start it - sched.startService() - - # check that it has set the basedir correctly - self.assertEqual(sched.watcher.basedir, self.jobdir) - - return sched.stopService() - - def test_startService_reldir(self): - return self.do_test_startService( - 'jobdir', - os.path.abspath('basedir/jobdir')) - - def test_startService_reldir_subdir(self): - return self.do_test_startService( - 'jobdir', - os.path.abspath('basedir/jobdir/cur')) - - def test_startService_absdir(self): - return self.do_test_startService( - os.path.abspath('jobdir'), - os.path.abspath('jobdir')) - - # parseJob - - def test_parseJob_empty(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['a'], jobdir='foo') - self.assertRaises( - trysched.BadJobfile, sched.parseJob, StringIO.StringIO('')) - - def test_parseJob_longer_than_netstring_MAXLENGTH(self): - self.patch(basic.NetstringReceiver, 'MAX_LENGTH', 100) - sched = trysched.Try_Jobdir(name='tsched', builderNames=['a'], jobdir='foo') - jobstr = self.makeNetstring( - '1', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'buildera', 'builderc' - ) - jobstr += 'x' * 200 - - test_temp_file = StringIO.StringIO(jobstr) - - self.assertRaises(trysched.BadJobfile, - lambda : sched.parseJob(test_temp_file)) - - def test_parseJob_invalid(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['a'], jobdir='foo') - self.assertRaises( - trysched.BadJobfile, sched.parseJob, - StringIO.StringIO('this is not a netstring')) - - def test_parseJob_invalid_version(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['a'], jobdir='foo') - self.assertRaises( - trysched.BadJobfile, sched.parseJob, StringIO.StringIO('1:9,')) - - def makeNetstring(self, *strings): - return ''.join(['%d:%s,' % (len(s), s) for s in strings]) - - def test_parseJob_v1(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '1', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob, { - 'baserev': '1234', - 'branch': 'trunk', - 'builderNames': ['buildera', 'builderc'], - 'jobid': 'extid', - 'patch_body': 'this is my diff, -- ++, etc.', - 'patch_level': 1, - 'project': '', - 'who': '', - 'comment': '', - 'repository': '', - 'properties': {}, - }) - - def test_parseJob_v1_empty_branch_rev(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - # blank branch, rev are turned to None - '1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['branch'], None) - self.assertEqual(parsedjob['baserev'], None) - - def test_parseJob_v1_no_builders(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['builderNames'], []) - - def test_parseJob_v1_no_properties(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '1', 'extid', '', '', '1', 'this is my diff, -- ++, etc.' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['properties'], {}) - - def test_parseJob_v2(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob, { - 'baserev': '1234', - 'branch': 'trunk', - 'builderNames': ['buildera', 'builderc'], - 'jobid': 'extid', - 'patch_body': 'this is my diff, -- ++, etc.', - 'patch_level': 1, - 'project': 'proj', - 'who': '', - 'comment': '', - 'repository': 'repo', - 'properties': {}, - }) - - def test_parseJob_v2_empty_branch_rev(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - # blank branch, rev are turned to None - '2', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['branch'], None) - self.assertEqual(parsedjob['baserev'], None) - - def test_parseJob_v2_no_builders(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['builderNames'], []) - - def test_parseJob_v2_no_properties(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '2', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['properties'], {}) - - def test_parseJob_v3(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob, { - 'baserev': '1234', - 'branch': 'trunk', - 'builderNames': ['buildera', 'builderc'], - 'jobid': 'extid', - 'patch_body': 'this is my diff, -- ++, etc.', - 'patch_level': 1, - 'project': 'proj', - 'who': 'who', - 'comment': '', - 'repository': 'repo', - 'properties': {}, - }) - - def test_parseJob_v3_empty_branch_rev(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - # blank branch, rev are turned to None - '3', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['branch'], None) - self.assertEqual(parsedjob['baserev'], None) - - def test_parseJob_v3_no_builders(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['builderNames'], []) - - def test_parseJob_v3_no_properties(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '3', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['properties'], {}) - - def test_parseJob_v4(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', 'comment', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob, { - 'baserev': '1234', - 'branch': 'trunk', - 'builderNames': ['buildera', 'builderc'], - 'jobid': 'extid', - 'patch_body': 'this is my diff, -- ++, etc.', - 'patch_level': 1, - 'project': 'proj', - 'who': 'who', - 'comment': 'comment', - 'repository': 'repo', - 'properties': {}, - }) - - def test_parseJob_v4_empty_branch_rev(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - # blank branch, rev are turned to None - '4', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', 'comment', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['branch'], None) - self.assertEqual(parsedjob['baserev'], None) - - def test_parseJob_v4_no_builders(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', 'comment' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['builderNames'], []) - - def test_parseJob_v4_no_properties(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '4', 'extid', 'trunk', '1234', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', 'comment' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['properties'], {}) - - def test_parseJob_v5(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '5', - json.dumps({ - 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', - 'patch_level': 1, 'patch_body': 'this is my diff, -- ++, etc.', - 'repository': 'repo', 'project': 'proj', 'who': 'who', - 'comment': 'comment', 'builderNames': ['buildera', 'builderc'], - 'properties': {'foo': 'bar'}, - })) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob, { - 'baserev': '1234', - 'branch': 'trunk', - 'builderNames': ['buildera', 'builderc'], - 'jobid': 'extid', - 'patch_body': 'this is my diff, -- ++, etc.', - 'patch_level': 1, - 'project': 'proj', - 'who': 'who', - 'comment': 'comment', - 'repository': 'repo', - 'properties': {'foo': 'bar'}, - }) - - def test_parseJob_v5_empty_branch_rev(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - # blank branch, rev are turned to None - '4', 'extid', '', '', '1', 'this is my diff, -- ++, etc.', - 'repo', 'proj', 'who', 'comment', - 'buildera', 'builderc' - ) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['branch'], None) - self.assertEqual(parsedjob['baserev'], None) - - def test_parseJob_v5_no_builders(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '5', - json.dumps({ - 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', - 'patch_level': '1', 'diff': 'this is my diff, -- ++, etc.', - 'repository': 'repo', 'project': 'proj', 'who': 'who', - 'comment': 'comment', 'builderNames': [], - 'properties': {'foo': 'bar'}, - })) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['builderNames'], []) - - def test_parseJob_v5_no_properties(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring( - '5', - json.dumps({ - 'jobid': 'extid', 'branch': 'trunk', 'baserev': '1234', - 'patch_level': '1', 'diff': 'this is my diff, -- ++, etc.', - 'repository': 'repo', 'project': 'proj', 'who': 'who', - 'comment': 'comment', 'builderNames': ['buildera', 'builderb'], - 'properties': {}, - })) - parsedjob = sched.parseJob(StringIO.StringIO(jobstr)) - self.assertEqual(parsedjob['properties'], {}) - - def test_parseJob_v5_invalid_json(self): - sched = trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], jobdir='foo') - jobstr = self.makeNetstring('5', '{"comment": "com}') - self.assertRaises( - trysched.BadJobfile, sched.parseJob, StringIO.StringIO(jobstr)) - - # handleJobFile - - def call_handleJobFile(self, parseJob): - sched = self.attachScheduler( - trysched.Try_Jobdir( - name='tsched', builderNames=['buildera', 'builderb'], - jobdir='foo'), self.OBJECTID) - fakefile = mock.Mock() - - def parseJob_(f): - assert f is fakefile - return parseJob(f) - sched.parseJob = parseJob_ - return sched.handleJobFile('fakefile', fakefile) - - def makeSampleParsedJob(self, **overrides): - pj = dict(baserev='1234', branch='trunk', - builderNames=['buildera', 'builderb'], - jobid='extid', patch_body='this is my diff, -- ++, etc.', - patch_level=1, project='proj', repository='repo', who='who', - comment='comment', properties={}) - pj.update(overrides) - return pj - - def test_handleJobFile(self): - d = self.call_handleJobFile(lambda f: self.makeSampleParsedJob()) - - def check(_): - self.db.buildsets.assertBuildset('?', - dict(reason="'try' job by user who", - external_idstring='extid', - properties=[('scheduler', ('tsched', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='repo', codebase='', - project='proj', revision='1234', - patch_body='this is my diff, -- ++, etc.', - patch_level=1, patch_subdir='', - patch_author='who', - patch_comment='comment', - sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_handleJobFile_exception(self): - def parseJob(f): - raise trysched.BadJobfile - d = self.call_handleJobFile(parseJob) - - def check(bsid): - self.db.buildsets.assertBuildsets(0) - self.assertEqual( - 1, len(self.flushLoggedErrors(trysched.BadJobfile))) - d.addCallback(check) - return d - if twisted.version.major <= 9 and sys.version_info[:2] >= (2, 7): - test_handleJobFile_exception.skip = ( - "flushLoggedErrors does not work correctly on 9.0.0 " - "and earlier with Python-2.7") - - def test_handleJobFile_bad_builders(self): - d = self.call_handleJobFile( - lambda f: self.makeSampleParsedJob(builderNames=['xxx'])) - - def check(_): - self.db.buildsets.assertBuildsets(0) - d.addCallback(check) - return d - - def test_handleJobFile_subset_builders(self): - d = self.call_handleJobFile( - lambda f: self.makeSampleParsedJob(builderNames=['buildera'])) - - def check(_): - self.db.buildsets.assertBuildset('?', - dict(reason="'try' job by user who", - external_idstring='extid', - properties=[('scheduler', ('tsched', 'Scheduler'))], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='repo', codebase='', - project='proj', revision='1234', - patch_body='this is my diff, -- ++, etc.', - patch_level=1, patch_subdir='', - patch_author='who', - patch_comment='comment', - sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_handleJobFile_with_try_properties(self): - d = self.call_handleJobFile( - lambda f: self.makeSampleParsedJob(properties={'foo': 'bar'})) - - def check(_): - self.db.buildsets.assertBuildset('?', - dict(reason="'try' job by user who", - external_idstring='extid', - properties=[ - ('foo', ('bar', 'try build')), - ('scheduler', ('tsched', 'Scheduler')), - ], - sourcestampsetid=100), - {'': - dict(branch='trunk', repository='repo', codebase='', - project='proj', revision='1234', - patch_body='this is my diff, -- ++, etc.', - patch_level=1, patch_subdir='', - patch_author='who', - patch_comment='comment', - sourcestampsetid=100) - }) - d.addCallback(check) - return d - - def test_handleJobFile_with_invalid_try_properties(self): - d = self.call_handleJobFile( - lambda f: self.makeSampleParsedJob(properties=['foo', 'bar'])) - return self.assertFailure(d, AttributeError) - - -class Try_Userpass_Perspective(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 26 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, **kwargs): - sched = self.attachScheduler(trysched.Try_Userpass(**kwargs), - self.OBJECTID) - # Try will return a remote version of master.status, so give it - # something to return - sched.master.status = mock.Mock() - return sched - - def call_perspective_try(self, *args, **kwargs): - sched = self.makeScheduler(name='tsched', builderNames=['a', 'b'], - port='xxx', userpass=[('a', 'b')], properties=dict(frm='schd')) - persp = trysched.Try_Userpass_Perspective(sched, 'a') - return persp.perspective_try(*args, **kwargs) - - def test_perspective_try(self): - d = self.call_perspective_try( - 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['a'], - properties={'pr': 'op'}) - - def check(_): - self.db.buildsets.assertBuildset('?', - dict(reason="'try' job", - external_idstring=None, - properties=[ - ('frm', ('schd', 'Scheduler')), - ('pr', ('op', 'try build')), - ('scheduler', ('tsched', 'Scheduler')), - ], - sourcestampsetid=100, - ), - {'': - dict(branch='default', repository='repo', codebase='', - project='proj', revision='abcdef', - sourcestampsetid=100, - patch_body='-- ++', patch_level=1, patch_subdir='', - patch_author="", patch_comment="") - }) - d.addCallback(check) - return d - - def test_perspective_try_who(self): - d = self.call_perspective_try( - 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['a'], - who='who', comment='comment', properties={'pr': 'op'}) - - def check(_): - self.db.buildsets.assertBuildset('?', - dict(reason="'try' job by user who (comment)", - external_idstring=None, - properties=[ - ('frm', ('schd', 'Scheduler')), - ('pr', ('op', 'try build')), - ('scheduler', ('tsched', 'Scheduler')), - ], - sourcestampsetid=100, - ), - {'': - dict(branch='default', repository='repo', codebase='', - project='proj', revision='abcdef', - sourcestampsetid=100, - patch_body='-- ++', patch_level=1, patch_subdir='', - patch_author='who', patch_comment="comment") - }) - d.addCallback(check) - return d - - def test_perspective_try_bad_builders(self): - d = self.call_perspective_try( - 'default', 'abcdef', (1, '-- ++'), 'repo', 'proj', ['xxx'], - properties={'pr': 'op'}) - - def check(_): - self.db.buildsets.assertBuildsets(0) - d.addCallback(check) - return d - - def test_getAvailableBuilderNames(self): - sched = self.makeScheduler(name='tsched', builderNames=['a', 'b'], - port='xxx', userpass=[('a', 'b')]) - persp = trysched.Try_Userpass_Perspective(sched, 'a') - d = defer.maybeDeferred( - lambda: persp.perspective_getAvailableBuilderNames()) - - def check(buildernames): - self.assertEqual(buildernames, ['a', 'b']) - d.addCallback(check) - return d - - -class Try_Userpass(scheduler.SchedulerMixin, unittest.TestCase): - - OBJECTID = 25 - - def setUp(self): - self.setUpScheduler() - - def tearDown(self): - self.tearDownScheduler() - - def makeScheduler(self, **kwargs): - sched = self.attachScheduler(trysched.Try_Userpass(**kwargs), - self.OBJECTID) - return sched - - def test_service(self): - sched = self.makeScheduler(name='tsched', builderNames=['a'], - port='tcp:9999', userpass=[('fred', 'derf')]) - # patch out the pbmanager's 'register' command both to be sure - # the registration is correct and to get a copy of the factory - registration = mock.Mock() - registration.unregister = lambda: defer.succeed(None) - sched.master.pbmanager = mock.Mock() - - def register(portstr, user, passwd, factory): - self.assertEqual([portstr, user, passwd], - ['tcp:9999', 'fred', 'derf']) - self.got_factory = factory - return registration - sched.master.pbmanager.register = register - # start it - sched.startService() - # make a fake connection by invoking the factory, and check that we - # get the correct perspective - persp = self.got_factory(mock.Mock(), 'fred') - self.failUnless(isinstance(persp, trysched.Try_Userpass_Perspective)) - return sched.stopService() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_base.py deleted file mode 100644 index 7d7d22de..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_base.py +++ /dev/null @@ -1,268 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import string -import cStringIO -import textwrap -from twisted.trial import unittest -from buildbot.scripts import base -from buildbot.test.util import dirs, misc -from twisted.python import usage, runtime - -class TestIBD(dirs.DirsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpDirs('test') - self.stdout = cStringIO.StringIO() - self.setUpStdoutAssertions() - - def test_isBuildmasterDir_no_dir(self): - self.assertFalse(base.isBuildmasterDir(os.path.abspath('test/nosuch'))) - self.assertInStdout('error reading') - self.assertInStdout('invalid buildmaster directory') - - def test_isBuildmasterDir_no_file(self): - self.assertFalse(base.isBuildmasterDir(os.path.abspath('test'))) - self.assertInStdout('error reading') - self.assertInStdout('invalid buildmaster directory') - - def test_isBuildmasterDir_no_Application(self): - with open(os.path.join('test', 'buildbot.tac'), 'w') as f: - f.write("foo\nx = Application('buildslave')\nbar") - self.assertFalse(base.isBuildmasterDir(os.path.abspath('test'))) - self.assertInStdout('unexpected content') - self.assertInStdout('invalid buildmaster directory') - - def test_isBuildmasterDir_matches(self): - with open(os.path.join('test', 'buildbot.tac'), 'w') as f: - f.write("foo\nx = Application('buildmaster')\nbar") - self.assertTrue(base.isBuildmasterDir(os.path.abspath('test'))) - self.assertWasQuiet() - -class TestTacFallback(dirs.DirsMixin, unittest.TestCase): - """ - Tests for L{base.getConfigFileFromTac}. - """ - - def setUp(self): - """ - Create a base directory. - """ - self.basedir = os.path.abspath('basedir') - return self.setUpDirs('basedir') - - def _createBuildbotTac(self, contents=None): - """ - Create a C{buildbot.tac} that points to a given C{configfile} - and create that file. - - @param configfile: Config file to point at and create. - @type configfile: L{str} - """ - if contents is None: - contents = '#dummy' - tacfile = os.path.join(self.basedir, "buildbot.tac") - with open(tacfile, "wt") as f: - f.write(contents) - return tacfile - - - def test_getConfigFileFromTac(self): - """ - When L{getConfigFileFromTac} is passed a C{basedir} - containing a C{buildbot.tac}, it reads the location - of the config file from there. - """ - self._createBuildbotTac("configfile='other.cfg'") - foundConfigFile = base.getConfigFileFromTac( - basedir=self.basedir) - self.assertEqual(foundConfigFile, "other.cfg") - - def test_getConfigFileFromTac_fallback(self): - """ - When L{getConfigFileFromTac} is passed a C{basedir} - which doesn't contain a C{buildbot.tac}, - it returns C{master.cfg} - """ - foundConfigFile = base.getConfigFileFromTac( - basedir=self.basedir) - self.assertEqual(foundConfigFile, 'master.cfg') - - - def test_getConfigFileFromTac_tacWithoutConfigFile(self): - """ - When L{getConfigFileFromTac} is passed a C{basedir} - containing a C{buildbot.tac}, but C{buildbot.tac} doesn't - define C{configfile}, L{getConfigFileFromTac} returns C{master.cfg} - """ - self._createBuildbotTac() - foundConfigFile = base.getConfigFileFromTac( - basedir=self.basedir) - self.assertEqual(foundConfigFile, 'master.cfg') - - - def test_getConfigFileFromTac_usingFile(self): - """ - Wehn L{getConfigFileFromTac} is passed a C{basedir} - containing a C{buildbot.tac} which references C{__file__}, - that reference points to C{buildbot.tac}. - """ - self._createBuildbotTac(textwrap.dedent(""" - from twisted.python.util import sibpath - configfile = sibpath(__file__, "relative.cfg") - """)) - foundConfigFile = base.getConfigFileFromTac(basedir=self.basedir) - self.assertEqual(foundConfigFile, os.path.join(self.basedir, "relative.cfg")) - - - -class TestSubcommandOptions(unittest.TestCase): - - def fakeOptionsFile(self, **kwargs): - self.patch(base.SubcommandOptions, 'loadOptionsFile', - lambda self : kwargs.copy()) - - def parse(self, cls, *args): - self.opts = cls() - self.opts.parseOptions(args) - return self.opts - - class Bare(base.SubcommandOptions): - optFlags = [ [ 'foo', 'f', 'Foo!' ] ] - - def test_bare_subclass(self): - self.fakeOptionsFile() - opts = self.parse(self.Bare, '-f') - self.assertTrue(opts['foo']) - - class ParamsAndOptions(base.SubcommandOptions): - optParameters = [ [ 'volume', 'v', '5', 'How Loud?' ] ] - buildbotOptions = [ [ 'volcfg', 'volume' ] ] - - def test_buildbotOptions(self): - self.fakeOptionsFile() - opts = self.parse(self.ParamsAndOptions) - self.assertEqual(opts['volume'], '5') - - def test_buildbotOptions_options(self): - self.fakeOptionsFile(volcfg='3') - opts = self.parse(self.ParamsAndOptions) - self.assertEqual(opts['volume'], '3') - - def test_buildbotOptions_override(self): - self.fakeOptionsFile(volcfg='3') - opts = self.parse(self.ParamsAndOptions, '--volume', '7') - self.assertEqual(opts['volume'], '7') - - class RequiredOptions(base.SubcommandOptions): - optParameters = [ [ 'volume', 'v', None, 'How Loud?' ] ] - requiredOptions = [ 'volume' ] - - def test_requiredOptions(self): - self.fakeOptionsFile() - self.assertRaises(usage.UsageError, - lambda : self.parse(self.RequiredOptions)) - -class TestLoadOptionsFile(dirs.DirsMixin, misc.StdoutAssertionsMixin, - unittest.TestCase): - - def setUp(self): - self.setUpDirs('test', 'home') - self.opts = base.SubcommandOptions() - self.dir = os.path.abspath('test') - self.home = os.path.abspath('home') - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - def do_loadOptionsFile(self, _here, exp): - # only patch these os.path functions briefly, to - # avoid breaking other parts of the test system - patches = [] - - if runtime.platformType == 'win32': - from win32com.shell import shell - patches.append(self.patch(shell, 'SHGetFolderPath', - lambda *args : self.home)) - else: - def expanduser(p): - return p.replace('~/', self.home + '/') - patches.append(self.patch(os.path, 'expanduser', expanduser)) - - old_dirname = os.path.dirname - def dirname(p): - # bottom out at self.dir, rather than / - if p == self.dir: - return p - return old_dirname(p) - patches.append(self.patch(os.path, 'dirname', dirname)) - - try: - self.assertEqual(self.opts.loadOptionsFile(_here=_here), exp) - finally: - for p in patches: - p.restore() - - def writeOptionsFile(self, dir, content, bbdir='.buildbot'): - os.makedirs(os.path.join(dir, bbdir)) - with open(os.path.join(dir, bbdir, 'options'), 'w') as f: - f.write(content) - - def test_loadOptionsFile_subdirs_not_found(self): - subdir = os.path.join(self.dir, 'a', 'b') - os.makedirs(subdir) - self.do_loadOptionsFile(_here=subdir, exp={}) - - def test_loadOptionsFile_subdirs_at_root(self): - subdir = os.path.join(self.dir, 'a', 'b') - os.makedirs(subdir) - self.writeOptionsFile(self.dir, 'abc="def"') - self.writeOptionsFile(self.home, 'abc=123') # not seen - self.do_loadOptionsFile(_here=subdir, exp={'abc':'def'}) - - def test_loadOptionsFile_subdirs_at_tip(self): - subdir = os.path.join(self.dir, 'a', 'b') - os.makedirs(subdir) - self.writeOptionsFile(os.path.join(self.dir, 'a', 'b'), 'abc="def"') - self.writeOptionsFile(self.dir, 'abc=123') # not seen - self.do_loadOptionsFile(_here=subdir, exp={'abc':'def'}) - - def test_loadOptionsFile_subdirs_at_homedir(self): - subdir = os.path.join(self.dir, 'a', 'b') - os.makedirs(subdir) - # on windows, the subdir of the home (well, appdata) dir - # is 'buildbot', not '.buildbot' - self.writeOptionsFile(self.home, 'abc=123', - 'buildbot' if runtime.platformType == 'win32' else '.buildbot') - self.do_loadOptionsFile(_here=subdir, exp={'abc':123}) - - def test_loadOptionsFile_syntax_error(self): - self.writeOptionsFile(self.dir, 'abc=abc') - self.assertRaises(NameError, lambda : - self.do_loadOptionsFile(_here=self.dir, exp={})) - self.assertInStdout('error while reading') - - def test_loadOptionsFile_toomany(self): - subdir = os.path.join(self.dir, *tuple(string.lowercase)) - os.makedirs(subdir) - self.do_loadOptionsFile(_here=subdir, exp={}) - self.assertInStdout('infinite glories') - - # NOTE: testing the ownership check requires patching os.stat, which causes - # other problems since it is so heavily used. diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_checkconfig.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_checkconfig.py deleted file mode 100644 index c6bf3bde..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_checkconfig.py +++ /dev/null @@ -1,169 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import mock -import re -import sys -import os -import textwrap -import cStringIO -from twisted.trial import unittest -from buildbot.test.util import dirs, compat -from buildbot.scripts import base, checkconfig - -class TestConfigLoader(dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - return self.setUpDirs('configdir') - - def tearDown(self): - return self.tearDownDirs() - - # tests - - def do_test_load(self, config='', other_files={}, - stdout_re=None, stderr_re=None): - configFile = os.path.join('configdir', 'master.cfg') - with open(configFile, "w") as f: - f.write(config) - for filename, contents in other_files.iteritems(): - if type(filename) == type(()): - fn = os.path.join('configdir', *filename) - dn = os.path.dirname(fn) - if not os.path.isdir(dn): - os.makedirs(dn) - else: - fn = os.path.join('configdir', filename) - with open(fn, "w") as f: - f.write(contents) - - old_stdout, old_stderr = sys.stdout, sys.stderr - stdout = sys.stdout = cStringIO.StringIO() - stderr = sys.stderr = cStringIO.StringIO() - try: - checkconfig._loadConfig( - basedir='configdir', configFile="master.cfg", quiet=False) - finally: - sys.stdout, sys.stderr = old_stdout, old_stderr - if stdout_re: - stdout = stdout.getvalue() - self.failUnless(stdout_re.search(stdout), stdout) - if stderr_re: - stderr = stderr.getvalue() - self.failUnless(stderr_re.search(stderr), stderr) - - def test_success(self): - len_sys_path = len(sys.path) - config = textwrap.dedent("""\ - c = BuildmasterConfig = {} - c['multiMaster'] = True - c['schedulers'] = [] - from buildbot.config import BuilderConfig - from buildbot.process.factory import BuildFactory - c['builders'] = [ - BuilderConfig('testbuilder', factory=BuildFactory(), - slavename='sl'), - ] - from buildbot.buildslave import BuildSlave - c['slaves'] = [ - BuildSlave('sl', 'pass'), - ] - c['slavePortnum'] = 9989 - """) - self.do_test_load(config=config, - stdout_re=re.compile('Config file is good!')) - - # (regression) check that sys.path hasn't changed - self.assertEqual(len(sys.path), len_sys_path) - - @compat.usesFlushLoggedErrors - def test_failure_ImportError(self): - config = textwrap.dedent("""\ - import test_scripts_checkconfig_does_not_exist - """) - self.do_test_load(config=config, - stderr_re=re.compile( - 'No module named test_scripts_checkconfig_does_not_exist')) - self.flushLoggedErrors() - - @compat.usesFlushLoggedErrors - def test_failure_no_slaves(self): - config = textwrap.dedent("""\ - BuildmasterConfig={} - """) - self.do_test_load(config=config, - stderr_re=re.compile('no slaves')) - self.flushLoggedErrors() - - def test_success_imports(self): - config = textwrap.dedent("""\ - from othermodule import port - c = BuildmasterConfig = {} - c['schedulers'] = [] - c['builders'] = [] - c['slaves'] = [] - c['slavePortnum'] = port - """) - other_files = { 'othermodule.py' : 'port = 9989' } - self.do_test_load(config=config, other_files=other_files) - - def test_success_import_package(self): - config = textwrap.dedent("""\ - from otherpackage.othermodule import port - c = BuildmasterConfig = {} - c['schedulers'] = [] - c['builders'] = [] - c['slaves'] = [] - c['slavePortnum'] = port - """) - other_files = { - ('otherpackage', '__init__.py') : '', - ('otherpackage', 'othermodule.py') : 'port = 9989', - } - self.do_test_load(config=config, other_files=other_files) - - -class TestCheckconfig(unittest.TestCase): - - def setUp(self): - self.loadConfig = mock.Mock(spec=checkconfig._loadConfig, return_value=3) - self.patch(checkconfig, '_loadConfig', self.loadConfig) - - def test_checkconfig_given_dir(self): - self.assertEqual(checkconfig.checkconfig(dict(configFile='.')), 3) - self.loadConfig.assert_called_with(basedir='.', configFile='master.cfg', quiet=None) - - def test_checkconfig_given_file(self): - config = dict(configFile='master.cfg') - self.assertEqual(checkconfig.checkconfig(config), 3) - self.loadConfig.assert_called_with(basedir=os.getcwd(), configFile='master.cfg', quiet=None) - - def test_checkconfig_quiet(self): - config = dict(configFile='master.cfg', quiet=True) - self.assertEqual(checkconfig.checkconfig(config), 3) - self.loadConfig.assert_called_with(basedir=os.getcwd(), configFile='master.cfg', quiet=True) - - def test_checkconfig_syntaxError_quiet(self): - """ - When C{base.getConfigFileFromTac} raises L{SyntaxError}, - C{checkconfig.checkconfig} return an error. - """ - mockGetConfig = mock.Mock(spec=base.getConfigFileFromTac, - side_effect=SyntaxError) - self.patch(checkconfig, 'getConfigFileFromTac', mockGetConfig) - config = dict(configFile='.', quiet=True) - self.assertEqual(checkconfig.checkconfig(config), 1) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_create_master.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_create_master.py deleted file mode 100644 index 081a2747..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_create_master.py +++ /dev/null @@ -1,214 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.scripts import create_master -from buildbot.db import connector, model -from buildbot.test.util import dirs, misc - -def mkconfig(**kwargs): - config = dict(force=False, relocatable=False, config='master.cfg', - db='sqlite:///state.sqlite', basedir=os.path.abspath('basedir'), - quiet=False, **{'no-logrotate':False, 'log-size':'10000000', - 'log-count':'10'}) - config.update(kwargs) - return config - -class TestCreateMaster(misc.StdoutAssertionsMixin, unittest.TestCase): - - def setUp(self): - # createMaster is decorated with @in_reactor, so strip that decoration - # since the master is already running - self.patch(create_master, 'createMaster', - create_master.createMaster._orig) - self.setUpStdoutAssertions() - - # tests - - def do_test_createMaster(self, config): - # mock out everything that createMaster calls, then check that - # they are called, in order - functions = [ 'makeBasedir', 'makeTAC', 'makeSampleConfig', - 'makePublicHtml', 'makeTemplatesDir', 'createDB' ] - repls = {} - calls = [] - for fn in functions: - repl = repls[fn] = mock.Mock(name=fn) - repl.side_effect = lambda config, fn=fn : calls.append(fn) - self.patch(create_master, fn, repl) - repls['createDB'].side_effect = (lambda config : - calls.append(fn) or defer.succeed(None)) - d = create_master.createMaster(config) - @d.addCallback - def check(rc): - self.assertEqual(rc, 0) - self.assertEqual(calls, functions) - for repl in repls.values(): - repl.assert_called_with(config) - return d - - def test_createMaster_quiet(self): - d = self.do_test_createMaster(mkconfig(quiet=True)) - @d.addCallback - def check(_): - self.assertWasQuiet() - return d - - def test_createMaster_loud(self): - d = self.do_test_createMaster(mkconfig(quiet=False)) - @d.addCallback - def check(_): - self.assertInStdout('buildmaster configured in') - return d - -class TestCreateMasterFunctions(dirs.DirsMixin, misc.StdoutAssertionsMixin, - unittest.TestCase): - - def setUp(self): - self.setUpDirs('test') - self.basedir = os.path.abspath(os.path.join('test', 'basedir')) - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - def assertInTacFile(self, str): - self.assertIn(str, - open(os.path.join('test', 'buildbot.tac'), 'rt').read()) - - def assertNotInTacFile(self, str): - self.assertNotIn(str, - open(os.path.join('test', 'buildbot.tac'), 'rt').read()) - - def assertDBSetup(self, basedir=None, db_url='sqlite:///state.sqlite', - verbose=True): - # mock out the database setup - self.db = mock.Mock() - self.db.setup.side_effect = lambda *a, **k : defer.succeed(None) - self.DBConnector = mock.Mock() - self.DBConnector.return_value = self.db - self.patch(connector, 'DBConnector', self.DBConnector) - - basedir = basedir or self.basedir - self.assertEqual( - dict(basedir=self.DBConnector.call_args[0][1], - db_url=self.DBConnector.call_args[0][0].mkconfig.db['db_url'], - verbose=self.db.setup.call_args[1]['verbose'], - check_version=self.db.setup.call_args[1]['check_version'], - ), - dict(basedir=self.basedir, - db_url=db_url, - verbose=True, - check_version=False)) - - # tests - - def test_makeBasedir(self): - self.assertFalse(os.path.exists(self.basedir)) - create_master.makeBasedir(mkconfig(basedir=self.basedir)) - self.assertTrue(os.path.exists(self.basedir)) - self.assertInStdout('mkdir %s' % (self.basedir,)) - - def test_makeBasedir_quiet(self): - self.assertFalse(os.path.exists(self.basedir)) - create_master.makeBasedir(mkconfig(basedir=self.basedir, quiet=True)) - self.assertTrue(os.path.exists(self.basedir)) - self.assertWasQuiet() - - def test_makeBasedir_existing(self): - os.mkdir(self.basedir) - create_master.makeBasedir(mkconfig(basedir=self.basedir)) - self.assertInStdout('updating existing installation') - - def test_makeTAC(self): - create_master.makeTAC(mkconfig(basedir='test')) - self.assertInTacFile("Application('buildmaster')") - self.assertWasQuiet() - - def test_makeTAC_relocatable(self): - create_master.makeTAC(mkconfig(basedir='test', relocatable=True)) - self.assertInTacFile("basedir = '.'") # repr() prefers '' - self.assertWasQuiet() - - def test_makeTAC_no_logrotate(self): - create_master.makeTAC(mkconfig(basedir='test', **{'no-logrotate':True})) - self.assertNotInTacFile("import Log") - self.assertWasQuiet() - - def test_makeTAC_existing_incorrect(self): - with open(os.path.join('test', 'buildbot.tac'), 'wt') as f: - f.write('WRONG') - create_master.makeTAC(mkconfig(basedir='test')) - self.assertInTacFile("WRONG") - self.assertTrue(os.path.exists( - os.path.join('test', 'buildbot.tac.new'))) - self.assertInStdout('not touching existing buildbot.tac') - - def test_makeTAC_existing_incorrect_quiet(self): - with open(os.path.join('test', 'buildbot.tac'), 'wt') as f: - f.write('WRONG') - create_master.makeTAC(mkconfig(basedir='test', quiet=True)) - self.assertInTacFile("WRONG") - self.assertWasQuiet() - - def test_makeTAC_existing_correct(self): - create_master.makeTAC(mkconfig(basedir='test', quiet=True)) - create_master.makeTAC(mkconfig(basedir='test')) - self.assertFalse(os.path.exists( - os.path.join('test', 'buildbot.tac.new'))) - self.assertInStdout('and is correct') - - def test_makeSampleConfig(self): - create_master.makeSampleConfig(mkconfig(basedir='test')) - self.assertTrue(os.path.exists( - os.path.join('test', 'master.cfg.sample'))) - self.assertInStdout('creating ') - - def test_makeSampleConfig_db(self): - create_master.makeSampleConfig(mkconfig(basedir='test', db='XXYYZZ', - quiet=True)) - with open(os.path.join('test', 'master.cfg.sample'), 'rt') as f: - self.assertIn("XXYYZZ", f.read()) - self.assertWasQuiet() - - def test_makePublicHtml(self): - create_master.makePublicHtml(mkconfig(basedir='test', quiet=True)) - self.assertTrue(os.path.exists( - os.path.join('test', 'public_html', 'robots.txt'))) - self.assertWasQuiet() - - def test_makeTemplatesDir(self): - create_master.makeTemplatesDir(mkconfig(basedir='test', quiet=True)) - self.assertTrue(os.path.exists( - os.path.join('test', 'templates', 'README.txt'))) - self.assertWasQuiet() - - @defer.inlineCallbacks - def test_createDB(self): - setup = mock.Mock(side_effect=lambda **kwargs : defer.succeed(None)) - self.patch(connector.DBConnector, 'setup', setup) - upgrade = mock.Mock(side_effect=lambda **kwargs : defer.succeed(None)) - self.patch(model.Model, 'upgrade', upgrade) - yield create_master.createDB( - mkconfig(basedir='test', quiet=True), - _noMonkey=True) - setup.asset_called_with(check_version=False, verbose=False) - upgrade.assert_called() - self.assertWasQuiet() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_restart.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_restart.py deleted file mode 100644 index 656d2005..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_restart.py +++ /dev/null @@ -1,70 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -from twisted.trial import unittest -from buildbot.scripts import restart, stop, start -from buildbot.test.util import dirs, misc - -def mkconfig(**kwargs): - config = dict(quiet=False, basedir=os.path.abspath('basedir')) - config.update(kwargs) - return config - -class TestStop(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.setUpDirs('basedir') - with open(os.path.join('basedir', 'buildbot.tac'), 'wt') as f: - f.write("Application('buildmaster')") - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - # tests - - def test_restart_not_basedir(self): - self.assertEqual(restart.restart(mkconfig(basedir='doesntexist')), 1) - self.assertInStdout('invalid buildmaster directory') - - def test_restart_stop_fails(self): - self.patch(stop, 'stop', lambda config, wait : 1) - self.assertEqual(restart.restart(mkconfig()), 1) - - def test_restart_stop_succeeds_start_fails(self): - self.patch(stop, 'stop', lambda config, wait : 0) - self.patch(start, 'start', lambda config : 1) - self.assertEqual(restart.restart(mkconfig()), 1) - - def test_restart_succeeds(self): - self.patch(stop, 'stop', lambda config, wait : 0) - self.patch(start, 'start', lambda config : 0) - self.assertEqual(restart.restart(mkconfig()), 0) - self.assertInStdout('now restarting') - - def test_restart_succeeds_quiet(self): - self.patch(stop, 'stop', lambda config, wait : 0) - self.patch(start, 'start', lambda config : 0) - self.assertEqual(restart.restart(mkconfig(quiet=True)), 0) - self.assertWasQuiet() - - def test_restart_clean(self): - self.patch(stop, 'stop', lambda config, wait : 0) - self.patch(start, 'start', lambda config : 0) - self.assertEqual(restart.restart(mkconfig(quiet=True, clean=True)), 0) - self.assertWasQuiet() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_runner.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_runner.py deleted file mode 100644 index 0da2c7d0..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_runner.py +++ /dev/null @@ -1,971 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import sys -import getpass -import mock -import cStringIO -from twisted.trial import unittest -from twisted.python import usage, runtime, log -from buildbot.scripts import base, runner -from buildbot.test.util import misc - -class OptionsMixin(object): - - def setUpOptions(self): - self.options_file = {} - self.patch(base.SubcommandOptions, 'loadOptionsFile', - lambda other_self : self.options_file) - - def assertOptions(self, opts, exp): - got = dict([(k, opts[k]) for k in exp]) - if got != exp: - msg = [] - for k in exp: - if opts[k] != exp[k]: - msg.append(" %s: expected %r, got %r" % - (k, exp[k], opts[k])) - self.fail("did not get expected options\n" + ("\n".join(msg))) - - -class TestUpgradeMasterOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.UpgradeMasterOptions() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = runner.UpgradeMasterOptions() - self.assertIn('buildbot upgrade-master', opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse() - exp = dict(quiet=False, replace=False) - self.assertOptions(opts, exp) - - def test_short(self): - opts = self.parse('-q', '-r') - exp = dict(quiet=True, replace=True) - self.assertOptions(opts, exp) - - def test_long(self): - opts = self.parse('--quiet', '--replace') - exp = dict(quiet=True, replace=True) - self.assertOptions(opts, exp) - - -class TestCreateMasterOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.CreateMasterOptions() - self.opts.parseOptions(args) - return self.opts - - def defaults_and(self, **kwargs): - defaults = dict(force=False, relocatable=False, config='master.cfg', - db='sqlite:///state.sqlite', basedir=os.getcwd(), quiet=False, - **{'no-logrotate':False, 'log-size':'10000000', - 'log-count':'10'}) - unk_keys = set(kwargs.keys()) - set(defaults.keys()) - assert not unk_keys, "invalid keys %s" % (unk_keys,) - opts = defaults.copy() - opts.update(kwargs) - return opts - - def test_synopsis(self): - opts = runner.CreateMasterOptions() - self.assertIn('buildbot create-master', opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse() - exp = self.defaults_and() - self.assertOptions(opts, exp) - - def test_db_quiet(self): - opts = self.parse('-q') - exp = self.defaults_and(quiet=True) - self.assertOptions(opts, exp) - - def test_db_quiet_long(self): - opts = self.parse('--quiet') - exp = self.defaults_and(quiet=True) - self.assertOptions(opts, exp) - - def test_force(self): - opts = self.parse('-f') - exp = self.defaults_and(force=True) - self.assertOptions(opts, exp) - - def test_force_long(self): - opts = self.parse('--force') - exp = self.defaults_and(force=True) - self.assertOptions(opts, exp) - - def test_relocatable(self): - opts = self.parse('-r') - exp = self.defaults_and(relocatable=True) - self.assertOptions(opts, exp) - - def test_relocatable_long(self): - opts = self.parse('--relocatable') - exp = self.defaults_and(relocatable=True) - self.assertOptions(opts, exp) - - def test_no_logrotate(self): - opts = self.parse('-n') - exp = self.defaults_and(**{'no-logrotate' : True}) - self.assertOptions(opts, exp) - - def test_no_logrotate_long(self): - opts = self.parse('--no-logrotate') - exp = self.defaults_and(**{'no-logrotate' : True}) - self.assertOptions(opts, exp) - - def test_config(self): - opts = self.parse('-cxyz') - exp = self.defaults_and(config='xyz') - self.assertOptions(opts, exp) - - def test_config_long(self): - opts = self.parse('--config=xyz') - exp = self.defaults_and(config='xyz') - self.assertOptions(opts, exp) - - def test_log_size(self): - opts = self.parse('-s124') - exp = self.defaults_and(**{'log-size':'124'}) - self.assertOptions(opts, exp) - - def test_log_size_long(self): - opts = self.parse('--log-size=124') - exp = self.defaults_and(**{'log-size':'124'}) - self.assertOptions(opts, exp) - - def test_log_size_noninteger(self): - self.assertRaises(usage.UsageError, - lambda :self.parse('--log-size=1M')) - - def test_log_count(self): - opts = self.parse('-l124') - exp = self.defaults_and(**{'log-count':'124'}) - self.assertOptions(opts, exp) - - def test_log_count_long(self): - opts = self.parse('--log-count=124') - exp = self.defaults_and(**{'log-count':'124'}) - self.assertOptions(opts, exp) - - def test_log_count_noninteger(self): - self.assertRaises(usage.UsageError, - lambda :self.parse('--log-count=M')) - - def test_db_long(self): - opts = self.parse('--db=foo://bar') - exp = self.defaults_and(db='foo://bar') - self.assertOptions(opts, exp) - - def test_db_basedir(self): - path = r'c:\foo\bar' if runtime.platformType == "win32" else '/foo/bar' - opts = self.parse('-f', path) - exp = self.defaults_and(force=True, basedir=path) - self.assertOptions(opts, exp) - - -class BaseTestSimpleOptions(OptionsMixin): - # tests for options with just --quiet and a usage message - - commandName = None - optionsClass = None - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = self.optionsClass() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = self.optionsClass() - self.assertIn('buildbot %s' % self.commandName, opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse() - exp = dict(quiet=False) - self.assertOptions(opts, exp) - - def test_quiet(self): - opts = self.parse('--quiet') - exp = dict(quiet=True) - self.assertOptions(opts, exp) - - -class TestStopOptions(BaseTestSimpleOptions, unittest.TestCase): - commandName = 'stop' - optionsClass = runner.StopOptions - - -class TestResetartOptions(BaseTestSimpleOptions, unittest.TestCase): - commandName = 'restart' - optionsClass = runner.RestartOptions - - def test_nodaemon(self): - opts = self.parse('--nodaemon') - exp = dict(nodaemon=True) - self.assertOptions(opts, exp) - - -class TestStartOptions(BaseTestSimpleOptions, unittest.TestCase): - commandName = 'start' - optionsClass = runner.StartOptions - - def test_nodaemon(self): - opts = self.parse('--nodaemon') - exp = dict(nodaemon=True) - self.assertOptions(opts, exp) - - -class TestReconfigOptions(BaseTestSimpleOptions, unittest.TestCase): - commandName = 'reconfig' - optionsClass = runner.ReconfigOptions - - -class TestDebugClientOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.DebugClientOptions() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = runner.DebugClientOptions() - self.assertIn('buildbot debugclient', opts.getSynopsis()) - - def test_defaults(self): - self.assertRaises(usage.UsageError, - lambda : self.parse()) - - def test_args_missing_passwd(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('-m', 'mm')) - - def test_options_long(self): - opts = self.parse('--master', 'mm:9989', '--passwd', 'pp') - exp = dict(master='mm:9989', passwd='pp') - self.assertOptions(opts, exp) - - def test_positional_master_passwd(self): - opts = self.parse('foo:9989', 'pass') - exp = dict(master='foo:9989', passwd='pass') - self.assertOptions(opts, exp) - - def test_positional_master(self): - opts = self.parse('-p', 'pass', 'foo:9989') - exp = dict(master='foo:9989', passwd='pass') - self.assertOptions(opts, exp) - - def test_args_master_passwd(self): - opts = self.parse('foo:9989', 'pass') - exp = dict(master='foo:9989', passwd='pass') - self.assertOptions(opts, exp) - - def test_missing_both(self): - self.assertRaises(usage.UsageError, - lambda :self.parse()) - - def test_missing_passwd(self): - self.assertRaises(usage.UsageError, - lambda :self.parse('master')) - - def test_missing_master(self): - self.assertRaises(usage.UsageError, - lambda :self.parse('-p', 'pass')) - - def test_invalid_master(self): - self.assertRaises(usage.UsageError, self.parse, - "-m", "foo", "-p", "pass") - - def test_options_extra_positional(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('mm', 'pp', '??')) - - def test_options_master(self): - self.options_file['master'] = 'opt:9989' - opts = self.parse('-p', 'pass') - exp = dict(master='opt:9989', passwd='pass') - self.assertOptions(opts, exp) - - def test_options_debugMaster(self): - self.options_file['master'] = 'not seen' - self.options_file['debugMaster'] = 'opt:9989' - opts = self.parse('-p', 'pass') - exp = dict(master='opt:9989', passwd='pass') - self.assertOptions(opts, exp) - - -class TestBaseStatusClientOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.BaseStatusClientOptions() - self.opts.parseOptions(args) - return self.opts - - def test_defaults(self): - opts = self.parse('--master', 'm:20') - exp = dict(master='m:20', username='statusClient', passwd='clientpw') - self.assertOptions(opts, exp) - - def test_short(self): - opts = self.parse('-m', 'm:20', '-u', 'u', '-p', 'p') - exp = dict(master='m:20', username='u', passwd='p') - self.assertOptions(opts, exp) - - def test_long(self): - opts = self.parse('--master', 'm:20', - '--username', 'u', '--passwd', 'p') - exp = dict(master='m:20', username='u', passwd='p') - self.assertOptions(opts, exp) - - def test_positional_master(self): - opts = self.parse('--username', 'u', '--passwd', 'p', 'm:20') - exp = dict(master='m:20', username='u', passwd='p') - self.assertOptions(opts, exp) - - def test_positional_extra(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('--username', 'u', '--passwd', 'p', 'm', '2')) - - def test_missing_master(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('--username', 'u', '--passwd', 'p')) - - def test_invalid_master(self): - self.assertRaises(usage.UsageError, self.parse, "-m foo") - - def test_options_masterstatus(self): - self.options_file['master'] = 'not_seen:2' - self.options_file['masterstatus'] = 'opt:3' - opts = self.parse('-p', 'pass', '-u', 'user') - exp = dict(master='opt:3', username='user', passwd='pass') - self.assertOptions(opts, exp) - - -class TestStatusLogOptions(unittest.TestCase): - - def test_synopsis(self): - opts = runner.StatusLogOptions() - self.assertIn('buildbot statuslog', opts.getSynopsis()) - - -class TestStatusGuiOptions(unittest.TestCase): - - def test_synopsis(self): - opts = runner.StatusGuiOptions() - self.assertIn('buildbot statusgui', opts.getSynopsis()) - - -class TestTryOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.TryOptions() - self.opts.parseOptions(args) - return self.opts - - def defaults_and(self, **kwargs): - defaults = dict(connect=None, host=None, jobdir=None, username=None, - master=None, passwd=None, who=None, comment=None, diff=None, - patchlevel=0, baserev=None, vc=None, branch=None, - repository=None, topfile=None, topdir=None, wait=False, - dryrun=False, quiet=False, builders=[], properties={}, - buildbotbin='buildbot') - # dashes make python syntax hard.. - defaults['get-builder-names'] = False - if 'get_builder_names' in kwargs: - kwargs['get-builder-names'] = kwargs['get_builder_names'] - del kwargs['get_builder_names'] - assert set(kwargs.keys()) <= set(defaults.keys()), "invalid keys" - opts = defaults.copy() - opts.update(kwargs) - return opts - - def test_synopsis(self): - opts = runner.TryOptions() - self.assertIn('buildbot try', opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse() - exp = self.defaults_and() - self.assertOptions(opts, exp) - - def test_properties(self): - opts = self.parse('--properties=a=b') - exp = self.defaults_and(properties=dict(a='b')) - self.assertOptions(opts, exp) - - def test_properties_multiple_opts(self): - opts = self.parse('--properties=X=1', '--properties=Y=2') - exp = self.defaults_and(properties=dict(X='1', Y='2')) - self.assertOptions(opts, exp) - - def test_properties_equals(self): - opts = self.parse('--properties=X=2+2=4') - exp = self.defaults_and(properties=dict(X='2+2=4')) - self.assertOptions(opts, exp) - - def test_properties_commas(self): - opts = self.parse('--properties=a=b,c=d') - exp = self.defaults_and(properties=dict(a='b', c='d')) - self.assertOptions(opts, exp) - - def test_property(self): - opts = self.parse('--property=a=b') - exp = self.defaults_and(properties=dict(a='b')) - self.assertOptions(opts, exp) - - def test_property_multiple_opts(self): - opts = self.parse('--property=X=1', '--property=Y=2') - exp = self.defaults_and(properties=dict(X='1', Y='2')) - self.assertOptions(opts, exp) - - def test_property_equals(self): - opts = self.parse('--property=X=2+2=4') - exp = self.defaults_and(properties=dict(X='2+2=4')) - self.assertOptions(opts, exp) - - def test_property_commas(self): - opts = self.parse('--property=a=b,c=d') - exp = self.defaults_and(properties=dict(a='b,c=d')) - self.assertOptions(opts, exp) - - def test_property_and_properties(self): - opts = self.parse('--property=X=1', '--properties=Y=2') - exp = self.defaults_and(properties=dict(X='1', Y='2')) - self.assertOptions(opts, exp) - - def test_properties_builders_multiple(self): - opts = self.parse('--builder=aa', '--builder=bb') - exp = self.defaults_and(builders=['aa', 'bb']) - self.assertOptions(opts, exp) - - def test_options_short(self): - opts = self.parse( - *'-n -q -c pb -u me -m mr:7 -w you -C comm -p 2 -b bb'.split()) - exp = self.defaults_and(dryrun=True, quiet=True, connect='pb', - username='me', master='mr:7', who='you', comment='comm', - patchlevel=2, builders=['bb']) - self.assertOptions(opts, exp) - - def test_options_long(self): - opts = self.parse( - *"""--wait --dryrun --get-builder-names --quiet --connect=pb - --host=h --jobdir=j --username=u --master=m:1234 --passwd=p - --who=w --comment=comm --diff=d --patchlevel=7 --baserev=br - --vc=cvs --branch=br --repository=rep --builder=bl - --properties=a=b --topfile=Makefile --topdir=. - --buildbotbin=.virtualenvs/buildbot/bin/buildbot""".split()) - exp = self.defaults_and(wait=True, dryrun=True, get_builder_names=True, - quiet=True, connect='pb', host='h', jobdir='j', username='u', - master='m:1234', passwd='p', who='w', comment='comm', diff='d', - patchlevel=7, baserev='br', vc='cvs', branch='br', - repository='rep', builders=['bl'], properties=dict(a='b'), - topfile='Makefile', topdir='.', - buildbotbin='.virtualenvs/buildbot/bin/buildbot') - self.assertOptions(opts, exp) - - def test_patchlevel_inval(self): - self.assertRaises(ValueError, lambda: - self.parse('-p', 'a')) - - def test_config_builders(self): - self.options_file['try_builders'] = ['a', 'b'] - opts = self.parse() - self.assertOptions(opts, dict(builders=['a', 'b'])) - - def test_config_builders_override(self): - self.options_file['try_builders'] = ['a', 'b'] - opts = self.parse('-b', 'd') # overrides a, b - self.assertOptions(opts, dict(builders=['d'])) - - def test_config_old_names(self): - self.options_file['try_masterstatus'] = 'ms' - self.options_file['try_dir'] = 'td' - self.options_file['try_password'] = 'pw' - opts = self.parse() - self.assertOptions(opts, dict(master='ms', jobdir='td', passwd='pw')) - - def test_config_masterstatus(self): - self.options_file['masterstatus'] = 'ms' - opts = self.parse() - self.assertOptions(opts, dict(master='ms')) - - def test_config_masterstatus_override(self): - self.options_file['masterstatus'] = 'ms' - opts = self.parse('-m', 'mm') - self.assertOptions(opts, dict(master='mm')) - - def test_config_options(self): - self.options_file.update(dict(try_connect='pb', try_vc='cvs', - try_branch='br', try_repository='rep', try_topdir='.', - try_topfile='Makefile', try_host='h', try_username='u', - try_jobdir='j', try_password='p', try_master='m:8', try_who='w', - try_comment='comm', try_quiet='y', try_wait='y', - try_buildbotbin='.virtualenvs/buildbot/bin/buildbot')) - opts = self.parse() - exp = self.defaults_and(wait=True, quiet=True, connect='pb', host='h', - jobdir='j', username='u', master='m:8', passwd='p', who='w', - comment='comm', vc='cvs', branch='br', repository='rep', - topfile='Makefile', topdir='.', - buildbotbin='.virtualenvs/buildbot/bin/buildbot') - self.assertOptions(opts, exp) - - def test_pb_withNoMaster(self): - """ - When 'builbot try' is asked to connect via pb, but no master is - specified, a usage error is raised. - """ - self.assertRaises(usage.UsageError, self.parse, '--connect=pb') - - def test_pb_withInvalidMaster(self): - """ - When 'buildbot try' is asked to conncect via pb, but an invalid - master is specified, a usage error is raised. - """ - self.assertRaises(usage.UsageError, self.parse, - '--connect=pb', '--master=foo') - -class TestSendChangeOptions(OptionsMixin, unittest.TestCase): - - master_and_who = ['-m', 'm:1', '-W', 'w'] - - def setUp(self): - self.setUpOptions() - self.getpass_response = 'typed-password' - self.patch(getpass, 'getpass', lambda prompt : self.getpass_response) - - def parse(self, *args): - self.opts = runner.SendChangeOptions() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = runner.SendChangeOptions() - self.assertIn('buildbot sendchange', opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse('-m', 'm:1', '-W', 'me') - exp = dict(master='m:1', auth=('change', 'changepw'), who='me', - vc=None, repository='', project='', branch=None, category=None, - revision=None, revision_file=None, property=None, - comments='', logfile=None, when=None, revlink='', - encoding='utf8', files=()) - self.assertOptions(opts, exp) - - def test_files(self): - opts = self.parse(*self.master_and_who + ['a', 'b', 'c']) - self.assertEqual(opts['files'], ('a', 'b', 'c')) - - def test_properties(self): - opts = self.parse('--property', 'x:y', '--property', 'a:b', - *self.master_and_who) - self.assertEqual(opts['properties'], dict(x="y", a="b")) - - def test_properties_with_colon(self): - opts = self.parse('--property', 'x:http://foo', *self.master_and_who) - self.assertEquals(opts['properties'], dict(x='http://foo')) - - def test_config_file(self): - self.options_file['master'] = 'MMM:123' - self.options_file['who'] = 'WWW' - self.options_file['branch'] = 'BBB' - self.options_file['category'] = 'CCC' - self.options_file['vc'] = 'svn' - opts = self.parse() - exp = dict(master='MMM:123', who='WWW', - branch='BBB', category='CCC', vc='svn') - self.assertOptions(opts, exp) - - def test_short_args(self): - opts = self.parse(*('-m m:1 -a a:b -W W -R r -P p -b b -s git ' + - '-C c -r r -p pn:pv -c c -F f -w 123 -l l -e e').split()) - exp = dict(master='m:1', auth=('a','b'), who='W', repository='r', - project='p', branch='b', category='c', revision='r', vc='git', - properties=dict(pn='pv'), comments='c', logfile='f', - when=123.0, revlink='l', encoding='e') - self.assertOptions(opts, exp) - - def test_long_args(self): - opts = self.parse(*('--master m:1 --auth a:b --who w --repository r ' + - '--project p --branch b --category c --revision r --vc git ' + - '--property pn:pv --comments c --logfile f ' + - '--when 123 --revlink l --encoding e').split()) - exp = dict(master='m:1', auth=('a', 'b'), who='w', repository='r', - project='p', branch='b', category='c', revision='r', vc='git', - properties=dict(pn='pv'), comments='c', logfile='f', - when=123.0, revlink='l', encoding='e') - self.assertOptions(opts, exp) - - def test_revision_file(self): - with open('revfile', 'wt') as f: - f.write('my-rev') - self.addCleanup(lambda : os.unlink('revfile')) - opts = self.parse('--revision_file', 'revfile', *self.master_and_who) - self.assertOptions(opts, dict(revision='my-rev')) - - def test_invalid_when(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('--when=foo', *self.master_and_who)) - - def test_comments_overrides_logfile(self): - opts = self.parse('--logfile', 'logs', '--comments', 'foo', - *self.master_and_who) - self.assertOptions(opts, dict(comments='foo')) - - def test_logfile(self): - with open('comments', 'wt') as f: - f.write('hi') - self.addCleanup(lambda : os.unlink('comments')) - opts = self.parse('--logfile', 'comments', *self.master_and_who) - self.assertOptions(opts, dict(comments='hi')) - - def test_logfile_stdin(self): - stdin = mock.Mock() - stdin.read = lambda : 'hi' - self.patch(sys, 'stdin', stdin) - opts = self.parse('--logfile', '-', *self.master_and_who) - self.assertOptions(opts, dict(comments='hi')) - - def test_auth_getpass(self): - opts = self.parse('--auth=dustin', *self.master_and_who) - self.assertOptions(opts, dict(auth=('dustin', 'typed-password'))) - - def test_invalid_vcs(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('--vc=foo', *self.master_and_who)) - - def test_invalid_master(self): - self.assertRaises(usage.UsageError, - self.parse, - "--who=test", "-m foo") - - -class TestTryServerOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.TryServerOptions() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = runner.TryServerOptions() - self.assertIn('buildbot tryserver', opts.getSynopsis()) - - def test_defaults(self): - self.assertRaises(usage.UsageError, - lambda : self.parse()) - - def test_with_jobdir(self): - opts = self.parse('--jobdir', 'xyz') - exp = dict(jobdir='xyz') - self.assertOptions(opts, exp) - - -class TestCheckConfigOptions(OptionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.CheckConfigOptions() - self.opts.parseOptions(args) - return self.opts - - def test_synopsis(self): - opts = runner.CheckConfigOptions() - self.assertIn('buildbot checkconfig', opts.getSynopsis()) - - def test_defaults(self): - opts = self.parse() - exp = dict(quiet=False, configFile='master.cfg') - self.assertOptions(opts, exp) - - def test_configfile(self): - opts = self.parse('foo.cfg') - exp = dict(quiet=False, configFile='foo.cfg') - self.assertOptions(opts, exp) - - def test_quiet(self): - opts = self.parse('-q') - exp = dict(quiet=True, configFile='master.cfg') - self.assertOptions(opts, exp) - - -class TestUserOptions(OptionsMixin, unittest.TestCase): - - # mandatory arguments - extra_args = [ '--master', 'a:1', - '--username', 'u', '--passwd', 'p' ] - - def setUp(self): - self.setUpOptions() - - def parse(self, *args): - self.opts = runner.UserOptions() - self.opts.parseOptions(args) - return self.opts - - def test_defaults(self): - self.assertRaises(usage.UsageError, - lambda : self.parse()) - - def test_synopsis(self): - opts = runner.UserOptions() - self.assertIn('buildbot user', opts.getSynopsis()) - - def test_master(self): - opts = self.parse("--master", "abcd:1234", - '--op=get', '--ids=x', '--username=u', '--passwd=p') - self.assertOptions(opts, dict(master="abcd:1234")) - - def test_ids(self): - opts = self.parse("--ids", "id1,id2,id3", - '--op', 'get', *self.extra_args) - self.assertEqual(opts['ids'], ['id1', 'id2', 'id3']) - - def test_info(self): - opts = self.parse("--info", "git=Tyler Durden <tyler@mayhem.net>", - '--op', 'add', *self.extra_args) - self.assertEqual(opts['info'], - [dict(git='Tyler Durden <tyler@mayhem.net>')]) - - def test_info_only_id(self): - opts = self.parse("--info", "tdurden", - '--op', 'update', *self.extra_args) - self.assertEqual(opts['info'], [dict(identifier='tdurden')]) - - def test_info_with_id(self): - opts = self.parse("--info", "tdurden:svn=marla", - '--op', 'update', *self.extra_args) - self.assertEqual(opts['info'], [dict(identifier='tdurden', svn='marla')]) - - def test_info_multiple(self): - opts = self.parse("--info", "git=Tyler Durden <tyler@mayhem.net>", - "--info", "git=Narrator <narrator@mayhem.net>", - '--op', 'add', *self.extra_args) - self.assertEqual(opts['info'], - [dict(git='Tyler Durden <tyler@mayhem.net>'), - dict(git='Narrator <narrator@mayhem.net>')]) - - def test_config_user_params(self): - self.options_file['user_master'] = 'mm:99' - self.options_file['user_username'] = 'un' - self.options_file['user_passwd'] = 'pw' - opts = self.parse('--op', 'get', '--ids', 'x') - self.assertOptions(opts, dict(master='mm:99', username='un', passwd='pw')) - - def test_config_master(self): - self.options_file['master'] = 'mm:99' - opts = self.parse('--op', 'get', '--ids', 'x', - '--username=u', '--passwd=p') - self.assertOptions(opts, dict(master='mm:99')) - - def test_config_master_override(self): - self.options_file['master'] = 'not seen' - self.options_file['user_master'] = 'mm:99' - opts = self.parse('--op', 'get', '--ids', 'x', - '--username=u', '--passwd=p') - self.assertOptions(opts, dict(master='mm:99')) - - def test_invalid_info(self): - self.assertRaises(usage.UsageError, - lambda : self.parse("--info", "foo=bar", - '--op', 'add', *self.extra_args)) - - def test_no_master(self): - self.assertRaises(usage.UsageError, - lambda : self.parse('-op=foo')) - - def test_invalid_master(self): - self.assertRaises(usage.UsageError, self.parse,'-m', 'foo') - - def test_no_operation(self): - self.assertRaises(usage.UsageError, self.parse, '-m', 'a:1') - - def test_bad_operation(self): - self.assertRaises(usage.UsageError, - self.parse, - '-m', 'a:1', '--op=mayhem') - - def test_no_username(self): - self.assertRaises(usage.UsageError, - self.parse, - '-m', 'a:1', '--op=add') - - def test_no_password(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=add', '-m', 'a:1', '-u', 'tdurden') - - def test_invalid_bb_username(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=add', '--bb_username=tdurden', - *self.extra_args) - - def test_invalid_bb_password(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=add', '--bb_password=marla', - *self.extra_args) - - def test_update_no_bb_username(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=update', '--bb_password=marla', - *self.extra_args) - - def test_update_no_bb_password(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=update', '--bb_username=tdurden', - *self.extra_args) - - def test_no_ids_info(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=add', *self.extra_args) - - def test_ids_with_add(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=add', '--ids=id1', *self.extra_args) - - def test_ids_with_update(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=update', '--ids=id1', *self.extra_args) - - def test_no_ids_found_update(self): - self.assertRaises(usage.UsageError, - self.parse, - "--op=update", "--info=svn=x", *self.extra_args) - - def test_id_with_add(self): - self.assertRaises(usage.UsageError, - self.parse, - "--op=add", "--info=id:x", *self.extra_args) - - def test_info_with_remove(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=remove', '--info=x=v', *self.extra_args) - - - def test_info_with_get(self): - self.assertRaises(usage.UsageError, - self.parse, - '--op=get', '--info=x=v', *self.extra_args) - - -class TestOptions(OptionsMixin, misc.StdoutAssertionsMixin, unittest.TestCase): - - def setUp(self): - self.setUpOptions() - self.setUpStdoutAssertions() - - def parse(self, *args): - self.opts = runner.Options() - self.opts.parseOptions(args) - return self.opts - - def test_defaults(self): - self.assertRaises(usage.UsageError, - lambda : self.parse()) - - def test_version(self): - try: - self.parse('--version') - except SystemExit, e: - self.assertEqual(e.args[0], 0) - self.assertInStdout('Buildbot version:') - - def test_verbose(self): - self.patch(log, 'startLogging', mock.Mock()) - self.assertRaises(usage.UsageError, self.parse, "--verbose") - log.startLogging.assert_called_once_with(sys.stderr) - - -class TestRun(unittest.TestCase): - - class MySubCommand(usage.Options): - subcommandFunction = 'buildbot.test.unit.test_scripts_runner.subcommandFunction' - optFlags = [ - [ 'loud', 'l', 'be noisy' ] - ] - def postOptions(self): - if self['loud']: - raise usage.UsageError('THIS IS ME BEING LOUD') - - def setUp(self): - # patch our subcommand in - self.patch(runner.Options, 'subCommands', - [ [ 'my', None, self.MySubCommand, 'my, my' ] ]) - - # and patch in the callback for it - global subcommandFunction - subcommandFunction = mock.Mock(name='subcommandFunction', - return_value=3) - - def test_run_good(self): - self.patch(sys, 'argv', [ 'buildbot', 'my' ]) - try: - runner.run() - except SystemExit, e: - self.assertEqual(e.args[0], 3) - else: - self.fail("didn't exit") - - def test_run_bad(self): - self.patch(sys, 'argv', [ 'buildbot', 'my', '-l' ]) - stdout = cStringIO.StringIO() - self.patch(sys, 'stdout', stdout) - try: - runner.run() - except SystemExit, e: - self.assertEqual(e.args[0], 1) - else: - self.fail("didn't exit") - self.assertIn('THIS IS ME', stdout.getvalue()) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_sendchange.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_sendchange.py deleted file mode 100644 index daeaab88..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_sendchange.py +++ /dev/null @@ -1,119 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import reactor, defer -from buildbot.scripts import sendchange -from buildbot.clients import sendchange as sendchange_client -from buildbot.test.util import misc - -class TestSendChange(misc.StdoutAssertionsMixin, unittest.TestCase): - - class FakeSender: - def __init__(self, testcase, master, auth, encoding=None): - self.master = master - self.auth = auth - self.encoding = encoding - self.testcase = testcase - - def send(self, branch, revision, comments, files, **kwargs): - kwargs['branch'] = branch - kwargs['revision'] = revision - kwargs['comments'] = comments - kwargs['files'] = files - self.send_kwargs = kwargs - d = defer.Deferred() - if self.testcase.fail: - reactor.callLater(0, d.errback, RuntimeError("oh noes")) - else: - reactor.callLater(0, d.callback, None) - return d - - def setUp(self): - self.fail = False # set to true to get Sender.send to fail - def Sender_constr(*args, **kwargs): - self.sender = self.FakeSender(self, *args, **kwargs) - return self.sender - self.patch(sendchange_client, 'Sender', Sender_constr) - - # undo the effects of @in_reactor - self.patch(sendchange, 'sendchange', sendchange.sendchange._orig) - - self.setUpStdoutAssertions() - - def test_sendchange_config(self): - d = sendchange.sendchange(dict(encoding='utf16', who='me', - auth=['a', 'b'], master='m', branch='br', category='cat', - revision='rr', properties={'a':'b'}, repository='rep', - project='prj', vc='git', revlink='rl', when=1234.0, - comments='comm', files=('a', 'b'), codebase='cb')) - def check(rc): - self.assertEqual((self.sender.master, self.sender.auth, - self.sender.encoding, self.sender.send_kwargs, - self.getStdout(), rc), - ('m', ['a','b'], 'utf16', { - 'branch': 'br', - 'category': 'cat', - 'codebase': 'cb', - 'comments': 'comm', - 'files': ('a', 'b'), - 'project': 'prj', - 'properties': {'a':'b'}, - 'repository': 'rep', - 'revision': 'rr', - 'revlink': 'rl', - 'when': 1234.0, - 'who': 'me', - 'vc': 'git'}, - 'change sent successfully', 0)) - d.addCallback(check) - return d - - def test_sendchange_config_no_codebase(self): - d = sendchange.sendchange(dict(encoding='utf16', who='me', - auth=['a', 'b'], master='m', branch='br', category='cat', - revision='rr', properties={'a':'b'}, repository='rep', - project='prj', vc='git', revlink='rl', when=1234.0, - comments='comm', files=('a', 'b'))) - def check(rc): - self.assertEqual((self.sender.master, self.sender.auth, - self.sender.encoding, self.sender.send_kwargs, - self.getStdout(), rc), - ('m', ['a','b'], 'utf16', { - 'branch': 'br', - 'category': 'cat', - 'codebase': None, - 'comments': 'comm', - 'files': ('a', 'b'), - 'project': 'prj', - 'properties': {'a':'b'}, - 'repository': 'rep', - 'revision': 'rr', - 'revlink': 'rl', - 'when': 1234.0, - 'who': 'me', - 'vc': 'git'}, - 'change sent successfully', 0)) - d.addCallback(check) - return d - - def test_sendchange_fail(self): - self.fail = True - d = sendchange.sendchange({}) - def check(rc): - self.assertEqual((self.getStdout().split('\n')[0], rc), - ('change not sent:', 1)) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_start.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_start.py deleted file mode 100644 index ddf04d9a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_start.py +++ /dev/null @@ -1,108 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os, sys -import twisted -from twisted.python import versions -from twisted.internet.utils import getProcessOutputAndValue -from twisted.trial import unittest -from buildbot.scripts import start -from buildbot.test.util import dirs, misc, compat - -def mkconfig(**kwargs): - config = { - 'quiet': False, - 'basedir': os.path.abspath('basedir'), - 'nodaemon': False, - } - config.update(kwargs) - return config - -fake_master_tac = """\ -from twisted.application import service -from twisted.python import log -from twisted.internet import reactor -application = service.Application('highscore') -class App(service.Service): - def startService(self): - service.Service.startService(self) - log.msg("BuildMaster is running") # heh heh heh - reactor.callLater(0, reactor.stop) -app = App() -app.setServiceParent(application) -# isBuildmasterDir wants to see this -> Application('buildmaster') -""" - -class TestStart(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.setUpDirs('basedir') - with open(os.path.join('basedir', 'buildbot.tac'), 'wt') as f: - f.write(fake_master_tac) - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - # tests - - def test_start_not_basedir(self): - self.assertEqual(start.start(mkconfig(basedir='doesntexist')), 1) - self.assertInStdout('invalid buildmaster directory') - - def runStart(self, **config): - args=[ - '-c', - 'from buildbot.scripts.start import start; start(%r)' % (mkconfig(**config),), - ] - env = os.environ.copy() - env['PYTHONPATH'] = os.pathsep.join(sys.path) - return getProcessOutputAndValue(sys.executable, args=args, env=env) - - def test_start_no_daemon(self): - d = self.runStart(nodaemon=True) - @d.addCallback - def cb(res): - self.assertEquals(res, ('', '', 0)) - print res - return d - - def test_start_quiet(self): - d = self.runStart(quiet=True) - @d.addCallback - def cb(res): - self.assertEquals(res, ('', '', 0)) - print res - return d - - @compat.skipUnlessPlatformIs('posix') - def test_start(self): - d = self.runStart() - @d.addCallback - def cb((out, err, rc)): - self.assertEqual((rc, err), (0, '')) - self.assertSubstring('BuildMaster is running', out) - return d - - if twisted.version <= versions.Version('twisted', 9, 0, 0): - test_start.skip = test_start_quiet.skip = "Skipping due to suprious PotentialZombieWarning." - - # the remainder of this script does obscene things: - # - forks - # - shells out to tail - # - starts and stops the reactor - # so testing it will be *far* more pain than is worthwhile diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_statuslog.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_statuslog.py deleted file mode 100644 index fd067afd..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_statuslog.py +++ /dev/null @@ -1,32 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from buildbot.clients import text -from buildbot.scripts import statuslog - -class TestStatusLog(unittest.TestCase): - - def test_statuslog(self): - TextClient = mock.Mock() - self.patch(text, 'TextClient', TextClient) - inst = TextClient.return_value = mock.Mock(name='TextClient-instance') - - rc = statuslog.statuslog(dict(master='mm', passwd='pp', username='uu')) - - TextClient.assert_called_with('mm', passwd='pp', username='uu') - inst.run.assert_called_with() - self.assertEqual(rc, 0) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_stop.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_stop.py deleted file mode 100644 index 07ac05b7..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_stop.py +++ /dev/null @@ -1,126 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import time -import signal -from twisted.trial import unittest -from buildbot.scripts import stop -from buildbot.test.util import dirs, misc, compat - -def mkconfig(**kwargs): - config = dict(quiet=False, clean=False, basedir=os.path.abspath('basedir')) - config.update(kwargs) - return config - -class TestStop(misc.StdoutAssertionsMixin, dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.setUpDirs('basedir') - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - # tests - - def do_test_stop(self, config, kill_sequence, is_running=True, **kwargs): - with open(os.path.join('basedir', 'buildbot.tac'), 'wt') as f: - f.write("Application('buildmaster')") - if is_running: - with open("basedir/twistd.pid", 'wt') as f: - f.write('1234') - def sleep(t): - what, exp_t = kill_sequence.pop(0) - self.assertEqual((what, exp_t), ('sleep', t)) - self.patch(time, 'sleep', sleep) - def kill(pid, signal): - exp_sig, result = kill_sequence.pop(0) - self.assertEqual((pid,signal), (1234,exp_sig)) - if isinstance(result, Exception): - raise result - else: - return result - self.patch(os, 'kill', kill) - rv = stop.stop(config, **kwargs) - self.assertEqual(kill_sequence, []) - return rv - - @compat.skipUnlessPlatformIs('posix') - def test_stop_not_running(self): - rv = self.do_test_stop(mkconfig(), [], is_running=False) - self.assertInStdout('not running') - self.assertEqual(rv, 0) - - @compat.skipUnlessPlatformIs('posix') - def test_stop_dead_but_pidfile_remains(self): - rv = self.do_test_stop(mkconfig(), - [ (signal.SIGTERM, OSError(3, 'No such process')) ]) - self.assertEqual(rv, 0) - self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) - self.assertInStdout('not running') - - @compat.skipUnlessPlatformIs('posix') - def test_stop_dead_but_pidfile_remains_quiet(self): - rv = self.do_test_stop(mkconfig(quiet=True), - [ (signal.SIGTERM, OSError(3, 'No such process')) ],) - self.assertEqual(rv, 0) - self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) - self.assertWasQuiet() - - @compat.skipUnlessPlatformIs('posix') - def test_stop_dead_but_pidfile_remains_wait(self): - rv = self.do_test_stop(mkconfig(), - [ (signal.SIGTERM, OSError(3, 'No such process')) ], - wait=True) - self.assertEqual(rv, 0) - self.assertFalse(os.path.exists(os.path.join('basedir', 'twistd.pid'))) - - @compat.skipUnlessPlatformIs('posix') - def test_stop_slow_death_wait(self): - rv = self.do_test_stop(mkconfig(), [ - (signal.SIGTERM, None), - ('sleep', 0.1), - (0, None), # polling.. - ('sleep', 1), - (0, None), - ('sleep', 1), - (0, None), - ('sleep', 1), - (0, OSError(3, 'No such process')), - ], - wait=True) - self.assertInStdout('is dead') - self.assertEqual(rv, 0) - - @compat.skipUnlessPlatformIs('posix') - def test_stop_slow_death_wait_timeout(self): - rv = self.do_test_stop(mkconfig(), [ - (signal.SIGTERM, None), - ('sleep', 0.1), ] + - [ (0, None), - ('sleep', 1), ] * 10, - wait=True) - self.assertInStdout('never saw process') - self.assertEqual(rv, 1) - - @compat.skipUnlessPlatformIs('posix') - def test_stop_clean(self): - rv = self.do_test_stop(mkconfig(clean=True), [ - (signal.SIGUSR1, None), ], wait=False) - self.assertInStdout('sent SIGUSR1 to process') - self.assertEqual(rv, 0) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_trycmd.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_trycmd.py deleted file mode 100644 index 88b32aba..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_trycmd.py +++ /dev/null @@ -1,33 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from buildbot.clients import tryclient -from buildbot.scripts import trycmd - -class TestStatusLog(unittest.TestCase): - - def test_trycmd(self): - Try = mock.Mock() - self.patch(tryclient, 'Try', Try) - inst = Try.return_value = mock.Mock(name='Try-instance') - - rc = trycmd.trycmd(dict(cfg=1)) - - Try.assert_called_with(dict(cfg=1)) - inst.run.assert_called_with() - self.assertEqual(rc, 0) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_tryserver.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_tryserver.py deleted file mode 100644 index 42ff72da..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_tryserver.py +++ /dev/null @@ -1,46 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import sys -from cStringIO import StringIO -from twisted.trial import unittest -from buildbot.scripts import tryserver -from buildbot.test.util import dirs - -class TestStatusLog(dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.newdir = os.path.join('jobdir', 'new') - self.tmpdir = os.path.join('jobdir', 'tmp') - self.setUpDirs("jobdir", self.newdir, self.tmpdir) - - def test_trycmd(self): - config = dict(jobdir='jobdir') - inputfile = StringIO('this is my try job') - self.patch(sys, 'stdin', inputfile) - - rc = tryserver.tryserver(config) - - self.assertEqual(rc, 0) - - newfiles = os.listdir(self.newdir) - tmpfiles = os.listdir(self.tmpdir) - self.assertEqual((len(newfiles), len(tmpfiles)), - (1, 0)) - with open(os.path.join(self.newdir, newfiles[0]), 'rt') as f: - self.assertEqual(f.read(), 'this is my try job') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_upgrade_master.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_upgrade_master.py deleted file mode 100644 index 1023d005..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_upgrade_master.py +++ /dev/null @@ -1,258 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.scripts import upgrade_master -from buildbot import config as config_module -from buildbot.db import connector, model -from buildbot.test.util import dirs, misc, compat - -def mkconfig(**kwargs): - config = dict(quiet=False, replace=False, basedir='test') - config.update(kwargs) - return config - -class TestUpgradeMaster(dirs.DirsMixin, misc.StdoutAssertionsMixin, - unittest.TestCase): - - def setUp(self): - # createMaster is decorated with @in_reactor, so strip that decoration - # since the master is already running - self.patch(upgrade_master, 'upgradeMaster', - upgrade_master.upgradeMaster._orig) - self.setUpDirs('test') - self.setUpStdoutAssertions() - - def patchFunctions(self, basedirOk=True, configOk=True): - self.calls = [] - - def checkBasedir(config): - self.calls.append('checkBasedir') - return basedirOk - self.patch(upgrade_master, 'checkBasedir', checkBasedir) - - def loadConfig(config, configFileName='master.cfg'): - self.calls.append('loadConfig') - return config_module.MasterConfig() if configOk else False - self.patch(upgrade_master, 'loadConfig', loadConfig) - - def upgradeFiles(config): - self.calls.append('upgradeFiles') - self.patch(upgrade_master, 'upgradeFiles', upgradeFiles) - - def upgradeDatabase(config, master_cfg): - self.assertIsInstance(master_cfg, config_module.MasterConfig) - self.calls.append('upgradeDatabase') - self.patch(upgrade_master, 'upgradeDatabase', upgradeDatabase) - - # tests - - def test_upgradeMaster_success(self): - self.patchFunctions() - d = upgrade_master.upgradeMaster(mkconfig(), _noMonkey=True) - @d.addCallback - def check(rv): - self.assertEqual(rv, 0) - self.assertInStdout('upgrade complete') - return d - - def test_upgradeMaster_quiet(self): - self.patchFunctions() - d = upgrade_master.upgradeMaster(mkconfig(quiet=True), _noMonkey=True) - @d.addCallback - def check(rv): - self.assertEqual(rv, 0) - self.assertWasQuiet() - return d - - def test_upgradeMaster_bad_basedir(self): - self.patchFunctions(basedirOk=False) - d = upgrade_master.upgradeMaster(mkconfig(), _noMonkey=True) - @d.addCallback - def check(rv): - self.assertEqual(rv, 1) - return d - - def test_upgradeMaster_bad_config(self): - self.patchFunctions(configOk=False) - d = upgrade_master.upgradeMaster(mkconfig(), _noMonkey=True) - @d.addCallback - def check(rv): - self.assertEqual(rv, 1) - return d - -class TestUpgradeMasterFunctions(dirs.DirsMixin, misc.StdoutAssertionsMixin, - unittest.TestCase): - - def setUp(self): - self.setUpDirs('test') - self.basedir = os.path.abspath(os.path.join('test', 'basedir')) - self.setUpStdoutAssertions() - - def tearDown(self): - self.tearDownDirs() - - def activeBasedir(self): - with open(os.path.join('test', 'buildbot.tac'), 'wt') as f: - f.write("Application('buildmaster')") - - def writeFile(self, path, contents): - with open(path, 'wt') as f: - f.write(contents) - - def readFile(self, path): - with open(path, 'rt') as f: - return f.read() - - # tests - - def test_checkBasedir(self): - self.activeBasedir() - rv = upgrade_master.checkBasedir(mkconfig()) - self.assertTrue(rv) - self.assertInStdout('checking basedir') - - def test_checkBasedir_quiet(self): - self.activeBasedir() - rv = upgrade_master.checkBasedir(mkconfig(quiet=True)) - self.assertTrue(rv) - self.assertWasQuiet() - - def test_checkBasedir_no_dir(self): - rv = upgrade_master.checkBasedir(mkconfig(basedir='doesntexist')) - self.assertFalse(rv) - self.assertInStdout('invalid buildmaster directory') - - @compat.skipUnlessPlatformIs('posix') - def test_checkBasedir_active_pidfile(self): - self.activeBasedir() - open(os.path.join('test', 'twistd.pid'), 'w').close() - rv = upgrade_master.checkBasedir(mkconfig()) - self.assertFalse(rv) - self.assertInStdout('still running') - - def test_loadConfig(self): - @classmethod - def loadConfig(cls, basedir, filename): - return config_module.MasterConfig() - self.patch(config_module.MasterConfig, 'loadConfig', loadConfig) - cfg = upgrade_master.loadConfig(mkconfig()) - self.assertIsInstance(cfg, config_module.MasterConfig) - self.assertInStdout('checking') - - def test_loadConfig_ConfigErrors(self): - @classmethod - def loadConfig(cls, basedir, filename): - raise config_module.ConfigErrors(['oh noes']) - self.patch(config_module.MasterConfig, 'loadConfig', loadConfig) - cfg = upgrade_master.loadConfig(mkconfig()) - self.assertIdentical(cfg, None) - self.assertInStdout('oh noes') - - def test_loadConfig_exception(self): - @classmethod - def loadConfig(cls, basedir, filename): - raise RuntimeError() - self.patch(config_module.MasterConfig, 'loadConfig', loadConfig) - cfg = upgrade_master.loadConfig(mkconfig()) - self.assertIdentical(cfg, None) - self.assertInStdout('RuntimeError') - - def test_installFile(self): - self.writeFile('test/srcfile', 'source data') - upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') - self.assertEqual(self.readFile('test/destfile'), 'source data') - self.assertInStdout('creating test/destfile') - - def test_installFile_existing_differing(self): - self.writeFile('test/srcfile', 'source data') - self.writeFile('test/destfile', 'dest data') - upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') - self.assertEqual(self.readFile('test/destfile'), 'dest data') - self.assertEqual(self.readFile('test/destfile.new'), 'source data') - self.assertInStdout('writing new contents to') - - def test_installFile_existing_differing_overwrite(self): - self.writeFile('test/srcfile', 'source data') - self.writeFile('test/destfile', 'dest data') - upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile', - overwrite=True) - self.assertEqual(self.readFile('test/destfile'), 'source data') - self.assertFalse(os.path.exists('test/destfile.new')) - self.assertInStdout('overwriting') - - def test_installFile_existing_same(self): - self.writeFile('test/srcfile', 'source data') - self.writeFile('test/destfile', 'source data') - upgrade_master.installFile(mkconfig(), 'test/destfile', 'test/srcfile') - self.assertEqual(self.readFile('test/destfile'), 'source data') - self.assertFalse(os.path.exists('test/destfile.new')) - self.assertWasQuiet() - - def test_installFile_quiet(self): - self.writeFile('test/srcfile', 'source data') - upgrade_master.installFile(mkconfig(quiet=True), 'test/destfile', - 'test/srcfile') - self.assertWasQuiet() - - def test_upgradeFiles(self): - upgrade_master.upgradeFiles(mkconfig()) - for f in [ - 'test/public_html', - 'test/public_html/bg_gradient.jpg', - 'test/public_html/default.css', - 'test/public_html/robots.txt', - 'test/public_html/favicon.ico', - 'test/templates', - 'test/master.cfg.sample', - ]: - self.assertTrue(os.path.exists(f), "%s not found" % f) - self.assertInStdout('upgrading basedir') - - def test_upgradeFiles_rename_index_html(self): - os.mkdir('test/public_html') - self.writeFile('test/public_html/index.html', 'INDEX') - upgrade_master.upgradeFiles(mkconfig()) - self.assertFalse(os.path.exists("test/public_html/index.html")) - self.assertEqual(self.readFile("test/templates/root.html"), 'INDEX') - self.assertInStdout('Moving ') - - def test_upgradeFiles_index_html_collision(self): - os.mkdir('test/public_html') - self.writeFile('test/public_html/index.html', 'INDEX') - os.mkdir('test/templates') - self.writeFile('test/templates/root.html', 'ROOT') - upgrade_master.upgradeFiles(mkconfig()) - self.assertTrue(os.path.exists("test/public_html/index.html")) - self.assertEqual(self.readFile("test/templates/root.html"), 'ROOT') - self.assertInStdout('Decide') - - @defer.inlineCallbacks - def test_upgradeDatabase(self): - setup = mock.Mock(side_effect=lambda **kwargs : defer.succeed(None)) - self.patch(connector.DBConnector, 'setup', setup) - upgrade = mock.Mock(side_effect=lambda **kwargs : defer.succeed(None)) - self.patch(model.Model, 'upgrade', upgrade) - yield upgrade_master.upgradeDatabase( - mkconfig(basedir='test', quiet=True), - config_module.MasterConfig()) - setup.asset_called_with(check_version=False, verbose=False) - upgrade.assert_called() - self.assertWasQuiet() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_user.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_user.py deleted file mode 100644 index 2291c50e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_scripts_user.py +++ /dev/null @@ -1,100 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer, reactor -from buildbot.scripts import user -from buildbot.clients import usersclient -from buildbot.process.users import users - -class TestUsersClient(unittest.TestCase): - - class FakeUsersClient(object): - def __init__(self, master, username="user", passwd="userpw", port=0): - self.master = master - self.port = port - self.username = username - self.passwd = passwd - self.fail = False - - def send(self, op, bb_username, bb_password, ids, info): - self.op = op - self.bb_username = bb_username - self.bb_password = bb_password - self.ids = ids - self.info = info - d = defer.Deferred() - if self.fail: - reactor.callLater(0, d.errback, RuntimeError("oh noes")) - else: - reactor.callLater(0, d.callback, None) - return d - - def setUp(self): - def fake_UsersClient(*args): - self.usersclient = self.FakeUsersClient(*args) - return self.usersclient - self.patch(usersclient, 'UsersClient', fake_UsersClient) - - # un-do the effects of @in_reactor - self.patch(user, 'user', user.user._orig) - - def test_usersclient_send_ids(self): - d = user.user(dict(master='a:9990', username="x", - passwd="y", op='get', bb_username=None, - bb_password=None, ids=['me', 'you'], - info=None)) - def check(_): - c = self.usersclient - self.assertEqual((c.master, c.port, c.username, c.passwd, c.op, - c.ids, c.info), - ('a', 9990, "x", "y", 'get', ['me', 'you'], None)) - d.addCallback(check) - return d - - def test_usersclient_send_update_info(self): - def _fake_encrypt(passwd): - assert passwd == 'day' - return 'ENCRY' - self.patch(users, 'encrypt', _fake_encrypt) - - d = user.user(dict(master='a:9990', username="x", - passwd="y", op='update', bb_username='bud', - bb_password='day', ids=None, - info=[{'identifier':'x', 'svn':'x'}])) - def check(_): - c = self.usersclient - self.assertEqual((c.master, c.port, c.username, c.passwd, c.op, - c.bb_username, c.bb_password, c.ids, c.info), - ('a', 9990, "x", "y", 'update', 'bud', 'ENCRY', - None, [{'identifier':'x', 'svn':'x'}])) - d.addCallback(check) - return d - - def test_usersclient_send_add_info(self): - d = user.user(dict(master='a:9990', username="x", - passwd="y", op='add', bb_username=None, - bb_password=None, ids=None, - info=[{'git':'x <h@c>', 'irc':'aaa'}])) - def check(_): - c = self.usersclient - self.assertEqual((c.master, c.port, c.username, c.passwd, c.op, - c.bb_username, c.bb_password, c.ids, c.info), - ('a', 9990, "x", "y", 'add', None, None, None, - [{'identifier':'aaa', - 'git': 'x <h@c>', - 'irc': 'aaa'}])) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_sourcestamp.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_sourcestamp.py deleted file mode 100644 index 3af7d505..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_sourcestamp.py +++ /dev/null @@ -1,195 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from buildbot.changes import changes -from buildbot.test.fake import fakedb, fakemaster -from buildbot import sourcestamp - -class TestBuilderBuildCreation(unittest.TestCase): - - def test_fromSsdict_changes(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.Change(changeid=13, branch='trunk', revision='9283', - repository='svn://...', codebase='cb', - project='world-domination'), - fakedb.Change(changeid=14, branch='trunk', revision='9284', - repository='svn://...', codebase='cb', - project='world-domination'), - fakedb.Change(changeid=15, branch='trunk', revision='9284', - repository='svn://...', codebase='cb', - project='world-domination'), - fakedb.Change(changeid=16, branch='trunk', revision='9284', - repository='svn://...', codebase='cb', - project='world-domination'), - fakedb.SourceStamp(id=234, branch='trunk', revision='9284', - repository='svn://...', codebase='cb', - project='world-domination'), - fakedb.SourceStampChange(sourcestampid=234, changeid=14), - fakedb.SourceStampChange(sourcestampid=234, changeid=13), - fakedb.SourceStampChange(sourcestampid=234, changeid=15), - fakedb.SourceStampChange(sourcestampid=234, changeid=16), - ]) - # use getSourceStamp to minimize the risk from changes to the format of - # the ssdict - d = master.db.sourcestamps.getSourceStamp(234) - d.addCallback(lambda ssdict : - sourcestamp.SourceStamp.fromSsdict(master, ssdict)) - def check(ss): - self.assertEqual(ss.ssid, 234) - self.assertEqual(ss.branch, 'trunk') - self.assertEqual(ss.revision, '9284') - self.assertEqual(ss.patch, None) - self.assertEqual(ss.patch_info, None) - self.assertEqual([ ch.number for ch in ss.changes], - [13, 14, 15, 16]) - self.assertEqual(ss.project, 'world-domination') - self.assertEqual(ss.repository, 'svn://...') - self.assertEqual(ss.codebase, 'cb') - d.addCallback(check) - return d - - def test_fromSsdict_patch(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.Patch(id=99, subdir='/foo', patchlevel=3, - patch_base64='LS0gKys=', - patch_author='Professor Chaos', - patch_comment='comment'), - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='trunk', revision='9284', - repository='svn://...', codebase='cb', project='world-domination', - patchid=99), - ]) - # use getSourceStamp to minimize the risk from changes to the format of - # the ssdict - d = master.db.sourcestamps.getSourceStamp(234) - d.addCallback(lambda ssdict : - sourcestamp.SourceStamp.fromSsdict(master, ssdict)) - def check(ss): - self.assertEqual(ss.ssid, 234) - self.assertEqual(ss.branch, 'trunk') - self.assertEqual(ss.revision, '9284') - self.assertEqual(ss.patch, (3, '-- ++', '/foo')) - self.assertEqual(ss.patch_info, ('Professor Chaos', 'comment')) - self.assertEqual(ss.changes, ()) - self.assertEqual(ss.project, 'world-domination') - self.assertEqual(ss.repository, 'svn://...') - self.assertEqual(ss.codebase, 'cb') - d.addCallback(check) - return d - - def test_fromSsdict_simple(self): - master = fakemaster.make_master() - master.db = fakedb.FakeDBConnector(self) - master.db.insertTestData([ - fakedb.SourceStamp(id=234, sourcestampsetid=234, branch='trunk', revision='9284', - repository='svn://...', codebase = 'cb', project='world-domination'), - ]) - # use getSourceStamp to minimize the risk from changes to the format of - # the ssdict - d = master.db.sourcestamps.getSourceStamp(234) - d.addCallback(lambda ssdict : - sourcestamp.SourceStamp.fromSsdict(master, ssdict)) - def check(ss): - self.assertEqual(ss.ssid, 234) - self.assertEqual(ss.branch, 'trunk') - self.assertEqual(ss.revision, '9284') - self.assertEqual(ss.patch, None) - self.assertEqual(ss.patch_info, None) - self.assertEqual(ss.changes, ()) - self.assertEqual(ss.project, 'world-domination') - self.assertEqual(ss.repository, 'svn://...') - self.assertEqual(ss.codebase, 'cb') - d.addCallback(check) - return d - - def test_getAbsoluteSourceStamp_from_relative(self): - ss = sourcestamp.SourceStamp(branch='dev', revision=None, - project='p', repository='r', codebase='cb') - abs_ss = ss.getAbsoluteSourceStamp('abcdef') - self.assertEqual(abs_ss.branch, 'dev') - self.assertEqual(abs_ss.revision, 'abcdef') - self.assertEqual(abs_ss.project, 'p') - self.assertEqual(abs_ss.repository, 'r') - self.assertEqual(abs_ss.codebase, 'cb') - - def test_getAbsoluteSourceStamp_from_absolute(self): - ss = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cb') - abs_ss = ss.getAbsoluteSourceStamp('abcdef') - self.assertEqual(abs_ss.branch, 'dev') - # revision gets overridden - self.assertEqual(abs_ss.revision, 'abcdef') - self.assertEqual(abs_ss.project, 'p') - self.assertEqual(abs_ss.repository, 'r') - self.assertEqual(abs_ss.codebase, 'cb') - - def test_getAbsoluteSourceStamp_from_absolute_with_changes(self): - c1 = mock.Mock() - c1.branch = 'dev' - c1.revision = 'xyz' - c1.project = 'p' - c1.repository = 'r' - c1.codebase = 'cb' - ss = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cb', changes=[c1]) - abs_ss = ss.getAbsoluteSourceStamp('abcdef') - self.assertEqual(abs_ss.branch, 'dev') - # revision changes, even though changes say different - this is - # useful for CVS, for example - self.assertEqual(abs_ss.revision, 'abcdef') - self.assertEqual(abs_ss.project, 'p') - self.assertEqual(abs_ss.repository, 'r') - self.assertEqual(abs_ss.codebase, 'cb') - - def test_canBeMergedWith_where_sourcestamp_do_not_both_have_changes(self): - c1 = mock.Mock() - c1.codebase = 'cb' - ss1 = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cb', changes=[c1]) - ss2 = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cb', changes=[]) - self.assertFalse(ss1.canBeMergedWith(ss2)) - - def test_canBeMergedWith_where_sourcestamp_have_different_codebases(self): - ss1 = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cbA', changes=[]) - ss2 = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cbB', changes=[]) - self.assertFalse(ss1.canBeMergedWith(ss2)) - - def test_canBeMergedWith_with_self_patched_sourcestamps(self): - ss = sourcestamp.SourceStamp(branch='dev', revision='xyz', - project='p', repository='r', codebase='cbA', changes=[], - patch=(1, '')) - self.assertTrue(ss.canBeMergedWith(ss)) - - def test_constructor_most_recent_change(self): - chgs = [ - changes.Change('author', [], 'comments', branch='branch', - revision='2'), - changes.Change('author', [], 'comments', branch='branch', - revision='3'), - changes.Change('author', [], 'comments', branch='branch', - revision='1'), - ] - for ch in chgs: # mock the DB changeid (aka build number) to match rev - ch.number = int(ch.revision) - ss = sourcestamp.SourceStamp(changes=chgs) - self.assertEquals(ss.revision, '3') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_build.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_build.py deleted file mode 100644 index 2917f855..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_build.py +++ /dev/null @@ -1,135 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from zope.interface import implements -import mock -from twisted.trial import unittest -from buildbot.status import build -from buildbot import interfaces -from buildbot.test.fake import fakemaster -from buildbot import util - -class FakeBuilderStatus: - implements(interfaces.IBuilderStatus) - -class FakeSource(util.ComparableMixin): - compare_attrs = ('codebase', 'revision') - def __init__(self, codebase, revision): - self.codebase = codebase - self.revision = revision - - def clone(self): - return FakeSource(self.codebase, self.revision) - - def getAbsoluteSourceStamp(self, revision): - return FakeSource(self.codebase, revision) - - def __repr__(self): - # note: this won't work for VC systems with huge 'revision' strings - text = [] - if self.codebase: - text.append("(%s)" % self.codebase) - if self.revision is None: - return text + [ "latest" ] - text.append(str(self.revision)) - return "FakeSource(%s)" % (', '.join(text),) - -class TestBuildProperties(unittest.TestCase): - """ - Test that a BuildStatus has the necessary L{IProperties} methods and that - they delegate to its C{properties} attribute properly - so really just a - test of the L{IProperties} adapter. - """ - - BUILD_NUMBER = 33 - - def setUp(self): - self.builder_status = FakeBuilderStatus() - self.master = fakemaster.make_master() - self.build_status = build.BuildStatus(self.builder_status, self.master, - self.BUILD_NUMBER) - self.build_status.properties = mock.Mock() - - def test_getProperty(self): - self.build_status.getProperty('x') - self.build_status.properties.getProperty.assert_called_with('x', None) - - def test_getProperty_default(self): - self.build_status.getProperty('x', 'nox') - self.build_status.properties.getProperty.assert_called_with('x', 'nox') - - def test_setProperty(self): - self.build_status.setProperty('n', 'v', 's') - self.build_status.properties.setProperty.assert_called_with('n', 'v', - 's', runtime=True) - - def test_hasProperty(self): - self.build_status.properties.hasProperty.return_value = True - self.assertTrue(self.build_status.hasProperty('p')) - self.build_status.properties.hasProperty.assert_called_with('p') - - def test_render(self): - self.build_status.render("xyz") - self.build_status.properties.render.assert_called_with("xyz") - -class TestBuildGetSourcestamps(unittest.TestCase): - """ - Test that a BuildStatus has the necessary L{IProperties} methods and that - they delegate to its C{properties} attribute properly - so really just a - test of the L{IProperties} adapter. - """ - BUILD_NUMBER = 33 - - def setUp(self): - self.builder_status = FakeBuilderStatus() - self.master = fakemaster.make_master() - self.build_status = build.BuildStatus(self.builder_status, self.master, - self.BUILD_NUMBER) - - def test_getSourceStamps_no_codebases(self): - got_revisions = {'': '1111111'} - self.build_status.sources = [FakeSource('', '0000000')] - self.build_status.setProperty('got_revision', got_revisions) - sourcestamps = [ss for ss in self.build_status.getSourceStamps(absolute=False)] - self.assertEqual(sourcestamps, [FakeSource('', '0000000')]) - - def test_getSourceStamps_no_codebases_absolute(self): - got_revisions = {'': '1111111'} - self.build_status.sources = [FakeSource('', '0000000')] - self.build_status.setProperty('got_revision', got_revisions) - sourcestamps = [ss for ss in self.build_status.getSourceStamps(absolute=True)] - self.assertEqual(sourcestamps, [FakeSource('', '1111111')]) - - def test_getSourceStamps_with_codebases_absolute(self): - got_revisions = {'lib1': '1111111', 'lib2': 'aaaaaaa'} - self.build_status.sources = [FakeSource('lib1', '0000000'), - FakeSource('lib2', '0000000')] - self.build_status.setProperty('got_revision', got_revisions) - sourcestamps = [ss for ss in self.build_status.getSourceStamps(absolute=True)] - expected_sourcestamps = [FakeSource('lib1', '1111111'), - FakeSource('lib2', 'aaaaaaa')] - self.assertEqual(sourcestamps, expected_sourcestamps) - - def test_getSourceStamps_with_codebases_less_gotrevisions_absolute(self): - got_revisions = {'lib1': '1111111', 'lib2': 'aaaaaaa'} - self.build_status.sources = [FakeSource('lib1', '0000000'), - FakeSource('lib2', '0000000'), - FakeSource('lib3', '0000000')] - self.build_status.setProperty('got_revision', got_revisions) - sourcestamps = [ss for ss in self.build_status.getSourceStamps(absolute=True)] - expected_sourcestamps = [FakeSource('lib1', '1111111'), - FakeSource('lib2', 'aaaaaaa'), - FakeSource('lib3', '0000000')] - self.assertEqual(sourcestamps, expected_sourcestamps) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_builder_cache.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_builder_cache.py deleted file mode 100644 index 4e7a36f7..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_builder_cache.py +++ /dev/null @@ -1,73 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -from mock import Mock -from twisted.trial import unittest -from buildbot.status import builder, master -from buildbot.test.fake import fakemaster - -class TestBuildStatus(unittest.TestCase): - - # that buildstep.BuildStepStatus is never instantiated here should tell you - # that these classes are not well isolated! - - def setupBuilder(self, buildername, category=None, description=None): - m = fakemaster.make_master() - b = builder.BuilderStatus(buildername=buildername, category=category, - master=m, description=description) - # Awkwardly, Status sets this member variable. - b.basedir = os.path.abspath(self.mktemp()) - os.mkdir(b.basedir) - # Otherwise, builder.nextBuildNumber is not defined. - b.determineNextBuildNumber() - # Must initialize these fields before pickling. - b.currentBigState = 'idle' - b.status = 'idle' - return b - - def setupStatus(self, b): - m = Mock() - m.buildbotURL = 'http://buildbot:8010/' - m.basedir = '/basedir' - s = master.Status(m) - b.status = s - return s - - def testBuildCache(self): - b = self.setupBuilder('builder_1') - builds = [] - for i in xrange(5): - build = b.newBuild() - build.setProperty('propkey', 'propval%d' % i, 'test') - builds.append(build) - build.buildStarted(build) - build.buildFinished() - for build in builds: - build2 = b.getBuild(build.number) - self.assertTrue(build2) - self.assertEqual(build2.number, build.number) - self.assertEqual(build2.getProperty('propkey'), - 'propval%d' % build.number) - # Do another round, to make sure we're hitting the cache - hits = b.buildCache.hits - for build in builds: - build2 = b.getBuild(build.number) - self.assertTrue(build2) - self.assertEqual(build2.number, build.number) - self.assertEqual(build2.getProperty('propkey'), - 'propval%d' % build.number) - self.assertEqual(b.buildCache.hits, hits+1) - hits = hits + 1 diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_buildstep.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_buildstep.py deleted file mode 100644 index 44e2d504..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_buildstep.py +++ /dev/null @@ -1,67 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -from twisted.trial import unittest -from buildbot.status import builder, master -from buildbot.test.fake import fakemaster - -class TestBuildStepStatus(unittest.TestCase): - - # that buildstep.BuildStepStatus is never instantiated here should tell you - # that these classes are not well isolated! - - def setupBuilder(self, buildername, category=None, description=None): - self.master = fakemaster.make_master() - self.master.basedir = '/basedir' - - b = builder.BuilderStatus(buildername, self.master, category, description) - b.master = self.master - # Ackwardly, Status sets this member variable. - b.basedir = os.path.abspath(self.mktemp()) - os.mkdir(b.basedir) - # Otherwise, builder.nextBuildNumber is not defined. - b.determineNextBuildNumber() - return b - - def setupStatus(self, b): - s = master.Status(self.master) - b.status = s - return s - - def testBuildStepNumbers(self): - b = self.setupBuilder('builder_1') - bs = b.newBuild() - self.assertEquals(0, bs.getNumber()) - bss1 = bs.addStepWithName('step_1') - self.assertEquals('step_1', bss1.getName()) - bss2 = bs.addStepWithName('step_2') - self.assertEquals(0, bss1.asDict()['step_number']) - self.assertEquals('step_2', bss2.getName()) - self.assertEquals(1, bss2.asDict()['step_number']) - self.assertEquals([bss1, bss2], bs.getSteps()) - - def testLogDict(self): - b = self.setupBuilder('builder_1') - self.setupStatus(b) - bs = b.newBuild() - bss1 = bs.addStepWithName('step_1') - bss1.stepStarted() - bss1.addLog('log_1') - self.assertEquals( - bss1.asDict()['logs'], - [['log_1', ('http://localhost:8080/builders/builder_1/' - 'builds/0/steps/step_1/logs/log_1')]] - ) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_client.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_client.py deleted file mode 100644 index 75e93fb4..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_client.py +++ /dev/null @@ -1,47 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from buildbot.status import master, client -from buildbot.test.fake import fakedb - -class TestStatusClientPerspective(unittest.TestCase): - - def makeStatusClientPersp(self): - m = mock.Mock(name='master') - self.db = m.db = fakedb.FakeDBConnector(self) - m.basedir = r'C:\BASEDIR' - s = master.Status(m) - persp = client.StatusClientPerspective(s) - return persp - - def test_getBuildSets(self): - persp = self.makeStatusClientPersp() - self.db.insertTestData([ - fakedb.SourceStampSet(id=234), - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - complete_at=298297875, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn1'), - ]) - - d = persp.perspective_getBuildSets() - def check(bslist): - self.assertEqual(len(bslist), 1) - self.assertEqual(bslist[0][1], 91) - self.failUnlessIsInstance(bslist[0][0], client.RemoteBuildSet) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_logfile.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_logfile.py deleted file mode 100644 index a2f7153f..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_logfile.py +++ /dev/null @@ -1,336 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -import cStringIO, cPickle -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.status import logfile -from buildbot.test.util import dirs -from buildbot import config - -class TestLogFileProducer(unittest.TestCase): - def make_static_logfile(self, contents): - "make a fake logfile with the given contents" - lf = mock.Mock() - lf.getFile = lambda : cStringIO.StringIO(contents) - lf.waitUntilFinished = lambda : defer.succeed(None) # already finished - lf.runEntries = [] - return lf - - def test_getChunks_static_helloworld(self): - lf = self.make_static_logfile("13:0hello world!,") - lfp = logfile.LogFileProducer(lf, mock.Mock()) - chunks = list(lfp.getChunks()) - self.assertEqual(chunks, [ (0, 'hello world!') ]) - - def test_getChunks_static_multichannel(self): - lf = self.make_static_logfile("2:0a,3:1xx,2:0c,") - lfp = logfile.LogFileProducer(lf, mock.Mock()) - chunks = list(lfp.getChunks()) - self.assertEqual(chunks, [ (0, 'a'), (1, 'xx'), (0, 'c') ]) - - # Remainder of LogFileProduer has a wacky interface that's not - # well-defined, so it's not tested yet - -class TestLogFile(unittest.TestCase, dirs.DirsMixin): - - def setUp(self): - step = self.build_step_status = mock.Mock(name='build_step_status') - self.basedir = step.build.builder.basedir = os.path.abspath('basedir') - self.setUpDirs(self.basedir) - self.logfile = logfile.LogFile(step, 'testlf', '123-stdio') - self.master = self.logfile.master = mock.Mock() - self.config = self.logfile.master.config = config.MasterConfig() - - def tearDown(self): - if self.logfile.openfile: - try: - self.logfile.openfile.close() - except: - pass # oh well, we tried - self.tearDownDirs() - - def pickle_and_restore(self): - pkl = cPickle.dumps(self.logfile) - self.logfile = cPickle.loads(pkl) - step = self.build_step_status - self.logfile.step = step - self.logfile.master = self.master - step.build.builder.basedir = self.basedir - - def delete_logfile(self): - if self.logfile.openfile: - try: - self.logfile.openfile.close() - except: - pass # oh well, we tried - os.unlink(os.path.join('basedir', '123-stdio')) - - # tests - - def test_getFilename(self): - self.assertEqual(self.logfile.getFilename(), - os.path.abspath(os.path.join('basedir', '123-stdio'))) - - def test_hasContents_yes(self): - self.assertTrue(self.logfile.hasContents()) - - def test_hasContents_no(self): - self.delete_logfile() - self.assertFalse(self.logfile.hasContents()) - - def test_hasContents_gz(self): - self.delete_logfile() - with open(os.path.join(self.basedir, '123-stdio.gz'), "w") as f: - f.write("hi") - self.assertTrue(self.logfile.hasContents()) - - def test_hasContents_gz_pickled(self): - self.delete_logfile() - with open(os.path.join(self.basedir, '123-stdio.gz'), "w") as f: - f.write("hi") - self.pickle_and_restore() - self.assertTrue(self.logfile.hasContents()) - - def test_hasContents_bz2(self): - self.delete_logfile() - with open(os.path.join(self.basedir, '123-stdio.bz2'), "w") as f: - f.write("hi") - self.assertTrue(self.logfile.hasContents()) - - def test_getName(self): - self.assertEqual(self.logfile.getName(), 'testlf') - - def test_getStep(self): - self.assertEqual(self.logfile.getStep(), self.build_step_status) - - def test_isFinished_no(self): - self.assertFalse(self.logfile.isFinished()) - - def test_isFinished_yes(self): - self.logfile.finish() - self.assertTrue(self.logfile.isFinished()) - - def test_waitUntilFinished(self): - state = [] - d = self.logfile.waitUntilFinished() - d.addCallback(lambda _ : state.append('called')) - self.assertEqual(state, []) # not called yet - self.logfile.finish() - self.assertEqual(state, ['called']) - - def test_getFile(self): - # test getFile at a number of points in the life-cycle - self.logfile.addEntry(0, 'hello, world') - self.logfile._merge() - - # while still open for writing - fp = self.logfile.getFile() - fp.seek(0, 0) - self.assertEqual(fp.read(), '13:0hello, world,') - - self.logfile.finish() - - # fp is still open after finish() - fp.seek(0, 0) - self.assertEqual(fp.read(), '13:0hello, world,') - - # but a fresh getFile call works, too - fp = self.logfile.getFile() - fp.seek(0, 0) - self.assertEqual(fp.read(), '13:0hello, world,') - - self.pickle_and_restore() - - # even after it is pickled - fp = self.logfile.getFile() - fp.seek(0, 0) - self.assertEqual(fp.read(), '13:0hello, world,') - - # ..and compressed - self.config.logCompressionMethod = 'bz2' - d = self.logfile.compressLog() - def check(_): - self.assertTrue( - os.path.exists(os.path.join(self.basedir, '123-stdio.bz2'))) - fp = self.logfile.getFile() - fp.seek(0, 0) - self.assertEqual(fp.read(), '13:0hello, world,') - d.addCallback(check) - return d - - def do_test_addEntry(self, entries, expected): - for chan, txt in entries: - self.logfile.addEntry(chan, txt) - self.logfile.finish() - fp = self.logfile.getFile() - fp.seek(0, 0) - self.assertEqual(fp.read(), expected) - - def test_addEntry_single(self): - return self.do_test_addEntry([(0, 'hello, world')], - '13:0hello, world,') - - def test_addEntry_run(self): - # test that addEntry is calling merge() correctly - return self.do_test_addEntry([ (0, c) for c in 'hello, world' ], - '13:0hello, world,') - - def test_addEntry_multichan(self): - return self.do_test_addEntry([(1, 'x'), (2, 'y'), (1, 'z')], - '2:1x,2:2y,2:1z,') - - def test_addEntry_length(self): - self.do_test_addEntry([(1, 'x'), (2, 'y')], - '2:1x,2:2y,') - self.assertEqual(self.logfile.length, 2) - - def test_addEntry_unicode(self): - return self.do_test_addEntry([(1, u'\N{SNOWMAN}')], - '4:1\xe2\x98\x83,') # utf-8 encoded - - def test_addEntry_logMaxSize(self): - self.config.logMaxSize = 10 # not evenly divisible by chunk size - return self.do_test_addEntry([(0, 'abcdef')] * 10 , - '11:0abcdefabcd,' - '64:2\nOutput exceeded 10 bytes, remaining output has been ' - 'truncated\n,') - - def test_addEntry_logMaxSize_ignores_header(self): - self.config.logMaxSize = 10 - return self.do_test_addEntry([(logfile.HEADER, 'abcdef')] * 10 , - '61:2' + 'abcdef'*10 + ',') - - def test_addEntry_logMaxSize_divisor(self): - self.config.logMaxSize = 12 # evenly divisible by chunk size - return self.do_test_addEntry([(0, 'abcdef')] * 10 , - '13:0abcdefabcdef,' - '64:2\nOutput exceeded 12 bytes, remaining output has been ' - 'truncated\n,') - - def test_addEntry_logMaxTailSize(self): - self.config.logMaxSize = 10 - self.config.logMaxTailSize = 14 - return self.do_test_addEntry([(0, 'abcdef')] * 10 , - '11:0abcdefabcd,' - '64:2\nOutput exceeded 10 bytes, remaining output has been ' - 'truncated\n,' - # NOTE: this gets too few bytes; this is OK for now, and - # easier than subdividing chunks in the tail tracking - '31:2\nFinal 12 bytes follow below:\n,' - '13:0abcdefabcdef,') - - def test_addEntry_logMaxTailSize_divisor(self): - self.config.logMaxSize = 10 - self.config.logMaxTailSize = 12 - return self.do_test_addEntry([(0, 'abcdef')] * 10 , - '11:0abcdefabcd,' - '64:2\nOutput exceeded 10 bytes, remaining output has been ' - 'truncated\n,' - '31:2\nFinal 12 bytes follow below:\n,' - '13:0abcdefabcdef,') - - # TODO: test that head and tail don't discriminate between stderr and stdout - - def test_addEntry_chunkSize(self): - self.logfile.chunkSize = 11 - return self.do_test_addEntry([(0, 'abcdef')] * 10 , - # note that this doesn't re-chunk everything; just shrinks - # chunks that will exceed the maximum size - '12:0abcdefabcde,2:0f,' * 5) - - def test_addEntry_big_channel(self): - # channels larger than one digit are not allowed - self.assertRaises(AssertionError, - lambda : self.do_test_addEntry([(9999, 'x')], '')) - - def test_addEntry_finished(self): - self.logfile.finish() - self.assertRaises(AssertionError, - lambda : self.do_test_addEntry([(0, 'x')], '')) - - def test_addEntry_merge_exception(self): - def fail(): - raise RuntimeError("FAIL") - self.patch(self.logfile, '_merge', fail) - self.assertRaises(RuntimeError, - lambda : self.do_test_addEntry([(0, 'x')], '')) - - def test_addEntry_watchers(self): - watcher = mock.Mock(name='watcher') - self.logfile.watchers.append(watcher) - self.do_test_addEntry([(0, 'x')], '2:0x,') - watcher.logChunk.assert_called_with(self.build_step_status.build, - self.build_step_status, self.logfile, 0, 'x') - - def test_addEntry_watchers_logMaxSize(self): - watcher = mock.Mock(name='watcher') - self.logfile.watchers.append(watcher) - self.config.logMaxSize = 10 - self.do_test_addEntry([(0, 'x')] * 15, - '11:0xxxxxxxxxx,' - '64:2\nOutput exceeded 10 bytes, remaining output has been ' - 'truncated\n,') - logChunk_chunks = [ tuple(args[0][3:]) - for args in watcher.logChunk.call_args_list ] - self.assertEqual(logChunk_chunks, [(0, 'x')] * 15) - - def test_addStdout(self): - addEntry = mock.Mock() - self.patch(self.logfile, 'addEntry', addEntry) - self.logfile.addStdout('oot') - addEntry.assert_called_with(0, 'oot') - - def test_addStderr(self): - addEntry = mock.Mock() - self.patch(self.logfile, 'addEntry', addEntry) - self.logfile.addStderr('eer') - addEntry.assert_called_with(1, 'eer') - - def test_addHeader(self): - addEntry = mock.Mock() - self.patch(self.logfile, 'addEntry', addEntry) - self.logfile.addHeader('hed') - addEntry.assert_called_with(2, 'hed') - - def do_test_compressLog(self, ext, expect_comp=True): - self.logfile.openfile.write('xyz' * 1000) - self.logfile.finish() - d = self.logfile.compressLog() - def check(_): - st = os.stat(self.logfile.getFilename() + ext) - if expect_comp: - self.assertTrue(0 < st.st_size < 3000) - else: - self.assertTrue(st.st_size == 3000) - d.addCallback(check) - return d - - def test_compressLog_gz(self): - self.config.logCompressionMethod = 'gz' - return self.do_test_compressLog('.gz') - - def test_compressLog_bz2(self): - self.config.logCompressionMethod = 'bz2' - return self.do_test_compressLog('.bz2') - - def test_compressLog_none(self): - self.config.logCompressionMethod = None - return self.do_test_compressLog('', expect_comp=False) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_mail.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_mail.py deleted file mode 100644 index 3ca64247..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_mail.py +++ /dev/null @@ -1,816 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sys -from mock import Mock -from buildbot import config -from twisted.trial import unittest -from buildbot.status.results import SUCCESS, FAILURE, WARNINGS, EXCEPTION -from buildbot.status.mail import MailNotifier -from twisted.internet import defer -from buildbot.test.fake import fakedb -from buildbot.test.fake.fakebuild import FakeBuildStatus -from buildbot.process import properties - -py_27 = sys.version_info[0] > 2 or (sys.version_info[0] == 2 - and sys.version_info[1] >= 7) - -class FakeLog(object): - def __init__(self, text): - self.text = text - - def getName(self): - return 'log-name' - - def getStep(self): - class FakeStep(object): - def getName(self): - return 'step-name' - return FakeStep() - - def getText(self): - return self.text - -class FakeSource: - def __init__(self, branch = None, revision = None, repository = None, - codebase = None, project = None): - self.changes = [] - self.branch = branch - self.revision = revision - self.repository = repository - self.codebase = codebase - self.project = project - self.patch_info = None - self.patch = None - -class TestMailNotifier(unittest.TestCase): - - def do_test_createEmail_cte(self, funnyChars, expEncoding): - builds = [ FakeBuildStatus(name='build') ] - msgdict = create_msgdict(funnyChars) - mn = MailNotifier('from@example.org') - d = mn.createEmail(msgdict, u'builder-name', u'project-name', - SUCCESS, builds) - @d.addCallback - def callback(m): - cte_lines = [ l for l in m.as_string().split("\n") - if l.startswith('Content-Transfer-Encoding:') ] - self.assertEqual(cte_lines, - [ 'Content-Transfer-Encoding: %s' % expEncoding ], - `m.as_string()`) - return d - - def test_createEmail_message_content_transfer_encoding_7bit(self): - return self.do_test_createEmail_cte(u"old fashioned ascii", - '7bit' if py_27 else 'base64') - - def test_createEmail_message_content_transfer_encoding_8bit(self): - return self.do_test_createEmail_cte(u"\U0001F4A7", - '8bit' if py_27 else 'base64') - - def test_createEmail_message_without_patch_and_log_contains_unicode(self): - builds = [ FakeBuildStatus(name="build") ] - msgdict = create_msgdict() - mn = MailNotifier('from@example.org') - d = mn.createEmail(msgdict, u'builder-n\u00E5me', u'project-n\u00E5me', - SUCCESS, builds) - @d.addCallback - def callback(m): - try: - m.as_string() - except UnicodeEncodeError: - self.fail('Failed to call as_string() on email message.') - return d - - def test_createEmail_extraHeaders_one_build(self): - builds = [ FakeBuildStatus(name="build") ] - builds[0].properties = properties.Properties() - builds[0].setProperty('hhh','vvv') - msgdict = create_msgdict() - mn = MailNotifier('from@example.org', extraHeaders=dict(hhh='vvv')) - # add some Unicode to detect encoding problems - d = mn.createEmail(msgdict, u'builder-n\u00E5me', u'project-n\u00E5me', - SUCCESS, builds) - @d.addCallback - def callback(m): - txt = m.as_string() - self.assertIn('hhh: vvv', txt) - return d - - def test_createEmail_extraHeaders_two_builds(self): - builds = [ FakeBuildStatus(name="build1"), - FakeBuildStatus(name="build2") ] - msgdict = create_msgdict() - mn = MailNotifier('from@example.org', extraHeaders=dict(hhh='vvv')) - d = mn.createEmail(msgdict, u'builder-n\u00E5me', u'project-n\u00E5me', - SUCCESS, builds) - @d.addCallback - def callback(m): - txt = m.as_string() - # note that the headers are *not* rendered - self.assertIn('hhh: vvv', txt) - return d - - def test_createEmail_message_with_patch_and_log_containing_unicode(self): - builds = [ FakeBuildStatus(name="build") ] - msgdict = create_msgdict() - patches = [ ['', u'\u00E5\u00E4\u00F6', ''] ] - msg = u'Unicode log with non-ascii (\u00E5\u00E4\u00F6).' - # add msg twice: as unicode and already encoded - logs = [ FakeLog(msg), FakeLog(msg.encode('utf-8')) ] - mn = MailNotifier('from@example.org', addLogs=True) - d = mn.createEmail(msgdict, u'builder-n\u00E5me', - u'project-n\u00E5me', SUCCESS, - builds, patches, logs) - @d.addCallback - def callback(m): - try: - m.as_string() - except UnicodeEncodeError: - self.fail('Failed to call as_string() on email message.') - return d - - def test_createEmail_message_with_nonascii_patch(self): - builds = [ FakeBuildStatus(name="build") ] - msgdict = create_msgdict() - patches = [ ['', '\x99\xaa', ''] ] - logs = [ FakeLog('simple log') ] - mn = MailNotifier('from@example.org', addLogs=True) - d = mn.createEmail(msgdict, u'builder', u'pr', SUCCESS, - builds, patches, logs) - @d.addCallback - def callback(m): - txt = m.as_string() - self.assertIn('application/octet-stream', txt) - return d - - def test_init_enforces_categories_and_builders_are_mutually_exclusive(self): - self.assertRaises(config.ConfigErrors, - MailNotifier, 'from@example.org', - categories=['fast','slow'], builders=['a','b']) - - def test_builderAdded_ignores_unspecified_categories(self): - mn = MailNotifier('from@example.org', categories=['fast']) - - builder = Mock() - builder.category = 'slow' - - self.assertEqual(None, mn.builderAdded('dummyBuilder', builder)) - self.assert_(builder not in mn.watched) - - def test_builderAdded_subscribes_to_all_builders_by_default(self): - mn = MailNotifier('from@example.org') - - builder = Mock() - builder.category = 'slow' - builder2 = Mock() - builder2.category = None - - self.assertEqual(mn, mn.builderAdded('dummyBuilder', builder)) - self.assertEqual(mn, mn.builderAdded('dummyBuilder2', builder2)) - self.assertTrue(builder in mn.watched) - self.assertTrue(builder2 in mn.watched) - - def test_buildFinished_ignores_unspecified_builders(self): - mn = MailNotifier('from@example.org', builders=['a','b']) - - build = FakeBuildStatus() - build.builder = Mock() - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, SUCCESS)) - - def test_buildsetFinished_sends_email(self): - fakeBuildMessage = Mock() - mn = MailNotifier('from@example.org', - buildSetSummary=True, - mode=("failing", "passing", "warnings"), - builders=["Builder1", "Builder2"]) - - mn.buildMessage = fakeBuildMessage - - builder1 = Mock() - builder1.getBuild = lambda number: build1 - builder1.name = "Builder1" - - build1 = FakeBuildStatus() - build1.results = FAILURE - build1.finished = True - build1.reason = "testReason" - build1.getBuilder.return_value = builder1 - - builder2 = Mock() - builder2.getBuild = lambda number: build2 - builder2.name = "Builder2" - - build2 = FakeBuildStatus() - build2.results = FAILURE - build2.finished = True - build2.reason = "testReason" - build2.getBuilder.return_value = builder1 - - def fakeGetBuilder(buildername): - return {"Builder1": builder1, "Builder2": builder2}[buildername] - - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=127), - fakedb.Buildset(id=99, sourcestampsetid=127, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder1'), - fakedb.Build(number=0, brid=11), - fakedb.BuildRequest(id=12, buildsetid=99, - buildername='Builder2'), - fakedb.Build(number=0, brid=12), - ]) - mn.master = self # FIXME: Should be FakeMaster - - self.status = Mock() - mn.master_status = Mock() - mn.master_status.getBuilder = fakeGetBuilder - mn.buildMessageDict = Mock() - mn.buildMessageDict.return_value = {"body":"body", "type":"text", - "subject":"subject"} - - mn.buildsetFinished(99, FAILURE) - fakeBuildMessage.assert_called_with("Buildset Complete: testReason", - [build1, build2], SUCCESS) - - def test_buildsetFinished_doesnt_send_email(self): - fakeBuildMessage = Mock() - mn = MailNotifier('from@example.org', - buildSetSummary=True, - mode=("failing", "warnings"), - builders=["Builder"]) - mn.buildMessage = fakeBuildMessage - - - def fakeGetBuild(number): - return build - - def fakeGetBuilder(buildername): - if buildername == builder.name: - return builder - return None - - def fakeGetBuildRequests(self, bsid): - return defer.succeed([{"buildername":"Builder", "brid":1}]) - - builder = Mock() - builder.getBuild = fakeGetBuild - builder.name = "Builder" - - build = FakeBuildStatus() - build.results = SUCCESS - build.finished = True - build.reason = "testReason" - build.getBuilder.return_value = builder - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=127), - fakedb.Buildset(id=99, sourcestampsetid=127, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder'), - fakedb.Build(number=0, brid=11), - ]) - mn.master = self - - self.status = Mock() - mn.master_status = Mock() - mn.master_status.getBuilder = fakeGetBuilder - mn.buildMessageDict = Mock() - mn.buildMessageDict.return_value = {"body":"body", "type":"text", - "subject":"subject"} - - mn.buildsetFinished(99, FAILURE) - self.assertFalse(fakeBuildMessage.called) - - def test_getCustomMesgData_multiple_sourcestamps(self): - self.passedAttrs = {} - def fakeCustomMessage(attrs): - self.passedAttrs = attrs - return ("", "") - - mn = MailNotifier('from@example.org', - buildSetSummary=True, - mode=("failing", "passing", "warnings"), - builders=["Builder"]) - - - def fakeBuildMessage(name, builds, results): - for build in builds: - mn.buildMessageDict(name=build.getBuilder().name, - build=build, results=build.results) - - mn.buildMessage = fakeBuildMessage - mn.customMesg = fakeCustomMessage - - def fakeGetBuild(number): - return build - - def fakeGetBuilder(buildername): - if buildername == builder.name: - return builder - return None - - def fakeGetBuildRequests(self, bsid): - return defer.succeed([{"buildername":"Builder", "brid":1}]) - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=127), - fakedb.Buildset(id=99, sourcestampsetid=127, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder'), - fakedb.Build(number=0, brid=11), - ]) - mn.master = self - - builder = Mock() - builder.getBuild = fakeGetBuild - builder.name = "Builder" - - build = FakeBuildStatus() - build.results = FAILURE - build.finished = True - build.reason = "testReason" - build.getLogs.return_value = [] - build.getBuilder.return_value = builder - - self.status = Mock() - mn.master_status = Mock() - mn.master_status.getBuilder = fakeGetBuilder - - ss1 = FakeSource(revision='111222', codebase='testlib1') - ss2 = FakeSource(revision='222333', codebase='testlib2') - build.getSourceStamps.return_value = [ss1, ss2] - - mn.buildsetFinished(99, FAILURE) - - self.assertTrue('revision' in self.passedAttrs, "No revision entry found in attrs") - self.assertTrue(isinstance(self.passedAttrs['revision'], dict)) - self.assertEqual(self.passedAttrs['revision']['testlib1'], '111222') - self.assertEqual(self.passedAttrs['revision']['testlib2'], '222333') - - def test_getCustomMesgData_single_sourcestamp(self): - self.passedAttrs = {} - def fakeCustomMessage(attrs): - self.passedAttrs = attrs - return ("", "") - - mn = MailNotifier('from@example.org', - buildSetSummary=True, - mode=("failing", "passing", "warnings"), - builders=["Builder"]) - - - def fakeBuildMessage(name, builds, results): - for build in builds: - mn.buildMessageDict(name=build.getBuilder().name, - build=build, results=build.results) - - mn.buildMessage = fakeBuildMessage - mn.customMesg = fakeCustomMessage - - def fakeGetBuild(number): - return build - - def fakeGetBuilder(buildername): - if buildername == builder.name: - return builder - return None - - def fakeGetBuildRequests(self, bsid): - return defer.succeed([{"buildername":"Builder", "brid":1}]) - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=127), - fakedb.Buildset(id=99, sourcestampsetid=127, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder'), - fakedb.Build(number=0, brid=11), - ]) - mn.master = self - - builder = Mock() - builder.getBuild = fakeGetBuild - builder.name = "Builder" - - build = FakeBuildStatus() - build.results = FAILURE - build.finished = True - build.reason = "testReason" - build.getLogs.return_value = [] - build.getBuilder.return_value = builder - - self.status = Mock() - mn.master_status = Mock() - mn.master_status.getBuilder = fakeGetBuilder - - ss1 = FakeSource(revision='111222', codebase='testlib1') - build.getSourceStamps.return_value = [ss1] - - mn.buildsetFinished(99, FAILURE) - - self.assertTrue('builderName' in self.passedAttrs, "No builderName entry found in attrs") - self.assertEqual(self.passedAttrs['builderName'], 'Builder') - self.assertTrue('revision' in self.passedAttrs, "No revision entry found in attrs") - self.assertTrue(isinstance(self.passedAttrs['revision'], str)) - self.assertEqual(self.passedAttrs['revision'], '111222') - - def test_buildFinished_ignores_unspecified_categories(self): - mn = MailNotifier('from@example.org', categories=['fast']) - - - build = FakeBuildStatus(name="build") - build.builder = Mock() - build.builder.category = 'slow' - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, SUCCESS)) - - def run_simple_test_sends_email_for_mode(self, mode, result): - mock_method = Mock() - self.patch(MailNotifier, "buildMessage", mock_method) - mn = MailNotifier('from@example.org', mode=mode) - - build = FakeBuildStatus(name="build") - mn.buildFinished('dummyBuilder', build, result) - - mock_method.assert_called_with('dummyBuilder', [build], result) - - def run_simple_test_ignores_email_for_mode(self, mode, result): - mock_method = Mock() - self.patch(MailNotifier, "buildMessage", mock_method) - mn = MailNotifier('from@example.org', mode=mode) - - build = FakeBuildStatus(name="build") - mn.buildFinished('dummyBuilder', build, result) - - self.assertFalse(mock_method.called) - - def test_buildFinished_mode_all_for_success(self): - self.run_simple_test_sends_email_for_mode("all", SUCCESS) - def test_buildFinished_mode_all_for_failure(self): - self.run_simple_test_sends_email_for_mode("all", FAILURE) - def test_buildFinished_mode_all_for_warnings(self): - self.run_simple_test_sends_email_for_mode("all", WARNINGS) - def test_buildFinished_mode_all_for_exception(self): - self.run_simple_test_sends_email_for_mode("all", EXCEPTION) - - def test_buildFinished_mode_failing_for_success(self): - self.run_simple_test_ignores_email_for_mode("failing", SUCCESS) - def test_buildFinished_mode_failing_for_failure(self): - self.run_simple_test_sends_email_for_mode("failing", FAILURE) - def test_buildFinished_mode_failing_for_warnings(self): - self.run_simple_test_ignores_email_for_mode("failing", WARNINGS) - def test_buildFinished_mode_failing_for_exception(self): - self.run_simple_test_ignores_email_for_mode("failing", EXCEPTION) - - def test_buildFinished_mode_exception_for_success(self): - self.run_simple_test_ignores_email_for_mode("exception", SUCCESS) - def test_buildFinished_mode_exception_for_failure(self): - self.run_simple_test_ignores_email_for_mode("exception", FAILURE) - def test_buildFinished_mode_exception_for_warnings(self): - self.run_simple_test_ignores_email_for_mode("exception", WARNINGS) - def test_buildFinished_mode_exception_for_exception(self): - self.run_simple_test_sends_email_for_mode("exception", EXCEPTION) - - def test_buildFinished_mode_warnings_for_success(self): - self.run_simple_test_ignores_email_for_mode("warnings", SUCCESS) - def test_buildFinished_mode_warnings_for_failure(self): - self.run_simple_test_sends_email_for_mode("warnings", FAILURE) - def test_buildFinished_mode_warnings_for_warnings(self): - self.run_simple_test_sends_email_for_mode("warnings", WARNINGS) - def test_buildFinished_mode_warnings_for_exception(self): - self.run_simple_test_ignores_email_for_mode("warnings", EXCEPTION) - - def test_buildFinished_mode_passing_for_success(self): - self.run_simple_test_sends_email_for_mode("passing", SUCCESS) - def test_buildFinished_mode_passing_for_failure(self): - self.run_simple_test_ignores_email_for_mode("passing", FAILURE) - def test_buildFinished_mode_passing_for_warnings(self): - self.run_simple_test_ignores_email_for_mode("passing", WARNINGS) - def test_buildFinished_mode_passing_for_exception(self): - self.run_simple_test_ignores_email_for_mode("passing", EXCEPTION) - - def test_buildFinished_mode_failing_ignores_successful_build(self): - mn = MailNotifier('from@example.org', mode=("failing",)) - - build = FakeBuildStatus(name="build") - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, SUCCESS)) - - def test_buildFinished_mode_passing_ignores_failed_build(self): - mn = MailNotifier('from@example.org', mode=("passing",)) - - build = FakeBuildStatus(name="build") - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, FAILURE)) - - def test_buildFinished_mode_problem_ignores_successful_build(self): - mn = MailNotifier('from@example.org', mode=("problem",)) - - build = FakeBuildStatus(name="build") - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, SUCCESS)) - - def test_buildFinished_mode_problem_ignores_two_failed_builds_in_sequence(self): - mn = MailNotifier('from@example.org', mode=("problem",)) - - build = FakeBuildStatus(name="build") - old_build = FakeBuildStatus(name="old_build") - build.getPreviousBuild.return_value = old_build - old_build.getResults.return_value = FAILURE - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, FAILURE)) - - def test_buildFinished_mode_change_ignores_first_build(self): - mn = MailNotifier('from@example.org', mode=("change",)) - - build = FakeBuildStatus(name="build") - build.getPreviousBuild.return_value = None - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, FAILURE)) - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, SUCCESS)) - - - def test_buildFinished_mode_change_ignores_same_result_in_sequence(self): - mn = MailNotifier('from@example.org', mode=("change",)) - - build = FakeBuildStatus(name="build") - old_build = FakeBuildStatus(name="old_build") - build.getPreviousBuild.return_value = old_build - old_build.getResults.return_value = FAILURE - - build2 = FakeBuildStatus(name="build2") - old_build2 = FakeBuildStatus(name="old_build2") - build2.getPreviousBuild.return_value = old_build2 - old_build2.getResults.return_value = SUCCESS - - self.assertEqual(None, mn.buildFinished('dummyBuilder', build, FAILURE)) - self.assertEqual(None, mn.buildFinished('dummyBuilder', build2, SUCCESS)) - - def test_buildMessage_addLogs(self): - mn = MailNotifier('from@example.org', mode=("change",), addLogs=True) - - mn.buildMessageDict = Mock() - mn.buildMessageDict.return_value = {"body":"body", "type":"text", - "subject":"subject"} - - mn.createEmail = Mock("createEmail") - - mn._gotRecipients = Mock("_gotReceipients") - mn._gotRecipients.return_value = None - - mn.master_status = Mock() - mn.master_status.getTitle.return_value = 'TITLE' - - bldr = Mock(name="builder") - builds = [ FakeBuildStatus(name='build1'), - FakeBuildStatus(name='build2') ] - logs = [ FakeLog('log1'), FakeLog('log2') ] - for b, l in zip(builds, logs): - b.builder = bldr - b.results = 0 - ss = Mock(name='ss') - b.getSourceStamps.return_value = [ss] - ss.patch = None - ss.changes = [] - b.getLogs.return_value = [ l ] - d = mn.buildMessage("mybldr", builds, 0) - def check(_): - mn.createEmail.assert_called_with( - dict(body='body\n\nbody\n\n', type='text', subject='subject'), - 'mybldr', 'TITLE', 0, builds, [], logs) - d.addCallback(check) - return d - - def do_test_sendToInterestedUsers(self, lookup=None, extraRecipients=[], - sendToInterestedUsers=True, - exp_called_with=None, exp_TO=None, - exp_CC=None): - from email.Message import Message - m = Message() - - mn = MailNotifier(fromaddr='from@example.org', - lookup=lookup, - sendToInterestedUsers=sendToInterestedUsers, - extraRecipients=extraRecipients) - mn.sendMessage = Mock() - - def fakeGetBuild(number): - return build - def fakeGetBuilder(buildername): - if buildername == builder.name: - return builder - return None - def fakeGetBuildRequests(self, bsid): - return defer.succeed([{"buildername":"Builder", "brid":1}]) - - builder = Mock() - builder.getBuild = fakeGetBuild - builder.name = "Builder" - - build = FakeBuildStatus(name="build") - build.result = FAILURE - build.finished = True - build.reason = "testReason" - build.builder = builder - - def fakeCreateEmail(msgdict, builderName, title, results, builds=None, - patches=None, logs=None): - # only concerned with m['To'] and m['CC'], which are added in - # _got_recipients later - return defer.succeed(m) - mn.createEmail = fakeCreateEmail - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=1099), - fakedb.Buildset(id=99, sourcestampsetid=1099, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder'), - fakedb.Build(number=0, brid=11), - fakedb.Change(changeid=9123), - fakedb.ChangeUser(changeid=9123, uid=1), - fakedb.User(uid=1, identifier="tdurden"), - fakedb.UserInfo(uid=1, attr_type='svn', - attr_data="tdurden"), - fakedb.UserInfo(uid=1, attr_type='email', - attr_data="tyler@mayhem.net") - ]) - - # fake sourcestamp with relevant user bits - ss = Mock(name="sourcestamp") - fake_change = Mock(name="change") - fake_change.number = 9123 - ss.changes = [fake_change] - ss.patch, ss.addPatch = None, None - - def fakeGetSSlist(): - return [ss] - build.getSourceStamps = fakeGetSSlist - - def _getInterestedUsers(): - # 'narrator' in this case is the owner, which tests the lookup - return ["narrator"] - build.getInterestedUsers = _getInterestedUsers - - def _getResponsibleUsers(): - return ["Big Bob <bob@mayhem.net>"] - build.getResponsibleUsers = _getResponsibleUsers - - mn.master = self # FIXME: Should be FakeMaster - self.status = mn.master_status = mn.buildMessageDict = Mock() - mn.master_status.getBuilder = fakeGetBuilder - mn.buildMessageDict.return_value = {"body": "body", "type": "text"} - - mn.buildMessage(builder.name, [build], build.result) - mn.sendMessage.assert_called_with(m, exp_called_with) - self.assertEqual(m['To'], exp_TO) - self.assertEqual(m['CC'], exp_CC) - - def test_sendToInterestedUsers_lookup(self): - self.do_test_sendToInterestedUsers( - lookup="example.org", - exp_called_with=['Big Bob <bob@mayhem.net>', - 'narrator@example.org'], - exp_TO="Big Bob <bob@mayhem.net>, " \ - "narrator@example.org") - - def test_buildMessage_sendToInterestedUsers_no_lookup(self): - self.do_test_sendToInterestedUsers( - exp_called_with=['tyler@mayhem.net'], - exp_TO="tyler@mayhem.net") - - def test_buildMessage_sendToInterestedUsers_extraRecipients(self): - self.do_test_sendToInterestedUsers( - extraRecipients=["marla@mayhem.net"], - exp_called_with=['tyler@mayhem.net', - 'marla@mayhem.net'], - exp_TO="tyler@mayhem.net", - exp_CC="marla@mayhem.net") - def test_sendToInterestedUsers_False(self): - self.do_test_sendToInterestedUsers( - extraRecipients=["marla@mayhem.net"], - sendToInterestedUsers=False, - exp_called_with=['marla@mayhem.net'], - exp_TO="marla@mayhem.net") - - def test_sendToInterestedUsers_two_builds(self): - from email.Message import Message - m = Message() - - mn = MailNotifier(fromaddr="from@example.org", lookup=None) - mn.sendMessage = Mock() - - def fakeGetBuilder(buildername): - if buildername == builder.name: - return builder - return None - def fakeGetBuildRequests(self, bsid): - return defer.succeed([{"buildername":"Builder", "brid":1}]) - - builder = Mock() - builder.name = "Builder" - - build1 = FakeBuildStatus(name="build") - build1.result = FAILURE - build1.finished = True - build1.reason = "testReason" - build1.builder = builder - - build2 = FakeBuildStatus(name="build") - build2.result = FAILURE - build2.finished = True - build2.reason = "testReason" - build2.builder = builder - - def fakeCreateEmail(msgdict, builderName, title, results, builds=None, - patches=None, logs=None): - # only concerned with m['To'] and m['CC'], which are added in - # _got_recipients later - return defer.succeed(m) - mn.createEmail = fakeCreateEmail - - self.db = fakedb.FakeDBConnector(self) - self.db.insertTestData([fakedb.SourceStampSet(id=1099), - fakedb.Buildset(id=99, sourcestampsetid=1099, - results=SUCCESS, - reason="testReason"), - fakedb.BuildRequest(id=11, buildsetid=99, - buildername='Builder'), - fakedb.Build(number=0, brid=11), - fakedb.Build(number=1, brid=11), - fakedb.Change(changeid=9123), - fakedb.Change(changeid=9124), - fakedb.ChangeUser(changeid=9123, uid=1), - fakedb.ChangeUser(changeid=9124, uid=2), - fakedb.User(uid=1, identifier="tdurden"), - fakedb.User(uid=2, identifier="user2"), - fakedb.UserInfo(uid=1, attr_type='email', - attr_data="tyler@mayhem.net"), - fakedb.UserInfo(uid=2, attr_type='email', - attr_data="user2@example.net") - ]) - - def _getInterestedUsers(): - # 'narrator' in this case is the owner, which tests the lookup - return ["narrator"] - build1.getInterestedUsers = _getInterestedUsers - build2.getInterestedUsers = _getInterestedUsers - - def _getResponsibleUsers(): - return ["Big Bob <bob@mayhem.net>"] - build1.getResponsibleUsers = _getResponsibleUsers - build2.getResponsibleUsers = _getResponsibleUsers - - # fake sourcestamp with relevant user bits - ss1 = Mock(name="sourcestamp") - fake_change1 = Mock(name="change") - fake_change1.number = 9123 - ss1.changes = [fake_change1] - ss1.patch, ss1.addPatch = None, None - - ss2 = Mock(name="sourcestamp") - fake_change2 = Mock(name="change") - fake_change2.number = 9124 - ss2.changes = [fake_change2] - ss2.patch, ss1.addPatch = None, None - - def fakeGetSSlist(ss): - return lambda: [ss] - build1.getSourceStamps = fakeGetSSlist(ss1) - build2.getSourceStamps = fakeGetSSlist(ss2) - - mn.master = self # FIXME: Should be FakeMaster - self.status = mn.master_status = mn.buildMessageDict = Mock() - mn.master_status.getBuilder = fakeGetBuilder - mn.buildMessageDict.return_value = {"body": "body", "type": "text"} - - mn.buildMessage(builder.name, [build1, build2], build1.result) - self.assertEqual(m['To'], "tyler@mayhem.net, user2@example.net") - -def create_msgdict(funny_chars=u'\u00E5\u00E4\u00F6'): - unibody = u'Unicode body with non-ascii (%s).' % funny_chars - msg_dict = dict(body=unibody, type='plain') - return msg_dict diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_master.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_master.py deleted file mode 100644 index 04ae5136..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_master.py +++ /dev/null @@ -1,95 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.status import master, base -from buildbot.test.fake import fakedb - -class FakeStatusReceiver(base.StatusReceiver): - pass - -class TestStatus(unittest.TestCase): - - def makeStatus(self): - m = mock.Mock(name='master') - self.db = m.db = fakedb.FakeDBConnector(self) - m.basedir = r'C:\BASEDIR' - s = master.Status(m) - return s - - def test_getBuildSets(self): - s = self.makeStatus() - self.db.insertTestData([ - fakedb.Buildset(id=91, sourcestampsetid=234, complete=0, - complete_at=298297875, results=-1, submitted_at=266761875, - external_idstring='extid', reason='rsn1'), - fakedb.Buildset(id=92, sourcestampsetid=234, complete=1, - complete_at=298297876, results=7, submitted_at=266761876, - external_idstring='extid', reason='rsn2'), - ]) - - d = s.getBuildSets() - def check(bslist): - self.assertEqual([ bs.id for bs in bslist ], [ 91 ]) - d.addCallback(check) - return d - - @defer.inlineCallbacks - def test_reconfigService(self): - m = mock.Mock(name='master') - status = master.Status(m) - status.startService() - - config = mock.Mock() - - # add a status reciever - sr0 = FakeStatusReceiver() - config.status = [ sr0 ] - - yield status.reconfigService(config) - - self.assertTrue(sr0.running) - self.assertIdentical(sr0.master, m) - - # add a status reciever - sr1 = FakeStatusReceiver() - sr2 = FakeStatusReceiver() - config.status = [ sr1, sr2 ] - - yield status.reconfigService(config) - - self.assertFalse(sr0.running) - self.assertIdentical(sr0.master, None) - self.assertTrue(sr1.running) - self.assertIdentical(sr1.master, m) - self.assertTrue(sr2.running) - self.assertIdentical(sr2.master, m) - - # reconfig with those two (a regression check) - sr1 = FakeStatusReceiver() - sr2 = FakeStatusReceiver() - config.status = [ sr1, sr2 ] - - yield status.reconfigService(config) - - # and back to nothing - config.status = [ ] - yield status.reconfigService(config) - - self.assertIdentical(sr0.master, None) - self.assertIdentical(sr1.master, None) - self.assertIdentical(sr2.master, None) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_persistent_queue.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_persistent_queue.py deleted file mode 100644 index 3bf65e5d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_persistent_queue.py +++ /dev/null @@ -1,147 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - - -import os -from twisted.trial import unittest -from buildbot.test.util import dirs - -from buildbot.status.persistent_queue import MemoryQueue, DiskQueue, \ - IQueue, PersistentQueue, WriteFile - -class test_Queues(dirs.DirsMixin, unittest.TestCase): - - def setUp(self): - self.setUpDirs('fake_dir') - - def tearDown(self): - self.assertEqual([], os.listdir('fake_dir')) - self.tearDownDirs() - - def testQueued(self): - # Verify behavior when starting up with queued items on disk. - WriteFile(os.path.join('fake_dir', '3'), 'foo3') - WriteFile(os.path.join('fake_dir', '5'), 'foo5') - WriteFile(os.path.join('fake_dir', '8'), 'foo8') - queue = PersistentQueue(MemoryQueue(3), - DiskQueue('fake_dir', 5, pickleFn=str, unpickleFn=str)) - self.assertEqual(['foo3', 'foo5', 'foo8'], queue.items()) - self.assertEqual(3, queue.nbItems()) - self.assertEqual(['foo3', 'foo5', 'foo8'], queue.popChunk()) - - def _test_helper(self, q): - self.assertTrue(IQueue.providedBy(q)) - self.assertEqual(8, q.maxItems()) - self.assertEqual(0, q.nbItems()) - self.assertEqual([], q.items()) - - for i in range(4): - self.assertEqual(None, q.pushItem(i), str(i)) - self.assertEqual(i + 1, q.nbItems(), str(i)) - self.assertEqual([0, 1, 2, 3], q.items()) - self.assertEqual(4, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([0, 1, 2], q.primaryQueue.items()) - self.assertEqual([3], q.secondaryQueue.items()) - - self.assertEqual(None, q.save()) - self.assertEqual([0, 1, 2, 3], q.items()) - self.assertEqual(4, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([], q.primaryQueue.items()) - self.assertEqual([0, 1, 2, 3], q.secondaryQueue.items()) - - for i in range(4): - self.assertEqual(None, q.pushItem(i + 4), str(i + 4)) - self.assertEqual(i + 5, q.nbItems(), str(i + 4)) - self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7], q.items()) - self.assertEqual(8, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([0, 1, 2], q.primaryQueue.items()) - self.assertEqual([3, 4, 5, 6, 7], q.secondaryQueue.items()) - - self.assertEqual(0, q.pushItem(8)) - self.assertEqual(8, q.nbItems()) - self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], q.items()) - if isinstance(q, PersistentQueue): - self.assertEqual([1, 2, 3], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual([1, 2], q.popChunk(2)) - self.assertEqual([3, 4, 5, 6, 7, 8], q.items()) - self.assertEqual(6, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([3], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual([3], q.popChunk(1)) - self.assertEqual([4, 5, 6, 7, 8], q.items()) - self.assertEqual(5, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual(None, q.save()) - self.assertEqual(5, q.nbItems()) - self.assertEqual([4, 5, 6, 7, 8], q.items()) - if isinstance(q, PersistentQueue): - self.assertEqual([], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual(None, q.insertBackChunk([2, 3])) - self.assertEqual([2, 3, 4, 5, 6, 7, 8], q.items()) - self.assertEqual(7, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([2, 3], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual([0], q.insertBackChunk([0, 1])) - self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], q.items()) - self.assertEqual(8, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([1, 2, 3], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual([10, 11], q.insertBackChunk([10, 11])) - self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], q.items()) - self.assertEqual(8, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([1, 2, 3], q.primaryQueue.items()) - self.assertEqual([4, 5, 6, 7, 8], q.secondaryQueue.items()) - - self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], q.popChunk(8)) - self.assertEqual([], q.items()) - self.assertEqual(0, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([], q.primaryQueue.items()) - self.assertEqual([], q.secondaryQueue.items()) - - self.assertEqual([], q.popChunk()) - self.assertEqual(0, q.nbItems()) - if isinstance(q, PersistentQueue): - self.assertEqual([], q.primaryQueue.items()) - self.assertEqual([], q.secondaryQueue.items()) - - def testMemoryQueue(self): - self._test_helper(MemoryQueue(maxItems=8)) - - def testDiskQueue(self): - self._test_helper(DiskQueue('fake_dir', maxItems=8)) - - def testPersistentQueue(self): - self._test_helper(PersistentQueue(MemoryQueue(3), - DiskQueue('fake_dir', 5))) - -# vim: set ts=4 sts=4 sw=4 et: diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_progress.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_progress.py deleted file mode 100644 index b1abc8b9..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_progress.py +++ /dev/null @@ -1,43 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.status import progress - -class TestExpectations(unittest.TestCase): - - def test_addNewStep(self): - """ - http://trac.buildbot.net/ticket/2252 - """ - buildProgress = progress.BuildProgress([]) - expectations = progress.Expectations(buildProgress) - stepProgress = progress.StepProgress("step", ["metric"]) - newProgress = progress.BuildProgress([stepProgress]) - stepProgress.start() - stepProgress.finish() - stepProgress.setProgress("metric", 42) - expectations.update(newProgress) - - - def test_removeOldStep(self): - """ - http://trac.buildbot.net/ticket/2281 - """ - stepProgress = progress.StepProgress("step", ["metric"]) - oldProgress = progress.BuildProgress([stepProgress]) - expectations = progress.Expectations(oldProgress) - buildProgress = progress.BuildProgress([]) - buildProgress.setExpectationsFrom(expectations) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAprAuth.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAprAuth.py deleted file mode 100644 index 27a0d24f..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAprAuth.py +++ /dev/null @@ -1,75 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members -""" -Test Passwords -desbuildmaster:yifux5rkzvI5w -desbuildslave:W8SPURMnCs7Tc -desbuildbot:IzclhyfHAq6Oc -md5buildmaster:$apr1$pSepI8Wp$eJZcfhnpENrRlUn28wak50 -md5buildslave:$apr1$dtX6FDei$vFB5BlnR9bjQisy7v3ZaC0 -md5buildbot:$apr1$UcfsHmrF$i9fYa4OsPI3AK8UBbN3ju1 -shabuildmaster:{SHA}vpAKSO3uPt6z8KL6cqf5W5Sredk= -shabuildslave:{SHA}sNA10GbdONwGJ+a8VGRNtEyWd9I= -shabuildbot:{SHA}TwEDa5Q31ZhI4GLmIbE1VrrAkpk= -""" - - -from twisted.trial import unittest - -from buildbot.status.web.auth import HTPasswdAprAuth -from buildbot.test.util import compat - -class TestHTPasswdAprAuth(unittest.TestCase): - - htpasswd = HTPasswdAprAuth(__file__) - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_des(self): - for key in ('buildmaster','buildslave','buildbot'): - if self.htpasswd.authenticate('des'+key, key) == False: - self.fail("authenticate failed for '%s'" % ('des'+key)) - - def test_authenticate_md5(self): - if not self.htpasswd.apr: - raise unittest.SkipTest("libaprutil-1 not found") - for key in ('buildmaster','buildslave','buildbot'): - if self.htpasswd.authenticate('md5'+key, key) == False: - self.fail("authenticate failed for '%s'" % ('md5'+key)) - - def test_authenticate_sha(self): - if not self.htpasswd.apr: - raise unittest.SkipTest("libaprutil-1 not found") - for key in ('buildmaster','buildslave','buildbot'): - if self.htpasswd.authenticate('sha'+key, key) == False: - self.fail("authenticate failed for '%s'" % ('sha'+key)) - - def test_authenticate_unknown(self): - if self.htpasswd.authenticate('foo', 'bar') == True: - self.fail("authenticate succeed for 'foo:bar'") - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_wopassword(self): - for algo in ('des','md5','sha'): - if self.htpasswd.authenticate(algo+'buildmaster', '') == True: - self.fail("authenticate succeed for %s w/o password" - % (algo+'buildmaster')) - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_wrongpassword(self): - for algo in ('des','md5','sha'): - if self.htpasswd.authenticate(algo+'buildmaster', algo) == True: - self.fail("authenticate succeed for %s w/ wrong password" - % (algo+'buildmaster')) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAuth.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAuth.py deleted file mode 100644 index d27dc193..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_auth_HTPasswdAuth.py +++ /dev/null @@ -1,55 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members -""" -Test Passwords -desbuildmaster:yifux5rkzvI5w -desbuildslave:W8SPURMnCs7Tc -desbuildbot:IzclhyfHAq6Oc -""" - - -from twisted.trial import unittest - -from buildbot.status.web.auth import HTPasswdAuth -from buildbot.test.util import compat - -class TestHTPasswdAuth(unittest.TestCase): - - htpasswd = HTPasswdAuth(__file__) - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_des(self): - for key in ('buildmaster','buildslave','buildbot'): - if self.htpasswd.authenticate('des'+key, key) == False: - self.fail("authenticate failed for '%s'" % ('des'+key)) - - def test_authenticate_unknown(self): - if self.htpasswd.authenticate('foo', 'bar') == True: - self.fail("authenticate succeed for 'foo:bar'") - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_wopassword(self): - for algo in ('des','md5','sha'): - if self.htpasswd.authenticate(algo+'buildmaster', '') == True: - self.fail("authenticate succeed for %s w/o password" - % (algo+'buildmaster')) - - @compat.skipUnlessPlatformIs('posix') # crypt module - def test_authenticate_wrongpassword(self): - for algo in ('des','md5','sha'): - if self.htpasswd.authenticate(algo+'buildmaster', algo) == True: - self.fail("authenticate succeed for %s w/ wrong password" - % (algo+'buildmaster')) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_authz_Authz.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_authz_Authz.py deleted file mode 100644 index a38201a2..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_authz_Authz.py +++ /dev/null @@ -1,227 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from zope.interface import implements -from twisted.trial import unittest -from twisted.internet import defer - -from buildbot.status.web.authz import Authz -from buildbot.status.web.auth import IAuth, AuthBase - -class StubRequest(object): - # all we need from a request is username/password - def __init__(self, username=None, passwd=None): - self.args = { - 'username' : [ username ], - 'passwd' : [ passwd ], - } - self.received_cookies = {} - self.send_cookies = [] - def getUser(self): - return '' - - def getPassword(self): - return None - def addCookie(self, key, cookie, expires, path): - self.send_cookies.append((key, cookie, expires, path)) - -class StubHttpAuthRequest(object): - # all we need from a request is username/password - def __init__(self, username, passwd): - self.args = {} - self.username = username - self.passwd = passwd - - def getUser(self): - return self.username - - def getPassword(self): - return self.passwd - -class StubAuth(AuthBase): - implements(IAuth) - def __init__(self, user): - self.user = user - - def authenticate(self, user, pw): - return user == self.user -class TestAuthz(unittest.TestCase): - - def test_actionAllowed_Defaults(self): - "by default, nothing is allowed" - z = Authz() - self.failedActions = [] - self.dl = [] - for a in Authz.knownActions: - md = z.actionAllowed(a, StubRequest('foo', 'bar')) - def check(res): - if res: - self.failedActions.append(a) - return - md.addCallback(check) - self.dl.append(md) - d = defer.DeferredList(self.dl) - def check_failed(_): - if self.failedActions: - raise unittest.FailTest("action(s) %s do not default to False" - % (self.failedActions,)) - d.addCallback(check_failed) - return d - - def test_actionAllowed_Positive(self): - "'True' should always permit access" - z = Authz(forceBuild=True) - d = z.actionAllowed('forceBuild', StubRequest('foo', 'bar')) - def check(res): - self.assertEqual(res, True) - d.addCallback(check) - return d - - def test_actionAllowed_AuthPositive(self): - z = Authz(auth=StubAuth('jrobinson'), - stopBuild='auth') - d = z.actionAllowed('stopBuild', StubRequest('jrobinson', 'bar')) - def check(res): - self.assertEqual(res, True) - d.addCallback(check) - return d - - def test_actionAllowed_AuthNegative(self): - z = Authz(auth=StubAuth('jrobinson'), - stopBuild='auth') - d = z.actionAllowed('stopBuild', StubRequest('apeterson', 'bar')) - def check(res): - self.assertEqual(res, False) - d.addCallback(check) - return d - - def test_actionAllowed_AuthCallable(self): - myargs = [] - def myAuthzFn(*args): - myargs.extend(args) - z = Authz(auth=StubAuth('uu'), - stopBuild=myAuthzFn) - d = z.actionAllowed('stopBuild', StubRequest('uu', 'shh'), 'arg', 'arg2') - def check(res): - self.assertEqual(myargs, ['uu', 'arg', 'arg2']) - d.addCallback(check) - return d - - def test_actionAllowed_AuthCallableTrue(self): - def myAuthzFn(*args): - return True - z = Authz(auth=StubAuth('uu'), - stopBuild=myAuthzFn) - d = z.actionAllowed('stopBuild', StubRequest('uu', 'shh')) - def check(res): - self.assertEqual(res, True) - d.addCallback(check) - return d - - def test_actionAllowed_AuthCallableFalse(self): - def myAuthzFn(*args): - return False - z = Authz(auth=StubAuth('uu'), - stopBuild=myAuthzFn) - d = z.actionAllowed('stopBuild', StubRequest('uu', 'shh')) - def check(res): - self.assertEqual(res, False) - d.addCallback(check) - return d - - def test_advertiseAction_False(self): - z = Authz(forceBuild = False) - assert not z.advertiseAction('forceBuild',StubRequest()) - - def test_advertiseAction_True(self): - z = Authz(forceAllBuilds = True) - assert z.advertiseAction('forceAllBuilds',StubRequest()) - - def test_advertiseAction_auth(self): - z = Authz(stopBuild = 'auth') - assert not z.advertiseAction('stopBuild',StubRequest()) - - def test_advertiseAction_auth_authenticated(self): - z = Authz(auth=StubAuth('uu'),stopBuild = 'auth') - r = StubRequest('uu','aa') - d = z.login(r) - def check(c): - assert z.advertiseAction('stopBuild',r) - d.addCallback(check) - - def test_advertiseAction_callable(self): - z = Authz(auth=StubAuth('uu'), stopAllBuilds = lambda u : False) - r = StubRequest('uu','aa') - d = z.login(r) - @d.addCallback - def check(c): - assert z.advertiseAction('stopAllBuilds',r) - return d - - def test_authenticated_False(self): - z = Authz(forceBuild = False) - assert not z.authenticated(StubRequest()) - - def test_authenticated_True(self): - z = Authz(auth=StubAuth('uu'), forceBuild = True) - r = StubRequest('uu','aa') - d = z.login(r) - @d.addCallback - def check(c): - assert z.authenticated(r) - return d - - def test_authenticated_http_False(self): - z = Authz(useHttpHeader = True) - assert not z.authenticated(StubRequest()) - - def test_authenticated_http_True(self): - z = Authz(useHttpHeader = True) - assert z.authenticated(StubHttpAuthRequest('foo', 'bar')) - - def test_constructor_invalidAction(self): - self.assertRaises(ValueError, Authz, someRandomAction=3) - - def test_getUsername_http(self): - z = Authz(useHttpHeader = True) - assert z.getUsername(StubHttpAuthRequest('foo', 'bar')) == 'foo' - - def test_getPassword_http(self): - z = Authz(useHttpHeader = True) - assert z.getPassword(StubHttpAuthRequest('foo', 'bar')) == 'bar' - - def test_getUsername_http_missing(self): - z = Authz(useHttpHeader = True) - assert z.getUsername(StubRequest('foo', 'bar')) == '' - - def test_getPassword_http_missing(self): - z = Authz(useHttpHeader = True) - assert z.getPassword(StubRequest('foo', 'bar')) == None - - def test_getUsername_request(self): - z = Authz() - assert z.getUsername(StubRequest('foo', 'bar')) == 'foo' - - def test_getPassword_request(self): - z = Authz() - assert z.getPassword(StubRequest('foo', 'bar')) == 'bar' - - def test_advertiseAction_invalidAction(self): - z = Authz() - self.assertRaises(KeyError, z.advertiseAction, 'someRandomAction', StubRequest('snow', 'foo')) - - def test_actionAllowed_invalidAction(self): - z = Authz() - self.assertRaises(KeyError, z.actionAllowed, 'someRandomAction', StubRequest('snow', 'foo')) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_base.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_base.py deleted file mode 100644 index a7d007c0..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_base.py +++ /dev/null @@ -1,98 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from buildbot.status.web import base -from twisted.internet import defer -from twisted.trial import unittest - -from buildbot.test.fake.web import FakeRequest - -class ActionResource(unittest.TestCase): - - def test_ActionResource_success(self): - - class MyActionResource(base.ActionResource): - def performAction(self, request): - self.got_request = request - return defer.succeed('http://buildbot.net') - - rsrc = MyActionResource() - request = FakeRequest() - rsrc.render(request) - d = request.deferred - - def check(_): - self.assertIdentical(rsrc.got_request, request) - self.assertTrue(request.finished) - self.assertIn('buildbot.net', request.written) - self.assertEqual(request.redirected_to, 'http://buildbot.net') - d.addCallback(check) - return d - - def test_ActionResource_exception(self): - - class MyActionResource(base.ActionResource): - def performAction(self, request): - return defer.fail(RuntimeError('sacrebleu')) - - rsrc = MyActionResource() - request = FakeRequest() - rsrc.render(request) - d = request.deferred - - def check(f): - f.trap(RuntimeError) - # pass - all good! - d.addErrback(check) - return d - -class Functions(unittest.TestCase): - - def do_test_getRequestCharset(self, hdr, exp): - req = mock.Mock() - req.getHeader.return_value = hdr - - self.assertEqual(base.getRequestCharset(req), exp) - - def fakeRequest(self, prepath): - r = mock.Mock() - r.prepath = prepath - return r - - def test_getRequestCharset_empty(self): - return self.do_test_getRequestCharset(None, 'utf-8') - - def test_getRequestCharset_specified(self): - return self.do_test_getRequestCharset( - 'application/x-www-form-urlencoded ; charset=ISO-8859-1', - 'ISO-8859-1') - - def test_getRequestCharset_other_params(self): - return self.do_test_getRequestCharset( - 'application/x-www-form-urlencoded ; charset=UTF-16 ; foo=bar', - 'UTF-16') - - def test_path_to_root_from_root(self): - self.assertEqual(base.path_to_root(self.fakeRequest([])), - './') - - def test_path_to_root_from_one_level(self): - self.assertEqual(base.path_to_root(self.fakeRequest(['waterfall'])), - './') - - def test_path_to_root_from_two_level(self): - self.assertEqual(base.path_to_root(self.fakeRequest(['a', 'b'])), - '../') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hook.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hook.py deleted file mode 100644 index 692ee4b4..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hook.py +++ /dev/null @@ -1,168 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.web import change_hook -from buildbot.util import json -from buildbot.test.util import compat -from buildbot.test.fake.web import FakeRequest - -from twisted.trial import unittest - -class TestChangeHookUnconfigured(unittest.TestCase): - def setUp(self): - self.request = FakeRequest() - self.changeHook = change_hook.ChangeHookResource() - - # A bad URI should cause an exception inside check_hook. - # After writing the test, it became apparent this can't happen. - # I'll leave the test anyway - def testDialectReMatchFail(self): - self.request.uri = "/garbage/garbage" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check(ret): - expected = "URI doesn't match change_hook regex: /garbage/garbage" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - d.addCallback(check) - return d - - def testUnkownDialect(self): - self.request.uri = "/change_hook/garbage" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check(ret): - expected = "The dialect specified, 'garbage', wasn't whitelisted in change_hook" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - d.addCallback(check) - return d - - def testDefaultDialect(self): - self.request.uri = "/change_hook/" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check(ret): - expected = "The dialect specified, 'base', wasn't whitelisted in change_hook" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - d.addCallback(check) - return d - -class TestChangeHookConfigured(unittest.TestCase): - def setUp(self): - self.request = FakeRequest() - self.changeHook = change_hook.ChangeHookResource(dialects={'base' : True}) - - def testDefaultDialectGetNullChange(self): - self.request.uri = "/change_hook/" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - self.assertEquals(len(self.request.addedChanges), 1) - change = self.request.addedChanges[0] - self.assertEquals(change["category"], None) - self.assertEquals(len(change["files"]), 0) - self.assertEquals(change["repository"], None) - self.assertEquals(change["when"], None) - self.assertEquals(change["author"], None) - self.assertEquals(change["revision"], None) - self.assertEquals(change["comments"], None) - self.assertEquals(change["project"], None) - self.assertEquals(change["branch"], None) - self.assertEquals(change["revlink"], None) - self.assertEquals(len(change["properties"]), 0) - self.assertEquals(change["revision"], None) - d.addCallback(check_changes) - return d - - # Test 'base' hook with attributes. We should get a json string representing - # a Change object as a dictionary. All values show be set. - def testDefaultDialectWithChange(self): - self.request.uri = "/change_hook/" - self.request.method = "GET" - self.request.args = { "category" : ["mycat"], - "files" : [json.dumps(['file1', 'file2'])], - "repository" : ["myrepo"], - "when" : ["1234"], - "author" : ["Santa Claus"], - "number" : ["2"], - "comments" : ["a comment"], - "project" : ["a project"], - "at" : ["sometime"], - "branch" : ["a branch"], - "revlink" : ["a revlink"], - "properties" : [json.dumps( { "prop1" : "val1", "prop2" : "val2" })], - "revision" : ["99"] } - d = self.request.test_render(self.changeHook) - def check_changes(r): - self.assertEquals(len(self.request.addedChanges), 1) - change = self.request.addedChanges[0] - self.assertEquals(change["category"], "mycat") - self.assertEquals(change["repository"], "myrepo") - self.assertEquals(change["when"], 1234) - self.assertEquals(change["author"], "Santa Claus") - self.assertEquals(change["src"], None) - self.assertEquals(change["revision"], "99") - self.assertEquals(change["comments"], "a comment") - self.assertEquals(change["project"], "a project") - self.assertEquals(change["branch"], "a branch") - self.assertEquals(change["revlink"], "a revlink") - self.assertEquals(change['properties'], dict(prop1='val1', prop2='val2')) - self.assertEquals(change['files'], ['file1', 'file2']) - d.addCallback(check_changes) - return d - - @compat.usesFlushLoggedErrors - def testDefaultWithNoChange(self): - self.request = FakeRequest() - self.request.uri = "/change_hook/" - self.request.method = "GET" - def namedModuleMock(name): - if name == 'buildbot.status.web.hooks.base': - class mock_hook_module(object): - def getChanges(self, request, options): - raise AssertionError - return mock_hook_module() - self.patch(change_hook, "namedModule", namedModuleMock) - - d = self.request.test_render(self.changeHook) - def check_changes(r): - expected = "Error processing changes." - self.assertEquals(len(self.request.addedChanges), 0) - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(500, expected) - self.assertEqual(len(self.flushLoggedErrors(AssertionError)), 1) - - d.addCallback(check_changes) - return d - -class TestChangeHookConfiguredBogus(unittest.TestCase): - def setUp(self): - self.request = FakeRequest() - self.changeHook = change_hook.ChangeHookResource(dialects={'garbage' : True}) - - @compat.usesFlushLoggedErrors - def testBogusDialect(self): - self.request.uri = "/change_hook/garbage" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check(ret): - expected = "Error processing changes." - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(500, expected) - self.assertEqual(len(self.flushLoggedErrors()), 1) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_github.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_github.py deleted file mode 100644 index dabc5118..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_github.py +++ /dev/null @@ -1,205 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import buildbot.status.web.change_hook as change_hook -from buildbot.test.fake.web import FakeRequest -from buildbot.test.util import compat - -from twisted.trial import unittest - -# Sample GITHUB commit payload from http://help.github.com/post-receive-hooks/ -# Added "modfied" and "removed", and change email - -gitJsonPayload = """ -{ - "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", - "repository": { - "url": "http://github.com/defunkt/github", - "name": "github", - "description": "You're lookin' at it.", - "watchers": 5, - "forks": 2, - "private": 1, - "owner": { - "email": "fred@flinstone.org", - "name": "defunkt" - } - }, - "commits": [ - { - "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", - "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", - "author": { - "email": "fred@flinstone.org", - "name": "Fred Flinstone" - }, - "message": "okay i give in", - "timestamp": "2008-02-15T14:57:17-08:00", - "added": ["filepath.rb"] - }, - { - "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", - "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", - "author": { - "email": "fred@flinstone.org", - "name": "Fred Flinstone" - }, - "message": "update pricing a tad", - "timestamp": "2008-02-15T14:36:34-08:00", - "modified": ["modfile"], - "removed": ["removedFile"] - } - ], - "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", - "ref": "refs/heads/master" -} -""" - -gitJsonPayloadNonBranch = """ -{ - "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", - "repository": { - "url": "http://github.com/defunkt/github", - "name": "github", - "description": "You're lookin' at it.", - "watchers": 5, - "forks": 2, - "private": 1, - "owner": { - "email": "fred@flinstone.org", - "name": "defunkt" - } - }, - "commits": [ - { - "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", - "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", - "author": { - "email": "fred@flinstone.org", - "name": "Fred Flinstone" - }, - "message": "okay i give in", - "timestamp": "2008-02-15T14:57:17-08:00", - "added": ["filepath.rb"] - } - ], - "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", - "ref": "refs/garbage/master" -} -""" - -gitJsonPayloadEmpty = """ -{ - "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", - "repository": { - "url": "http://github.com/defunkt/github", - "name": "github", - "description": "You're lookin' at it.", - "watchers": 5, - "forks": 2, - "private": 1, - "owner": { - "email": "fred@flinstone.org", - "name": "defunkt" - } - }, - "commits": [ - ], - "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", - "ref": "refs/heads/master" -} -""" -class TestChangeHookConfiguredWithGitChange(unittest.TestCase): - def setUp(self): - self.changeHook = change_hook.ChangeHookResource(dialects={'github' : True}) - - # Test 'base' hook with attributes. We should get a json string representing - # a Change object as a dictionary. All values show be set. - def testGitWithChange(self): - changeDict={"payload" : [gitJsonPayload]} - self.request = FakeRequest(changeDict) - self.request.uri = "/change_hook/github" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - self.assertEquals(len(self.request.addedChanges), 2) - change = self.request.addedChanges[0] - - self.assertEquals(change['files'], ['filepath.rb']) - self.assertEquals(change["repository"], "http://github.com/defunkt/github") - self.assertEquals(change["when"], 1203116237) - self.assertEquals(change["who"], "Fred Flinstone <fred@flinstone.org>") - self.assertEquals(change["revision"], '41a212ee83ca127e3c8cf465891ab7216a705f59') - self.assertEquals(change["comments"], "okay i give in") - self.assertEquals(change["branch"], "master") - self.assertEquals(change["revlink"], "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59") - - change = self.request.addedChanges[1] - self.assertEquals(change['files'], [ 'modfile', 'removedFile' ]) - self.assertEquals(change["repository"], "http://github.com/defunkt/github") - self.assertEquals(change["when"], 1203114994) - self.assertEquals(change["who"], "Fred Flinstone <fred@flinstone.org>") - self.assertEquals(change["src"], "git") - self.assertEquals(change["revision"], 'de8251ff97ee194a289832576287d6f8ad74e3d0') - self.assertEquals(change["comments"], "update pricing a tad") - self.assertEquals(change["branch"], "master") - self.assertEquals(change["revlink"], "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0") - - d.addCallback(check_changes) - return d - - @compat.usesFlushLoggedErrors - def testGitWithNoJson(self): - self.request = FakeRequest() - self.request.uri = "/change_hook/github" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - expected = "Error processing changes." - self.assertEquals(len(self.request.addedChanges), 0) - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(500, expected) - self.assertEqual(len(self.flushLoggedErrors()), 1) - - d.addCallback(check_changes) - return d - - def testGitWithNoChanges(self): - changeDict={"payload" : [gitJsonPayloadEmpty]} - self.request = FakeRequest(changeDict) - self.request.uri = "/change_hook/github" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - expected = "no changes found" - self.assertEquals(len(self.request.addedChanges), 0) - self.assertEqual(self.request.written, expected) - - d.addCallback(check_changes) - return d - - def testGitWithNonBranchChanges(self): - changeDict={"payload" : [gitJsonPayloadNonBranch]} - self.request = FakeRequest(changeDict) - self.request.uri = "/change_hook/github" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - expected = "no changes found" - self.assertEquals(len(self.request.addedChanges), 0) - self.assertEqual(self.request.written, expected) - - d.addCallback(check_changes) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_googlecode.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_googlecode.py deleted file mode 100644 index 2eb30674..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_googlecode.py +++ /dev/null @@ -1,90 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright 2011 Louis Opter <kalessin@kalessin.fr> -# -# Written from the github change hook unit test - -import StringIO - -import buildbot.status.web.change_hook as change_hook -from buildbot.test.fake.web import FakeRequest - -from twisted.trial import unittest - -# Sample Google Code commit payload extracted from a Google Code test project -# { -# "repository_path": "https://code.google.com/p/webhook-test/", -# "project_name": "webhook-test", -# "revision_count": 1, -# "revisions": [ -# { -# "added": [], -# "parents": ["6574485e26a09a0e743e0745374056891d6a836a"], -# "author": "Louis Opter \\u003Clouis@lse.epitech.net\\u003E", -# "url": "http://webhook-test.googlecode.com/hg-history/68e5df283a8e751cdbf95516b20357b2c46f93d4/", -# "timestamp": 1324082130, -# "message": "Print a message", -# "path_count": 1, -# "removed": [], -# "modified": ["/CMakeLists.txt"], -# "revision": "68e5df283a8e751cdbf95516b20357b2c46f93d4" -# } -# ] -# } -googleCodeJsonBody = '{"repository_path":"https://code.google.com/p/webhook-test/","project_name":"webhook-test","revisions":[{"added":[],"parents":["6574485e26a09a0e743e0745374056891d6a836a"],"author":"Louis Opter \u003Clouis@lse.epitech.net\u003E","url":"http://webhook-test.googlecode.com/hg-history/68e5df283a8e751cdbf95516b20357b2c46f93d4/","timestamp":1324082130,"message":"Print a message","path_count":1,"removed":[],"modified":["/CMakeLists.txt"],"revision":"68e5df283a8e751cdbf95516b20357b2c46f93d4"}],"revision_count":1}' - -class TestChangeHookConfiguredWithGoogleCodeChange(unittest.TestCase): - def setUp(self): - self.request = FakeRequest() - # Google Code simply transmit the payload as an UTF-8 JSON body - self.request.content = StringIO.StringIO(googleCodeJsonBody) - self.request.received_headers = { - 'Google-Code-Project-Hosting-Hook-Hmac': '85910bf93ba5c266402d9328b0c7a856', - 'Content-Length': '509', - 'Accept-Encoding': 'gzip', - 'User-Agent': 'Google Code Project Hosting (+http://code.google.com/p/support/wiki/PostCommitWebHooks)', - 'Host': 'buildbot6-lopter.dotcloud.com:19457', - 'Content-Type': 'application/json; charset=UTF-8' - } - - self.changeHook = change_hook.ChangeHookResource(dialects={ - 'googlecode': { - 'secret_key': 'FSP3p-Ghdn4T0oqX', - 'branch': 'test' - } - }) - - # Test 'base' hook with attributes. We should get a json string representing - # a Change object as a dictionary. All values show be set. - def testGoogleCodeWithHgChange(self): - self.request.uri = "/change_hook/googlecode" - self.request.method = "GET" - d = self.request.test_render(self.changeHook) - def check_changes(r): - # Only one changeset has been submitted. - self.assertEquals(len(self.request.addedChanges), 1) - - # First changeset. - change = self.request.addedChanges[0] - self.assertEquals(change['files'], ['/CMakeLists.txt']) - self.assertEquals(change["repository"], "https://code.google.com/p/webhook-test/") - self.assertEquals(change["when"], 1324082130) - self.assertEquals(change["author"], "Louis Opter <louis@lse.epitech.net>") - self.assertEquals(change["revision"], '68e5df283a8e751cdbf95516b20357b2c46f93d4') - self.assertEquals(change["comments"], "Print a message") - self.assertEquals(change["branch"], "test") - self.assertEquals(change["revlink"], "http://webhook-test.googlecode.com/hg-history/68e5df283a8e751cdbf95516b20357b2c46f93d4/") - - d.addCallback(check_changes) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_poller.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_poller.py deleted file mode 100644 index fca1b66e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_change_hooks_poller.py +++ /dev/null @@ -1,107 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.changes import base -import buildbot.status.web.change_hook as change_hook -from buildbot.test.fake.web import FakeRequest -from buildbot.changes.manager import ChangeManager - - -class TestPollingChangeHook(unittest.TestCase): - class Subclass(base.PollingChangeSource): - pollInterval = None - called = False - - def poll(self): - self.called = True - - def setUpRequest(self, args, options=True): - self.changeHook = change_hook.ChangeHookResource(dialects={'poller' : options}) - - self.request = FakeRequest(args=args) - self.request.uri = "/change_hook/poller" - self.request.method = "GET" - - master = self.request.site.buildbot_service.master - master.change_svc = ChangeManager(master) - - self.changesrc = self.Subclass("example", None) - self.changesrc.setServiceParent(master.change_svc) - - self.disabledChangesrc = self.Subclass("disabled", None) - self.disabledChangesrc.setServiceParent(master.change_svc) - - anotherchangesrc = base.ChangeSource() - anotherchangesrc.setName("notapoller") - anotherchangesrc.setServiceParent(master.change_svc) - - return self.request.test_render(self.changeHook) - - @defer.inlineCallbacks - def test_no_args(self): - yield self.setUpRequest({}) - self.assertEqual(self.request.written, "no changes found") - self.assertEqual(self.changesrc.called, True) - self.assertEqual(self.disabledChangesrc.called, True) - - @defer.inlineCallbacks - def test_no_poller(self): - yield self.setUpRequest({"poller": ["nosuchpoller"]}) - expected = "Could not find pollers: nosuchpoller" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - self.assertEqual(self.changesrc.called, False) - self.assertEqual(self.disabledChangesrc.called, False) - - @defer.inlineCallbacks - def test_invalid_poller(self): - yield self.setUpRequest({"poller": ["notapoller"]}) - expected = "Could not find pollers: notapoller" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - self.assertEqual(self.changesrc.called, False) - self.assertEqual(self.disabledChangesrc.called, False) - - @defer.inlineCallbacks - def test_trigger_poll(self): - yield self.setUpRequest({"poller": ["example"]}) - self.assertEqual(self.request.written, "no changes found") - self.assertEqual(self.changesrc.called, True) - self.assertEqual(self.disabledChangesrc.called, False) - - @defer.inlineCallbacks - def test_allowlist_deny(self): - yield self.setUpRequest({"poller": ["disabled"]}, options={"allowed": ["example"]}) - expected = "Could not find pollers: disabled" - self.assertEqual(self.request.written, expected) - self.request.setResponseCode.assert_called_with(400, expected) - self.assertEqual(self.changesrc.called, False) - self.assertEqual(self.disabledChangesrc.called, False) - - @defer.inlineCallbacks - def test_allowlist_allow(self): - yield self.setUpRequest({"poller": ["example"]}, options={"allowed": ["example"]}) - self.assertEqual(self.request.written, "no changes found") - self.assertEqual(self.changesrc.called, True) - self.assertEqual(self.disabledChangesrc.called, False) - - @defer.inlineCallbacks - def test_allowlist_all(self): - yield self.setUpRequest({}, options={"allowed": ["example"]}) - self.assertEqual(self.request.written, "no changes found") - self.assertEqual(self.changesrc.called, True) - self.assertEqual(self.disabledChangesrc.called, False) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_links.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_links.py deleted file mode 100644 index 4abe1573..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_web_links.py +++ /dev/null @@ -1,239 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import buildbot.status.web.base as wb -import jinja2, re - -from twisted.trial import unittest - -class RevisionLinks(unittest.TestCase): - """ - Test webstatus revision link filters - """ - - def setUp(self): - pass - - def _test(self, env, should_have_links=True): - for name in ['shortrev', 'revlink']: - f = env.filters[name] - for r in [None, 'repo', 'repo2', 'sub/repo']: - self.assertNotSubstring('<a', f(None, r), 'repo: %s' % r) - if should_have_links: - self.assertSubstring('<a', f(1234, r), 'repo: %s' % r) - self.assertSubstring('<a', f('deadbeef1234', r), 'repo: %s' % r) - else: - self.assertNotSubstring('<a', f(1234, r), 'repo: %s' % r) - self.assertNotSubstring('<a', f('deadbeef1234', r), 'repo: %s' % r) - - def test_default(self): - env = wb.createJinjaEnv() - self._test(env, False) - - def test_format(self): - env = wb.createJinjaEnv('http://myserver.net/repo/%s') - self._test(env) - - def test_dict(self): - env = wb.createJinjaEnv({None: 'http://default.net/repo/%s', - 'repo': 'http://myserver.net/repo/%s', - 'repo2': 'http://myserver2.net/repo/%s', - 'sub/repo': 'http://otherserver.com/%s'}) - self._test(env) - - def test_callable(self): - def my_revlink(rev, repo): - import urllib - if not rev: - return None - if not repo: - repo = 'main' - rev = urllib.quote(rev) - repo = urllib.quote(repo) - return 'http://myserver.net/repos/%s/rev/%s' % (repo, rev) - - env = wb.createJinjaEnv(my_revlink) - self._test(env) - - - def test_template(self): - template_str = '''{{ rev|revlink('repo') }} - {{ rev|shortrev('repo') }}''' - env = wb.createJinjaEnv(revlink='http://myserver.net/repo/%s') - template = env.from_string(template_str) - - rev = '1234567890' * 4 # reasonably long - html = template.render(rev=rev) - self.assertSubstring('http://myserver.net/repo/%s' % rev, html) - self.assertSubstring('...', html) # did it get shortened? - self.assertEquals(html.count('<a'), 3) # one in revlink, two in shortrev - - -class ChangeCommentLinks(unittest.TestCase): - """ - Tests webstatus changecomment link filter - """ - - def setUp(self): - pass - - def _test(self, env): - f = env.filters['changecomment'] - for p in [None, 'project1', 'project2']: - self.assertNotSubstring('<a', f('', p)) - self.assertNotSubstring('<a', f('There is no ticket...', p)) - self.assertSubstring('<a', f('There is a ticket #123', p)) - self.assertEquals(f('There are two tickets #123 and #456', p).count("<a"), 2) - - - def test_default(self): - env = wb.createJinjaEnv() - f = env.filters['changecomment'] - self.assertNotSubstring('<a', f(None, '')) - self.assertNotSubstring('<a', f(None, 'There is no ticket #123')) - self.assertNotSubstring('<a', f('project', '')) - self.assertNotSubstring('<a', f('project', 'There is no ticket #123')) - - def test_tuple2(self): - env = wb.createJinjaEnv( - changecommentlink=(r'#(\d+)', r'http://buildbot.net/trac/ticket/\1')) - self._test(env) - - def test_tuple3(self): - env = wb.createJinjaEnv( - changecommentlink=(r'#(\d+)', r'http://buildbot.net/trac/ticket/\1', - r'Ticket #\1')) - self._test(env) - - def test_dict_2tuple(self): - env = wb.createJinjaEnv( - changecommentlink={ - None: (r'#(\d+)', r'http://server/trac/ticket/\1'), - 'project1': (r'#(\d+)', r'http://server/trac/p1/ticket/\1'), - 'project2': (r'#(\d+)', r'http://server/trac/p2/ticket/\1') - }) - self._test(env) - - f = env.filters['changecomment'] - self.assertNotSubstring('<a', f('fixed #123', 'nonexistingproject')) - - - def test_dict_3tuple(self): - env = wb.createJinjaEnv( - changecommentlink={ - None: (r'#(\d+)', r'http://server/trac/ticket/\1', r'Ticket #\1'), - 'project1': (r'#(\d+)', r'http://server/trac/p1/ticket/\1', r'Ticket #\1'), - 'project2': (r'#(\d+)', r'http://server/bugzilla/p2/ticket/\1', r'Bug #\1') - }) - self._test(env) - - f = env.filters['changecomment'] - self.assertNotSubstring('<a', f('fixed #123', 'nonexistingproject')) - - def test_callable(self): - r1 = re.compile(r'#(\d+)') - r2 = re.compile(r'bug ([a-eA-E0-9]+)') - - r1_sub = jinja2.Markup(r'<a href="\1" title="Ticket #\1">\g<0></a>') - r2_sub = jinja2.Markup(r'<a href="\1" title="Bug \1"><img src="\bug.png">\g<0></a>') - - def my_changelink(changehtml, project): - if project == 'nonexistingproject': - return changehtml - - html1 = r1.sub(r1_sub, changehtml) - html2 = r2.sub(r2_sub, html1) - return html2 - - env = wb.createJinjaEnv(changecommentlink=my_changelink) - self._test(env) - - f = env.filters['changecomment'] - self.assertNotSubstring('<a', f('fixed #123', 'nonexistingproject')) - - -class DictLinkfilter(unittest.TestCase): - '''test the dictlink filter used for top-level links to - projects and repostiories''' - - def test_default(self): - f = wb.dictlinkfilter(None) - - self.assertNotSubstring('<a', f(None)) - self.assertNotSubstring('<a', f('repo')) - self.assertNotSubstring('<a', f('repo2')) - - def test_simple(self): - f = wb.dictlinkfilter({'repo': 'http://myrepo.net'}) - - self.assertNotSubstring('<a', f(None)) - self.assertSubstring('<a', f('repo')) - self.assertNotSubstring('<a', f('repo2')) - self.assertEquals(f('bah'), 'bah') # passthrough - - def test_callable(self): - def my_dictlink(value): - if len(value) == 0: - return 'http://thevoid.net' - if len(value) == 1: - return 'http://highlander.net' - if value == 'hiddenproject': - return None - else: - return 'http://legion.net' - - f = wb.dictlinkfilter(my_dictlink) - self.assertSubstring('thevoid', f('')) - self.assertSubstring('highlander', f('X')) - self.assertSubstring('legion', f('many')) - self.assertSubstring('<a', f('many')) - self.assertNotSubstring('<a', f('hiddenproject')) - - - def test_jinjaenv(self): - env = wb.createJinjaEnv(repositories={'a': 'http://a.net'}, - projects={'b': 'http://b.net'}) - - self.assertSubstring('<a href="http://a.net">', env.filters['repolink']('a')) - self.assertSubstring('<a href="http://b.net">', env.filters['projectlink']('b')) - - -class EmailFilter(unittest.TestCase): - ''' test that the email filter actually obfuscates email addresses''' - - def test_emailfilter(self): - self.assertNotSubstring('me@the.net', wb.emailfilter('me@the.net')) - self.assertSubstring('me', wb.emailfilter('me@the.net')) - self.assertSubstring('@', wb.emailfilter('me@the.net')) - self.assertSubstring('the.net', wb.emailfilter('me@the.net')) - - - -class UserFilter(unittest.TestCase): - '''test commit user names filtering, should be safe from complete - email addresses and split user/email into separate HTML instances''' - - def test_emailfilter(self): - self.assertNotSubstring('me@the.net', wb.userfilter('me@the.net')) - self.assertNotSubstring('me@the.net', wb.userfilter('Me <me@the.net>')) - - def test_emailfilter_split(self): - self.assertNotSubstring('Me <me', wb.userfilter('Me <me@the.net>')) - self.assertSubstring('me', wb.userfilter('Me <me@the.net>')) - self.assertSubstring('the.net', wb.userfilter('Me <me@the.net>')) - self.assertSubstring('John Doe', wb.userfilter('John Doe <me@the.net>')) - - - - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_words.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_words.py deleted file mode 100644 index d1300ac5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_status_words.py +++ /dev/null @@ -1,617 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest -from twisted.application import internet -from twisted.internet import task, reactor -from buildbot.status import words -from buildbot.test.util import compat, config - -class TestIrcContactChannel(unittest.TestCase): - - def setUp(self): - self.bot = mock.Mock(name='IRCStatusBot-instance') - self.bot.nickname = 'nick' - self.bot.notify_events = { 'success' : 1, 'failure' : 1 } - - # fake out subscription/unsubscription - self.subscribed = False - def subscribe(contact): - self.subscribed = True - self.bot.status.subscribe = subscribe - def unsubscribe(contact): - self.subscribed = False - self.bot.status.unsubscribe = unsubscribe - - # fake out clean shutdown - self.bot.master = mock.Mock(name='IRCStatusBot-instance.master') - self.bot.master.botmaster = mock.Mock(name='IRCStatusBot-instance.master.botmaster') - self.bot.master.botmaster.shuttingDown = False - def cleanShutdown(): - self.bot.master.botmaster.shuttingDown = True - self.bot.master.botmaster.cleanShutdown = cleanShutdown - def cancelCleanShutdown(): - self.bot.master.botmaster.shuttingDown = False - self.bot.master.botmaster.cancelCleanShutdown = cancelCleanShutdown - - self.contact = words.IRCContact(self.bot, '#buildbot') - - def patch_send(self): - self.sent = [] - def send(msg): - self.sent.append(msg) - self.contact.send = send - - def patch_act(self): - self.actions = [] - def act(msg): - self.actions.append(msg) - self.contact.act = act - - def do_test_command(self, command, args='', who='me', clock_ticks=None, - exp_usage=True, exp_UsageError=False, allowShutdown=False, - shuttingDown=False): - cmd = getattr(self.contact, 'command_' + command.upper()) - - if exp_usage: - self.assertTrue(hasattr(cmd, 'usage')) - - clock = task.Clock() - self.patch(reactor, 'callLater', clock.callLater) - self.patch_send() - self.patch_act() - self.bot.factory.allowShutdown = allowShutdown - self.bot.master.botmaster.shuttingDown = shuttingDown - - if exp_UsageError: - try: - cmd(args, who) - except words.UsageError: - return - else: - self.fail("no UsageError") - else: - cmd(args, who) - if clock_ticks: - clock.pump(clock_ticks) - - # tests - - def test_doSilly(self): - clock = task.Clock() - self.patch(reactor, 'callLater', clock.callLater) - self.patch_send() - silly_prompt, silly_response = self.contact.silly.items()[0] - - self.contact.doSilly(silly_prompt) - clock.pump([0.5] * 20) - - self.assertEqual(self.sent, silly_response) - - # TODO: remaining commands - # (all depend on status, which interface will change soon) - - def test_command_mute(self): - self.do_test_command('mute') - self.assertTrue(self.contact.muted) - - def test_command_unmute(self): - self.contact.muted = True - self.do_test_command('unmute') - self.assertFalse(self.contact.muted) - - def test_command_unmute_not_muted(self): - self.do_test_command('unmute') - self.assertFalse(self.contact.muted) - self.assertIn("hadn't told me to be quiet", self.sent[0]) - - def test_command_help_noargs(self): - self.do_test_command('help') - self.assertIn('help on what', self.sent[0]) - - def test_command_help_arg(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = 'foo - bar' - self.do_test_command('help', args='foo') - self.assertIn('Usage: foo - bar', self.sent[0]) - - def test_command_help_no_usage(self): - self.contact.command_FOO = lambda : None - self.do_test_command('help', args='foo') - self.assertIn('No usage info for', self.sent[0]) - - def test_command_help_dict_command(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = { - None : 'foo - bar' - } - self.do_test_command('help', args='foo') - self.assertIn('Usage: foo - bar', self.sent[0]) - - def test_command_help_dict_command_no_usage(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = {} - self.do_test_command('help', args='foo') - self.assertIn("No usage info for 'foo'", self.sent[0]) - - def test_command_help_dict_command_arg(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = { - 'this' : 'foo this - bar' - } - self.do_test_command('help', args='foo this') - self.assertIn('Usage: foo this - bar', self.sent[0]) - - def test_command_help_dict_command_arg_no_usage(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = { - # nothing for arg 'this' - ('this', 'first') : 'foo this first - bar' - } - self.do_test_command('help', args='foo this') - self.assertIn("No usage info for 'foo' 'this'", self.sent[0]) - - def test_command_help_dict_command_arg_subarg(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = { - ('this', 'first') : 'foo this first - bar' - } - self.do_test_command('help', args='foo this first') - self.assertIn('Usage: foo this first - bar', self.sent[0]) - - def test_command_help_dict_command_arg_subarg_no_usage(self): - self.contact.command_FOO = lambda : None - self.contact.command_FOO.usage = { - None : 'foo - bar', - 'this' : 'foo this - bar', - ('this', 'first') : 'foo this first - bar' - # nothing for subarg 'missing' - } - self.do_test_command('help', args='foo this missing') - self.assertIn("No usage info for 'foo' 'this' 'missing'", self.sent[0]) - - def test_command_help_nosuch(self): - self.do_test_command('help', args='foo', exp_UsageError=True) - - def test_command_shutdown(self): - self.do_test_command('shutdown', exp_UsageError=True) - self.assertEqual(self.bot.factory.allowShutdown, False) - self.assertEqual(self.bot.master.botmaster.shuttingDown, False) - - def test_command_shutdown_dissalowed(self): - self.do_test_command('shutdown', args='check', exp_UsageError=True) - self.assertEqual(self.bot.factory.allowShutdown, False) - self.assertEqual(self.bot.master.botmaster.shuttingDown, False) - - def test_command_shutdown_check_running(self): - self.do_test_command('shutdown', args='check', allowShutdown=True, shuttingDown=False) - self.assertEqual(self.bot.factory.allowShutdown, True) - self.assertEqual(self.bot.master.botmaster.shuttingDown, False) - self.assertIn('buildbot is running', self.sent[0]) - - def test_command_shutdown_check_shutting_down(self): - self.do_test_command('shutdown', args='check', allowShutdown=True, shuttingDown=True) - self.assertEqual(self.bot.factory.allowShutdown, True) - self.assertEqual(self.bot.master.botmaster.shuttingDown, True) - self.assertIn('buildbot is shutting down', self.sent[0]) - - def test_command_shutdown_start(self): - self.do_test_command('shutdown', args='start', allowShutdown=True, shuttingDown=False) - self.assertEqual(self.bot.factory.allowShutdown, True) - self.assertEqual(self.bot.master.botmaster.shuttingDown, True) - - def test_command_shutdown_stop(self): - self.do_test_command('shutdown', args='stop', allowShutdown=True, shuttingDown=True) - self.assertEqual(self.bot.factory.allowShutdown, True) - self.assertEqual(self.bot.master.botmaster.shuttingDown, False) - - def test_command_shutdown_now(self): - stop = mock.Mock() - self.patch(reactor, 'stop', stop) - self.do_test_command('shutdown', args='now', allowShutdown=True) - self.assertEqual(self.bot.factory.allowShutdown, True) - self.assertEqual(self.bot.master.botmaster.shuttingDown, False) - stop.assert_called_with() - - def test_command_source(self): - self.do_test_command('source') - self.assertIn('My source', self.sent[0]) - - def test_command_commands(self): - self.do_test_command('commands') - self.assertIn('buildbot commands', self.sent[0]) - - def test_command_destroy(self): - self.do_test_command('destroy', exp_usage=False) - self.assertEqual(self.actions, [ 'readies phasers' ]) - - def test_command_dance(self): - self.do_test_command('dance', clock_ticks=[1.0]*10, exp_usage=False) - self.assertTrue(self.sent) # doesn't matter what it sent - - def test_send(self): - events = [] - def msgOrNotice(dest, msg): - events.append((dest, msg)) - self.contact.bot.msgOrNotice = msgOrNotice - - self.contact.send("unmuted") - self.contact.send(u"unmuted, unicode \N{SNOWMAN}") - self.contact.muted = True - self.contact.send("muted") - - self.assertEqual(events, [ - ('#buildbot', 'unmuted'), - ('#buildbot', 'unmuted, unicode ?'), - ]) - - def test_act(self): - events = [] - def describe(dest, msg): - events.append((dest, msg)) - self.contact.bot.describe = describe - - self.contact.act("unmuted") - self.contact.act(u"unmuted, unicode \N{SNOWMAN}") - self.contact.muted = True - self.contact.act("muted") - - self.assertEqual(events, [ - ('#buildbot', 'unmuted'), - ('#buildbot', 'unmuted, unicode ?'), - ]) - - def test_handleMessage_silly(self): - silly_prompt = self.contact.silly.keys()[0] - self.contact.doSilly = mock.Mock() - d = self.contact.handleMessage(silly_prompt, 'me') - @d.addCallback - def cb(_): - self.contact.doSilly.assert_called_with(silly_prompt) - return d - - def test_handleMessage_short_command(self): - self.contact.command_TESTY = mock.Mock() - d = self.contact.handleMessage('testy', 'me') - @d.addCallback - def cb(_): - self.contact.command_TESTY.assert_called_with('', 'me') - return d - - def test_handleMessage_long_command(self): - self.contact.command_TESTY = mock.Mock() - d = self.contact.handleMessage('testy westy boo', 'me') - @d.addCallback - def cb(_): - self.contact.command_TESTY.assert_called_with('westy boo', 'me') - return d - - def test_handleMessage_excited(self): - self.patch_send() - d = self.contact.handleMessage('hi!', 'me') - @d.addCallback - def cb(_): - self.assertEqual(len(self.sent), 1) # who cares what it says.. - return d - - @compat.usesFlushLoggedErrors - def test_handleMessage_exception(self): - self.patch_send() - def command_TESTY(msg, who): - raise RuntimeError("FAIL") - self.contact.command_TESTY = command_TESTY - d = self.contact.handleMessage('testy boom', 'me') - @d.addCallback - def cb(_): - self.assertEqual(self.sent, - [ "Something bad happened (see logs)" ]) - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - return d - - def test_handleMessage_UsageError(self): - self.patch_send() - def command_TESTY(msg, who): - raise words.UsageError("oh noes") - self.contact.command_TESTY = command_TESTY - d = self.contact.handleMessage('testy boom', 'me') - @d.addCallback - def cb(_): - self.assertEqual(self.sent, [ "oh noes" ]) - return d - - def test_handleAction_ignored(self): - self.patch_act() - self.contact.handleAction('waves hi', 'me') - self.assertEqual(self.actions, []) - - def test_handleAction_kick(self): - self.patch_act() - self.contact.handleAction('kicks nick', 'me') - self.assertEqual(self.actions, ['kicks back']) - - def test_handleAction_stpuid(self): - self.patch_act() - self.contact.handleAction('stupids nick', 'me') - self.assertEqual(self.actions, ['stupids me too']) - - def test_unclosed_quote(self): - self.do_test_command('list', args='args\'', exp_UsageError=True) - self.do_test_command('status', args='args\'', exp_UsageError=True) - self.do_test_command('notify', args='args\'', exp_UsageError=True) - self.do_test_command('watch', args='args\'', exp_UsageError=True) - self.do_test_command('force', args='args\'', exp_UsageError=True) - self.do_test_command('stop', args='args\'', exp_UsageError=True) - self.do_test_command('last', args='args\'', exp_UsageError=True) - self.do_test_command('help', args='args\'', exp_UsageError=True) - - -class FakeContact(object): - - def __init__(self, bot, name): - self.bot = bot - self.name = name - self.messages = [] - self.actions = [] - - def handleMessage(self, message, user): - self.messages.append((message, user)) - - def handleAction(self, data, user): - self.actions.append((data, user)) - - -class TestIrcStatusBot(unittest.TestCase): - - def setUp(self): - self.status = mock.Mock(name='status') - - def makeBot(self, *args, **kwargs): - if not args: - args = ('nick', 'pass', ['#ch'], [], self.status, [], {}) - return words.IrcStatusBot(*args, **kwargs) - - def test_msgOrNotice(self): - b = self.makeBot(noticeOnChannel=False) - b.notice = lambda d, m : evts.append(('n', d, m)) - b.msg = lambda d, m : evts.append(('m', d, m)) - - evts = [] - b.msgOrNotice('nick', 'hi') - self.assertEqual(evts, [('m', 'nick', 'hi')]) - - evts = [] - b.msgOrNotice('#chan', 'hi') - self.assertEqual(evts, [('m', '#chan', 'hi')]) - - b.noticeOnChannel = True - - evts = [] - b.msgOrNotice('#chan', 'hi') - self.assertEqual(evts, [('n', '#chan', 'hi')]) - - def test_getContact(self): - b = self.makeBot() - - c1 = b.getContact('c1') - c2 = b.getContact('c2') - c1b = b.getContact('c1') - - self.assertIdentical(c1, c1b) - self.assertIsInstance(c2, words.IRCContact) - - def test_getContact_case_insensitive(self): - b = self.makeBot() - - c1 = b.getContact('c1') - c1b = b.getContact('C1') - - self.assertIdentical(c1, c1b) - - def test_privmsg_user(self): - b = self.makeBot() - b.contactClass = FakeContact - b.privmsg('jimmy!~foo@bar', 'nick', 'hello') - - c = b.getContact('jimmy') - self.assertEqual(c.messages, [('hello', 'jimmy')]) - - def test_privmsg_user_uppercase(self): - b = self.makeBot('NICK', 'pass', ['#ch'], [], self.status, [], {}) - b.contactClass = FakeContact - b.privmsg('jimmy!~foo@bar', 'NICK', 'hello') - - c = b.getContact('jimmy') - self.assertEqual(c.messages, [('hello', 'jimmy')]) - - def test_privmsg_channel_unrelated(self): - b = self.makeBot() - b.contactClass = FakeContact - b.privmsg('jimmy!~foo@bar', '#ch', 'hello') - - c = b.getContact('#ch') - self.assertEqual(c.messages, []) - - def test_privmsg_channel_related(self): - b = self.makeBot() - b.contactClass = FakeContact - b.privmsg('jimmy!~foo@bar', '#ch', 'nick: hello') - - c = b.getContact('#ch') - self.assertEqual(c.messages, [(' hello', 'jimmy')]) - - def test_action_unrelated(self): - b = self.makeBot() - b.contactClass = FakeContact - b.action('jimmy!~foo@bar', '#ch', 'waves') - - c = b.getContact('#ch') - self.assertEqual(c.actions, []) - - def test_action_unrelated_buildbot(self): - b = self.makeBot() - b.contactClass = FakeContact - b.action('jimmy!~foo@bar', '#ch', 'waves at buildbot')# b.nickname is not 'buildbot' - - c = b.getContact('#ch') - self.assertEqual(c.actions, []) - - def test_action_related(self): - b = self.makeBot() - b.contactClass = FakeContact - b.action('jimmy!~foo@bar', '#ch', 'waves at nick') - - c = b.getContact('#ch') - self.assertEqual(c.actions, [('waves at nick', 'jimmy')]) - - def test_signedOn(self): - b = self.makeBot('nick', 'pass', - ['#ch1', dict(channel='#ch2', password='sekrits')], - ['jimmy', 'bobby'], self.status, [], {}) - evts = [] - def msg(d, m): - evts.append(('m', d, m)) - b.msg = msg - def join(channel, key): - evts.append(('k', channel, key)) - b.join = join - b.contactClass = FakeContact - - b.signedOn() - - self.assertEqual(sorted(evts), [ - ('k', '#ch1', None), - ('k', '#ch2', 'sekrits'), - ('m', 'Nickserv', 'IDENTIFY pass'), - ]) - self.assertEqual(sorted(b.contacts.keys()), - # channels don't get added until joined() is called - sorted(['jimmy', 'bobby'])) - - def test_joined(self): - b = self.makeBot() - b.joined('#ch1') - b.joined('#ch2') - self.assertEqual(sorted(b.contacts.keys()), - sorted(['#ch1', '#ch2'])) - - def test_other(self): - # these methods just log, but let's get them covered anyway - b = self.makeBot() - b.left('#ch1') - b.kickedFrom('#ch1', 'dustin', 'go away!') - - -class TestIrcStatusFactory(unittest.TestCase): - - def makeFactory(self, *args, **kwargs): - if not args: - args = ('nick', 'pass', ['ch'], [], [], {}) - return words.IrcStatusFactory(*args, **kwargs) - - def test_shutdown(self): - # this is kinda lame, but the factory would be better tested - # in an integration-test environment - f = self.makeFactory() - self.assertFalse(f.shuttingDown) - f.shutdown() - self.assertTrue(f.shuttingDown) - - -class TestIRC(config.ConfigErrorsMixin, unittest.TestCase): - - def makeIRC(self, **kwargs): - kwargs.setdefault('host', 'localhost') - kwargs.setdefault('nick', 'russo') - kwargs.setdefault('channels', ['#buildbot']) - self.factory = None - def TCPClient(host, port, factory): - client = mock.Mock(name='tcp-client') - client.host = host - client.port = port - client.factory = factory - # keep for later - self.factory = factory - self.client = client - return client - self.patch(internet, 'TCPClient', TCPClient) - return words.IRC(**kwargs) - - def test_constr(self): - irc = self.makeIRC(host='foo', port=123) - self.client.setServiceParent.assert_called_with(irc) - self.assertEqual(self.client.host, 'foo') - self.assertEqual(self.client.port, 123) - self.assertIsInstance(self.client.factory, words.IrcStatusFactory) - - def test_constr_args(self): - # test that the args to IRC(..) make it all the way down to - # the IrcStatusBot class - self.makeIRC( - host='host', - nick='nick', - channels=['channels'], - pm_to_nicks=['pm', 'to', 'nicks'], - port=1234, - allowForce=True, - categories=['categories'], - password='pass', - notify_events={ 'successToFailure': 1, }, - noticeOnChannel=True, - showBlameList=False, - useRevisions=True, - useSSL=False, - lostDelay=10, - failedDelay=20, - useColors=False) - - # patch it up - factory = self.factory - proto_obj = mock.Mock(name='proto_obj') - factory.protocol = mock.Mock(name='protocol', return_value=proto_obj) - factory.status = 'STATUS' - - # run it - p = factory.buildProtocol('address') - self.assertIdentical(p, proto_obj) - factory.protocol.assert_called_with( - 'nick', 'pass', ['channels'], ['pm', 'to', 'nicks'], - factory.status, ['categories'], { 'successToFailure': 1 }, - noticeOnChannel=True, - useColors=False, - useRevisions=True, - showBlameList=False) - - def test_allowForce_notBool(self): - """ - When L{IRCClient} is called with C{allowForce} not a boolean, - a config error is reported. - """ - self.assertRaisesConfigError("allowForce must be boolean, not", - lambda: self.makeIRC(allowForce=object())) - - def test_allowShutdown_notBool(self): - """ - When L{IRCClient} is called with C{allowShutdown} not a boolean, - a config error is reported. - """ - self.assertRaisesConfigError("allowShutdown must be boolean, not", - lambda: self.makeIRC(allowShutdown=object())) - - def test_service(self): - irc = self.makeIRC() - # just put it through its paces - irc.startService() - return irc.stopService() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_master.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_master.py deleted file mode 100644 index 5b5ce6b8..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_master.py +++ /dev/null @@ -1,229 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import os -import sys -from twisted.python import failure, runtime -from twisted.internet import error, reactor -from twisted.trial import unittest -from buildbot.test.util import steps -from buildbot.status.results import SUCCESS, FAILURE, EXCEPTION -from buildbot.steps import master -from buildbot.process.properties import WithProperties -from buildbot.process.properties import Interpolate -import pprint - -class TestMasterShellCommand(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - if runtime.platformType == 'win32': - self.comspec = os.environ.get('COMPSPEC') - os.environ['COMSPEC'] = r'C:\WINDOWS\system32\cmd.exe' - return self.setUpBuildStep() - - def tearDown(self): - if runtime.platformType == 'win32': - if self.comspec: - os.environ['COMSPEC'] = self.comspec - else: - del os.environ['COMSPEC'] - return self.tearDownBuildStep() - - def patchSpawnProcess(self, exp_cmd, exp_argv, exp_path, exp_usePTY, - exp_env, outputs): - def spawnProcess(pp, cmd, argv, path, usePTY, env): - self.assertEqual([cmd, argv, path, usePTY, env], - [exp_cmd, exp_argv, exp_path, exp_usePTY, exp_env]) - for output in outputs: - if output[0] == 'out': - pp.outReceived(output[1]) - elif output[0] == 'err': - pp.errReceived(output[1]) - elif output[0] == 'rc': - if output[1] != 0: - so = error.ProcessTerminated(exitCode=output[1]) - else: - so = error.ProcessDone(None) - pp.processEnded(failure.Failure(so)) - self.patch(reactor, 'spawnProcess', spawnProcess) - - def test_real_cmd(self): - cmd = [ sys.executable, '-c', 'print "hello"' ] - self.setupStep( - master.MasterShellCommand(command=cmd)) - if runtime.platformType == 'win32': - self.expectLogfile('stdio', "hello\r\n") - else: - self.expectLogfile('stdio', "hello\n") - self.expectOutcome(result=SUCCESS, status_text=["Ran"]) - return self.runStep() - - def test_real_cmd_interrupted(self): - cmd = [ sys.executable, '-c', 'while True: pass' ] - self.setupStep( - master.MasterShellCommand(command=cmd)) - self.expectLogfile('stdio', "") - if runtime.platformType == 'win32': - # windows doesn't have signals, so we don't get 'killed' - self.expectOutcome(result=EXCEPTION, - status_text=["failed (1)", "interrupted"]) - else: - self.expectOutcome(result=EXCEPTION, - status_text=["killed (9)", "interrupted"]) - d = self.runStep() - self.step.interrupt("KILL") - return d - - def test_real_cmd_fails(self): - cmd = [ sys.executable, '-c', 'import sys; sys.exit(1)' ] - self.setupStep( - master.MasterShellCommand(command=cmd)) - self.expectLogfile('stdio', "") - self.expectOutcome(result=FAILURE, status_text=["failed (1)"]) - return self.runStep() - - def test_constr_args(self): - self.setupStep( - master.MasterShellCommand(description='x', descriptionDone='y', - env={'a':'b'}, path=['/usr/bin'], usePTY=True, - command='true')) - - self.assertEqual(self.step.describe(), ['x']) - - if runtime.platformType == 'win32': - exp_argv = [ r'C:\WINDOWS\system32\cmd.exe', '/c', 'true' ] - else: - exp_argv = [ '/bin/sh', '-c', 'true' ] - self.patchSpawnProcess( - exp_cmd=exp_argv[0], exp_argv=exp_argv, - exp_path=['/usr/bin'], exp_usePTY=True, exp_env={'a':'b'}, - outputs=[ - ('out', 'hello!\n'), - ('err', 'world\n'), - ('rc', 0), - ]) - self.expectOutcome(result=SUCCESS, status_text=['y']) - return self.runStep() - - def test_env_subst(self): - cmd = [ sys.executable, '-c', 'import os; print os.environ["HELLO"]' ] - os.environ['WORLD'] = 'hello' - self.setupStep( - master.MasterShellCommand(command=cmd, - env={'HELLO': '${WORLD}'})) - if runtime.platformType == 'win32': - self.expectLogfile('stdio', "hello\r\n") - else: - self.expectLogfile('stdio', "hello\n") - self.expectOutcome(result=SUCCESS, status_text=["Ran"]) - def _restore_env(res): - del os.environ['WORLD'] - return res - d = self.runStep() - d.addBoth(_restore_env) - return d - - def test_env_list_subst(self): - cmd = [ sys.executable, '-c', 'import os; print os.environ["HELLO"]' ] - os.environ['WORLD'] = 'hello' - os.environ['LIST'] = 'world' - self.setupStep( - master.MasterShellCommand(command=cmd, - env={'HELLO': ['${WORLD}', '${LIST}']})) - if runtime.platformType == 'win32': - self.expectLogfile('stdio', "hello;world\r\n") - else: - self.expectLogfile('stdio', "hello:world\n") - self.expectOutcome(result=SUCCESS, status_text=["Ran"]) - def _restore_env(res): - del os.environ['WORLD'] - del os.environ['LIST'] - return res - d = self.runStep() - d.addBoth(_restore_env) - return d - - def test_prop_rendering(self): - cmd = [ sys.executable, '-c', WithProperties( - 'import os; print "%s"; print os.environ[\"BUILD\"]', - 'project') ] - self.setupStep( - master.MasterShellCommand(command=cmd, - env={'BUILD': WithProperties('%s', "project")})) - self.properties.setProperty("project", "BUILDBOT-TEST", "TEST") - if runtime.platformType == 'win32': - self.expectLogfile('stdio', "BUILDBOT-TEST\r\nBUILDBOT-TEST\r\n") - else: - self.expectLogfile('stdio', "BUILDBOT-TEST\nBUILDBOT-TEST\n") - self.expectOutcome(result=SUCCESS, status_text=["Ran"]) - return self.runStep() - - def test_constr_args_descriptionSuffix(self): - self.setupStep( - master.MasterShellCommand(description='x', descriptionDone='y', - descriptionSuffix='z', - env={'a':'b'}, path=['/usr/bin'], usePTY=True, - command='true')) - - # call twice to make sure the suffix doesn't get double added - self.assertEqual(self.step.describe(), ['x', 'z']) - self.assertEqual(self.step.describe(), ['x', 'z']) - - if runtime.platformType == 'win32': - exp_argv = [ r'C:\WINDOWS\system32\cmd.exe', '/c', 'true' ] - else: - exp_argv = [ '/bin/sh', '-c', 'true' ] - self.patchSpawnProcess( - exp_cmd=exp_argv[0], exp_argv=exp_argv, - exp_path=['/usr/bin'], exp_usePTY=True, exp_env={'a':'b'}, - outputs=[ - ('out', 'hello!\n'), - ('err', 'world\n'), - ('rc', 0), - ]) - self.expectOutcome(result=SUCCESS, status_text=['y', 'z']) - return self.runStep() - -class TestSetProperty(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_simple(self): - self.setupStep(master.SetProperty(property="testProperty", value=Interpolate("sch=%(prop:scheduler)s, slave=%(prop:slavename)s"))) - self.properties.setProperty('scheduler', 'force', source='SetProperty', runtime=True) - self.properties.setProperty('slavename', 'testSlave', source='SetPropery', runtime=True) - self.expectOutcome(result=SUCCESS, status_text=["SetProperty"]) - self.expectProperty('testProperty', 'sch=force, slave=testSlave', source='SetProperty') - return self.runStep() - -class TestLogRenderable(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_simple(self): - self.setupStep(master.LogRenderable(content=Interpolate('sch=%(prop:scheduler)s, slave=%(prop:slavename)s'))) - self.properties.setProperty('scheduler', 'force', source='TestSetProperty', runtime=True) - self.properties.setProperty('slavename', 'testSlave', source='TestSetProperty', runtime=True) - self.expectOutcome(result=SUCCESS, status_text=['LogRenderable']) - self.expectLogfile('Output', pprint.pformat('sch=force, slave=testSlave')) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_maxq.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_maxq.py deleted file mode 100644 index 07f3edef..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_maxq.py +++ /dev/null @@ -1,71 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.test.util import steps -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.steps import maxq -from buildbot import config - -class TestShellCommandExecution(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_testdir_required(self): - self.assertRaises(config.ConfigErrors, lambda : maxq.MaxQ()) - - def test_success(self): - self.setupStep( - maxq.MaxQ(testdir='x')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="run_maxq.py x") - + ExpectShell.log('stdio', stdout='no failures\n') - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['maxq', 'tests']) - return self.runStep() - - def test_nonzero_rc_no_failures(self): - self.setupStep( - maxq.MaxQ(testdir='x')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="run_maxq.py x") - + ExpectShell.log('stdio', stdout='no failures\n') - + 2 - ) - self.expectOutcome(result=FAILURE, - status_text=['1', 'maxq', 'failures']) - return self.runStep() - - def test_failures(self): - self.setupStep( - maxq.MaxQ(testdir='x')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="run_maxq.py x") - + ExpectShell.log('stdio', stdout='\nTEST FAILURE: foo\n' * 10) - + 2 - ) - self.expectOutcome(result=FAILURE, - status_text=['10', 'maxq', 'failures']) - return self.runStep() - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_lintian.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_lintian.py deleted file mode 100644 index cec98927..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_lintian.py +++ /dev/null @@ -1,55 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.results import SUCCESS -from buildbot.steps.package.deb import lintian -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps -from twisted.trial import unittest -from buildbot import config - -class TestDebLintian(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_fileloc(self): - self.assertRaises(config.ConfigErrors, lambda : - lintian.DebLintian()) - - def test_success(self): - self.setupStep(lintian.DebLintian('foo_0.23_i386.changes')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['lintian', '-v', 'foo_0.23_i386.changes']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['Lintian']) - return self.runStep() - - def test_success_suppressTags(self): - self.setupStep(lintian.DebLintian('foo_0.23_i386.changes', - suppressTags=['bad-distribution-in-changes-file'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['lintian', '-v', 'foo_0.23_i386.changes', - '--suppress-tags', 'bad-distribution-in-changes-file']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['Lintian']) - return self.runStep() - - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_pbuilder.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_pbuilder.py deleted file mode 100644 index 975b431e..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_deb_pbuilder.py +++ /dev/null @@ -1,372 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import stat -import time - -from twisted.trial import unittest -from buildbot.steps.package.deb import pbuilder -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import steps -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot import config - -class TestDebPbuilder(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_new(self): - self.setupStep(pbuilder.DebPbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_update(self): - self.setupStep(pbuilder.DebPbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + Expect.update('stat', [stat.S_IFREG, 99, 99, 1, 0, 0, 99, 0, 0, 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--update', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz',]) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_buildonly(self): - self.setupStep(pbuilder.DebPbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + Expect.update('stat', [stat.S_IFREG, 99, 99, 1, 0, 0, 99, 0, int(time.time()), 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_architecture(self): - self.setupStep(pbuilder.DebPbuilder(architecture='amd64')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-amd64-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-amd64-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/', - '--architecture', 'amd64']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', - '--architecture', 'amd64', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-amd64-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_distribution(self): - self.setupStep(pbuilder.DebPbuilder(distribution='woody')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/woody-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/woody-local-buildbot.tgz', - '--distribution', 'woody', - '--mirror', 'http://cdn.debian.net/debian/']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/woody-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_basetgz(self): - self.setupStep(pbuilder.DebPbuilder(basetgz='/buildbot/%(distribution)s-%(architecture)s.tgz')) - self.expectCommands( - Expect('stat', {'file': '/buildbot/stable-local.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/buildbot/stable-local.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/buildbot/stable-local.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_mirror(self): - self.setupStep(pbuilder.DebPbuilder(mirror='http://apt:9999/debian')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://apt:9999/debian']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_extrapackages(self): - self.setupStep(pbuilder.DebPbuilder(extrapackages=['buildbot'])) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/', - '--extrapackages', 'buildbot']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--extrapackages', 'buildbot']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_keyring(self): - self.setupStep(pbuilder.DebPbuilder(keyring='/builbot/buildbot.gpg')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/', - '--debootstrapopts', '--keyring=/builbot/buildbot.gpg']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_components(self): - self.setupStep(pbuilder.DebPbuilder(components='main universe')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/', - '--components', 'main universe']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/stable-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - -class TestDebCowbuilder(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_new(self): - self.setupStep(pbuilder.DebCowbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.cow/'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/cowbuilder', '--create', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow/', - '--distribution', 'stable', - '--mirror', 'http://cdn.debian.net/debian/']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/cowbuilder', '--', '--buildresult', '.', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow/']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_update(self): - self.setupStep(pbuilder.DebCowbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.cow/'}) - + Expect.update('stat', [stat.S_IFDIR, 99, 99, 1, 0, 0, 99, 0, 0, 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/cowbuilder', '--update', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow/',]) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/cowbuilder', '--', '--buildresult', '.', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow/']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_buildonly(self): - self.setupStep(pbuilder.DebCowbuilder()) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.cow/'}) - + Expect.update('stat', [stat.S_IFDIR, 99, 99, 1, 0, 0, 99, 0, int(time.time()), 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/cowbuilder', '--', '--buildresult', '.', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow/']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - - def test_update_reg(self): - self.setupStep(pbuilder.DebCowbuilder(basetgz='/var/cache/pbuilder/stable-local-buildbot.cow')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.cow'}) - + Expect.update('stat', [stat.S_IFREG, 99, 99, 1, 0, 0, 99, 0, 0, 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/cowbuilder', '--update', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow']) - + 1) - self.expectOutcome(result=FAILURE, status_text=['PBuilder update.']) - return self.runStep() - - def test_buildonly_reg(self): - self.setupStep(pbuilder.DebCowbuilder(basetgz='/var/cache/pbuilder/stable-local-buildbot.cow')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/stable-local-buildbot.cow'}) - + Expect.update('stat', [stat.S_IFREG, 99, 99, 1, 0, 0, 99, 0, int(time.time()), 0]) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/cowbuilder', '--', '--buildresult', '.', - '--basepath', '/var/cache/pbuilder/stable-local-buildbot.cow']) - + 1) - self.expectOutcome(result=FAILURE, status_text=['pdebuild', 'failed']) - return self.runStep() - -class TestUbuPbuilder(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_distribution(self): - self.assertRaises(config.ConfigErrors, lambda : - pbuilder.UbuPbuilder()) - - def test_new(self): - self.setupStep(pbuilder.UbuPbuilder(distribution='oneiric')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/oneiric-local-buildbot.tgz'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/pbuilder', '--create', - '--basetgz', '/var/cache/pbuilder/oneiric-local-buildbot.tgz', - '--distribution', 'oneiric', - '--mirror', 'http://archive.ubuntu.com/ubuntu/', - '--components', 'main universe']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/pbuilder', '--', '--buildresult', '.', - '--basetgz', '/var/cache/pbuilder/oneiric-local-buildbot.tgz']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() - -class TestUbuCowbuilder(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_distribution(self): - self.assertRaises(config.ConfigErrors, lambda : - pbuilder.UbuCowbuilder()) - - def test_new(self): - self.setupStep(pbuilder.UbuCowbuilder(distribution='oneiric')) - self.expectCommands( - Expect('stat', {'file': '/var/cache/pbuilder/oneiric-local-buildbot.cow/'}) - + 1, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sudo', '/usr/sbin/cowbuilder', '--create', - '--basepath', '/var/cache/pbuilder/oneiric-local-buildbot.cow/', - '--distribution', 'oneiric', - '--mirror', 'http://archive.ubuntu.com/ubuntu/', - '--components', 'main universe']) - +0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['pdebuild', '--buildresult', '.', - '--pbuilder', '/usr/sbin/cowbuilder', '--', '--buildresult', '.', - '--basepath', '/var/cache/pbuilder/oneiric-local-buildbot.cow/']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['pdebuild']) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_mock.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_mock.py deleted file mode 100644 index df0e937b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_mock.py +++ /dev/null @@ -1,128 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.steps.package.rpm import mock -from buildbot.status.results import SUCCESS -from buildbot.test.util import steps -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot import config - -class TestMock(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_root(self): - self.assertRaises(config.ConfigErrors, lambda : - mock.Mock()) - - def test_class_attrs(self): - step = self.setupStep(mock.Mock(root='TESTROOT')) - self.assertEqual(step.command, ['mock', '--root', 'TESTROOT']) - - def test_success(self): - self.setupStep(mock.Mock(root='TESTROOT')) - self.expectCommands( - Expect('rmdir', {'dir': ['build/build.log', 'build/root.log', - 'build/state.log']}) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['mock', '--root', 'TESTROOT'], - logfiles={'build.log': 'build.log', - 'root.log': 'root.log', - 'state.log': 'state.log'}) - +0) - self.expectOutcome(result=SUCCESS, status_text=["'mock", '--root', "...'"]) - return self.runStep() - - def test_resultdir_success(self): - self.setupStep(mock.Mock(root='TESTROOT', resultdir='RESULT')) - self.expectCommands( - Expect('rmdir', {'dir': ['build/RESULT/build.log', - 'build/RESULT/root.log', - 'build/RESULT/state.log']}) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['mock', '--root', 'TESTROOT', - '--resultdir', 'RESULT'], - logfiles={'build.log': 'RESULT/build.log', - 'root.log': 'RESULT/root.log', - 'state.log': 'RESULT/state.log'}) - +0) - self.expectOutcome(result=SUCCESS, status_text=["'mock", '--root', "...'"]) - return self.runStep() - - - -class TestMockBuildSRPM(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_spec(self): - self.assertRaises(config.ConfigErrors, lambda : - mock.MockBuildSRPM(root='TESTROOT')) - - def test_success(self): - self.setupStep(mock.MockBuildSRPM(root='TESTROOT', spec="foo.spec")) - self.expectCommands( - Expect('rmdir', {'dir': ['build/build.log', 'build/root.log', - 'build/state.log']}) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['mock', '--root', 'TESTROOT', - '--buildsrpm', '--spec', 'foo.spec', - '--sources', '.'], - logfiles={'build.log': 'build.log', - 'root.log': 'root.log', - 'state.log': 'state.log'},) - +0) - self.expectOutcome(result=SUCCESS, status_text=['mock buildsrpm']) - return self.runStep() - -class TestMockRebuild(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_srpm(self): - self.assertRaises(config.ConfigErrors, lambda : - mock.MockRebuild(root='TESTROOT')) - - def test_success(self): - self.setupStep(mock.MockRebuild(root='TESTROOT', srpm="foo.src.rpm")) - self.expectCommands( - Expect('rmdir', {'dir': ['build/build.log', 'build/root.log', - 'build/state.log']}) - + 0, - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['mock', '--root', 'TESTROOT', - '--rebuild', 'foo.src.rpm'], - logfiles={'build.log': 'build.log', - 'root.log': 'root.log', - 'state.log': 'state.log'},) - +0) - self.expectOutcome(result=SUCCESS, status_text=['mock rebuild srpm']) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmbuild.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmbuild.py deleted file mode 100644 index 97dee1e5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmbuild.py +++ /dev/null @@ -1,64 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.results import SUCCESS -from buildbot.steps.package.rpm import rpmbuild -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps -from twisted.trial import unittest -from buildbot import config - -class RpmBuild(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_specfile(self): - self.assertRaises(config.ConfigErrors, lambda : - rpmbuild.RpmBuild()) - - def test_success(self): - self.setupStep(rpmbuild.RpmBuild(specfile="foo.spec", dist=".el6")) - self.expectCommands( - ExpectShell(workdir='wkdir', command='rpmbuild --define "_topdir ' - '`pwd`" --define "_builddir `pwd`" --define "_rpmdir ' - '`pwd`" --define "_sourcedir `pwd`" --define "_specdir ' - '`pwd`" --define "_srcrpmdir `pwd`" --define "dist .el6" ' - '-ba foo.spec', - usePTY='slave-config') - + ExpectShell.log('stdio', - stdout='lalala') - +0) - self.expectOutcome(result=SUCCESS, status_text=['RPMBUILD']) - return self.runStep() - - def test_autoRelease(self): - self.setupStep(rpmbuild.RpmBuild(specfile="foo.spec", dist=".el6", - autoRelease=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', command='rpmbuild --define "_topdir ' - '`pwd`" --define "_builddir `pwd`" --define "_rpmdir `pwd`" ' - '--define "_sourcedir `pwd`" --define "_specdir `pwd`" ' - '--define "_srcrpmdir `pwd`" --define "dist .el6" ' - '--define "_release 0" -ba foo.spec', - usePTY='slave-config') - + ExpectShell.log('stdio', - stdout='Your code has been rated at 10/10') - +0) - self.expectOutcome(result=SUCCESS, status_text=['RPMBUILD']) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmlint.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmlint.py deleted file mode 100644 index cb36e31c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_package_rpm_rpmlint.py +++ /dev/null @@ -1,56 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.results import SUCCESS -from buildbot.steps.package.rpm import rpmlint -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps -from twisted.trial import unittest - -class TestRpmLint(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(rpmlint.RpmLint()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['rpmlint', '-i', '.']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['Finished checking RPM/SPEC issues']) - return self.runStep() - - def test_fileloc_success(self): - self.setupStep(rpmlint.RpmLint(fileloc='RESULT')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['rpmlint', '-i', 'RESULT']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['Finished checking RPM/SPEC issues']) - return self.runStep() - - def test_config_success(self): - self.setupStep(rpmlint.RpmLint(config='foo.cfg')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['rpmlint', '-i', '-f', 'foo.cfg', '.']) - +0) - self.expectOutcome(result=SUCCESS, status_text=['Finished checking RPM/SPEC issues']) - return self.runStep() - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python.py deleted file mode 100644 index 4bc31cbc..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python.py +++ /dev/null @@ -1,445 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.results import FAILURE, SUCCESS, WARNINGS -from buildbot.steps import python -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps -from twisted.trial import unittest -from buildbot import config - -log_output_success = '''\ -Making output directory... -Running Sphinx v1.0.7 -loading pickled environment... not yet created -No builder selected, using default: html -building [html]: targets for 24 source files that are out of date -updating environment: 24 added, 0 changed, 0 removed -reading sources... [ 4%] index -reading sources... [ 8%] manual/cfg-builders -... -copying static files... done -dumping search index... done -dumping object inventory... done -build succeeded. -''' - -log_output_nochange = '''\ -Running Sphinx v1.0.7 -loading pickled environment... done -No builder selected, using default: html -building [html]: targets for 0 source files that are out of date -updating environment: 0 added, 0 changed, 0 removed -looking for now-outdated files... none found -no targets are out of date. -''' - -log_output_warnings = '''\ -Running Sphinx v1.0.7 -loading pickled environment... done -building [html]: targets for 1 source files that are out of date -updating environment: 0 added, 1 changed, 0 removed -reading sources... [100%] file - -file.rst:18: (WARNING/2) Literal block expected; none found. - -looking for now-outdated files... none found -pickling environment... done -checking consistency... done -preparing documents... done -writing output... [ 50%] index -writing output... [100%] file - -index.rst:: WARNING: toctree contains reference to document 'preamble' that \ -doesn't have a title: no link will be generated -writing additional files... search -copying static files... done -dumping search index... done -dumping object inventory... done -build succeeded, 2 warnings.''' - -warnings = '''\ -file.rst:18: (WARNING/2) Literal block expected; none found. -index.rst:: WARNING: toctree contains reference to document 'preamble' that \ -doesn't have a title: no link will be generated\ -''' - - -class PyLint(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log('stdio', - stdout='Your code has been rated at 10/10') - + python.PyLint.RC_OK) - self.expectOutcome(result=SUCCESS, status_text=['pylint']) - return self.runStep() - - def test_error(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W: 11: Bad indentation. Found 6 spaces, expected 4\n' - 'E: 12: Undefined variable \'foo\'\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_ERROR)) - self.expectOutcome(result=FAILURE, - status_text=['pylint', 'error=1', 'warning=1', - 'failed']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-error', 1) - return self.runStep() - - def test_failure(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W: 11: Bad indentation. Found 6 spaces, expected 4\n' - 'F: 13: something really strange happened\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_FATAL)) - self.expectOutcome(result=FAILURE, - status_text=['pylint', 'fatal=1', 'warning=1', - 'failed']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-fatal', 1) - return self.runStep() - - def test_failure_zero_returncode(self): - # Make sure that errors result in a failed step when pylint's - # return code is 0, e.g. when run through a wrapper script. - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W: 11: Bad indentation. Found 6 spaces, expected 4\n' - 'E: 12: Undefined variable \'foo\'\n')) - + 0) - self.expectOutcome(result=FAILURE, - status_text=['pylint', 'error=1', 'warning=1', - 'failed']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-error', 1) - return self.runStep() - - def test_regex_text(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W: 11: Bad indentation. Found 6 spaces, expected 4\n' - 'C: 1:foo123: Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - - def test_regex_text_0_24(self): - # pylint >= 0.24.0 prints out column offsets when using text format - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W: 11,0: Bad indentation. Found 6 spaces, expected 4\n' - 'C: 3,10:foo123: Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - - def test_regex_text_ids(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W0311: 11: Bad indentation.\n' - 'C0111: 1:funcName: Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - - def test_regex_text_ids_0_24(self): - # pylint >= 0.24.0 prints out column offsets when using text format - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('W0311: 11,0: Bad indentation.\n' - 'C0111: 3,10:foo123: Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - - def test_regex_parseable_ids(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('test.py:9: [W0311] Bad indentation.\n' - 'test.py:3: [C0111, foo123] Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - - def test_regex_parseable(self): - self.setupStep(python.PyLint(command=['pylint'])) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['pylint'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout=('test.py:9: [W] Bad indentation.\n' - 'test.py:3: [C, foo123] Missing docstring\n')) - + (python.PyLint.RC_WARNING|python.PyLint.RC_CONVENTION)) - self.expectOutcome(result=WARNINGS, - status_text=['pylint', 'convention=1', 'warning=1', - 'warnings']) - self.expectProperty('pylint-warning', 1) - self.expectProperty('pylint-convention', 1) - self.expectProperty('pylint-total', 2) - return self.runStep() - -class PyFlakes(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + 0) - self.expectOutcome(result=SUCCESS, status_text=['pyflakes']) - return self.runStep() - - def test_unused(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout="foo.py:1: 'bar' imported but unused\n") - + 1) - self.expectOutcome(result=WARNINGS, - status_text=['pyflakes', 'unused=1', 'warnings']) - self.expectProperty('pyflakes-unused', 1) - self.expectProperty('pyflakes-total', 1) - return self.runStep() - - def test_undefined(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout="foo.py:1: undefined name 'bar'\n") - + 1) - self.expectOutcome(result=FAILURE, - status_text=['pyflakes', 'undefined=1', 'failed']) - self.expectProperty('pyflakes-undefined', 1) - self.expectProperty('pyflakes-total', 1) - return self.runStep() - - def test_redefs(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout="foo.py:2: redefinition of unused 'foo' from line 1\n") - + 1) - self.expectOutcome(result=WARNINGS, - status_text=['pyflakes', 'redefs=1', 'warnings']) - self.expectProperty('pyflakes-redefs', 1) - self.expectProperty('pyflakes-total', 1) - return self.runStep() - - def test_importstar(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout="foo.py:1: 'from module import *' used; unable to detect undefined names\n") - + 1) - self.expectOutcome(result=WARNINGS, - status_text=['pyflakes', 'import*=1', 'warnings']) - self.expectProperty('pyflakes-import*', 1) - self.expectProperty('pyflakes-total', 1) - return self.runStep() - - def test_misc(self): - self.setupStep(python.PyFlakes()) - self.expectCommands( - ExpectShell(workdir='wkdir', command=['make', 'pyflakes'], - usePTY='slave-config') - + ExpectShell.log( - 'stdio', - stdout="foo.py:2: redefinition of function 'bar' from line 1\n") - + 1) - self.expectOutcome(result=WARNINGS, - status_text=['pyflakes', 'misc=1', 'warnings']) - self.expectProperty('pyflakes-misc', 1) - self.expectProperty('pyflakes-total', 1) - return self.runStep() - - -class TestSphinx(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_builddir_required(self): - self.assertRaises(config.ConfigErrors, lambda : - python.Sphinx()) - - def test_bad_mode(self): - self.assertRaises(config.ConfigErrors, lambda: python.Sphinx( - sphinx_builddir="_build", mode="don't care")) - - def test_success(self): - self.setupStep(python.Sphinx(sphinx_builddir="_build")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sphinx-build', '.', '_build']) - + ExpectShell.log('stdio', - stdout=log_output_success) - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["sphinx", "0 warnings"]) - return self.runStep() - - def test_failure(self): - self.setupStep(python.Sphinx(sphinx_builddir="_build")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sphinx-build', '.', '_build']) - + ExpectShell.log('stdio', - stdout='oh noes!') - + 1 - ) - self.expectOutcome(result=FAILURE, status_text=["sphinx", "0 warnings", "failed"]) - return self.runStep() - - def test_nochange(self): - self.setupStep(python.Sphinx(sphinx_builddir="_build")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sphinx-build', '.', '_build']) - + ExpectShell.log('stdio', - stdout=log_output_nochange) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["sphinx", "0 warnings"]) - return self.runStep() - - def test_warnings(self): - self.setupStep(python.Sphinx(sphinx_builddir="_build")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['sphinx-build', '.', '_build']) - + ExpectShell.log('stdio', - stdout=log_output_warnings) - + 0 - ) - self.expectOutcome(result=WARNINGS, - status_text=["sphinx", "2 warnings", "warnings"]) - self.expectLogfile("warnings", warnings) - d = self.runStep() - def check(_): - self.assertEqual(self.step_statistics, { 'warnings' : 2 }) - d.addCallback(check) - return d - - def test_constr_args(self): - self.setupStep(python.Sphinx(sphinx_sourcedir='src', - sphinx_builddir="bld", - sphinx_builder='css', - sphinx="/path/to/sphinx-build", - tags=['a', 'b'], - defines=dict(empty=None, t=True, f=False, s="str"), - mode='full')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['/path/to/sphinx-build', '-b', 'css', - '-t', 'a', '-t', 'b', '-D', 'empty', - '-D', 'f=0', '-D', 's=str', '-D', 't=1', - '-E', 'src', 'bld']) - + ExpectShell.log('stdio', - stdout=log_output_success) - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["sphinx", "0 warnings"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python_twisted.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python_twisted.py deleted file mode 100644 index daefb43b..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_python_twisted.py +++ /dev/null @@ -1,194 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.steps import python_twisted -from buildbot.status.results import SUCCESS -from buildbot.test.util import steps -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.process.properties import Property - - - -class Trial(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_run_env(self): - self.setupStep( - python_twisted.Trial(workdir='build', - tests = 'testname', - testpath = None, - env = {'PYTHONPATH': 'somepath'})) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}, - env=dict(PYTHONPATH='somepath')) - + ExpectShell.log('stdio', stdout="Ran 0 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['no tests', 'run']) - return self.runStep() - - def test_run_env_supplement(self): - self.setupStep( - python_twisted.Trial(workdir='build', - tests = 'testname', - testpath = 'path1', - env = {'PYTHONPATH': ['path2','path3']})) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}, - env=dict(PYTHONPATH=['path1', 'path2', 'path3'])) - + ExpectShell.log('stdio', stdout="Ran 0 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['no tests', 'run']) - return self.runStep() - - def test_run_env_nodupe(self): - self.setupStep( - python_twisted.Trial(workdir='build', - tests = 'testname', - testpath = 'path2', - env = {'PYTHONPATH': ['path1','path2']})) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}, - env=dict(PYTHONPATH=['path1','path2'])) - + ExpectShell.log('stdio', stdout="Ran 0 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['no tests', 'run']) - return self.runStep() - - def test_run_singular(self): - self.setupStep( - python_twisted.Trial(workdir='build', - tests = 'testname', - testpath=None)) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}) - + ExpectShell.log('stdio', stdout="Ran 1 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['1 test', 'passed']) - return self.runStep() - - def test_run_plural(self): - self.setupStep( - python_twisted.Trial(workdir='build', - tests = 'testname', - testpath=None)) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}) - + ExpectShell.log('stdio', stdout="Ran 2 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['2 tests', 'passed']) - return self.runStep() - - def testProperties(self): - self.setupStep(python_twisted.Trial(workdir='build', - tests = Property('test_list'), - testpath=None)) - self.properties.setProperty('test_list',['testname'], 'Test') - - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', 'testname'], - usePTY="slave-config", - logfiles={'test.log': '_trial_temp/test.log'}) - + ExpectShell.log('stdio', stdout="Ran 2 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['2 tests', 'passed']) - return self.runStep() - - def test_run_jobs(self): - """ - The C{jobs} kwarg should correspond to trial's -j option ( - included since Twisted 12.3.0), and make corresponding changes to - logfiles. - """ - self.setupStep(python_twisted.Trial(workdir='build', - tests = 'testname', - testpath = None, - jobs=2)) - - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', '--jobs=2', - 'testname'], - usePTY="slave-config", - logfiles={ - 'test.0.log': '_trial_temp/0/test.log', - 'err.0.log': '_trial_temp/0/err.log', - 'out.0.log': '_trial_temp/0/out.log', - 'test.1.log': '_trial_temp/1/test.log', - 'err.1.log': '_trial_temp/1/err.log', - 'out.1.log': '_trial_temp/1/out.log', - }) - + ExpectShell.log('stdio', stdout="Ran 1 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['1 test', 'passed']) - return self.runStep() - - def test_run_jobsProperties(self): - """ - C{jobs} should accept Properties - """ - self.setupStep(python_twisted.Trial(workdir='build', - tests = 'testname', - jobs=Property('jobs_count'), - testpath=None)) - self.properties.setProperty('jobs_count', '2', 'Test') - - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '--reporter=bwverbose', '--jobs=2', - 'testname'], - usePTY="slave-config", - logfiles={ - 'test.0.log': '_trial_temp/0/test.log', - 'err.0.log': '_trial_temp/0/err.log', - 'out.0.log': '_trial_temp/0/out.log', - 'test.1.log': '_trial_temp/1/test.log', - 'err.1.log': '_trial_temp/1/err.log', - 'out.1.log': '_trial_temp/1/out.log', - }) - + ExpectShell.log('stdio', stdout="Ran 1 tests\n") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=['1 test', 'passed']) - return self.runStep() - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_shell.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_shell.py deleted file mode 100644 index 9f914600..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_shell.py +++ /dev/null @@ -1,836 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import re -import textwrap -from twisted.trial import unittest -from buildbot.steps import shell -from buildbot.status.results import SKIPPED, SUCCESS, WARNINGS, FAILURE -from buildbot.status.results import EXCEPTION -from buildbot.test.util import steps, compat -from buildbot.test.util import config as configmixin -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot.test.fake.remotecommand import ExpectRemoteRef -from buildbot import config -from buildbot.process import properties - -class TestShellCommandExecution(steps.BuildStepMixin, unittest.TestCase, configmixin.ConfigErrorsMixin): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_doStepIf_False(self): - self.setupStep( - shell.ShellCommand(command="echo hello", doStepIf=False)) - self.expectOutcome(result=SKIPPED, - status_text=["'echo", "hello'", "skipped"]) - return self.runStep() - - def test_constructor_args_strings(self): - step = shell.ShellCommand(workdir='build', command="echo hello", - usePTY=False, description="echoing", - descriptionDone="echoed") - self.assertEqual(step.description, ['echoing']) - self.assertEqual(step.descriptionDone, ['echoed']) - - def test_constructor_args_lists(self): - step = shell.ShellCommand(workdir='build', command="echo hello", - usePTY=False, description=["echoing"], - descriptionDone=["echoed"]) - self.assertEqual(step.description, ['echoing']) - self.assertEqual(step.descriptionDone, ['echoed']) - - def test_constructor_args_kwargs(self): - # this is an ugly way to define an API, but for now check that - # the RemoteCommand arguments are properly passed on - step = shell.ShellCommand(workdir='build', command="echo hello", - want_stdout=0, logEnviron=False) - self.assertEqual(step.remote_kwargs, dict(want_stdout=0, - logEnviron=False, workdir='build', - usePTY='slave-config')) - - def test_constructor_args_validity(self): - # this checks that an exception is raised for invalid arguments - self.assertRaisesConfigError( - "Invalid argument(s) passed to RemoteShellCommand: ", - lambda: shell.ShellCommand('build', "echo Hello World", - wrongArg1=1, wrongArg2='two')) - - def test_describe_no_command(self): - step = shell.ShellCommand(workdir='build') - self.assertEqual((step.describe(), step.describe(done=True)), - (['???'],)*2) - - def test_describe_from_empty_command(self): - # this is more of a regression test for a potential failure, really - step = shell.ShellCommand(workdir='build', command=' ') - self.assertEqual((step.describe(), step.describe(done=True)), - (['???'],)*2) - - def test_describe_from_short_command(self): - step = shell.ShellCommand(workdir='build', command="true") - self.assertEqual((step.describe(), step.describe(done=True)), - (["'true'"],)*2) - - def test_describe_from_short_command_list(self): - step = shell.ShellCommand(workdir='build', command=["true"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'true'"],)*2) - - def test_describe_from_med_command(self): - step = shell.ShellCommand(command="echo hello") - self.assertEqual((step.describe(), step.describe(done=True)), - (["'echo", "hello'"],)*2) - - def test_describe_from_med_command_list(self): - step = shell.ShellCommand(command=["echo", "hello"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'echo", "hello'"],)*2) - - def test_describe_from_long_command(self): - step = shell.ShellCommand(command="this is a long command") - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_from_long_command_list(self): - step = shell.ShellCommand(command="this is a long command".split()) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_from_nested_command_list(self): - step = shell.ShellCommand(command=["this", ["is", "a"], "nested"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_from_nested_command_tuples(self): - step = shell.ShellCommand(command=["this", ("is", "a"), "nested"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_from_nested_command_list_empty(self): - step = shell.ShellCommand(command=["this", [], ["is", "a"], "nested"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_from_nested_command_list_deep(self): - step = shell.ShellCommand(command=[["this", [[["is", ["a"]]]]]]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'this", "is", "...'"],)*2) - - def test_describe_custom(self): - step = shell.ShellCommand(command="echo hello", - description=["echoing"], descriptionDone=["echoed"]) - self.assertEqual((step.describe(), step.describe(done=True)), - (['echoing'], ['echoed'])) - - def test_describe_with_suffix(self): - step = shell.ShellCommand(command="echo hello", descriptionSuffix="suffix") - self.assertEqual((step.describe(), step.describe(done=True)), - (["'echo", "hello'", 'suffix'],)*2) - - def test_describe_custom_with_suffix(self): - step = shell.ShellCommand(command="echo hello", - description=["echoing"], descriptionDone=["echoed"], - descriptionSuffix="suffix") - self.assertEqual((step.describe(), step.describe(done=True)), - (['echoing', 'suffix'], ['echoed', 'suffix'])) - - def test_describe_no_command_with_suffix(self): - step = shell.ShellCommand(workdir='build', descriptionSuffix="suffix") - self.assertEqual((step.describe(), step.describe(done=True)), - (['???', 'suffix'],)*2) - - def test_describe_unrendered_WithProperties(self): - step = shell.ShellCommand(command=properties.WithProperties('')) - self.assertEqual((step.describe(), step.describe(done=True)), - (['???'],)*2) - - def test_describe_unrendered_WithProperties_list(self): - step = shell.ShellCommand( - command=[ 'x', properties.WithProperties(''), 'y' ]) - self.assertEqual((step.describe(), step.describe(done=True)), - (["'x", "y'"],)*2) - - @compat.usesFlushLoggedErrors - def test_describe_fail(self): - step = shell.ShellCommand(command=object()) - self.assertEqual((step.describe(), step.describe(done=True)), - (['???'],)*2) - # (describe is called twice, so two exceptions) - self.assertEqual(len(self.flushLoggedErrors(TypeError)), 2) - - def test_run_simple(self): - self.setupStep( - shell.ShellCommand(workdir='build', command="echo hello")) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello', - usePTY="slave-config") - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'echo", "hello'"]) - return self.runStep() - - def test_run_list(self): - self.setupStep( - shell.ShellCommand(workdir='build', - command=['trial', '-b', '-B', 'buildbot.test'])) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '-b', '-B', 'buildbot.test'], - usePTY="slave-config") - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["'trial", "-b", "...'"]) - return self.runStep() - - def test_run_nested_command(self): - self.setupStep( - shell.ShellCommand(workdir='build', - command=['trial', ['-b', '-B'], 'buildbot.test'])) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '-b', '-B', 'buildbot.test'], - usePTY="slave-config") - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["'trial", "-b", "...'"]) - return self.runStep() - - def test_run_nested_deeply_command(self): - self.setupStep( - shell.ShellCommand(workdir='build', - command=[['trial', ['-b', ['-B']]], 'buildbot.test'])) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '-b', '-B', 'buildbot.test'], - usePTY="slave-config") - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["'trial", "-b", "...'"]) - return self.runStep() - - def test_run_nested_empty_command(self): - self.setupStep( - shell.ShellCommand(workdir='build', - command=['trial', [], '-b', [], 'buildbot.test'])) - self.expectCommands( - ExpectShell(workdir='build', - command=['trial', '-b', 'buildbot.test'], - usePTY="slave-config") - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["'trial", "-b", "...'"]) - return self.runStep() - - def test_run_env(self): - self.setupStep( - shell.ShellCommand(workdir='build', command="echo hello"), - slave_env=dict(DEF='HERE')) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello', - usePTY="slave-config", - env=dict(DEF='HERE')) - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'echo", "hello'"]) - return self.runStep() - - def test_run_env_override(self): - self.setupStep( - shell.ShellCommand(workdir='build', env={'ABC':'123'}, - command="echo hello"), - slave_env=dict(ABC='XXX', DEF='HERE')) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello', - usePTY="slave-config", - env=dict(ABC='123', DEF='HERE')) - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'echo", "hello'"]) - return self.runStep() - - def test_run_usePTY(self): - self.setupStep( - shell.ShellCommand(workdir='build', command="echo hello", - usePTY=False)) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello', - usePTY=False) - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'echo", "hello'"]) - return self.runStep() - - def test_run_usePTY_old_slave(self): - self.setupStep( - shell.ShellCommand(workdir='build', command="echo hello", - usePTY=True), - slave_version=dict(shell='1.1')) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello') - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'echo", "hello'"]) - return self.runStep() - - def test_run_decodeRC(self, rc=1, results=WARNINGS, extra_text = ["warnings"]): - self.setupStep( - shell.ShellCommand(workdir='build', command="echo hello", - decodeRC={1:WARNINGS})) - self.expectCommands( - ExpectShell(workdir='build', command='echo hello', - usePTY="slave-config") - + rc - ) - self.expectOutcome(result=results, status_text=["'echo", "hello'"]+extra_text) - return self.runStep() - - def test_run_decodeRC_defaults(self): - return self.test_run_decodeRC(2, FAILURE,extra_text=["failed"]) - - def test_run_decodeRC_defaults_0_is_failure(self): - return self.test_run_decodeRC(0, FAILURE,extra_text=["failed"]) - - - -class TreeSize(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_run_success(self): - self.setupStep(shell.TreeSize()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['du', '-s', '-k', '.']) - + ExpectShell.log('stdio', stdout='9292 .\n') - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["treesize", "9292 KiB"]) - self.expectProperty('tree-size-KiB', 9292) - return self.runStep() - - def test_run_misparsed(self): - self.setupStep(shell.TreeSize()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['du', '-s', '-k', '.']) - + ExpectShell.log('stdio', stdio='abcdef\n') - + 0 - ) - self.expectOutcome(result=WARNINGS, - status_text=["treesize", "unknown"]) - return self.runStep() - - def test_run_failed(self): - self.setupStep(shell.TreeSize()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['du', '-s', '-k', '.']) - + ExpectShell.log('stdio', stderr='abcdef\n') - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["treesize", "unknown"]) - return self.runStep() - -class SetPropertyFromCommand(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_constructor_conflict(self): - self.assertRaises(config.ConfigErrors, lambda : - shell.SetPropertyFromCommand(property='foo', extract_fn=lambda : None)) - - def test_run_property(self): - self.setupStep(shell.SetPropertyFromCommand(property="res", command="cmd")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + ExpectShell.log('stdio', stdout='\n\nabcdef\n') - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["property 'res' set"]) - self.expectProperty("res", "abcdef") # note: stripped - self.expectLogfile('property changes', r"res: 'abcdef'") - return self.runStep() - - def test_run_property_no_strip(self): - self.setupStep(shell.SetPropertyFromCommand(property="res", command="cmd", - strip=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + ExpectShell.log('stdio', stdout='\n\nabcdef\n') - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["property 'res' set"]) - self.expectProperty("res", "\n\nabcdef\n") - self.expectLogfile('property changes', r"res: '\n\nabcdef\n'") - return self.runStep() - - def test_run_failure(self): - self.setupStep(shell.SetPropertyFromCommand(property="res", command="blarg")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="blarg") - + ExpectShell.log('stdio', stderr='cannot blarg: File not found') - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["'blarg'", "failed"]) - self.expectNoProperty("res") - return self.runStep() - - def test_run_extract_fn(self): - def extract_fn(rc, stdout, stderr): - self.assertEqual((rc, stdout, stderr), (0, 'startend', 'STARTEND')) - return dict(a=1, b=2) - self.setupStep(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + ExpectShell.log('stdio', stdout='start', stderr='START') - + ExpectShell.log('stdio', stdout='end') - + ExpectShell.log('stdio', stderr='END') - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["2 properties set"]) - self.expectLogfile('property changes', 'a: 1\nb: 2') - self.expectProperty("a", 1) - self.expectProperty("b", 2) - return self.runStep() - - def test_run_extract_fn_cmdfail(self): - def extract_fn(rc, stdout, stderr): - self.assertEqual((rc, stdout, stderr), (3, '', '')) - return dict(a=1, b=2) - self.setupStep(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + 3 - ) - # note that extract_fn *is* called anyway - self.expectOutcome(result=FAILURE, - status_text=["2 properties set"]) - self.expectLogfile('property changes', 'a: 1\nb: 2') - return self.runStep() - - def test_run_extract_fn_cmdfail_empty(self): - def extract_fn(rc, stdout, stderr): - self.assertEqual((rc, stdout, stderr), (3, '', '')) - return dict() - self.setupStep(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + 3 - ) - # note that extract_fn *is* called anyway, but returns no properties - self.expectOutcome(result=FAILURE, - status_text=["'cmd'", "failed"]) - return self.runStep() - - @compat.usesFlushLoggedErrors - def test_run_extract_fn_exception(self): - def extract_fn(rc, stdout, stderr): - raise RuntimeError("oh noes") - self.setupStep(shell.SetPropertyFromCommand(extract_fn=extract_fn, command="cmd")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="cmd") - + 0 - ) - # note that extract_fn *is* called anyway, but returns no properties - self.expectOutcome(result=EXCEPTION, - status_text=["setproperty", "exception"]) - d = self.runStep() - d.addCallback(lambda _ : - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)) - return d - -class SetPropertyDeprecation(unittest.TestCase): - """ - Tests for L{shell.SetProperty} - """ - - def test_deprecated(self): - """ - Accessing L{shell.SetProperty} reports a deprecation error. - """ - shell.SetProperty - warnings = self.flushWarnings([self.test_deprecated]) - self.assertEqual(len(warnings), 1) - self.assertIdentical(warnings[0]['category'], DeprecationWarning) - self.assertEqual(warnings[0]['message'], - "buildbot.steps.shell.SetProperty was deprecated in Buildbot 0.8.8: " - "It has been renamed to SetPropertyFromCommand" - ) - - -class Configure(unittest.TestCase): - - def test_class_attrs(self): - # nothing too exciting here, but at least make sure the class is present - step = shell.Configure() - self.assertEqual(step.command, ['./configure']) - -class WarningCountingShellCommand(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_no_warnings(self): - self.setupStep(shell.WarningCountingShellCommand(workdir='w', - command=['make'])) - self.expectCommands( - ExpectShell(workdir='w', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', stdout='blarg success!') - + 0 - ) - self.expectOutcome(result=SUCCESS, status_text=["'make'"]) - self.expectProperty("warnings-count", 0) - return self.runStep() - - def test_default_pattern(self): - self.setupStep(shell.WarningCountingShellCommand(command=['make'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', - stdout='normal: foo\nwarning: blarg!\nalso normal') - + 0 - ) - self.expectOutcome(result=WARNINGS, status_text=["'make'", "warnings"]) - self.expectProperty("warnings-count", 1) - self.expectLogfile("warnings (1)", "warning: blarg!\n") - return self.runStep() - - def test_custom_pattern(self): - self.setupStep(shell.WarningCountingShellCommand(command=['make'], - warningPattern=r"scary:.*")) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', - stdout='scary: foo\nwarning: bar\nscary: bar') - + 0 - ) - self.expectOutcome(result=WARNINGS, status_text=["'make'", "warnings"]) - self.expectProperty("warnings-count", 2) - self.expectLogfile("warnings (2)", "scary: foo\nscary: bar\n") - return self.runStep() - - def test_maxWarnCount(self): - self.setupStep(shell.WarningCountingShellCommand(command=['make'], - maxWarnCount=9)) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', stdout='warning: noo!\n' * 10) - + 0 - ) - self.expectOutcome(result=FAILURE, status_text=["'make'", "failed"]) - self.expectProperty("warnings-count", 10) - return self.runStep() - - def test_fail_with_warnings(self): - self.setupStep(shell.WarningCountingShellCommand(command=['make'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', stdout='warning: I might fail') - + 3 - ) - self.expectOutcome(result=FAILURE, status_text=["'make'", "failed"]) - self.expectProperty("warnings-count", 1) - self.expectLogfile("warnings (1)", "warning: I might fail\n") - return self.runStep() - - def do_test_suppressions(self, step, supps_file='', stdout='', - exp_warning_count=0, exp_warning_log='', - exp_exception=False): - self.setupStep(step) - - # Invoke the expected callbacks for the suppression file upload. Note - # that this assumes all of the remote_* are synchronous, but can be - # easily adapted to suit if that changes (using inlineCallbacks) - def upload_behavior(command): - writer = command.args['writer'] - writer.remote_write(supps_file) - writer.remote_close() - - self.expectCommands( - # step will first get the remote suppressions file - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='supps', workdir='wkdir', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(upload_behavior), - - # and then run the command - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=["make"]) - + ExpectShell.log('stdio', stdout=stdout) - + 0 - ) - if exp_exception: - self.expectOutcome(result=EXCEPTION, - status_text=["shell", "exception"]) - else: - if exp_warning_count != 0: - self.expectOutcome(result=WARNINGS, - status_text=["'make'", "warnings"]) - self.expectLogfile("warnings (%d)" % exp_warning_count, - exp_warning_log) - else: - self.expectOutcome(result=SUCCESS, - status_text=["'make'"]) - self.expectProperty("warnings-count", exp_warning_count) - return self.runStep() - - def test_suppressions(self): - step = shell.WarningCountingShellCommand(command=['make'], - suppressionFile='supps') - supps_file = textwrap.dedent("""\ - # example suppressions file - - amar.c : .*unused variable.* - holding.c : .*invalid access to non-static.* - """).strip() - stdout = textwrap.dedent("""\ - /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah - /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah - amar.c: In function 'write_record': - amar.c:164: warning: unused variable 'x' - amar.c:164: warning: this should show up - /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah - /bin/sh ../libtool --tag=CC --silent --mode=link gcc blah - holding.c: In function 'holding_thing': - holding.c:984: warning: invalid access to non-static 'y' - """) - exp_warning_log = textwrap.dedent("""\ - amar.c:164: warning: this should show up - """) - return self.do_test_suppressions(step, supps_file, stdout, 1, - exp_warning_log) - - def test_suppressions_directories(self): - def warningExtractor(step, line, match): - return line.split(':', 2) - step = shell.WarningCountingShellCommand(command=['make'], - suppressionFile='supps', - warningExtractor=warningExtractor) - supps_file = textwrap.dedent("""\ - # these should be suppressed: - amar-src/amar.c : XXX - .*/server-src/.* : AAA - # these should not, as the dirs do not match: - amar.c : YYY - server-src.* : BBB - """).strip() - # note that this uses the unicode smart-quotes that gcc loves so much - stdout = textwrap.dedent(u"""\ - make: Entering directory \u2019amar-src\u2019 - amar.c:164: warning: XXX - amar.c:165: warning: YYY - make: Leaving directory 'amar-src' - make: Entering directory "subdir" - make: Entering directory 'server-src' - make: Entering directory `one-more-dir` - holding.c:999: warning: BBB - holding.c:1000: warning: AAA - """) - exp_warning_log = textwrap.dedent("""\ - amar.c:165: warning: YYY - holding.c:999: warning: BBB - """) - return self.do_test_suppressions(step, supps_file, stdout, 2, - exp_warning_log) - - def test_suppressions_directories_custom(self): - def warningExtractor(step, line, match): - return line.split(':', 2) - step = shell.WarningCountingShellCommand(command=['make'], - suppressionFile='supps', - warningExtractor=warningExtractor, - directoryEnterPattern="^IN: (.*)", - directoryLeavePattern="^OUT:") - supps_file = "dir1/dir2/abc.c : .*" - stdout = textwrap.dedent(u"""\ - IN: dir1 - IN: decoy - OUT: decoy - IN: dir2 - abc.c:123: warning: hello - """) - return self.do_test_suppressions(step, supps_file, stdout, 0, '') - - def test_suppressions_linenos(self): - def warningExtractor(step, line, match): - return line.split(':', 2) - step = shell.WarningCountingShellCommand(command=['make'], - suppressionFile='supps', - warningExtractor=warningExtractor) - supps_file = "abc.c:.*:100-199\ndef.c:.*:22" - stdout = textwrap.dedent(u"""\ - abc.c:99: warning: seen 1 - abc.c:150: warning: unseen - def.c:22: warning: unseen - abc.c:200: warning: seen 2 - """) - exp_warning_log = textwrap.dedent(u"""\ - abc.c:99: warning: seen 1 - abc.c:200: warning: seen 2 - """) - return self.do_test_suppressions(step, supps_file, stdout, 2, - exp_warning_log) - - @compat.usesFlushLoggedErrors - def test_suppressions_warningExtractor_exc(self): - def warningExtractor(step, line, match): - raise RuntimeError("oh noes") - step = shell.WarningCountingShellCommand(command=['make'], - suppressionFile='supps', - warningExtractor=warningExtractor) - supps_file = 'x:y' # need at least one supp to trigger warningExtractor - stdout = "abc.c:99: warning: seen 1" - d = self.do_test_suppressions(step, supps_file, stdout, - exp_exception=True) - d.addCallback(lambda _ : - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)) - return d - - def test_suppressions_addSuppression(self): - # call addSuppression "manually" from a subclass - class MyWCSC(shell.WarningCountingShellCommand): - def start(self): - self.addSuppression([('.*', '.*unseen.*', None, None)]) - return shell.WarningCountingShellCommand.start(self) - - def warningExtractor(step, line, match): - return line.split(':', 2) - step = MyWCSC(command=['make'], suppressionFile='supps', - warningExtractor=warningExtractor) - stdout = textwrap.dedent(u"""\ - abc.c:99: warning: seen 1 - abc.c:150: warning: unseen - abc.c:200: warning: seen 2 - """) - exp_warning_log = textwrap.dedent(u"""\ - abc.c:99: warning: seen 1 - abc.c:200: warning: seen 2 - """) - return self.do_test_suppressions(step, '', stdout, 2, - exp_warning_log) - - def test_warnExtractFromRegexpGroups(self): - step = shell.WarningCountingShellCommand(command=['make']) - we = shell.WarningCountingShellCommand.warnExtractFromRegexpGroups - line, pat, exp_file, exp_lineNo, exp_text = \ - ('foo:123:text', '(.*):(.*):(.*)', 'foo', 123, 'text') - self.assertEqual(we(step, line, re.match(pat, line)), - (exp_file, exp_lineNo, exp_text)) - -class Compile(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_class_args(self): - # since this step is just a pre-configured WarningCountingShellCommand, - # there' not much to test! - step = self.setupStep(shell.Compile()) - self.assertEqual(step.name, "compile") - self.assertTrue(step.haltOnFailure) - self.assertTrue(step.flunkOnFailure) - self.assertEqual(step.description, ["compiling"]) - self.assertEqual(step.descriptionDone, ["compile"]) - self.assertEqual(step.command, ["make", "all"]) - -class Test(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - self.setUpBuildStep() - - def tearDown(self): - self.tearDownBuildStep() - - def test_setTestResults(self): - step = self.setupStep(shell.Test()) - step.setTestResults(total=10, failed=3, passed=5, warnings=3) - self.assertEqual(self.step_statistics, { - 'tests-total' : 10, - 'tests-failed' : 3, - 'tests-passed' : 5, - 'tests-warnings' : 3, - }) - # ensure that they're additive - step.setTestResults(total=1, failed=2, passed=3, warnings=4) - self.assertEqual(self.step_statistics, { - 'tests-total' : 11, - 'tests-failed' : 5, - 'tests-passed' : 8, - 'tests-warnings' : 7, - }) - - def test_describe_not_done(self): - step = self.setupStep(shell.Test()) - self.assertEqual(step.describe(), ['testing']) - - def test_describe_done(self): - step = self.setupStep(shell.Test()) - self.step_statistics['tests-total'] = 93 - self.step_statistics['tests-failed'] = 10 - self.step_statistics['tests-passed'] = 20 - self.step_statistics['tests-warnings'] = 30 - self.assertEqual(step.describe(done=True), [ 'test', '93 tests', - '20 passed', '30 warnings', '10 failed']) - - def test_describe_done_no_total(self): - step = self.setupStep(shell.Test()) - self.step_statistics['tests-total'] = 0 - self.step_statistics['tests-failed'] = 10 - self.step_statistics['tests-passed'] = 20 - self.step_statistics['tests-warnings'] = 30 - # describe calculates 60 = 10+20+30 - self.assertEqual(step.describe(done=True), [ 'test', '60 tests', - '20 passed', '30 warnings', '10 failed']) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_slave.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_slave.py deleted file mode 100644 index 8052dca7..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_slave.py +++ /dev/null @@ -1,381 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import stat -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.steps import slave -from buildbot.status.results import SUCCESS, FAILURE, EXCEPTION -from buildbot.process import properties, buildstep -from buildbot.test.fake.remotecommand import Expect -from buildbot.test.util import steps, compat -from buildbot.interfaces import BuildSlaveTooOldError - -class TestSetPropertiesFromEnv(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_simple(self): - self.setupStep(slave.SetPropertiesFromEnv( - variables=["one", "two", "three", "five", "six"], - source="me")) - self.buildslave.slave_environ = { "one": "1", "two": None, "six": "6", "FIVE" : "555" } - self.properties.setProperty("four", 4, "them") - self.properties.setProperty("five", 5, "them") - self.properties.setProperty("six", 99, "them") - self.expectOutcome(result=SUCCESS, - status_text=["Set"]) - self.expectProperty('one', "1", source='me') - self.expectNoProperty('two') - self.expectNoProperty('three') - self.expectProperty('four', 4, source='them') - self.expectProperty('five', 5, source='them') - self.expectProperty('six', '6', source='me') - self.expectLogfile("properties", - "one = '1'\nsix = '6'") - return self.runStep() - - def test_case_folding(self): - self.setupStep(slave.SetPropertiesFromEnv( - variables=["eNv"], source="me")) - self.buildslave.slave_environ = { "ENV": 'EE' } - self.buildslave.slave_system = 'win32' - self.expectOutcome(result=SUCCESS, - status_text=["Set"]) - self.expectProperty('eNv', 'EE', source='me') - self.expectLogfile("properties", - "eNv = 'EE'") - return self.runStep() - - -class TestFileExists(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_found(self): - self.setupStep(slave.FileExists(file="x")) - self.expectCommands( - Expect('stat', { 'file' : 'x' }) - + Expect.update('stat', [stat.S_IFREG, 99, 99]) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["File found."]) - return self.runStep() - - def test_not_found(self): - self.setupStep(slave.FileExists(file="x")) - self.expectCommands( - Expect('stat', { 'file' : 'x' }) - + Expect.update('stat', [0, 99, 99]) - + 0 - ) - self.expectOutcome(result=FAILURE, - status_text=["Not a file."]) - return self.runStep() - - def test_failure(self): - self.setupStep(slave.FileExists(file="x")) - self.expectCommands( - Expect('stat', { 'file' : 'x' }) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["File not found."]) - return self.runStep() - - def test_render(self): - self.setupStep(slave.FileExists(file=properties.Property("x"))) - self.properties.setProperty('x', 'XXX', 'here') - self.expectCommands( - Expect('stat', { 'file' : 'XXX' }) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["File not found."]) - return self.runStep() - - @compat.usesFlushLoggedErrors - def test_old_version(self): - self.setupStep(slave.FileExists(file="x"), - slave_version=dict()) - self.expectOutcome(result=EXCEPTION, - status_text=["FileExists", "exception"]) - d = self.runStep() - def check(_): - self.assertEqual( - len(self.flushLoggedErrors(BuildSlaveTooOldError)), 1) - d.addCallback(check) - return d - - -class TestCopyDirectory(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(slave.CopyDirectory(src="s", dest="d")) - self.expectCommands( - Expect('cpdir', { 'fromdir' : 's', 'todir' : 'd' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Copied", "s", "to", "d"]) - return self.runStep() - - def test_timeout(self): - self.setupStep(slave.CopyDirectory(src="s", dest="d", timeout=300)) - self.expectCommands( - Expect('cpdir', { 'fromdir' : 's', 'todir' : 'd', 'timeout': 300 }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Copied", "s", "to", "d"]) - return self.runStep() - - def test_maxTime(self): - self.setupStep(slave.CopyDirectory(src="s", dest="d", maxTime=10)) - self.expectCommands( - Expect('cpdir', { 'fromdir' : 's', 'todir' : 'd', 'maxTime': 10 }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Copied", "s", "to", "d"]) - return self.runStep() - - def test_failure(self): - self.setupStep(slave.CopyDirectory(src="s", dest="d")) - self.expectCommands( - Expect('cpdir', { 'fromdir' : 's', 'todir' : 'd' }) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["Copying", "s", "to", "d", "failed."]) - return self.runStep() - - def test_render(self): - self.setupStep(slave.CopyDirectory(src=properties.Property("x"), dest=properties.Property("y"))) - self.properties.setProperty('x', 'XXX', 'here') - self.properties.setProperty('y', 'YYY', 'here') - self.expectCommands( - Expect('cpdir', { 'fromdir' : 'XXX', 'todir' : 'YYY' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Copied", "XXX", "to", "YYY"]) - return self.runStep() - -class TestRemoveDirectory(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(slave.RemoveDirectory(dir="d")) - self.expectCommands( - Expect('rmdir', { 'dir' : 'd' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Deleted"]) - return self.runStep() - - def test_failure(self): - self.setupStep(slave.RemoveDirectory(dir="d")) - self.expectCommands( - Expect('rmdir', { 'dir' : 'd' }) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["Delete failed."]) - return self.runStep() - - def test_render(self): - self.setupStep(slave.RemoveDirectory(dir=properties.Property("x"))) - self.properties.setProperty('x', 'XXX', 'here') - self.expectCommands( - Expect('rmdir', { 'dir' : 'XXX' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Deleted"]) - return self.runStep() - -class TestMakeDirectory(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_success(self): - self.setupStep(slave.MakeDirectory(dir="d")) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Created"]) - return self.runStep() - - def test_failure(self): - self.setupStep(slave.MakeDirectory(dir="d")) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' }) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["Create failed."]) - return self.runStep() - - def test_render(self): - self.setupStep(slave.MakeDirectory(dir=properties.Property("x"))) - self.properties.setProperty('x', 'XXX', 'here') - self.expectCommands( - Expect('mkdir', { 'dir' : 'XXX' }) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["Created"]) - return self.runStep() - -class CompositeUser(buildstep.LoggingBuildStep, slave.CompositeStepMixin): - def __init__(self, payload): - self.payload = payload - self.logEnviron=False - buildstep.LoggingBuildStep.__init__(self) - def start(self): - self.addLogForRemoteCommands('stdio') - d = self.payload(self) - d.addCallback(self.commandComplete) - d.addErrback(self.failed) - def commandComplete(self,res): - self.finished(FAILURE if res else SUCCESS) - -class TestCompositeStepMixin(steps.BuildStepMixin, unittest.TestCase): - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_runRemoteCommand(self): - cmd_args = ('foo', {'bar': False}) - def testFunc(x): - x.runRemoteCommand(*cmd_args) - self.setupStep(CompositeUser(testFunc)) - self.expectCommands(Expect(*cmd_args)+0) - self.expectOutcome(result=SUCCESS, - status_text=["generic"]) - - def test_runRemoteCommandFail(self): - cmd_args = ('foo', {'bar': False}) - @defer.inlineCallbacks - def testFunc(x): - yield x.runRemoteCommand(*cmd_args) - self.setupStep(CompositeUser(testFunc)) - self.expectCommands(Expect(*cmd_args)+1) - self.expectOutcome(result=FAILURE, - status_text=["generic"]) - return self.runStep() - - def test_runRemoteCommandFailNoAbandon(self): - cmd_args = ('foo', {'bar': False}) - @defer.inlineCallbacks - def testFunc(x): - res = yield x.runRemoteCommand(*cmd_args, - **dict(abandonOnFailure=False)) - x.step_status.setText([str(res)]) - self.setupStep(CompositeUser(testFunc)) - self.expectCommands(Expect(*cmd_args)+1) - self.expectOutcome(result=SUCCESS, - status_text=["True"]) - return self.runStep() - - def test_mkdir(self): - self.setupStep(CompositeUser(lambda x:x.runMkdir("d"))) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' , 'logEnviron': False}) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["generic"]) - return self.runStep() - - def test_rmdir(self): - self.setupStep(CompositeUser(lambda x:x.runRmdir("d"))) - self.expectCommands( - Expect('rmdir', { 'dir' : 'd' , 'logEnviron': False}) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["generic"]) - return self.runStep() - - def test_mkdir_fail(self): - self.setupStep(CompositeUser(lambda x:x.runMkdir("d"))) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' , 'logEnviron': False}) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["generic"]) - return self.runStep() - - def test_abandonOnFailure(self): - @defer.inlineCallbacks - def testFunc(x): - yield x.runMkdir("d") - yield x.runMkdir("d") - self.setupStep(CompositeUser(testFunc)) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' , 'logEnviron': False}) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["generic"]) - return self.runStep() - - def test_notAbandonOnFailure(self): - @defer.inlineCallbacks - def testFunc(x): - yield x.runMkdir("d", abandonOnFailure=False) - yield x.runMkdir("d", abandonOnFailure=False) - self.setupStep(CompositeUser(testFunc)) - self.expectCommands( - Expect('mkdir', { 'dir' : 'd' , 'logEnviron': False}) - + 1, - Expect('mkdir', { 'dir' : 'd' , 'logEnviron': False}) - + 1 - ) - self.expectOutcome(result=SUCCESS, - status_text=["generic"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_base_Source.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_base_Source.py deleted file mode 100644 index 3260e479..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_base_Source.py +++ /dev/null @@ -1,137 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest - -from buildbot.steps.source import Source -from buildbot.test.util import steps, sourcesteps - -class TestSource(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_start_alwaysUseLatest_True(self): - step = self.setupStep(Source(alwaysUseLatest=True), - { - 'branch': 'other-branch', - 'revision': 'revision', - }, - patch = 'patch' - ) - step.branch = 'branch' - step.startVC = mock.Mock() - - step.startStep(mock.Mock()) - - self.assertEqual(step.startVC.call_args, (('branch', None, None), {})) - - def test_start_alwaysUseLatest_False(self): - step = self.setupStep(Source(), - { - 'branch': 'other-branch', - 'revision': 'revision', - }, - patch = 'patch' - ) - step.branch = 'branch' - step.startVC = mock.Mock() - - step.startStep(mock.Mock()) - - self.assertEqual(step.startVC.call_args, (('other-branch', 'revision', 'patch'), {})) - - def test_start_alwaysUseLatest_False_no_branch(self): - step = self.setupStep(Source()) - step.branch = 'branch' - step.startVC = mock.Mock() - - step.startStep(mock.Mock()) - - self.assertEqual(step.startVC.call_args, (('branch', None, None), {})) - - def test_start_no_codebase(self): - step = self.setupStep(Source()) - step.branch = 'branch' - step.startVC = mock.Mock() - step.build.getSourceStamp = mock.Mock() - step.build.getSourceStamp.return_value = None - - self.assertEqual(step.describe(), ['updating']) - self.assertEqual(step.name, Source.name) - - step.startStep(mock.Mock()) - self.assertEqual(step.build.getSourceStamp.call_args[0], ('',)) - - self.assertEqual(step.description, ['updating']) - - def test_start_with_codebase(self): - step = self.setupStep(Source(codebase='codebase')) - step.branch = 'branch' - step.startVC = mock.Mock() - step.build.getSourceStamp = mock.Mock() - step.build.getSourceStamp.return_value = None - - self.assertEqual(step.describe(), ['updating', 'codebase']) - self.assertEqual(step.name, Source.name + " codebase") - - step.startStep(mock.Mock()) - self.assertEqual(step.build.getSourceStamp.call_args[0], ('codebase',)) - - self.assertEqual(step.describe(True), ['update', 'codebase']) - - def test_start_with_codebase_and_descriptionSuffix(self): - step = self.setupStep(Source(codebase='my-code', - descriptionSuffix='suffix')) - step.branch = 'branch' - step.startVC = mock.Mock() - step.build.getSourceStamp = mock.Mock() - step.build.getSourceStamp.return_value = None - - self.assertEqual(step.describe(), ['updating', 'suffix']) - self.assertEqual(step.name, Source.name + " my-code") - - step.startStep(mock.Mock()) - self.assertEqual(step.build.getSourceStamp.call_args[0], ('my-code',)) - - self.assertEqual(step.describe(True), ['update', 'suffix']) - - -class TestSourceDescription(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_constructor_args_strings(self): - step = Source(workdir='build', - description='svn update (running)', - descriptionDone='svn update') - self.assertEqual(step.description, ['svn update (running)']) - self.assertEqual(step.descriptionDone, ['svn update']) - - def test_constructor_args_lists(self): - step = Source(workdir='build', - description=['svn', 'update', '(running)'], - descriptionDone=['svn', 'update']) - self.assertEqual(step.description, ['svn', 'update', '(running)']) - self.assertEqual(step.descriptionDone, ['svn', 'update']) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_bzr.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_bzr.py deleted file mode 100644 index e1e84dbb..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_bzr.py +++ /dev/null @@ -1,482 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.python.reflect import namedModule -from buildbot.steps.source import bzr -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import sourcesteps -from buildbot.test.fake.remotecommand import ExpectShell, Expect -import os.path - -class TestBzr(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def test_mode_full(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='fresh')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_win32path(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='fresh')) - self.build.path_module = namedModule('ntpath') - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file=r'wkdir\.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_timeout(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='fresh', timeout=1)) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['bzr', 'clean-tree', '--force']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_revision(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='fresh'), - args=dict(revision='3730')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update', '-r', '3730']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_clean(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--ignored', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_clean_revision(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='clean'), - args=dict(revision='2345')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--ignored', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update', '-r', '2345']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_fresh(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='fresh')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'clean-tree', '--force']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_full_clobber(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='clobber')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - 'http://bzr.squid-cache.org/bzr/squid3/trunk', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - - def test_mode_full_clobber_revision(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='clobber'), - args=dict(revision='3730')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - 'http://bzr.squid-cache.org/bzr/squid3/trunk', - '.', '-r', '3730']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - - def test_mode_full_clobber_baseurl(self): - self.setupStep( - bzr.Bzr(baseURL='http://bzr.squid-cache.org/bzr/squid3', - defaultBranch='trunk', mode='full', method='clobber')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - os.path.join('http://bzr.squid-cache.org/bzr/squid3', 'trunk'), '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - - def test_mode_full_clobber_baseurl_nodefault(self): - self.setupStep( - bzr.Bzr(baseURL='http://bzr.squid-cache.org/bzr/squid3', - defaultBranch='trunk', mode='full', method='clobber'), - args=dict(branch='branches/SQUID_3_0')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - os.path.join('http://bzr.squid-cache.org/bzr/squid3', 'branches/SQUID_3_0'), '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - - def test_mode_full_copy(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='full', method='copy')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('rmdir', dict(dir='build', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['bzr', 'update']) - + 0, - Expect('cpdir', {'fromdir': 'source', - 'logEnviron': True, - 'todir': 'build'}) - + 0, - ExpectShell(workdir='source', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_incremental(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_incremental_revision(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='incremental'), - args=dict(revision='9384')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'update', '-r', '9384']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'Bzr') - return self.runStep() - - def test_mode_incremental_no_existing_repo(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - 'http://bzr.squid-cache.org/bzr/squid3/trunk', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='100\n') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100\n', 'Bzr') - return self.runStep() - - def test_bad_revparse(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - 'http://bzr.squid-cache.org/bzr/squid3/trunk', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['bzr', 'version-info', '--custom', "--template='{revno}"]) - + ExpectShell.log('stdio', - stdout='oiasdfj010laksjfd') - + 0, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_bad_checkout(self): - self.setupStep( - bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['bzr', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.bzr', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['bzr', 'checkout', - 'http://bzr.squid-cache.org/bzr/squid3/trunk', '.']) - + ExpectShell.log('stdio', - stderr='failed\n') - + 128, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_cvs.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_cvs.py deleted file mode 100644 index 7f39cdb5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_cvs.py +++ /dev/null @@ -1,765 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import time -from twisted.trial import unittest -from buildbot.steps import shell -from buildbot.steps.source import cvs -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import sourcesteps -from buildbot.test.fake.remotecommand import ExpectShell, Expect, ExpectRemoteRef - -def uploadString(cvsroot): - def behavior(command): - writer = command.args['writer'] - writer.remote_write(cvsroot + "\n") - writer.remote_close() - return behavior - -class TestCVS(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def setupStep(self, step, *args, **kwargs): - sourcesteps.SourceStepMixin.setupStep(self, step, *args, **kwargs) - - # make parseGotRevision return something consistent, patching the class - # instead of the object since a new object is constructed by runTest. - def parseGotRevision(self, res): - self.updateSourceProperty('got_revision', - '2012-09-09 12:00:39 +0000') - return res - self.patch(cvs.CVS, 'parseGotRevision', parseGotRevision) - - def test_parseGotRevision(self): - def gmtime(): - return time.struct_time((2012, 9, 9, 12, 9, 33, 6, 253, 0)) - self.patch(time, 'gmtime', gmtime) - - step = cvs.CVS(cvsroot="x", cvsmodule="m", mode='full', method='clean') - props = [] - def updateSourceProperty(prop, name): - props.append((prop, name)) - step.updateSourceProperty = updateSourceProperty - - self.assertEqual(step.parseGotRevision(10), 10) # passes res along - self.assertEqual(props, - [('got_revision', '2012-09-09 12:09:33 +0000')]) - - def test_mode_full_clean(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_clean_timeout(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - login=True, timeout=1)) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['cvsdiscard']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_clean_branch(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - branch='branch', login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP', '-r', 'branch']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_clean_branch_sourcestamp(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - login=True), args={'branch':'my_branch'}) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP', '-r', 'my_branch']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_fresh(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='fresh', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard', '--ignore']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_clobber(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clobber', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_copy(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='copy', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='source/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='source/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='source', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - Expect('cpdir', {'fromdir': 'source', 'todir': 'build', - 'logEnviron': True}) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_full_copy_wrong_repo(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='copy', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='source/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('the-end-of-the-universe')) - + 0, - Expect('rmdir', dict(dir='source', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'source', 'mozilla/browser/']) - + 0, - Expect('cpdir', {'fromdir': 'source', 'todir': 'build', - 'logEnviron': True}) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_incremental(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_incremental_password_windows(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:dustin:secrets@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - # on Windows, this file does not contain the password, per - # http://trac.buildbot.net/ticket/2355 - + Expect.behavior(uploadString(':pserver:dustin@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_branch(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - branch='my_branch', login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP', '-r', 'my_branch']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_incremental_special_case(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - branch='HEAD', login=True), - args=dict(revision='2012-08-16 16:05:16 +0000')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP', - # note, no -r HEAD here - that's the special case - '-D', '2012-08-16 16:05:16 +0000']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_branch_sourcestamp(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True), args={'branch':'my_branch'}) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP', '-r', 'my_branch']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_incremental_not_loggedin(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - 'login']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_incremental_no_existing_repo(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_incremental_wrong_repo(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('the-end-of-the-universe')) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_incremental_wrong_module(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('the-end-of-the-universe')) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - - def test_mode_full_clean_no_existing_repo(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + 1, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_clean_wrong_repo(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='clean', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('the-end-of-the-universe')) - + 0, - ExpectShell(workdir='', - command=['cvs', - '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_full_no_method(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard', '--ignore']) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP']) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_incremental_with_options(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True, global_options=['-q'], extra_options=['-l'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='', - command=['cvs', '-q', '-d', - ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot', - '-z3', 'checkout', '-d', 'wkdir', '-l', 'mozilla/browser/']) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_mode_incremental_with_env_logEnviron(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True, env={'abc': '123'}, logEnviron=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version'], - env={'abc': '123'}, - logEnviron=False) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvs', '-z3', 'update', '-dP'], - env={'abc': '123'}, - logEnviron=False) - + 0, - ) - - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '2012-09-09 12:00:39 +0000', 'CVS') - return self.runStep() - - def test_command_fails(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='incremental', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 128, - ) - - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_cvsdiscard_fails(self): - self.setupStep( - cvs.CVS(cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot", - cvsmodule="mozilla/browser/", mode='full', method='fresh', - login=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['cvs', '--version']) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Root', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString(':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot')) - + 0, - Expect('uploadFile', dict(blocksize=32768, maxsize=None, - slavesrc='Repository', workdir='wkdir/CVS', - writer=ExpectRemoteRef(shell.StringFileWriter))) - + Expect.behavior(uploadString('mozilla/browser/')) - + 0, - ExpectShell(workdir='wkdir', - command=['cvsdiscard', '--ignore']) - + ExpectShell.log('stdio', - stderr='FAIL!\n') - + 1, - ) - - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_git.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_git.py deleted file mode 100644 index 4f60813d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_git.py +++ /dev/null @@ -1,1457 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.python.reflect import namedModule -from buildbot.steps.source import git -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import config, sourcesteps -from buildbot.test.fake.remotecommand import ExpectShell, Expect - -class TestGit(sourcesteps.SourceStepMixin, config.ConfigErrorsMixin, unittest.TestCase): - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def test_mode_full_clean(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clean_win32path(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean')) - self.build.path_module = namedModule('ntpath') - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file=r'wkdir\.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clean_timeout(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - timeout=1, - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clean_patch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean'), - patch=(1, 'patch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'apply', '--index', '-p', '1'], - initialStdin='patch') - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clean_patch_fail(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean'), - patch=(1, 'patch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'apply', '--index', '-p', '1'], - initialStdin='patch') - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - self.expectNoProperty('got_revision') - return self.runStep() - - def test_mode_full_clean_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean', branch='test-branch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'branch', '-M', 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clean_parsefail(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + ExpectShell.log('stdio', - stderr="fatal: Could not parse object " - "'b08076bc71c7813038f2cefedff9c5b678d225a8'.\n") - + 128, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - self.expectNoProperty('got_revision') - return self.runStep() - - def test_mode_full_clean_no_existing_repo(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_no_existing_repo_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clean', branch='test-branch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - '--branch', 'test-branch', - 'http://github.com/buildbot/buildbot.git', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clobber(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', progress=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clobber_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', progress=True, branch='test-branch')) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - '--branch', 'test-branch', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', branch='test-branch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'branch', '-M', 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_fresh(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='fresh')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d', '-x']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_given_revision(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental'), dict( - revision='abcdef01', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'cat-file', '-e', 'abcdef01']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'abcdef01', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_fresh_submodule(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='fresh', submodules=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d', '-x']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'submodule', 'update', '--recursive']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'submodule', 'foreach', 'git', 'clean', - '-f', '-d', '-x']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clobber_shallow(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', shallow=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', '--depth', '1', - 'http://github.com/buildbot/buildbot.git', - '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clobber_no_shallow(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber')) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_retryFetch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', retryFetch=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_retryFetch_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', retryFetch=True, branch='test-branch')) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'branch', '-M', 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_clobberOnFailure(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', clobberOnFailure=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_incremental_clobberOnFailure_branch(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', clobberOnFailure=True, branch = 'test-branch')) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'test-branch']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - '--branch', 'test-branch', - 'http://github.com/buildbot/buildbot.git', - '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_copy(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='copy')) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)), - Expect('stat', dict(file='source/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='source', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - Expect('cpdir', {'fromdir': 'source', 'todir': 'build', - 'logEnviron': True, 'timeout': 1200}) - + 0, - ExpectShell(workdir='build', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_copy_shallow(self): - self.assertRaisesConfigError("shallow only possible with mode 'full' and method 'clobber'", lambda : - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='copy', shallow=True)) - - def test_mode_incremental_no_existing_repo(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_clobber_given_revision(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', progress=True), dict( - revision='abcdef01', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'abcdef01', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_revparse_failure(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', progress=True), dict( - revision='abcdef01', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'abcdef01', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ada95a1d') # too short - + 0, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - self.expectNoProperty('got_revision') - return self.runStep() - - def test_mode_full_clobber_submodule(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', submodules=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'submodule', 'update', - '--init', '--recursive']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_repourl(self): - self.assertRaisesConfigError("must provide repourl", lambda : - git.Git(mode="full")) - - def test_mode_full_fresh_revision(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='fresh', progress=True), dict( - revision='abcdef01', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'abcdef01', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_fresh_clobberOnFailure(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='fresh', clobberOnFailure=True)) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', '.']) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_no_method(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d', '-x']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_with_env(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', env={'abc': '123'})) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version'], - env={'abc': '123'}) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d', '-x'], - env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD'], - env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--'], - env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD'], - env={'abc': '123'}) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_mode_full_logEnviron(self): - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', logEnviron=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['git', '--version'], - logEnviron=False) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=False)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clean', '-f', '-d', '-x'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD'], - logEnviron=False) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - return self.runStep() - - def test_getDescription(self): - # clone of: test_mode_incremental - # only difference is to set the getDescription property - - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', - getDescription=True)) - self.expectCommands( - ## copied from test_mode_incremental: - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ## plus this to test describe: - ExpectShell(workdir='wkdir', - command=['git', 'describe', 'HEAD']) - + ExpectShell.log('stdio', - stdout='Tag-1234') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - self.expectProperty('commit-description', 'Tag-1234', 'Git') - return self.runStep() - - def test_getDescription_failed(self): - # clone of: test_mode_incremental - # only difference is to set the getDescription property - - # this tests when 'git describe' fails; for example, there are no - # tags in the repository - - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='incremental', - getDescription=True)) - self.expectCommands( - ## copied from test_mode_incremental: - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'fetch', '-t', - 'http://github.com/buildbot/buildbot.git', - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'reset', '--hard', 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ## plus this to test describe: - ExpectShell(workdir='wkdir', - command=['git', 'describe', 'HEAD']) - + ExpectShell.log('stdio', - stdout='') - + 128, # error, but it's suppressed - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - self.expectNoProperty('commit-description') - return self.runStep() - - def setup_getDescription_test(self, setup_args, output_args, codebase=None): - # clone of: test_mode_full_clobber - # only difference is to set the getDescription property - - kwargs = {} - if codebase is not None: - kwargs.update(codebase=codebase) - - self.setupStep( - git.Git(repourl='http://github.com/buildbot/buildbot.git', - mode='full', method='clobber', progress=True, - getDescription=setup_args, - **kwargs)) - - self.expectCommands( - ## copied from test_mode_full_clobber: - ExpectShell(workdir='wkdir', - command=['git', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True, - timeout=1200)) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'clone', - 'http://github.com/buildbot/buildbot.git', - '.', '--progress']) - + 0, - ExpectShell(workdir='wkdir', - command=['git', 'rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - - ## plus this to test describe: - ExpectShell(workdir='wkdir', - command=['git', 'describe'] + - output_args + - ['HEAD']) - + ExpectShell.log('stdio', - stdout='Tag-1234') - + 0, - ) - - if codebase: - self.expectOutcome(result=SUCCESS, status_text=["update", codebase]) - self.expectProperty('got_revision', {codebase:'f6ad368298bd941e934a41f3babc827b2aa95a1d'}, 'Git') - self.expectProperty('commit-description', {codebase:'Tag-1234'}, 'Git') - else: - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'f6ad368298bd941e934a41f3babc827b2aa95a1d', 'Git') - self.expectProperty('commit-description', 'Tag-1234', 'Git') - - def test_getDescription_empty_dict(self): - self.setup_getDescription_test( - setup_args = {}, - output_args = [] - ) - return self.runStep() - - def test_getDescription_empty_dict_with_codebase(self): - self.setup_getDescription_test( - setup_args = {}, - output_args = [], - codebase = 'baz' - ) - return self.runStep() - - def test_getDescription_match(self): - self.setup_getDescription_test( - setup_args = { 'match': 'stuff-*' }, - output_args = ['--match', 'stuff-*'] - ) - return self.runStep() - def test_getDescription_match_false(self): - self.setup_getDescription_test( - setup_args = { 'match': None }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_tags(self): - self.setup_getDescription_test( - setup_args = { 'tags': True }, - output_args = ['--tags'] - ) - return self.runStep() - def test_getDescription_tags_false(self): - self.setup_getDescription_test( - setup_args = { 'tags': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_all(self): - self.setup_getDescription_test( - setup_args = { 'all': True }, - output_args = ['--all'] - ) - return self.runStep() - def test_getDescription_all_false(self): - self.setup_getDescription_test( - setup_args = { 'all': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_abbrev(self): - self.setup_getDescription_test( - setup_args = { 'abbrev': 7 }, - output_args = ['--abbrev=7'] - ) - return self.runStep() - def test_getDescription_abbrev_zero(self): - self.setup_getDescription_test( - setup_args = { 'abbrev': 0 }, - output_args = ['--abbrev=0'] - ) - return self.runStep() - def test_getDescription_abbrev_false(self): - self.setup_getDescription_test( - setup_args = { 'abbrev': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_dirty(self): - self.setup_getDescription_test( - setup_args = { 'dirty': True }, - output_args = ['--dirty'] - ) - return self.runStep() - def test_getDescription_dirty_empty_str(self): - self.setup_getDescription_test( - setup_args = { 'dirty': '' }, - output_args = ['--dirty'] - ) - return self.runStep() - def test_getDescription_dirty_str(self): - self.setup_getDescription_test( - setup_args = { 'dirty': 'foo' }, - output_args = ['--dirty=foo'] - ) - return self.runStep() - def test_getDescription_dirty_false(self): - self.setup_getDescription_test( - setup_args = { 'dirty': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_contains(self): - self.setup_getDescription_test( - setup_args = { 'contains': True }, - output_args = ['--contains'] - ) - return self.runStep() - def test_getDescription_contains_false(self): - self.setup_getDescription_test( - setup_args = { 'contains': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_candidates(self): - self.setup_getDescription_test( - setup_args = { 'candidates': 7 }, - output_args = ['--candidates=7'] - ) - return self.runStep() - def test_getDescription_candidates_zero(self): - self.setup_getDescription_test( - setup_args = { 'candidates': 0 }, - output_args = ['--candidates=0'] - ) - return self.runStep() - def test_getDescription_candidates_false(self): - self.setup_getDescription_test( - setup_args = { 'candidates': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_exact_match(self): - self.setup_getDescription_test( - setup_args = { 'exact-match': True }, - output_args = ['--exact-match'] - ) - return self.runStep() - def test_getDescription_exact_match_false(self): - self.setup_getDescription_test( - setup_args = { 'exact-match': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_debug(self): - self.setup_getDescription_test( - setup_args = { 'debug': True }, - output_args = ['--debug'] - ) - return self.runStep() - def test_getDescription_debug_false(self): - self.setup_getDescription_test( - setup_args = { 'debug': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_long(self): - self.setup_getDescription_test( - setup_args = { 'long': True }, - output_args = ['--long'] - ) - def test_getDescription_long_false(self): - self.setup_getDescription_test( - setup_args = { 'long': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_always(self): - self.setup_getDescription_test( - setup_args = { 'always': True }, - output_args = ['--always'] - ) - def test_getDescription_always_false(self): - self.setup_getDescription_test( - setup_args = { 'always': False }, - output_args = [] - ) - return self.runStep() - - def test_getDescription_lotsa_stuff(self): - self.setup_getDescription_test( - setup_args = { 'match': 'stuff-*', - 'abbrev': 6, - 'exact-match': True}, - output_args = ['--exact-match', - '--match', 'stuff-*', - '--abbrev=6'], - codebase='baz' - ) - return self.runStep() - - def test_config_option(self): - name = 'url.http://github.com.insteadOf' - value = 'blahblah' - self.setupStep( - git.Git(repourl='%s/buildbot/buildbot.git' % (value,), - mode='full', method='clean', - config={name: value})) - prefix = ['git', '-c', '%s=%s' % (name, value)] - self.expectCommands( - ExpectShell(workdir='wkdir', - command=prefix + ['--version']) - + 0, - Expect('stat', dict(file='wkdir/.git', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=prefix + ['clean', '-f', '-d']) - + 0, - ExpectShell(workdir='wkdir', - command=prefix + ['fetch', '-t', - '%s/buildbot/buildbot.git' % (value,), - 'HEAD']) - + 0, - ExpectShell(workdir='wkdir', - command=prefix + ['reset', '--hard', - 'FETCH_HEAD', '--']) - + 0, - ExpectShell(workdir='wkdir', - command=prefix + ['rev-parse', 'HEAD']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_mercurial.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_mercurial.py deleted file mode 100644 index e8543d97..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_mercurial.py +++ /dev/null @@ -1,863 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.python.reflect import namedModule -from buildbot.steps.source import mercurial -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import sourcesteps -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot import config - -class TestMercurial(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def patch_slaveVersionIsOlderThan(self, result): - self.patch(mercurial.Mercurial, 'slaveVersionIsOlderThan', lambda x, y, z: result) - - def test_no_repourl(self): - self.assertRaises(config.ConfigErrors, lambda : - mercurial.Mercurial(mode="full")) - - def test_incorrect_mode(self): - self.assertRaises(config.ConfigErrors, lambda : - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='invalid')) - - def test_incorrect_method(self): - self.assertRaises(config.ConfigErrors, lambda : - mercurial.Mercurial(repourl='http://hg.mozilla.org', - method='invalid')) - - def test_incorrect_branchType(self): - self.assertRaises(config.ConfigErrors, lambda : - mercurial.Mercurial(repourl='http://hg.mozilla.org', - branchType='invalid')) - - def test_mode_full_clean(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_win32path(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo')) - self.build.path_module = namedModule('ntpath') - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file=r'wkdir\.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_timeout(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - timeout=1, - mode='full', method='clean', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_patch(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo'), - patch=(1, 'patch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'import', - '--no-commit', '-p', '1', '-'], - initialStdin='patch') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_patch_fail(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo'), - patch=(1, 'patch')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'import', - '--no-commit', '-p', '1', '-'], - initialStdin='patch') - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_mode_full_clean_no_existing_repo(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', - 'http://hg.mozilla.org', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clobber(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clobber', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', '--noupdate', - 'http://hg.mozilla.org', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_fresh(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='fresh', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge', '--all']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_fresh_no_existing_repo(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='fresh', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', - 'http://hg.mozilla.org', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_no_existing_repo_dirname(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='dirname'), - ) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 1, # does not exist - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', - 'http://hg.mozilla.org', '.', '--noupdate']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - - def test_mode_incremental_branch_change_dirname(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org/', - mode='incremental', branchType='dirname', defaultBranch='devel'), - dict(branch='stable') - ) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org/stable']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', '--noupdate', - 'http://hg.mozilla.org/stable', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_no_existing_repo_inrepo(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 1, # does not exist - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', - 'http://hg.mozilla.org', '.', '--noupdate']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_existing_repo(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, # directory exists - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_existing_repo_added_files(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, # directory exists - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + ExpectShell.log('stdio', stdout='foo\nbar/baz\n') - + 1, - Expect('rmdir', dict(dir=['wkdir/foo','wkdir/bar/baz'], - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_existing_repo_added_files_old_rmdir(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo')) - self.patch_slaveVersionIsOlderThan(True) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, # directory exists - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + ExpectShell.log('stdio', stdout='foo\nbar/baz\n') - + 1, - Expect('rmdir', dict(dir='wkdir/foo', - logEnviron=True)) - + 0, - Expect('rmdir', dict(dir='wkdir/bar/baz', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'default']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_given_revision(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo'), dict( - revision='abcdef01', - )) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'abcdef01']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_branch_change(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo'), dict( - branch='stable', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'clone', '--noupdate', - 'http://hg.mozilla.org', '.']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'stable']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_branch_change_no_clobberOnBranchChange(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='incremental', branchType='inrepo', - clobberOnBranchChange=False), dict( - branch='stable', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch']) - + ExpectShell.log('stdio', stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()']) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'stable']) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n']) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_env(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', branchType='inrepo', - env={'abc': '123'})) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version'], env={'abc': '123'}) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge'], env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org'], env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch'], - env={'abc': '123'}) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()'], - env={'abc': '123'}) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', '--clean', - '--rev', 'default'], env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n'], env={'abc': '123'}) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_full_clean_logEnviron(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='clean', - branchType='inrepo', - logEnviron=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version'], - logEnviron=False) - + 0, - Expect('stat', dict(file='wkdir/.hg', - logEnviron=False)) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--config', - 'extensions.purge=', 'purge'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'pull', - 'http://hg.mozilla.org'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'identify', '--branch'], - logEnviron=False) - + ExpectShell.log('stdio', - stdout='default') - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'locate', 'set:added()'], - logEnviron=False) - + 1, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'update', - '--clean', '--rev', 'default'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', 'parents', - '--template', '{node}\\n'], - logEnviron=False) - + ExpectShell.log('stdio', stdout='\n') - + ExpectShell.log('stdio', - stdout='f6ad368298bd941e934a41f3babc827b2aa95a1d') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_command_fails(self): - self.setupStep( - mercurial.Mercurial(repourl='http://hg.mozilla.org', - mode='full', method='fresh', branchType='inrepo')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['hg', '--verbose', '--version']) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource.py deleted file mode 100644 index 300ae091..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource.py +++ /dev/null @@ -1,74 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -from twisted.trial import unittest - -from buildbot.steps.source import oldsource - -class SlaveSource(unittest.TestCase): - - def doCommandCompleteTest(self, - cmdHasGotRevision=True, - cmdGotRevision='rev', - initialPropertyValue=None, - expectedPropertyValue=None, - expectSetProperty=True): - - # set up a step with getProperty and setProperty - step = oldsource.SlaveSource(codebase='foo') - def getProperty(prop, default=None): - self.assert_(prop == 'got_revision') - if initialPropertyValue is None: - return default - return initialPropertyValue - step.getProperty = getProperty - - def setProperty(prop, value, source): - raise RuntimeError("should not be calling setProperty directly") - step.setProperty = setProperty - - def updateSourceProperty(prop, value): - self.failUnlessEqual((prop, value), - ('got_revision', expectedPropertyValue)) - self.propSet = True - step.updateSourceProperty = updateSourceProperty - - # fake RemoteCommand, optionally with a got_revision update - cmd = mock.Mock() - cmd.updates = dict() - if cmdHasGotRevision: - cmd.updates['got_revision'] = [ cmdGotRevision ] - - # run the method and ensure it set something; the set asserts the - # value is correct - self.propSet = False - step.commandComplete(cmd) - self.assertEqual(self.propSet, expectSetProperty) - - def test_commandComplete_got_revision(self): - self.doCommandCompleteTest( - expectedPropertyValue='rev') - - def test_commandComplete_no_got_revision(self): - self.doCommandCompleteTest( - cmdHasGotRevision=False, - expectSetProperty=False) - - def test_commandComplete_None_got_revision(self): - self.doCommandCompleteTest( - cmdGotRevision=None, - expectSetProperty=False) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_ComputeRepositoryURL.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_ComputeRepositoryURL.py deleted file mode 100644 index 65c8739d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_ComputeRepositoryURL.py +++ /dev/null @@ -1,106 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest - -from twisted.internet import defer - -from buildbot.interfaces import IRenderable -from buildbot.process.properties import Properties, WithProperties -from buildbot.steps.source.oldsource import _ComputeRepositoryURL - - -class SourceStamp(object): - repository = "test" - -class Build(object): - s = SourceStamp() - props = Properties(foo = "bar") - def getSourceStamp(self, codebase): - assert codebase == '' - return self.s - def getProperties(self): - return self.props - def render(self, value): - self.props.build = self - return defer.maybeDeferred(IRenderable(value).getRenderingFor, self.props) - -class FakeStep(object): - codebase = '' - -class RepoURL(unittest.TestCase): - def setUp(self): - self.build = Build() - - def test_backward_compatibility(self): - url = _ComputeRepositoryURL(FakeStep(), "repourl") - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "repourl") - return d - - def test_format_string(self): - url = _ComputeRepositoryURL(FakeStep(), "http://server/%s") - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "http://server/test") - return d - - def test_dict(self): - dict = {} - dict['test'] = "ssh://server/testrepository" - url = _ComputeRepositoryURL(FakeStep(), dict) - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "ssh://server/testrepository") - return d - - def test_callable(self): - func = lambda x: x[::-1] - url = _ComputeRepositoryURL(FakeStep(), func) - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "tset") - return d - - def test_backward_compatibility_render(self): - url = _ComputeRepositoryURL(FakeStep(), WithProperties("repourl%(foo)s")) - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "repourlbar") - return d - - def test_dict_render(self): - d = dict(test=WithProperties("repourl%(foo)s")) - url = _ComputeRepositoryURL(FakeStep(), d) - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "repourlbar") - return d - - def test_callable_render(self): - func = lambda x: WithProperties(x+"%(foo)s") - url = _ComputeRepositoryURL(FakeStep(), func) - d = self.build.render(url) - @d.addCallback - def callback(res): - self.assertEquals(res, "testbar") - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_Repo.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_Repo.py deleted file mode 100644 index bb8c8a26..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_oldsource_Repo.py +++ /dev/null @@ -1,31 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest - -from buildbot.steps.source import Repo - -class RepoURL(unittest.TestCase): - - def test_parse1(self): - r = Repo() - self.assertEqual(r.parseDownloadProperty("repo download test/bla 564/12"),["test/bla 564/12"]) - def test_parse2(self): - r = Repo() - self.assertEqual(r.parseDownloadProperty("repo download test/bla 564/12 repo download test/bla 564/2"),["test/bla 564/12","test/bla 564/2"]) - def test_parse3(self): - r = Repo() - self.assertEqual(r.parseDownloadProperty("repo download test/bla 564/12 repo download test/bla 564/2 test/foo 5/1"),["test/bla 564/12","test/bla 564/2","test/foo 5/1"]) - self.assertEqual(r.parseDownloadProperty("repo download test/bla 564/12"),["test/bla 564/12"]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_p4.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_p4.py deleted file mode 100644 index b822f01f..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_p4.py +++ /dev/null @@ -1,423 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members -# Portions Copyright 2013 Bad Dog Consulting - - -from twisted.trial import unittest -from buildbot.steps.source.p4 import P4 -from buildbot.status.results import SUCCESS -from buildbot.test.util import sourcesteps -from buildbot.test.util.properties import ConstantRenderable -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot import config -import textwrap - - -class TestP4(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def setupStep(self, step, args={}, patch=None, **kwargs): - step = sourcesteps.SourceStepMixin.setupStep(self, step, args={}, patch=None, **kwargs) - self.build.getSourceStamp().revision = args.get('revision', None) - - # builddir propety used to create absolute path required in perforce client spec. - self.properties.setProperty('builddir', '/home/user/workspace', 'P4') - - def test_no_empty_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: P4()) - - def test_no_multiple_type_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4viewspec=('//depot/trunk', ''), - p4base='//depot', p4branch='trunk', - p4extra_views=['src', 'doc'])) - - def test_no_p4viewspec_is_string_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4viewspec='a_bad_idea')) - - def test_no_p4base_has_trailing_slash_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4base='//depot/')) - - def test_no_p4branch_has_trailing_slash_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4base='//depot', p4branch='blah/')) - - def test_no_p4branch_with_no_p4base_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4branch='blah')) - - def test_no_p4extra_views_with_no_p4base_step_config(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4extra_views='blah')) - - def test_incorrect_mode(self): - self.assertRaises(config.ConfigErrors, lambda: - P4(p4base='//depot', - mode='invalid')) - - def test_mode_incremental_p4base_with_revision(self): - self.setupStep(P4(p4port='localhost:12000', mode='incremental', - p4base='//depot', p4branch='trunk', - p4user='user', p4client='p4_client1', p4passwd='pass'), - dict(revision='100',)) - - client_spec = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client1/... - '''); - - self.expectCommands( - ExpectShell(workdir='wkdir', # defaults to this, only changes if it has a copy mode. - command=['p4', '-V']) # expected remote command - + 0, # expected exit status - - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'client', '-i'], - initialStdin=client_spec) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'sync', '//depot...@100']) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'changes', '-m1', '#have']) - + ExpectShell.log('stdio', - stdout="Change 100 on 2013/03/21 by user@machine \'duh\'") - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'P4') - return self.runStep() - - def _incremental(self, client_stdin=''): - self.expectCommands( - ExpectShell(workdir='wkdir', # defaults to this, only changes if it has a copy mode. - command=['p4', '-V']) # expected remote command - + 0, # expected exit status - - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'client', '-i'], - initialStdin=client_stdin,) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'sync']) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', 'user', - '-P', 'pass', '-c', 'p4_client1', - 'changes', '-m1', '#have']) - + ExpectShell.log('stdio', - stdout="Change 100 on 2013/03/21 by user@machine \'duh\'") - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'P4') - return self.runStep() - - def test_mode_incremental_p4base(self): - self.setupStep(P4(p4port='localhost:12000', mode='incremental', - p4base='//depot', p4branch='trunk', - p4user='user', p4client='p4_client1', p4passwd='pass')) - - client_spec = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client1/... - ''') - self._incremental(client_stdin=client_spec) - - def test_mode_incremental_p4base_with_p4extra_views(self): - self.setupStep(P4(p4port='localhost:12000', mode='incremental', - p4base='//depot', p4branch='trunk', - p4extra_views=[('-//depot/trunk/test', 'test'), - ('-//depot/trunk/doc', 'doc')], - p4user='user', p4client='p4_client1', p4passwd='pass')) - client_spec = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client1/... - \t-//depot/trunk/test/... //p4_client1/test/... - \t-//depot/trunk/doc/... //p4_client1/doc/... - ''') - self._incremental(client_stdin=client_spec) - - def test_mode_incremental_p4viewspec(self): - self.setupStep(P4(p4port='localhost:12000', mode='incremental', - p4viewspec=[('//depot/trunk/', '')], - p4user='user', p4client='p4_client1', p4passwd='pass')) - client_spec = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client1/... - ''') - self._incremental(client_stdin=client_spec) - - def _full(self, client_stdin='', p4client='p4_client1', p4user='user'): - self.expectCommands( - ExpectShell(workdir='wkdir', # defaults to this, only changes if it has a copy mode. - command=['p4', '-V']) # expected remote command - + 0, # expected exit status - - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', p4user, - '-P', 'pass', '-c', p4client, 'client', - '-i'], - initialStdin=client_stdin) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', p4user, - '-P', 'pass', '-c', p4client, 'sync', - '#none']) - + 0, - - Expect('rmdir', {'dir': 'wkdir', 'logEnviron': True}) - + 0, - - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', p4user, - '-P', 'pass', '-c', p4client, 'sync']) - + 0, - ExpectShell(workdir='wkdir', - command=['p4', '-p', 'localhost:12000', '-u', p4user, - '-P', 'pass', '-c', p4client, 'changes', - '-m1', '#have']) - + ExpectShell.log('stdio', - stdout="Change 100 on 2013/03/21 by user@machine \'duh\'") - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'P4') - return self.runStep() - - def test_mode_full_p4base(self): - self.setupStep( - P4(p4port='localhost:12000', - mode='full', p4base='//depot', p4branch='trunk', - p4user='user', p4client='p4_client1', p4passwd='pass')) - - client_stdin = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client1/...\n''') - self._full(client_stdin=client_stdin) - - def test_mode_full_p4viewspec(self): - self.setupStep( - P4(p4port='localhost:12000', - mode='full', p4viewspec=[('//depot/main/', '')], - p4user='user', p4client='p4_client1', p4passwd='pass')) - client_stdin = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/main/... //p4_client1/...\n''') - - self._full(client_stdin=client_stdin) - - def test_mode_full_renderable_p4base(self): - # Note that the config check skips checking p4base if it's a renderable - self.setupStep( - P4(p4port='localhost:12000', - mode='full', p4base=ConstantRenderable('//depot'), - p4branch='release/1.0', p4user='user', p4client='p4_client2', - p4passwd='pass')) - - client_stdin = textwrap.dedent('''\ - Client: p4_client2 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/release/1.0/... //p4_client2/...\n''') - - self._full(client_stdin=client_stdin, p4client='p4_client2') - - def test_mode_full_renderable_p4client(self): - # Note that the config check skips checking p4base if it's a renderable - self.setupStep( - P4(p4port='localhost:12000', - mode='full', p4base='//depot', p4branch='trunk', - p4user='user', p4client=ConstantRenderable('p4_client_render'), - p4passwd='pass')) - - client_stdin = textwrap.dedent('''\ - Client: p4_client_render - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/trunk/... //p4_client_render/...\n''') - - self._full(client_stdin=client_stdin, p4client='p4_client_render') - - def test_mode_full_renderable_p4branch(self): - # Note that the config check skips checking p4base if it's a renderable - self.setupStep( - P4(p4port='localhost:12000', - mode='full', p4base='//depot', - p4branch=ConstantRenderable('render_branch'), - p4user='user', p4client='p4_client1', p4passwd='pass')) - - client_stdin = textwrap.dedent('''\ - Client: p4_client1 - - Owner: user - - Description: - \tCreated by user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/render_branch/... //p4_client1/...\n''') - - self._full(client_stdin=client_stdin) - - def test_mode_full_renderable_p4viewspec(self): - self.setupStep( - P4(p4port='localhost:12000', - mode='full', - p4viewspec=[(ConstantRenderable('//depot/render_trunk/'), '')], - p4user='different_user', p4client='p4_client1', - p4passwd='pass')) - - client_stdin = textwrap.dedent('''\ - Client: p4_client1 - - Owner: different_user - - Description: - \tCreated by different_user - - Root:\t/home/user/workspace/wkdir - - Options:\tallwrite rmdir - - LineEnd:\tlocal - - View: - \t//depot/render_trunk/... //p4_client1/...\n''') - - self._full(client_stdin=client_stdin, p4user='different_user') diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_repo.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_repo.py deleted file mode 100644 index 0baaa0ed..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_repo.py +++ /dev/null @@ -1,613 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.steps.source import repo -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import sourcesteps -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot.process.properties import Properties -from .test_changes_gerritchangesource import TestGerritChangeSource -from buildbot.changes.changes import Change -import os - - -class RepoURL(unittest.TestCase): - # testcases taken from old_source/Repo test - - def oneTest(self, props, expected): - p = Properties() - p.update(props, "test") - r = repo.RepoDownloadsFromProperties(props.keys()) - self.assertEqual(r.getRenderingFor(p), expected) - - def test_parse1(self): - self.oneTest( - {'a': "repo download test/bla 564/12"}, ["test/bla 564/12"]) - - def test_parse2(self): - self.oneTest( - {'a': - "repo download test/bla 564/12 repo download test/bla 564/2"}, - ["test/bla 564/12", "test/bla 564/2"]) - self.oneTest({'a': "repo download test/bla 564/12", 'b': "repo download test/bla 564/2"}, [ - "test/bla 564/12", "test/bla 564/2"]) - - def test_parse3(self): - self.oneTest({'a': "repo download test/bla 564/12 repo download test/bla 564/2 test/foo 5/1"}, [ - "test/bla 564/12", "test/bla 564/2", "test/foo 5/1"]) - self.oneTest( - {'a': "repo download test/bla 564/12"}, ["test/bla 564/12"]) - - -class TestRepo(sourcesteps.SourceStepMixin, unittest.TestCase): - - def setUp(self): - self.shouldRetry = False - self.logEnviron = True - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def shouldLogEnviron(self): - r = self.logEnviron - self.logEnviron = False - return r - - def ExpectShell(self, **kw): - if 'workdir' not in kw: - kw['workdir'] = 'wkdir' - if 'logEnviron' not in kw: - kw['logEnviron'] = self.shouldLogEnviron() - return ExpectShell(**kw) - - def mySetupStep(self, **kwargs): - if "repoDownloads" not in kwargs: - kwargs.update( - dict(repoDownloads=repo.RepoDownloadsFromProperties(["repo_download", "repo_download2"]))) - self.setupStep( - repo.Repo(manifestURL='git://myrepo.com/manifest.git', - manifestBranch="mb", - manifestFile="mf", - **kwargs)) - self.build.allChanges = lambda x=None: [] - - def myRunStep(self, result=SUCCESS, status_text=["update"]): - self.expectOutcome(result=result, status_text=status_text) - d = self.runStep() - - def printlogs(res): - text = self.step.stdio_log.getTextWithHeaders() - if "Failure instance" in text and not self.shouldRetry: - print text - return res - d.addBoth(printlogs) - return d - - def expectClobber(self): - # stat return 1 so we clobber - self.expectCommands( - Expect('stat', dict(file=os.path.join('wkdir', '.repo'), - logEnviron=self.logEnviron)) - + 1, - Expect('rmdir', dict(dir='wkdir', - logEnviron=self.logEnviron)) - + 0, - Expect('mkdir', dict(dir='wkdir', - logEnviron=self.logEnviron)) - + 0, - ) - - def expectnoClobber(self): - # stat return 0, so nothing - self.expectCommands( - Expect('stat', dict(file=os.path.join('wkdir', '.repo'), - logEnviron=self.logEnviron)) - + 0, - ) - - def expectRepoSync(self, which_fail=-1, breakatfail=False, syncoptions=["-c"], override_commands=[]): - commands = [ - self.ExpectShell( - command=[ - 'bash', '-c', self.step._getCleanupCommand()]), - self.ExpectShell( - command=['repo', 'init', '-u', 'git://myrepo.com/manifest.git', - '-b', 'mb', '-m', 'mf']) - ] + override_commands + [ - self.ExpectShell(command=['repo', 'sync'] + syncoptions), - self.ExpectShell( - command=['repo', 'manifest', '-r', '-o', 'manifest-original.xml']) - ] - for i in xrange(len(commands)): - self.expectCommands(commands[i] + (which_fail == i and 1 or 0)) - if which_fail == i and breakatfail: - break - - def test_basic(self): - """basic first time repo sync""" - self.mySetupStep(repoDownloads=None) - self.expectClobber() - self.expectRepoSync() - return self.myRunStep(status_text=["update"]) - - def test_update(self): - """basic second time repo sync""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync() - return self.myRunStep(status_text=["update"]) - - def test_jobs(self): - """basic first time repo sync with jobs""" - self.mySetupStep(jobs=2) - self.expectClobber() - self.expectRepoSync(syncoptions=["-j2", "-c"]) - return self.myRunStep(status_text=["update"]) - - def test_sync_all_branches(self): - """basic first time repo sync with all branches""" - self.mySetupStep(syncAllBranches=True) - self.expectClobber() - self.expectRepoSync(syncoptions=[]) - return self.myRunStep(status_text=["update"]) - - def test_manifest_override(self): - """repo sync with manifest_override_url property set - download via wget - """ - self.mySetupStep(manifestOverrideUrl= - "http://u.rl/test.manifest", - syncAllBranches=True) - self.expectClobber() - override_commands = [ - Expect( - 'stat', dict(file=os.path.join('wkdir', 'http://u.rl/test.manifest'), - logEnviron=False)), - self.ExpectShell(logEnviron=False, command=['wget', - 'http://u.rl/test.manifest', - '-O', 'manifest_override.xml']), - self.ExpectShell( - logEnviron=False, workdir=os.path.join('wkdir', '.repo'), - command=['ln', '-sf', '../manifest_override.xml', - 'manifest.xml']) - ] - self.expectRepoSync(which_fail=2, syncoptions=[], - override_commands=override_commands) - return self.myRunStep(status_text=["update"]) - - def test_manifest_override_local(self): - """repo sync with manifest_override_url property set - copied from local FS - """ - self.mySetupStep(manifestOverrideUrl= - "test.manifest", - syncAllBranches=True) - self.expectClobber() - override_commands = [ - Expect('stat', dict(file=os.path.join('wkdir', 'test.manifest'), - logEnviron=False)), - self.ExpectShell(logEnviron=False, - command=[ - 'cp', '-f', 'test.manifest', 'manifest_override.xml']), - self.ExpectShell(logEnviron=False, - workdir=os.path.join('wkdir', '.repo'), - command=['ln', '-sf', '../manifest_override.xml', - 'manifest.xml']) - ] - self.expectRepoSync( - syncoptions=[], override_commands=override_commands) - return self.myRunStep(status_text=["update"]) - - def test_tarball(self): - """repo sync using the tarball cache - """ - self.mySetupStep(tarball="/tarball.tar") - self.expectClobber() - self.expectCommands( - self.ExpectShell(command=['tar', '-xvf', '/tarball.tar']) + 0) - self.expectRepoSync() - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '/tarball.tar']) - + Expect.log('stdio', stdout=str(10000)) - + 0) - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '.']) - + Expect.log( - 'stdio', stdout=str(10000 + 7 * 24 * 3600)) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_create_tarball(self): - """repo sync create the tarball if its not here - """ - self.mySetupStep(tarball="/tarball.tgz") - self.expectClobber() - self.expectCommands( - self.ExpectShell( - command=['tar', '-z', '-xvf', '/tarball.tgz']) + 1, - self.ExpectShell(command=['rm', '-f', '/tarball.tgz']) + 1, - Expect('rmdir', dict(dir=os.path.join('wkdir', '.repo'), - logEnviron=False)) - + 1) - self.expectRepoSync() - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '/tarball.tgz']) - + Expect.log('stdio', stderr="file not found!") - + 1, - self.ExpectShell(command=['tar', '-z', - '-cvf', '/tarball.tgz', '.repo']) - + 0) - return self.myRunStep(status_text=["update"]) - - def do_test_update_tarball(self, suffix, option): - """repo sync update the tarball cache at the end (tarball older than a week) - """ - self.mySetupStep(tarball="/tarball." + suffix) - self.expectClobber() - self.expectCommands( - self.ExpectShell(command=['tar'] + option + ['-xvf', '/tarball.' + suffix]) + 0) - self.expectRepoSync() - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) - + Expect.log('stdio', stdout=str(10000)) - + 0, - self.ExpectShell(command=['stat', '-c%Y', '.']) - + Expect.log( - 'stdio', stdout=str(10001 + 7 * 24 * 3600)) - + 0, - self.ExpectShell(command=['tar'] + option + - ['-cvf', '/tarball.' + suffix, '.repo']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_update_tarball(self): - self.do_test_update_tarball("tar", []) - - def test_update_tarball_gz(self): - """tarball compression variants""" - self.do_test_update_tarball("tar.gz", ["-z"]) - - def test_update_tarball_tgz(self): - self.do_test_update_tarball("tgz", ["-z"]) - - def test_update_tarball_bzip(self): - self.do_test_update_tarball("tar.bz2", ["-j"]) - - def test_update_tarball_lzma(self): - self.do_test_update_tarball("tar.lzma", ["--lzma"]) - - def test_update_tarball_lzop(self): - self.do_test_update_tarball("tar.lzop", ["--lzop"]) - - def test_update_tarball_fail1(self, suffix="tar", option=[]): - """tarball extract fail -> remove the tarball + remove .repo dir - """ - self.mySetupStep(tarball="/tarball." + suffix) - self.expectClobber() - self.expectCommands( - self.ExpectShell( - command=[ - 'tar'] + option + ['-xvf', '/tarball.' + suffix]) + 1, - self.ExpectShell( - command=['rm', '-f', '/tarball.tar']) + 0, - Expect( - 'rmdir', dict(dir=os.path.join('wkdir', '.repo'), - logEnviron=False)) - + 0) - self.expectRepoSync() - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) - + Expect.log('stdio', stdout=str(10000)) - + 0, - self.ExpectShell(command=['stat', '-c%Y', '.']) - + Expect.log( - 'stdio', stdout=str(10001 + 7 * 24 * 3600)) - + 0, - self.ExpectShell(command=['tar'] + option + - ['-cvf', '/tarball.' + suffix, '.repo']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_update_tarball_fail2(self, suffix="tar", option=[]): - """tarball update fail -> remove the tarball + continue repo download - """ - self.mySetupStep(tarball="/tarball." + suffix) - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectClobber() - self.expectCommands( - self.ExpectShell(command=['tar'] + option + ['-xvf', '/tarball.' + suffix]) + 0) - self.expectRepoSync() - self.expectCommands(self.ExpectShell(command=['stat', '-c%Y', '/tarball.' + suffix]) - + Expect.log('stdio', stdout=str(10000)) - + 0, - self.ExpectShell(command=['stat', '-c%Y', '.']) - + Expect.log( - 'stdio', stdout=str(10001 + 7 * 24 * 3600)) - + 0, - self.ExpectShell(command=['tar'] + option + - ['-cvf', '/tarball.' + suffix, '.repo']) - + 1, - self.ExpectShell( - command=['rm', '-f', '/tarball.tar']) + 0, - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_repo_downloads(self): - """basic repo download, and check that repo_downloaded is updated""" - self.mySetupStep() - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0 - + Expect.log( - 'stdio', stderr="test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") - + Expect.log('stdio', stderr="HEAD is now at 0123456789abcdef...\n")) - self.expectProperty( - "repo_downloaded", "564/12 0123456789abcdef ", "Source") - return self.myRunStep(status_text=["update"]) - - def test_repo_downloads2(self): - """2 repo downloads""" - self.mySetupStep() - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.build.setProperty("repo_download2", - "repo download test/bla2 565/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0, - self.ExpectShell( - command=['repo', 'download', 'test/bla2', '565/12']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_repo_download_manifest(self): - """2 repo downloads, with one manifest patch""" - self.mySetupStep() - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.build.setProperty("repo_download2", - "repo download manifest 565/12", "test") - self.expectnoClobber() - self.expectCommands( - self.ExpectShell( - command=['bash', '-c', self.step._getCleanupCommand()]) - + 0, - self.ExpectShell( - command=['repo', 'init', '-u', 'git://myrepo.com/manifest.git', - '-b', 'mb', '-m', 'mf']) - + 0, - self.ExpectShell( - workdir=os.path.join('wkdir', '.repo', 'manifests'), - command=[ - 'git', 'fetch', 'git://myrepo.com/manifest.git', - 'refs/changes/65/565/12']) - + 0, - self.ExpectShell( - workdir=os.path.join('wkdir', '.repo', 'manifests'), - command=['git', 'cherry-pick', 'FETCH_HEAD']) - + 0, - self.ExpectShell(command=['repo', 'sync', '-c']) - + 0, - self.ExpectShell( - command=['repo', 'manifest', '-r', '-o', 'manifest-original.xml']) - + 0) - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_repo_downloads_mirror_sync(self): - """repo downloads, with mirror synchronization issues""" - self.mySetupStep() - self.step.mirror_sync_sleep = 0.001 # we dont really want the test to wait... - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 1 + - Expect.log( - "stdio", stderr="fatal: Couldn't find remote ref \n"), - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 1 + - Expect.log( - "stdio", stderr="fatal: Couldn't find remote ref \n"), - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0) - return self.myRunStep(status_text=["update"]) - - def test_repo_downloads_change_missing(self): - """repo downloads, with no actual mirror synchronization issues (still retries 2 times)""" - self.mySetupStep() - self.step.mirror_sync_sleep = 0.001 # we dont really want the test to wait... - self.step.mirror_sync_retry = 1 # on retry once - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 1 + - Expect.log( - "stdio", stderr="fatal: Couldn't find remote ref \n"), - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 1 + - Expect.log( - "stdio", stderr="fatal: Couldn't find remote ref \n"), - ) - return self.myRunStep(result=FAILURE, status_text=["repo: change test/bla 564/12 does not exist"]) - - def test_repo_downloads_fail1(self): - """repo downloads, cherry-pick returns 1""" - self.mySetupStep() - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 1 + Expect.log("stdio", stderr="patch \n"), - self.ExpectShell( - command=['repo', 'forall', '-c', 'git', 'diff', 'HEAD']) - + 0 - ) - return self.myRunStep(result=FAILURE, status_text=["download failed: test/bla 564/12"]) - - def test_repo_downloads_fail2(self): - """repo downloads, cherry-pick returns 0 but error in stderr""" - self.mySetupStep() - self.build.setProperty("repo_download", - "repo download test/bla 564/12", "test") - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell( - command=['repo', 'download', 'test/bla', '564/12']) - + 0 + - Expect.log("stdio", stderr="Automatic cherry-pick failed \n"), - self.ExpectShell( - command=['repo', 'forall', '-c', 'git', 'diff', 'HEAD']) - + 0 - ) - return self.myRunStep(result=FAILURE, status_text=["download failed: test/bla 564/12"]) - - def test_repo_downloads_from_change_source(self): - """basic repo download from change source, and check that repo_downloaded is updated""" - self.mySetupStep(repoDownloads=repo.RepoDownloadsFromChangeSource()) - chdict = TestGerritChangeSource.expected_change - change = Change(None, None, None, properties=chdict['properties']) - self.build.allChanges = lambda x=None: [change] - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell(command=['repo', 'download', 'pr', '4321/12']) - + 0 - + Expect.log( - 'stdio', stderr="test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") - + Expect.log('stdio', stderr="HEAD is now at 0123456789abcdef...\n")) - self.expectProperty( - "repo_downloaded", "564/12 0123456789abcdef ", "Source") - return self.myRunStep(status_text=["update"]) - - def test_repo_downloads_from_change_source_codebase(self): - """basic repo download from change source, and check that repo_downloaded is updated""" - self.mySetupStep(repoDownloads=repo.RepoDownloadsFromChangeSource("mycodebase")) - chdict = TestGerritChangeSource.expected_change - change = Change(None, None, None, properties=chdict['properties']) - # getSourceStamp is faked by SourceStepMixin - ss = self.build.getSourceStamp("") - ss.changes = [change] - self.expectnoClobber() - self.expectRepoSync() - self.expectCommands( - self.ExpectShell(command=['repo', 'download', 'pr', '4321/12']) - + 0 - + Expect.log( - 'stdio', stderr="test/bla refs/changes/64/564/12 -> FETCH_HEAD\n") - + Expect.log('stdio', stderr="HEAD is now at 0123456789abcdef...\n")) - self.expectProperty( - "repo_downloaded", "564/12 0123456789abcdef ", "Source") - return self.myRunStep(status_text=["update"]) - - def test_update_fail1(self): - """ fail at cleanup: ignored""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=0, breakatfail=False) - return self.myRunStep(status_text=["update"]) - - def test_update_fail2(self): - """fail at repo init: clobber""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=1, breakatfail=True) - self.expectClobber() - self.expectRepoSync() - self.shouldRetry = True - return self.myRunStep(status_text=["update"]) - - def test_update_fail3(self): - """ fail at repo sync: clobber""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=2, breakatfail=True) - self.expectClobber() - self.expectRepoSync() - self.shouldRetry = True - return self.myRunStep(status_text=["update"]) - - def test_update_fail4(self): - """fail at repo manifest: clobber""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=3, breakatfail=True) - self.expectClobber() - self.expectRepoSync() - self.shouldRetry = True - return self.myRunStep(status_text=["update"]) - - def test_update_doublefail(self): - """fail at repo manifest: clobber but still fail""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=3, breakatfail=True) - self.expectClobber() - self.expectRepoSync(which_fail=3, breakatfail=True) - self.shouldRetry = True - return self.myRunStep(result=FAILURE, status_text=["repo failed at: repo manifest"]) - - def test_update_doublefail2(self): - """fail at repo sync: clobber but still fail""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=2, breakatfail=True) - self.expectClobber() - self.expectRepoSync(which_fail=2, breakatfail=True) - self.shouldRetry = True - return self.myRunStep(result=FAILURE, status_text=["repo failed at: repo sync"]) - - def test_update_doublefail3(self): - """fail at repo init: clobber but still fail""" - self.mySetupStep() - self.expectnoClobber() - self.expectRepoSync(which_fail=1, breakatfail=True) - self.expectClobber() - self.expectRepoSync(which_fail=1, breakatfail=True) - self.shouldRetry = True - return self.myRunStep(result=FAILURE, status_text=["repo failed at: repo init"]) - - def test_basic_fail(self): - """fail at repo init: no need to re-clobber but still fail""" - self.mySetupStep() - self.expectClobber() - self.expectRepoSync(which_fail=1, breakatfail=True) - self.shouldRetry = True - return self.myRunStep(result=FAILURE, status_text=["repo failed at: repo init"]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_svn.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_svn.py deleted file mode 100644 index b1c4e2ce..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_source_svn.py +++ /dev/null @@ -1,1477 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.python.reflect import namedModule -from buildbot.steps.source import svn -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.util import sourcesteps -from buildbot.process import buildstep -from buildbot.test.fake.remotecommand import ExpectShell, Expect -from buildbot.test.util.properties import ConstantRenderable -from buildbot import config - -class TestSVN(sourcesteps.SourceStepMixin, unittest.TestCase): - - svn_st_xml = """<?xml version="1.0"?> - <status> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file1"> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file2"> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - </target> - </status> - """ - svn_st_xml_corrupt = """<?xml version="1.0"?> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file"> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - </target> - </status> - """ - svn_st_xml_empty = """<?xml version="1.0"?> - <status> - <target path="."> - </target> - </status>""" - svn_info_stdout_xml = """<?xml version="1.0"?> - <info> - <entry - kind="dir" - path="." - revision="100"> - <url>http://svn.red-bean.com/repos/test</url> - <repository> - <root>http://svn.red-bean.com/repos/test</root> - <uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid> - </repository> - <wc-info> - <schedule>normal</schedule> - <depth>infinity</depth> - </wc-info> - <commit - revision="90"> - <author>sally</author> - <date>2003-01-15T23:35:12.847647Z</date> - </commit> - </entry> - </info>""" - svn_info_stdout_xml_nonintegerrevision = """<?xml version="1.0"?> - <info> - <entry - kind="dir" - path="." - revision="a10"> - <url>http://svn.red-bean.com/repos/test</url> - <repository> - <root>http://svn.red-bean.com/repos/test</root> - <uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid> - </repository> - <wc-info> - <schedule>normal</schedule> - <depth>infinity</depth> - </wc-info> - <commit - revision="a10"> - <author>sally</author> - <date>2003-01-15T23:35:12.847647Z</date> - </commit> - </entry> - </info>""" - - def setUp(self): - return self.setUpSourceStep() - - def tearDown(self): - return self.tearDownSourceStep() - - def patch_slaveVersionIsOlderThan(self, result): - self.patch(svn.SVN, 'slaveVersionIsOlderThan', lambda x, y, z: result) - - def test_no_repourl(self): - self.assertRaises(config.ConfigErrors, lambda : - svn.SVN()) - - def test_incorrect_mode(self): - self.assertRaises(config.ConfigErrors, lambda : - svn.SVN(repourl='http://svn.local/app/trunk', - mode='invalid')) - - def test_incorrect_method(self): - self.assertRaises(config.ConfigErrors, lambda : - svn.SVN(repourl='http://svn.local/app/trunk', - method='invalid')) - - def test_corrupt_xml(self): - self.setupStep(svn.SVN(repourl='http://svn.local/app/trunk')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml_corrupt) - + 0, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_revision_noninteger(self): - svnTestStep = svn.SVN(repourl='http://svn.local/app/trunk') - self.setupStep(svnTestStep) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml_nonintegerrevision) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', 'a10', 'SVN') - d = self.runStep() - def _checkType(): - revision = self.step.getProperty('got_revision') - self.assertRaises(ValueError, lambda: int(revision)) - d.addCallback(lambda _: _checkType()) - return d - - def test_revision_missing(self): - """Fail if 'revision' tag isnt there""" - svn_info_stdout = self.svn_info_stdout_xml.replace('entry', 'Blah') - - svnTestStep = svn.SVN(repourl='http://svn.local/app/trunk') - self.setupStep(svnTestStep) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=svn_info_stdout) - + 0, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_mode_incremental(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_timeout(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - timeout=1, - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - timeout=1, - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_repourl_renderable(self): - self.setupStep( - svn.SVN(repourl=ConstantRenderable('http://svn.local/trunk'), - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_repourl_not_updatable(self): - self.setupStep( - svn.SVN(repourl=ConstantRenderable('http://svn.local/trunk/app'), - mode='incremental',)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 1, - Expect('rmdir', {'dir': 'wkdir', 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', 'http://svn.local/trunk/app', - '.', '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_repourl_not_updatable_svninfo_mismatch(self): - self.setupStep( - svn.SVN(repourl=ConstantRenderable('http://svn.local/trunk/app'), - mode='incremental')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', # expecting ../trunk/app - stdout="""<?xml version="1.0"?><url>http://svn.local/branch/foo/app</url>""") - + 0, - Expect('rmdir', {'dir': 'wkdir', 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', 'http://svn.local/trunk/app', - '.', '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental'), dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_win32path(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'])) - self.build.path_module = namedModule("ntpath") - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file=r'wkdir\.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - return self.runStep() - - def test_mode_incremental_preferLastChangedRev(self): - """Give the last-changed rev if 'preferLastChangedRev' is set""" - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - preferLastChangedRev=True, - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '90', 'SVN') - return self.runStep() - - def test_mode_incremental_preferLastChangedRev_butMissing(self): - """If 'preferLastChangedRev' is set, but missing, fall back - to the regular revision value.""" - svn_info_stdout = self.svn_info_stdout_xml.replace('commit', 'Blah') - - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - preferLastChangedRev=True, - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=svn_info_stdout) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clobber(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clobber')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', {'dir': 'wkdir', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', - 'http://svn.local/app/trunk', '.', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clobber_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clobber'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', {'dir': 'wkdir', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', - 'http://svn.local/app/trunk', '.', - '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_fresh(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='fresh', depth='infinite')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--depth', 'infinite' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', '--no-ignore', - '--non-interactive', '--no-auth-cache', - '--depth', 'infinite']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml_empty) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', - '--non-interactive', '--no-auth-cache', '--depth', 'infinite']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + ExpectShell.log('stdio', stdout='\n') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_fresh_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='fresh', depth='infinite'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--depth', 'infinite' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', '--no-ignore', - '--non-interactive', '--no-auth-cache', - '--depth', 'infinite']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml_empty) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--revision', '100', - '--non-interactive', '--no-auth-cache', '--depth', 'infinite']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + ExpectShell.log('stdio', stdout='\n') - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_fresh_keep_on_purge(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', - keep_on_purge=['svn_external_path/unversioned_file1'])) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', '--no-ignore', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml) - + 0, - Expect('rmdir', {'dir': - ['wkdir/svn_external_path/unversioned_file2'], - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clean(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml_empty) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clean_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml_empty) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_not_updatable(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 1, - Expect('rmdir', {'dir': 'wkdir', 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', 'http://svn.local/app/trunk', - '.', '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_not_updatable_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 1, - Expect('rmdir', {'dir': 'wkdir', 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'checkout', 'http://svn.local/app/trunk', - '.', '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clean_old_rmdir(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean')) - self.patch_slaveVersionIsOlderThan(True) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml) - + 0, - Expect('rmdir', {'dir': - 'wkdir/svn_external_path/unversioned_file1', - 'logEnviron': True}) - + 0, - Expect('rmdir', {'dir': - 'wkdir/svn_external_path/unversioned_file2', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_clean_new_rmdir(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clean')) - - self.patch_slaveVersionIsOlderThan(False) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml) - + 0, - Expect('rmdir', {'dir': - ['wkdir/svn_external_path/unversioned_file1', - 'wkdir/svn_external_path/unversioned_file2'], - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_copy(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='copy')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - Expect('cpdir', {'fromdir': 'source', - 'todir': 'wkdir', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_copy_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='copy'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - command=['svn', 'update', '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - Expect('cpdir', {'fromdir': 'source', - 'todir': 'wkdir', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_export(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='export')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='', - command=['svn', 'export', 'source', 'wkdir']) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_export_timeout(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - timeout=1, - mode='full', method='export')) - self.expectCommands( - ExpectShell(workdir='wkdir', - timeout=1, - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - timeout=1, - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - timeout=1, - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - ExpectShell(workdir='', - timeout=1, - command=['svn', 'export', 'source', 'wkdir']) - + 0, - ExpectShell(workdir='source', - timeout=1, - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_full_export_given_revision(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='export'),dict( - revision='100', - )) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - command=['svn', 'update', '--revision', '100', - '--non-interactive', '--no-auth-cache']) - + 0, - ExpectShell(workdir='', - command=['svn', 'export', '--revision', '100', - 'source', 'wkdir']) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_with_env(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'], - env={'abc': '123'})) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version'], - env={'abc': '123'}) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random'], - env={'abc': '123'}) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random'], - env={'abc': '123'}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml'], - env={'abc': '123'}) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_mode_incremental_logEnviron(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'], - logEnviron=False)) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version'], - logEnviron=False) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=False)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random'], - logEnviron=False) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random'], - logEnviron=False) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml'], - logEnviron=False) - + ExpectShell.log('stdio', - stdout=self.svn_info_stdout_xml) - + 0, - ) - self.expectOutcome(result=SUCCESS, status_text=["update"]) - self.expectProperty('got_revision', '100', 'SVN') - return self.runStep() - - def test_command_fails(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_bogus_svnversion(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='incremental',username='user', - password='pass', extra_args=['--random'])) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', dict(file='wkdir/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + ExpectShell.log('stdio', stdout="""<?xml version="1.0"?><entry kind="dir" path="/a/b/c" revision="1"><url>http://svn.local/app/trunk</url></entry>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache', '--username', 'user', - '--password', 'pass', '--random']) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml']) - + ExpectShell.log('stdio', - stdout='1x0y0') - + 0, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_rmdir_fails_clobber(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='clobber')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', {'dir': 'wkdir', - 'logEnviron': True}) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_rmdir_fails_copy(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='copy')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_cpdir_fails_copy(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', method='copy')) - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('rmdir', dict(dir='wkdir', - logEnviron=True)) - + 0, - Expect('stat', dict(file='source/.svn', - logEnviron=True)) - + 0, - ExpectShell(workdir='source', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='source', - command=['svn', 'update', '--non-interactive', - '--no-auth-cache']) - + 0, - Expect('cpdir', {'fromdir': 'source', - 'todir': 'wkdir', - 'logEnviron': True}) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - - def test_rmdir_fails_purge(self): - self.setupStep( - svn.SVN(repourl='http://svn.local/app/trunk', - mode='full', - keep_on_purge=['svn_external_path/unversioned_file1'])) - - self.expectCommands( - ExpectShell(workdir='wkdir', - command=['svn', '--version']) - + 0, - Expect('stat', {'file': 'wkdir/.svn', - 'logEnviron': True}) - + 0, - ExpectShell(workdir='wkdir', - command=['svn', 'info', '--xml', - '--non-interactive', - '--no-auth-cache' ]) - + ExpectShell.log('stdio', - stdout="""<?xml version="1.0"?><url>http://svn.local/app/trunk</url>""") - + 0, - ExpectShell(workdir='wkdir', - command=['svn', - 'status', '--xml', '--no-ignore', - '--non-interactive', '--no-auth-cache']) - + ExpectShell.log('stdio', - stdout=self.svn_st_xml) - + 0, - Expect('rmdir', {'dir': - ['wkdir/svn_external_path/unversioned_file2'], - 'logEnviron': True}) - + 1, - ) - self.expectOutcome(result=FAILURE, status_text=["updating"]) - return self.runStep() - -class TestGetUnversionedFiles(unittest.TestCase): - def test_getUnversionedFiles_does_not_list_externals(self): - svn_st_xml = """<?xml version="1.0"?> - <status> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file"> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - </target> - </status> - """ - unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) - self.assertEquals(["svn_external_path/unversioned_file"], unversioned_files) - - def test_getUnversionedFiles_does_not_list_missing(self): - svn_st_xml = """<?xml version="1.0"?> - <status> - <target path="."> - <entry path="missing_file"> - <wc-status props="none" item="missing"></wc-status> - </entry> - </target> - </status> - """ - unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) - self.assertEquals([], unversioned_files) - - def test_getUnversionedFiles_corrupted_xml(self): - svn_st_xml_corrupt = """<?xml version="1.0"?> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file"> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - </target> - </status> - """ - self.assertRaises(buildstep.BuildStepFailed, - lambda : list(svn.SVN.getUnversionedFiles(svn_st_xml_corrupt, []))) - - def test_getUnversionedFiles_no_path(self): - svn_st_xml = """<?xml version="1.0"?> - <status> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry> - <wc-status props="none" item="unversioned"> - </wc-status> - </entry> - </target> - </status> - """ - unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) - self.assertEquals([], unversioned_files) - - def test_getUnversionedFiles_no_item(self): - svn_st_xml = """<?xml version="1.0"?> - <status> - <target path="."> - <entry path="svn_external_path"> - <wc-status props="none" item="external"> - </wc-status> - </entry> - <entry path="svn_external_path/unversioned_file"> - <wc-status props="none"> - </wc-status> - </entry> - </target> - </status> - """ - unversioned_files = list(svn.SVN.getUnversionedFiles(svn_st_xml, [])) - self.assertEquals(["svn_external_path/unversioned_file"], unversioned_files) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_subunit.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_subunit.py deleted file mode 100644 index a639b071..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_subunit.py +++ /dev/null @@ -1,86 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import mock -import StringIO -from zope.interface import implements -from twisted.trial import unittest -from buildbot import interfaces -from buildbot.steps import subunit -from buildbot.process import subunitlogobserver -from buildbot.status.results import SUCCESS, FAILURE -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps - -class StubLogObserver(mock.Mock): - implements(interfaces.ILogObserver) - -class TestSetPropertiesFromEnv(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - self.logobserver = StubLogObserver() - self.logobserver.failures = [] - self.logobserver.errors = [] - self.logobserver.skips = [] - self.logobserver.testsRun = 0 - self.logobserver.warningio = StringIO.StringIO() - self.patch(subunitlogobserver, 'SubunitLogObserver', - lambda : self.logobserver) - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_empty(self): - self.setupStep(subunit.SubunitShellCommand(command='test')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="test") - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["shell", "no tests", "run"]) - return self.runStep() - - def test_empty_error(self): - self.setupStep(subunit.SubunitShellCommand(command='test', - failureOnNoTests=True)) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="test") - + 0 - ) - self.expectOutcome(result=FAILURE, - status_text=["shell", "no tests", "run"]) - return self.runStep() - - def test_warnings(self): - self.setupStep(subunit.SubunitShellCommand(command='test')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command="test") - + 0 - ) - self.logobserver.warnings.append('not quite up to snuff (list)') - self.logobserver.warningio.write('not quite up to snuff (io)\n') - self.logobserver.testsRun = 3 - self.expectOutcome(result=SUCCESS, # N.B. not WARNINGS - status_text=["shell", "3 tests", "passed"]) - # note that the warnings list is ignored.. - self.expectLogfile('warnings', 'not quite up to snuff (io)\n') - return self.runStep() - - # TODO: test text2 generation? - # TODO: tests are represented as objects?! diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_transfer.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_transfer.py deleted file mode 100644 index cfdcefb9..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_transfer.py +++ /dev/null @@ -1,267 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import tempfile, os -import shutil -import tarfile -from twisted.trial import unittest - -from mock import Mock - -from buildbot.process.properties import Properties -from buildbot.util import json -from buildbot.steps import transfer -from buildbot.status.results import SUCCESS -from buildbot import config -from buildbot.test.util import steps -from buildbot.test.fake.remotecommand import Expect, ExpectRemoteRef - -class TestFileUpload(unittest.TestCase): - def setUp(self): - fd, self.destfile = tempfile.mkstemp() - os.close(fd) - os.unlink(self.destfile) - - def tearDown(self): - if os.path.exists(self.destfile): - os.unlink(self.destfile) - - def test_constructor_mode_type(self): - self.assertRaises(config.ConfigErrors, lambda : - transfer.FileUpload(slavesrc=__file__, masterdest='xyz', mode='g+rwx')) - - def testBasic(self): - s = transfer.FileUpload(slavesrc=__file__, masterdest=self.destfile) - s.build = Mock() - s.build.getProperties.return_value = Properties() - s.build.getSlaveCommandVersion.return_value = 1 - - s.step_status = Mock() - s.buildslave = Mock() - s.remote = Mock() - - s.start() - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'uploadFile': - self.assertEquals(kwargs['slavesrc'], __file__) - writer = kwargs['writer'] - with open(__file__, "rb") as f: - writer.remote_write(f.read()) - self.assert_(not os.path.exists(self.destfile)) - writer.remote_close() - break - else: - self.assert_(False, "No uploadFile command found") - - with open(self.destfile, "rb") as dest: - with open(__file__, "rb") as expect: - self.assertEquals(dest.read(), expect.read()) - - def testTimestamp(self): - s = transfer.FileUpload(slavesrc=__file__, masterdest=self.destfile, keepstamp=True) - s.build = Mock() - s.build.getProperties.return_value = Properties() - s.build.getSlaveCommandVersion.return_value = "2.13" - - s.step_status = Mock() - s.buildslave = Mock() - s.remote = Mock() - s.start() - timestamp = ( os.path.getatime(__file__), - os.path.getmtime(__file__) ) - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'uploadFile': - self.assertEquals(kwargs['slavesrc'], __file__) - writer = kwargs['writer'] - with open(__file__, "rb") as f: - writer.remote_write(f.read()) - self.assert_(not os.path.exists(self.destfile)) - writer.remote_close() - writer.remote_utime(timestamp) - break - else: - self.assert_(False, "No uploadFile command found") - - desttimestamp = ( os.path.getatime(self.destfile), - os.path.getmtime(self.destfile) ) - - timestamp = map(int, timestamp) - desttimestamp = map(int, desttimestamp) - - self.assertEquals(timestamp[0],desttimestamp[0]) - self.assertEquals(timestamp[1],desttimestamp[1]) - - def testURL(self): - s = transfer.FileUpload(slavesrc=__file__, masterdest=self.destfile, url="http://server/file") - s.build = Mock() - s.build.getProperties.return_value = Properties() - s.build.getSlaveCommandVersion.return_value = "2.13" - - s.step_status = Mock() - s.step_status.addURL = Mock() - s.buildslave = Mock() - s.remote = Mock() - s.start() - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'uploadFile': - self.assertEquals(kwargs['slavesrc'], __file__) - writer = kwargs['writer'] - with open(__file__, "rb") as f: - writer.remote_write(f.read()) - self.assert_(not os.path.exists(self.destfile)) - writer.remote_close() - break - else: - self.assert_(False, "No uploadFile command found") - - s.step_status.addURL.assert_called_once_with( - os.path.basename(self.destfile), "http://server/file") - -class TestDirectoryUpload(steps.BuildStepMixin, unittest.TestCase): - def setUp(self): - self.destdir = os.path.abspath('destdir') - if os.path.exists(self.destdir): - shutil.rmtree(self.destdir) - - return self.setUpBuildStep() - - def tearDown(self): - if os.path.exists(self.destdir): - shutil.rmtree(self.destdir) - - return self.tearDownBuildStep() - - def testBasic(self): - self.setupStep( - transfer.DirectoryUpload(slavesrc="srcdir", masterdest=self.destdir)) - - def upload_behavior(command): - from cStringIO import StringIO - f = StringIO() - archive = tarfile.TarFile(fileobj=f, name='fake.tar', mode='w') - archive.addfile(tarfile.TarInfo("test"), StringIO("Hello World!")) - writer = command.args['writer'] - writer.remote_write(f.getvalue()) - writer.remote_unpack() - - self.expectCommands( - Expect('uploadDirectory', dict( - slavesrc="srcdir", workdir='wkdir', - blocksize=16384, compress=None, maxsize=None, - writer=ExpectRemoteRef(transfer._DirectoryWriter))) - + Expect.behavior(upload_behavior) - + 0) - - self.expectOutcome(result=SUCCESS, status_text=["uploading", "srcdir"]) - d = self.runStep() - return d - -class TestStringDownload(unittest.TestCase): - def testBasic(self): - s = transfer.StringDownload("Hello World", "hello.txt") - s.build = Mock() - s.build.getProperties.return_value = Properties() - s.build.getSlaveCommandVersion.return_value = 1 - - s.step_status = Mock() - s.buildslave = Mock() - s.remote = Mock() - - s.start() - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'downloadFile': - self.assertEquals(kwargs['slavedest'], 'hello.txt') - reader = kwargs['reader'] - data = reader.remote_read(100) - self.assertEquals(data, "Hello World") - break - else: - self.assert_(False, "No downloadFile command found") - -class TestJSONStringDownload(unittest.TestCase): - def testBasic(self): - msg = dict(message="Hello World") - s = transfer.JSONStringDownload(msg, "hello.json") - s.build = Mock() - s.build.getProperties.return_value = Properties() - s.build.getSlaveCommandVersion.return_value = 1 - - s.step_status = Mock() - s.buildslave = Mock() - s.remote = Mock() - - s.start() - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'downloadFile': - self.assertEquals(kwargs['slavedest'], 'hello.json') - reader = kwargs['reader'] - data = reader.remote_read(100) - self.assertEquals(data, json.dumps(msg)) - break - else: - self.assert_(False, "No downloadFile command found") - -class TestJSONPropertiesDownload(unittest.TestCase): - def testBasic(self): - s = transfer.JSONPropertiesDownload("props.json") - s.build = Mock() - props = Properties() - props.setProperty('key1', 'value1', 'test') - s.build.getProperties.return_value = props - s.build.getSlaveCommandVersion.return_value = 1 - ss = Mock() - ss.asDict.return_value = dict(revision="12345") - s.build.getSourceStamp.return_value = ss - - s.step_status = Mock() - s.buildslave = Mock() - s.remote = Mock() - - s.start() - - for c in s.remote.method_calls: - name, command, args = c - commandName = command[3] - kwargs = command[-1] - if commandName == 'downloadFile': - self.assertEquals(kwargs['slavedest'], 'props.json') - reader = kwargs['reader'] - data = reader.remote_read(100) - self.assertEquals(data, json.dumps(dict(sourcestamp=ss.asDict(), properties={'key1': 'value1'}))) - break - else: - self.assert_(False, "No downloadFile command found") diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_trigger.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_trigger.py deleted file mode 100644 index 245985a5..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_trigger.py +++ /dev/null @@ -1,502 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from zope.interface import implements - -from twisted.trial import unittest -from twisted.python import failure -from twisted.internet import defer, reactor -from buildbot import config, interfaces -from buildbot.process import properties -from buildbot.status import master -from buildbot.status.results import SUCCESS, FAILURE, EXCEPTION -from buildbot.steps import trigger -from buildbot.test.util import steps, compat -from buildbot.test.fake import fakemaster, fakedb - -class FakeTriggerable(object): - implements(interfaces.ITriggerableScheduler) - - triggered_with = None - result = SUCCESS - brids = {} - exception = False - - def __init__(self, name): - self.name = name - - def trigger(self, sourcestamps = None, set_props=None): - self.triggered_with = (sourcestamps, set_props.properties) - d = defer.Deferred() - if self.exception: - reactor.callLater(0, d.errback, RuntimeError('oh noes')) - else: - reactor.callLater(0, d.callback, (self.result, self.brids)) - return d - - -class FakeSourceStamp(object): - - def __init__(self, **kwargs): - self.__dict__.update(kwargs) - - def asDict(self, includePatch = True): - return self.__dict__.copy() - -# Magic numbers that relate brid to other build settings -BRID_TO_BSID = lambda brid: brid+2000 -BRID_TO_BID = lambda brid: brid+3000 -BRID_TO_BUILD_NUMBER = lambda brid: brid+4000 - -class TestTrigger(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def setupStep(self, step, sourcestampsInBuild=None, gotRevisionsInBuild=None, *args, **kwargs): - sourcestamps = sourcestampsInBuild or [] - got_revisions = gotRevisionsInBuild or {} - - steps.BuildStepMixin.setupStep(self, step, *args, **kwargs) - - # This step reaches deeply into a number of parts of Buildbot. That - # should be fixed! - - # set up a buildmaster that knows about two fake schedulers, a and b - m = fakemaster.make_master() - self.build.builder.botmaster = m.botmaster - m.db = fakedb.FakeDBConnector(self) - m.status = master.Status(m) - m.config.buildbotURL = "baseurl/" - - self.scheduler_a = a = FakeTriggerable(name='a') - self.scheduler_b = b = FakeTriggerable(name='b') - def allSchedulers(): - return [ a, b ] - m.allSchedulers = allSchedulers - - a.brids = {'A': 11} - b.brids = {'B': 22} - - make_fake_br = lambda brid, name: fakedb.BuildRequest(id=brid, - buildsetid=BRID_TO_BSID(brid), - buildername=name) - make_fake_build = lambda brid: fakedb.Build(brid=brid, - id=BRID_TO_BID(brid), - number=BRID_TO_BUILD_NUMBER(brid)) - - m.db.insertTestData([ - make_fake_br(11, "A"), - make_fake_br(22, "B"), - make_fake_build(11), - make_fake_build(22), - ]) - - def getAllSourceStamps(): - return sourcestamps - self.build.getAllSourceStamps = getAllSourceStamps - def getAllGotRevisions(): - return got_revisions - self.build.build_status.getAllGotRevisions = getAllGotRevisions - - self.exp_add_sourcestamp = None - self.exp_a_trigger = None - self.exp_b_trigger = None - self.exp_added_urls = [] - - def runStep(self, expect_waitForFinish=False): - d = steps.BuildStepMixin.runStep(self) - - if expect_waitForFinish: - # the build doesn't finish until after a callLater, so this has the - # effect of checking whether the deferred has been fired already; - # it should not have been! - early = [] - d.addCallback(early.append) - self.assertEqual(early, []) - - def check(_): - self.assertEqual(self.scheduler_a.triggered_with, - self.exp_a_trigger) - self.assertEqual(self.scheduler_b.triggered_with, - self.exp_b_trigger) - self.assertEqual(self.step_status.addURL.call_args_list, - self.exp_added_urls) - - if self.exp_add_sourcestamp: - self.assertEqual(self.addSourceStamp_kwargs, - self.exp_add_sourcestamp) - d.addCallback(check) - - # pause runStep's completion until after any other callLater's are done - def wait(_): - d = defer.Deferred() - reactor.callLater(0, d.callback, None) - return d - d.addCallback(wait) - - return d - - def expectTriggeredWith(self, a=None, b=None): - self.exp_a_trigger = a - self.exp_b_trigger = b - - def expectAddedSourceStamp(self, **kwargs): - self.exp_add_sourcestamp = kwargs - - def expectTriggeredLinks(self, *args): - def get_args(sch, name): - label = lambda name, num: "%s #%d" % (name, num) - url = lambda name, num: "baseurl/builders/%s/builds/%d" % (name, num ) - - num = BRID_TO_BUILD_NUMBER(sch.brids[name]) - - #returns the *args and **kwargs that will be called on addURL... - # which is just addURL('label', 'url') - return ( (label(name,num), url(name,num)) , {} ) - - if 'a' in args: - self.exp_added_urls.append(get_args(self.scheduler_a, 'A')) - if 'b' in args: - self.exp_added_urls.append(get_args(self.scheduler_b, 'B')) - - - # tests - - def test_no_schedulerNames(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger()) - - def test_sourceStamp_and_updateSourceStamp(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger(schedulerNames=['c'], - sourceStamp=dict(x=1), updateSourceStamp=True)) - - def test_sourceStamps_and_updateSourceStamp(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger(schedulerNames=['c'], - sourceStamps=[dict(x=1), dict(x=2)], - updateSourceStamp=True)) - - def test_updateSourceStamp_and_alwaysUseLatest(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger(schedulerNames=['c'], - updateSourceStamp=True, alwaysUseLatest=True)) - - def test_sourceStamp_and_alwaysUseLatest(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger(schedulerNames=['c'], - sourceStamp=dict(x=1), alwaysUseLatest=True)) - - def test_sourceStamps_and_alwaysUseLatest(self): - self.assertRaises(config.ConfigErrors, lambda : - trigger.Trigger(schedulerNames=['c'], - sourceStamps=[dict(x=1), dict(x=2)], - alwaysUseLatest=True)) - - def test_simple(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], sourceStamps = {})) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, {})) - return self.runStep() - - def test_simple_failure(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'])) - self.scheduler_a.result = FAILURE - # not waitForFinish, so trigger step succeeds even though the build - # didn't fail - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, {})) - return self.runStep() - - @compat.usesFlushLoggedErrors - def test_simple_exception(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'])) - self.scheduler_a.exception = True - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=( {}, {})) - d = self.runStep() - def flush(_): - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - d.addCallback(flush) - return d - - def test_bogus_scheduler(self): - self.setupStep(trigger.Trigger(schedulerNames=['a', 'x'])) - self.expectOutcome(result=FAILURE, status_text=['not valid scheduler:', 'x']) - self.expectTriggeredWith(a=None) # a is not triggered! - return self.runStep() - - def test_updateSourceStamp(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=True), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ], - gotRevisionsInBuild = {'': 23456}, - ) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({'':{'codebase':'', - 'repository': 'x', - 'revision': 23456} - }, {})) - return self.runStep() - - def test_updateSourceStamp_no_got_revision(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=True), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ]) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({'':{'codebase':'', - 'repository': 'x', - 'revision': 11111} # uses old revision - }, {})) - return self.runStep() - - def test_not_updateSourceStamp(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=False), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ], - gotRevisionsInBuild = {'': 23456}, - ) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({'':{'codebase':'', - 'repository': 'x', - 'revision': 11111} - }, {})) - return self.runStep() - - def test_updateSourceStamp_multiple_repositories(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=True), - sourcestampsInBuild = [ - FakeSourceStamp(codebase='cb1', - revision='12345'), - FakeSourceStamp(codebase='cb2', - revision='12345') - ], - gotRevisionsInBuild = {'cb1': 23456, 'cb2': 34567}, - ) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({'cb1': {'codebase':'cb1', - 'revision':23456}, - 'cb2': {'codebase':'cb2', - 'revision':34567} - }, {})) - return self.runStep() - - def test_updateSourceStamp_prop_false(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=properties.Property('usess')), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ], - gotRevisionsInBuild = {'': 23456}, - ) - self.properties.setProperty('usess', False, 'me') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - # didn't use got_revision - self.expectTriggeredWith(a=({'': { 'codebase':'', - 'repository': 'x', - 'revision': 11111 - }}, {})) - return self.runStep() - - def test_updateSourceStamp_prop_true(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - updateSourceStamp=properties.Property('usess')), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ], - gotRevisionsInBuild = {'': 23456}, - ) - self.properties.setProperty('usess', True, 'me') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - # didn't use got_revision - self.expectTriggeredWith(a=({'': { 'codebase':'', - 'repository': 'x', - 'revision': 23456 - }}, {})) - return self.runStep() - - def test_alwaysUseLatest(self): - self.setupStep(trigger.Trigger(schedulerNames=['b'], - alwaysUseLatest=True), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ]) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - # Do not pass setid - self.expectTriggeredWith(b=({}, {})) - return self.runStep() - - def test_alwaysUseLatest_prop_false(self): - self.setupStep(trigger.Trigger(schedulerNames=['b'], - alwaysUseLatest=properties.Property('aul')), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ]) - self.properties.setProperty('aul', False, 'me') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - # didn't use latest - self.expectTriggeredWith(b=({'': { 'codebase':'', - 'repository': 'x', - 'revision': 11111} - }, {})) - return self.runStep() - - def test_alwaysUseLatest_prop_true(self): - self.setupStep(trigger.Trigger(schedulerNames=['b'], - alwaysUseLatest=properties.Property('aul')), - sourcestampsInBuild = [FakeSourceStamp(codebase='', - repository='x', - revision=11111) - ]) - self.properties.setProperty('aul', True, 'me') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - # didn't use latest - self.expectTriggeredWith(b=({}, {})) - return self.runStep() - - def test_sourceStamp(self): - ss = dict(revision=9876, branch='dev') - self.setupStep(trigger.Trigger(schedulerNames=['b'], - sourceStamp=ss)) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - self.expectTriggeredWith(b=({'': ss}, {})) - return self.runStep() - - def test_set_of_sourceStamps(self): - ss1 = dict(codebase='cb1', repository='r1', revision=9876, branch='dev') - ss2 = dict(codebase='cb2',repository='r2', revision=5432, branch='dev') - self.setupStep(trigger.Trigger(schedulerNames=['b'], - sourceStamps=[ss1,ss2])) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - self.expectTriggeredWith(b=({'cb1':ss1, 'cb2':ss2}, {})) - return self.runStep() - - def test_set_of_sourceStamps_override_build(self): - ss1 = dict(codebase='cb1', repository='r1', revision=9876, branch='dev') - ss2 = dict(codebase='cb2',repository='r2', revision=5432, branch='dev') - ss3 = FakeSourceStamp(codebase='cb3', repository='r3', revision=1234, branch='dev') - ss4 = FakeSourceStamp(codebase='cb4',repository='r4', revision=2345, branch='dev') - self.setupStep(trigger.Trigger(schedulerNames=['b'], - sourceStamps=[ss1,ss2]), sourcestampsInBuild=[ss3, ss4]) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - self.expectTriggeredWith(b=({'cb1':ss1, 'cb2':ss2}, {})) - return self.runStep() - - - def test_sourceStamp_prop(self): - self.setupStep(trigger.Trigger(schedulerNames=['b'], - sourceStamp=dict(revision=properties.Property('rev'), - branch='dev'))) - self.properties.setProperty('rev', 602, 'me') - expected_ss = dict(revision=602, branch='dev') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'b']) - self.expectTriggeredWith(b=({'': expected_ss}, {})) - return self.runStep() - - def test_waitForFinish(self): - self.setupStep(trigger.Trigger(schedulerNames=['a', 'b'], - waitForFinish=True)) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a', 'b']) - self.expectTriggeredWith( - a=({}, {}), - b=({}, {})) - self.expectTriggeredLinks('a','b') - return self.runStep(expect_waitForFinish=True) - - def test_waitForFinish_failure(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - waitForFinish=True)) - self.scheduler_a.result = FAILURE - self.expectOutcome(result=FAILURE, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, {})) - self.expectTriggeredLinks('a') - return self.runStep(expect_waitForFinish=True) - - @compat.usesFlushLoggedErrors - def test_waitForFinish_exception(self): - self.setupStep(trigger.Trigger(schedulerNames=['a', 'b'], - waitForFinish=True)) - self.scheduler_b.exception = True - self.expectOutcome(result=EXCEPTION, - status_text=['triggered', 'a', 'b']) - self.expectTriggeredWith( - a=({}, {}), - b=({}, {})) - self.expectTriggeredLinks('a') # b doesn't return a brid - d = self.runStep(expect_waitForFinish=True) - def flush(_): - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - d.addCallback(flush) - return d - - def test_set_properties(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - set_properties=dict(x=1, y=2))) - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, - dict(x=(1, 'Trigger'), y=(2, 'Trigger')))) - return self.runStep() - - def test_set_properties_prop(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - set_properties=dict(x=properties.Property('X'), y=2))) - self.properties.setProperty('X', 'xxx', 'here') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, - dict(x=('xxx', 'Trigger'), y=(2, 'Trigger')))) - return self.runStep() - - def test_copy_properties(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - copy_properties=['a', 'b'])) - self.properties.setProperty('a', 'A', 'AA') - self.properties.setProperty('b', 'B', 'BB') - self.properties.setProperty('c', 'C', 'CC') - self.expectOutcome(result=SUCCESS, status_text=['triggered', 'a']) - self.expectTriggeredWith(a=({}, - dict(a=('A', 'Trigger'), - b=('B', 'Trigger')))) - return self.runStep() - - def test_interrupt(self): - self.setupStep(trigger.Trigger(schedulerNames=['a'], - waitForFinish=True)) - self.expectOutcome(result=EXCEPTION, status_text=['interrupted']) - self.expectTriggeredWith(a=({}, {})) - d = self.runStep(expect_waitForFinish=True) - - # interrupt before the callLater representing the Triggerable - # schedulers completes - self.step.interrupt(failure.Failure(RuntimeError('oh noes'))) - - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_vstudio.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_vstudio.py deleted file mode 100644 index d2cfcb63..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_steps_vstudio.py +++ /dev/null @@ -1,824 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from buildbot.status.results import SUCCESS, FAILURE, WARNINGS -from buildbot.steps import vstudio -from buildbot.test.fake.remotecommand import ExpectShell -from buildbot.test.util import steps -from twisted.trial import unittest -from buildbot.process.properties import Property - -from mock import Mock - -real_log = r""" -1>------ Build started: Project: lib1, Configuration: debug Win32 ------ -1>Compiling... -1>SystemLog.cpp -1>c:\absolute\path\to\systemlog.cpp(7) : warning C4100: 'op' : unreferenced formal parameter -1>c:\absolute\path\to\systemlog.cpp(12) : warning C4100: 'statusword' : unreferenced formal parameter -1>c:\absolute\path\to\systemlog.cpp(12) : warning C4100: 'op' : unreferenced formal parameter -1>c:\absolute\path\to\systemlog.cpp(17) : warning C4100: 'retryCounter' : unreferenced formal parameter -1>c:\absolute\path\to\systemlog.cpp(17) : warning C4100: 'op' : unreferenced formal parameter -1>c:\absolute\path\to\systemlog.cpp(22) : warning C4100: 'op' : unreferenced formal parameter -1>Creating library... -1>Build log was saved at "file://c:\another\absolute\path\to\debug\BuildLog.htm" -1>lib1 - 0 error(s), 6 warning(s) -2>------ Build started: Project: product, Configuration: debug Win32 ------ -2>Linking... -2>LINK : fatal error LNK1168: cannot open ../../debug/directory/dllname.dll for writing -2>Build log was saved at "file://c:\another\similar\path\to\debug\BuildLog.htm" -2>product - 1 error(s), 0 warning(s) -========== Build: 1 succeeded, 1 failed, 6 up-to-date, 0 skipped ========== -""" - -class TestAddEnvPath(unittest.TestCase): - - def do_test(self, initial_env, name, value, expected_env): - vstudio.addEnvPath(initial_env, name, value) - self.assertEqual(initial_env, expected_env) - - def test_new(self): - self.do_test({}, 'PATH', r'C:\NOTHING', - { 'PATH' : r'C:\NOTHING;' }) - - def test_new_semi(self): - self.do_test({}, 'PATH', r'C:\NOTHING;', - { 'PATH' : r'C:\NOTHING;' }) - - def test_existing(self): - self.do_test({'PATH' : '/bin' }, 'PATH', r'C:\NOTHING', - { 'PATH' : r'/bin;C:\NOTHING;' }) - - def test_existing_semi(self): - self.do_test({'PATH' : '/bin;' }, 'PATH', r'C:\NOTHING', - { 'PATH' : r'/bin;C:\NOTHING;' }) - - def test_existing_both_semi(self): - self.do_test({'PATH' : '/bin;' }, 'PATH', r'C:\NOTHING;', - { 'PATH' : r'/bin;C:\NOTHING;' }) - - -class MSLogLineObserver(unittest.TestCase): - - def setUp(self): - self.warnings = [] - lw = Mock() - lw.addStdout = lambda l : self.warnings.append(l.rstrip()) - - self.errors = [] - self.errors_stderr = [] - le = Mock() - le.addStdout = lambda l : self.errors.append(('o', l.rstrip())) - le.addStderr = lambda l : self.errors.append(('e', l.rstrip())) - - self.llo = vstudio.MSLogLineObserver(lw, le) - - self.progress = {} - self.llo.step = Mock() - self.llo.step.setProgress = \ - lambda n,prog : self.progress.__setitem__(n, prog) - - def receiveLines(self, *lines): - for line in lines: - self.llo.outLineReceived(line) - - def assertResult(self, nbFiles=0, nbProjects=0, nbWarnings=0, nbErrors=0, - errors=[], warnings=[], progress={}): - self.assertEqual( - dict(nbFiles=self.llo.nbFiles, nbProjects=self.llo.nbProjects, - nbWarnings=self.llo.nbWarnings, - nbErrors=self.llo.nbErrors, errors=self.errors, - warnings=self.warnings, progress=self.progress), - dict(nbFiles=nbFiles, nbProjects=nbProjects, nbWarnings=nbWarnings, - nbErrors=nbErrors, errors=errors, - warnings=warnings, progress=progress)) - - def test_outLineReceived_empty(self): - self.llo.outLineReceived('abcd\r\n') - self.assertResult() - - def test_outLineReceived_projects(self): - lines = [ - "123>----- some project 1 -----", - "123>----- some project 2 -----", - ] - self.receiveLines(*lines) - self.assertResult(nbProjects=2, progress=dict(projects=2), - errors=[ ('o', l) for l in lines ], - warnings=lines) - - def test_outLineReceived_files(self): - lines = [ - "123>SomeClass.cpp", - "123>SomeStuff.c", - "123>SomeStuff.h", # .h files not recognized - ] - self.receiveLines(*lines) - self.assertResult(nbFiles=2, progress=dict(files=2)) - - def test_outLineReceived_warnings(self): - lines = [ - "abc: warning ABC123: xyz!", - "def : warning DEF456: wxy!", - ] - self.receiveLines(*lines) - self.assertResult(nbWarnings=2, progress=dict(warnings=2), - warnings=lines) - - def test_outLineReceived_errors(self): - lines = [ - "error ABC123: foo", - " error DEF456 : bar", - " error : bar", - " error: bar", # NOTE: not matched - ] - self.receiveLines(*lines) - self.assertResult(nbErrors=3, # note: no progress - errors=[ - ('e', "error ABC123: foo"), - ('e', " error DEF456 : bar"), - ('e', " error : bar"), - ]) - - def test_outLineReceived_real(self): - # based on a real logfile donated by Ben Allard - lines = real_log.split("\n") - self.receiveLines(*lines) - errors = [ - ('o', '1>------ Build started: Project: lib1, Configuration: debug Win32 ------'), - ('o', '2>------ Build started: Project: product, Configuration: debug Win32 ------'), - ('e', '2>LINK : fatal error LNK1168: cannot open ../../debug/directory/dllname.dll for writing') - ] - warnings = [ - '1>------ Build started: Project: lib1, Configuration: debug Win32 ------', - "1>c:\\absolute\\path\\to\\systemlog.cpp(7) : warning C4100: 'op' : unreferenced formal parameter", - "1>c:\\absolute\\path\\to\\systemlog.cpp(12) : warning C4100: 'statusword' : unreferenced formal parameter", - "1>c:\\absolute\\path\\to\\systemlog.cpp(12) : warning C4100: 'op' : unreferenced formal parameter", - "1>c:\\absolute\\path\\to\\systemlog.cpp(17) : warning C4100: 'retryCounter' : unreferenced formal parameter", - "1>c:\\absolute\\path\\to\\systemlog.cpp(17) : warning C4100: 'op' : unreferenced formal parameter", - "1>c:\\absolute\\path\\to\\systemlog.cpp(22) : warning C4100: 'op' : unreferenced formal parameter", - '2>------ Build started: Project: product, Configuration: debug Win32 ------', - ] - self.assertResult(nbFiles=1, nbErrors=1, nbProjects=2, nbWarnings=6, - progress={'files': 1, 'projects': 2, 'warnings': 6}, - errors=errors, warnings=warnings) - -class VCx(vstudio.VisualStudio): - - def start(self): - command = ["command", "here"] - self.setCommand(command) - return vstudio.VisualStudio.start(self) - -class VisualStudio(steps.BuildStepMixin, unittest.TestCase): - """ - Test L{VisualStudio} with a simple subclass, L{VCx}. - """ - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_default_config(self): - vs = vstudio.VisualStudio() - self.assertEqual(vs.config, 'release') - - def test_simple(self): - self.setupStep(VCx()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_installdir(self): - self.setupStep(VCx(installdir=r'C:\I')) - self.step.exp_installdir = r'C:\I' - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - d = self.runStep() - def check_installdir(_): - self.assertEqual(self.step.installdir, r'C:\I') - d.addCallback(check_installdir) - return d - - def test_evaluateCommand_failure(self): - self.setupStep(VCx()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + 1 - ) - self.expectOutcome(result=FAILURE, - status_text=["compile", "0 projects", "0 files", "failed"]) - return self.runStep() - - def test_evaluateCommand_errors(self): - self.setupStep(VCx()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + ExpectShell.log('stdio', - stdout='error ABC123: foo\r\n') - + 0 - ) - self.expectOutcome(result=FAILURE, - status_text=["compile", "0 projects", "0 files", - "1 errors", "failed"]) - return self.runStep() - - def test_evaluateCommand_warnings(self): - self.setupStep(VCx()) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + ExpectShell.log('stdio', - stdout='foo: warning ABC123: foo\r\n') - + 0 - ) - self.expectOutcome(result=WARNINGS, - status_text=["compile", "0 projects", "0 files", - "1 warnings", "warnings"]) - return self.runStep() - - def test_env_setup(self): - self.setupStep(VCx( - INCLUDE=[ r'c:\INC1', r'c:\INC2' ], - LIB=[ r'c:\LIB1', r'C:\LIB2' ], - PATH=[ r'c:\P1', r'C:\P2' ])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here'], - env=dict( - INCLUDE=r'c:\INC1;c:\INC2;', - LIB=r'c:\LIB1;C:\LIB2;', - PATH=r'c:\P1;C:\P2;')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_env_setup_existing(self): - self.setupStep(VCx( - INCLUDE=[ r'c:\INC1', r'c:\INC2' ], - LIB=[ r'c:\LIB1', r'C:\LIB2' ], - PATH=[ r'c:\P1', r'C:\P2' ])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here'], - env=dict( - INCLUDE=r'c:\INC1;c:\INC2;', - LIB=r'c:\LIB1;C:\LIB2;', - PATH=r'c:\P1;C:\P2;')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_rendering(self): - self.setupStep(VCx( - projectfile=Property('a'), - config=Property('b'), - project=Property('c'))) - self.properties.setProperty('a', 'aa', 'Test') - self.properties.setProperty('b', 'bb', 'Test') - self.properties.setProperty('c', 'cc', 'Test') - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['command', 'here']) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - d = self.runStep() - def check_props(_): - self.assertEqual( - [ self.step.projectfile, self.step.config, self.step.project ], - [ 'aa', 'bb', 'cc' ]) - d.addCallback(check_props) - return d - - -class TestVC6(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def getExpectedEnv(self, installdir, l=None, p=None, i=None): - include = [ - installdir + r'\VC98\INCLUDE;', - installdir + r'\VC98\ATL\INCLUDE;', - installdir + r'\VC98\MFC\INCLUDE;', - ] - lib = [ - installdir + r'\VC98\LIB;', - installdir + r'\VC98\MFC\LIB;', - ] - path = [ - installdir + r'\Common\msdev98\BIN;', - installdir + r'\VC98\BIN;', - installdir + r'\Common\TOOLS\WINNT;', - installdir + r'\Common\TOOLS;', - ] - if p: - path.insert(0, '%s;' % p) - if i: - include.insert(0, '%s;' % i) - if l: - lib.insert(0, '%s;' % l) - return dict( - INCLUDE = ''.join(include), - LIB = ''.join(lib), - PATH = ''.join(path), - ) - - def test_args(self): - self.setupStep(vstudio.VC6(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['msdev', 'pf', '/MAKE', - 'pj - cfg', '/REBUILD'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_clean(self): - self.setupStep(vstudio.VC6(projectfile='pf', config='cfg', - project='pj', mode='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['msdev', 'pf', '/MAKE', - 'pj - cfg', '/CLEAN'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_noproj_build(self): - self.setupStep(vstudio.VC6(projectfile='pf', config='cfg', - mode='build')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['msdev', 'pf', '/MAKE', - 'ALL - cfg', '/BUILD'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_env_prepend(self): - self.setupStep(vstudio.VC6(projectfile='pf', config='cfg', - project='pj', PATH=['p'], INCLUDE=['i'], - LIB=['l'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['msdev', 'pf', '/MAKE', - 'pj - cfg', '/REBUILD', - '/USEENV'], # note extra param - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio', - l='l', p='p', i='i')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class TestVC7(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def getExpectedEnv(self, installdir, l=None, p=None, i=None): - include = [ - installdir + r'\VC7\INCLUDE;', - installdir + r'\VC7\ATLMFC\INCLUDE;', - installdir + r'\VC7\PlatformSDK\include;', - installdir + r'\SDK\v1.1\include;', - ] - lib = [ - installdir + r'\VC7\LIB;', - installdir + r'\VC7\ATLMFC\LIB;', - installdir + r'\VC7\PlatformSDK\lib;', - installdir + r'\SDK\v1.1\lib;', - ] - path = [ - installdir + r'\Common7\IDE;', - installdir + r'\VC7\BIN;', - installdir + r'\Common7\Tools;', - installdir + r'\Common7\Tools\bin;', - ] - if p: - path.insert(0, '%s;' % p) - if i: - include.insert(0, '%s;' % i) - if l: - lib.insert(0, '%s;' % l) - return dict( - INCLUDE = ''.join(include), - LIB = ''.join(lib), - PATH = ''.join(path), - ) - - def test_args(self): - self.setupStep(vstudio.VC7(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', 'cfg', - '/Project', 'pj'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio .NET 2003')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_clean(self): - self.setupStep(vstudio.VC7(projectfile='pf', config='cfg', - project='pj', mode='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Clean', 'cfg', - '/Project', 'pj'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio .NET 2003')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_noproj_build(self): - self.setupStep(vstudio.VC7(projectfile='pf', config='cfg', - mode='build')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Build', 'cfg'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio .NET 2003')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_env_prepend(self): - self.setupStep(vstudio.VC7(projectfile='pf', config='cfg', - project='pj', PATH=['p'], INCLUDE=['i'], - LIB=['l'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', 'cfg', - '/UseEnv', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio .NET 2003', - l='l', p='p', i='i')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class VC8ExpectedEnvMixin(object): - # used for VC8 and VC9Express - def getExpectedEnv(self, installdir, x64=False, l=None, i=None, p=None): - include = [ - installdir + r'\VC\INCLUDE;', - installdir + r'\VC\ATLMFC\include;', - installdir + r'\VC\PlatformSDK\include;', - ] - lib = [ - installdir + r'\VC\LIB;', - installdir + r'\VC\ATLMFC\LIB;', - installdir + r'\VC\PlatformSDK\lib;', - installdir + r'\SDK\v2.0\lib;', - ] - path = [ - installdir + r'\Common7\IDE;', - installdir + r'\VC\BIN;', - installdir + r'\Common7\Tools;', - installdir + r'\Common7\Tools\bin;', - installdir + r'\VC\PlatformSDK\bin;', - installdir + r'\SDK\v2.0\bin;', - installdir + r'\VC\VCPackages;', - r'${PATH};', - ] - if x64: - path.insert(1, installdir + r'\VC\BIN\x86_amd64;') - lib = [ lb[:-1] + r'\amd64;' for lb in lib ] - if l: - lib.insert(0, '%s;' % l) - if p: - path.insert(0, '%s;' % p) - if i: - include.insert(0, '%s;' % i) - return dict( - INCLUDE = ''.join(include), - LIB = ''.join(lib), - PATH = ''.join(path), - ) - -class TestVC8(VC8ExpectedEnvMixin, steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_args(self): - self.setupStep(vstudio.VC8(projectfile='pf', config='cfg', - project='pj', arch='arch')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 8')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_args_x64(self): - self.setupStep(vstudio.VC8(projectfile='pf', config='cfg', - project='pj', arch='x64')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 8', - x64=True)) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_clean(self): - self.setupStep(vstudio.VC8(projectfile='pf', config='cfg', - project='pj', mode='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Clean', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 8')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_rendering(self): - self.setupStep(vstudio.VC8(projectfile='pf', config='cfg', - arch=Property('a'))) - self.properties.setProperty('a', 'x64', 'Test') - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', 'cfg'], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 8', - x64=True)) # property has expected effect - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - d = self.runStep() - def check_props(_): - self.assertEqual(self.step.arch, 'x64') - d.addCallback(check_props) - return d - - -class TestVCExpress9(VC8ExpectedEnvMixin, steps.BuildStepMixin, - unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_args(self): - self.setupStep(vstudio.VCExpress9(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['vcexpress', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - # note: still uses version 8 (?!) - r'C:\Program Files\Microsoft Visual Studio 8')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_clean(self): - self.setupStep(vstudio.VCExpress9(projectfile='pf', config='cfg', - project='pj', mode='clean')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['vcexpress', 'pf', '/Clean', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - # note: still uses version 8 (?!) - r'C:\Program Files\Microsoft Visual Studio 8')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - def test_mode_build_env(self): - self.setupStep(vstudio.VCExpress9(projectfile='pf', config='cfg', - project='pj', mode='build', INCLUDE=['i'])) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['vcexpress', 'pf', '/Build', - 'cfg', '/UseEnv', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 8', - i='i')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class TestVC9(VC8ExpectedEnvMixin, steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_installdir(self): - self.setupStep(vstudio.VC9(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 9.0')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class TestVC10(VC8ExpectedEnvMixin, steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_installdir(self): - self.setupStep(vstudio.VC10(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 10.0')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class TestVC11(VC8ExpectedEnvMixin, steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_installdir(self): - self.setupStep(vstudio.VC11(projectfile='pf', config='cfg', - project='pj')) - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['devenv.com', 'pf', '/Rebuild', - 'cfg', '/Project', 'pj' ], - env=self.getExpectedEnv( - r'C:\Program Files\Microsoft Visual Studio 11.0')) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["compile", "0 projects", "0 files"]) - return self.runStep() - - -class TestMsBuild(steps.BuildStepMixin, unittest.TestCase): - - def setUp(self): - return self.setUpBuildStep() - - def tearDown(self): - return self.tearDownBuildStep() - - def test_build_project(self): - self.setupStep(vstudio.MsBuild(projectfile='pf', config='cfg', platform='Win32', project='pj')) - - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['%VCENV_BAT%', 'x86', '&&', - 'msbuild', 'pf', '/p:Configuration=cfg', '/p:Platform=Win32', - '/t:pj'], - env={'VCENV_BAT': '"${VS110COMNTOOLS}..\\..\\VC\\vcvarsall.bat"'}) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["built", "pj for", 'cfg|Win32']) - return self.runStep() - - def test_build_solution(self): - self.setupStep(vstudio.MsBuild(projectfile='pf', config='cfg', platform='x64')) - - self.expectCommands( - ExpectShell(workdir='wkdir', usePTY='slave-config', - command=['%VCENV_BAT%', 'x86', '&&', - 'msbuild', 'pf', '/p:Configuration=cfg', '/p:Platform=x64'], - env={'VCENV_BAT': '"${VS110COMNTOOLS}..\\..\\VC\\vcvarsall.bat"'}) - + 0 - ) - self.expectOutcome(result=SUCCESS, - status_text=["built", "solution for", 'cfg|x64']) - return self.runStep() - - -class Aliases(unittest.TestCase): - - def test_vs2003(self): - self.assertIdentical(vstudio.VS2003, vstudio.VC7) - - def test_vs2005(self): - self.assertIdentical(vstudio.VS2005, vstudio.VC8) - - def test_vs2008(self): - self.assertIdentical(vstudio.VS2008, vstudio.VC9) - - def test_vs2010(self): - self.assertIdentical(vstudio.VS2010, vstudio.VC10) - - def test_vs2012(self): - self.assertIdentical(vstudio.VS2012, vstudio.VC11) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_test_util_gpo.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_test_util_gpo.py deleted file mode 100644 index 3b6a90f9..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_test_util_gpo.py +++ /dev/null @@ -1,323 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import sys -import twisted -from twisted.trial import reporter, unittest -from twisted.internet import utils -from buildbot.test.util.gpo import GetProcessOutputMixin, Expect - -class TestGPOMixin(unittest.TestCase): - - # these tests use self.patch, but the SkipTest exception gets eaten, so - # explicitly skip things here. - if twisted.version.major <= 9 and sys.version_info[:2] == (2,7): - skip = "unittest.TestCase.patch is not available" - - def runTestMethod(self, method): - class TestCase(GetProcessOutputMixin, unittest.TestCase): - def setUp(self): - self.setUpGetProcessOutput() - def runTest(self): - return method(self) - self.testcase = TestCase() - result = reporter.TestResult() - self.testcase.run(result) # This blocks - return result - - def assertTestFailure(self, result, expectedFailure): - self.assertEqual(result.errors, []) - self.assertEqual(len(result.failures), 1) - self.failUnless(result.failures[0][1].check(unittest.FailTest)) - if expectedFailure: - self.assertSubstring(expectedFailure, result.failures[0][1].getErrorMessage()) - - def assertSuccessful(self, result): - if not result.wasSuccessful(): - output = 'expected success' - if result.failures: - output += ('\ntest failed: %s' % - result.failures[0][1].getErrorMessage()) - if result.errors: - output += ('\nerrors: %s' % - map(lambda x: x[1].value, result.errors)) - raise self.failureException(output) - - self.failUnless(result.wasSuccessful()) - - def test_patch(self): - original_getProcessOutput = utils.getProcessOutput - original_getProcessOutputAndValue = utils.getProcessOutputAndValue - def method(testcase): - testcase.expectCommands() - self.assertEqual(utils.getProcessOutput, - testcase.patched_getProcessOutput) - self.assertEqual(utils.getProcessOutputAndValue, - testcase.patched_getProcessOutputAndValue) - result = self.runTestMethod(method) - self.assertSuccessful(result) - self.assertEqual(utils.getProcessOutput, - original_getProcessOutput) - self.assertEqual(utils.getProcessOutputAndValue, - original_getProcessOutputAndValue) - - def test_methodChaining(self): - expect = Expect('command') - self.assertEqual(expect, expect.exit(0)) - self.assertEqual(expect, expect.stdout("output")) - self.assertEqual(expect, expect.stderr("error")) - - def test_gpo_oneCommand(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - d = utils.getProcessOutput("command", ()) - d.addCallback(self.assertEqual, '') - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_expectTwo_runOne(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - testcase.expectCommands(Expect("command2")) - d = utils.getProcessOutput("command", ()) - d.addCallback(self.assertEqual, '') - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "assert all expected commands were run") - - def test_gpo_wrongCommand(self): - def method(testcase): - testcase.expectCommands(Expect("command2")) - d = utils.getProcessOutput("command", ()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpo_wrongArgs(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg")) - d = utils.getProcessOutput("command", ("otherarg",)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpo_missingPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg").path("/home")) - d = utils.getProcessOutput("command", ("otherarg",)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpo_wrongPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg").path("/home")) - d = utils.getProcessOutput("command", ("otherarg",), path="/work") - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpo_notCurrentPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg")) - d = utils.getProcessOutput("command", ("otherarg",), path="/work") - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpo_errorOutput(self): - def method(testcase): - testcase.expectCommands(Expect("command").stderr("some test")) - d = testcase.assertFailure(utils.getProcessOutput("command", ()), [IOError]) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "got stderr: 'some test'") - - def test_gpo_errorOutput_errtoo(self): - def method(testcase): - testcase.expectCommands(Expect("command").stderr("some test")) - d = utils.getProcessOutput("command", (), errortoo=True) - d.addCallback(testcase.assertEqual, "some test") - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_exitIgnored(self): - def method(testcase): - testcase.expectCommands(Expect("command").exit(1)) - d = utils.getProcessOutput("command", ()) - d.addCallback(self.assertEqual, '') - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_output(self): - def method(testcase): - testcase.expectCommands(Expect("command").stdout("stdout")) - d = utils.getProcessOutput("command", ()) - d.addCallback(testcase.assertEqual, "stdout") - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_outputAndError(self): - def method(testcase): - testcase.expectCommands(Expect("command").stdout("stdout").stderr("stderr")) - d = utils.getProcessOutput("command", (), errortoo=True) - @d.addCallback - def cb(res): - testcase.assertSubstring("stdout", res) - testcase.assertSubstring("stderr", res) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_environ_success(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - testcase.addGetProcessOutputExpectEnv({'key': 'value'}) - d = utils.getProcessOutput("command", (), env={'key': 'value'}) - d.addCallback(self.assertEqual, '') - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpo_environ_wrongValue(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - testcase.addGetProcessOutputExpectEnv({'key': 'value'}) - d = utils.getProcessOutput("command", (), env={'key': 'wrongvalue'}) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "Expected environment to have key = 'value'") - - def test_gpo_environ_missing(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - testcase.addGetProcessOutputExpectEnv({'key': 'value'}) - d = utils.getProcessOutput("command", ()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "Expected environment to have key = 'value'") - - def test_gpoav_oneCommand(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(self.assertEqual, ('','',0)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpoav_expectTwo_runOne(self): - def method(testcase): - testcase.expectCommands(Expect("command")) - testcase.expectCommands(Expect("command2")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(self.assertEqual, ('','',0)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "assert all expected commands were run") - - def test_gpoav_wrongCommand(self): - def method(testcase): - testcase.expectCommands(Expect("command2")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpoav_wrongArgs(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg")) - d = utils.getProcessOutputAndValue("command", ("otherarg",)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpoav_missingPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg").path("/home")) - d = utils.getProcessOutputAndValue("command", ("otherarg",)) - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpoav_wrongPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg").path("/home")) - d = utils.getProcessOutputAndValue("command", ("otherarg",), path="/work") - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpoav_notCurrentPath(self): - def method(testcase): - testcase.expectCommands(Expect("command", "arg")) - d = utils.getProcessOutputAndValue("command", ("otherarg",), path="/work") - d.addCallback(lambda _: testcase.assertAllCommandsRan()) - return d - result = self.runTestMethod(method) - self.assertTestFailure(result, "unexpected command run") - - def test_gpoav_errorOutput(self): - def method(testcase): - testcase.expectCommands(Expect("command").stderr("some test")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(self.assertEqual, ('','some test',0)) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpoav_exit(self): - def method(testcase): - testcase.expectCommands(Expect("command").exit(1)) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(self.assertEqual, ('','',1)) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpoav_output(self): - def method(testcase): - testcase.expectCommands(Expect("command").stdout("stdout")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(testcase.assertEqual, ("stdout",'',0)) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) - - def test_gpoav_outputAndError(self): - def method(testcase): - testcase.expectCommands(Expect("command").stdout("stdout").stderr("stderr")) - d = utils.getProcessOutputAndValue("command", ()) - d.addCallback(testcase.assertEqual, ("stdout",'stderr',0)) - return d - result = self.runTestMethod(method) - self.assertSuccessful(result) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util.py deleted file mode 100644 index 8411e92c..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util.py +++ /dev/null @@ -1,194 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import datetime - -from twisted.trial import unittest - -from buildbot import util - -class formatInterval(unittest.TestCase): - - def test_zero(self): - self.assertEqual(util.formatInterval(0), "0 secs") - - def test_seconds_singular(self): - self.assertEqual(util.formatInterval(1), "1 secs") - - def test_seconds(self): - self.assertEqual(util.formatInterval(7), "7 secs") - - def test_minutes_one(self): - self.assertEqual(util.formatInterval(60), "60 secs") - - def test_minutes_over_one(self): - self.assertEqual(util.formatInterval(61), "1 mins, 1 secs") - - def test_minutes(self): - self.assertEqual(util.formatInterval(300), "5 mins, 0 secs") - - def test_hours_one(self): - self.assertEqual(util.formatInterval(3600), "60 mins, 0 secs") - - def test_hours_over_one_sec(self): - self.assertEqual(util.formatInterval(3601), "1 hrs, 1 secs") - - def test_hours_over_one_min(self): - self.assertEqual(util.formatInterval(3660), "1 hrs, 60 secs") - - def test_hours(self): - self.assertEqual(util.formatInterval(7200), "2 hrs, 0 secs") - - def test_mixed(self): - self.assertEqual(util.formatInterval(7392), "2 hrs, 3 mins, 12 secs") - -class safeTranslate(unittest.TestCase): - - def test_str_good(self): - self.assertEqual(util.safeTranslate(str("full")), str("full")) - - def test_str_bad(self): - self.assertEqual(util.safeTranslate(str("speed=slow;quality=high")), - str("speed_slow_quality_high")) - - def test_str_pathological(self): - # if you needed proof this wasn't for use with sensitive data - self.assertEqual(util.safeTranslate(str("p\ath\x01ogy")), - str("p\ath\x01ogy")) # bad chars still here! - - def test_unicode_good(self): - self.assertEqual(util.safeTranslate(u"full"), str("full")) - - def test_unicode_bad(self): - self.assertEqual(util.safeTranslate(unicode("speed=slow;quality=high")), - str("speed_slow_quality_high")) - - def test_unicode_pathological(self): - self.assertEqual(util.safeTranslate(u"\u0109"), - str("\xc4\x89")) # yuck! - -class naturalSort(unittest.TestCase): - - def test_alpha(self): - self.assertEqual( - util.naturalSort(['x', 'aa', 'ab']), - ['aa', 'ab', 'x']) - - def test_numeric(self): - self.assertEqual( - util.naturalSort(['1', '10', '11', '2', '20']), - ['1', '2', '10', '11', '20']) - - def test_alphanum(self): - l1 = 'aa10ab aa1ab aa10aa f a aa3 aa30 aa3a aa30a'.split() - l2 = 'a aa1ab aa3 aa3a aa10aa aa10ab aa30 aa30a f'.split() - self.assertEqual(util.naturalSort(l1), l2) - -class none_or_str(unittest.TestCase): - - def test_none(self): - self.assertEqual(util.none_or_str(None), None) - - def test_str(self): - self.assertEqual(util.none_or_str("hi"), "hi") - - def test_int(self): - self.assertEqual(util.none_or_str(199), "199") - -class TimeFunctions(unittest.TestCase): - - def test_UTC(self): - self.assertEqual(util.UTC.utcoffset(datetime.datetime.now()), - datetime.timedelta(0)) - self.assertEqual(util.UTC.dst(datetime.datetime.now()), - datetime.timedelta(0)) - self.assertEqual(util.UTC.tzname(), "UTC") - - def test_epoch2datetime(self): - self.assertEqual(util.epoch2datetime(0), - datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=util.UTC)) - self.assertEqual(util.epoch2datetime(1300000000), - datetime.datetime(2011, 3, 13, 7, 6, 40, tzinfo=util.UTC)) - - def test_datetime2epoch(self): - dt = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=util.UTC) - self.assertEqual(util.datetime2epoch(dt), 0) - dt = datetime.datetime(2011, 3, 13, 7, 6, 40, tzinfo=util.UTC) - self.assertEqual(util.datetime2epoch(dt), 1300000000) - -class DiffSets(unittest.TestCase): - - def test_empty(self): - removed, added = util.diffSets(set([]), set([])) - self.assertEqual((removed, added), (set([]), set([]))) - - def test_no_lists(self): - removed, added = util.diffSets([1, 2], [2, 3]) - self.assertEqual((removed, added), (set([1]), set([3]))) - - def test_no_overlap(self): - removed, added = util.diffSets(set([1, 2]), set([3, 4])) - self.assertEqual((removed, added), (set([1, 2]), set([3, 4]))) - - def test_no_change(self): - removed, added = util.diffSets(set([1, 2]), set([1, 2])) - self.assertEqual((removed, added), (set([]), set([]))) - - def test_added(self): - removed, added = util.diffSets(set([1, 2]), set([1, 2, 3])) - self.assertEqual((removed, added), (set([]), set([3]))) - - def test_removed(self): - removed, added = util.diffSets(set([1, 2]), set([1])) - self.assertEqual((removed, added), (set([2]), set([]))) - -class MakeList(unittest.TestCase): - - def test_empty_string(self): - self.assertEqual(util.makeList(''), [ '' ]) - - def test_None(self): - self.assertEqual(util.makeList(None), [ ]) - - def test_string(self): - self.assertEqual(util.makeList('hello'), [ 'hello' ]) - - def test_unicode(self): - self.assertEqual(util.makeList(u'\N{SNOWMAN}'), [ u'\N{SNOWMAN}' ]) - - def test_list(self): - self.assertEqual(util.makeList(['a','b']), [ 'a', 'b' ]) - - def test_tuple(self): - self.assertEqual(util.makeList(('a','b')), [ 'a', 'b' ]) - - def test_copy(self): - input = ['a', 'b'] - output = util.makeList(input) - input.append('c') - self.assertEqual(output, [ 'a', 'b' ]) - -class Flatten(unittest.TestCase): - - def test_simple(self): - self.assertEqual(util.flatten([1, 2, 3]), [1, 2, 3]) - - def test_deep(self): - self.assertEqual(util.flatten([ [ 1, 2 ], 3, [ [ 4 ] ] ]), - [1, 2, 3, 4]) - - def test_tuples(self): - self.assertEqual(util.flatten([ ( 1, 2 ), 3 ]), [ (1, 2), 3 ]) - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_ComparableMixin.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_ComparableMixin.py deleted file mode 100644 index a7c34de0..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_ComparableMixin.py +++ /dev/null @@ -1,72 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - - -from twisted.trial import unittest - -from buildbot import util - - -class ComparableMixin(unittest.TestCase): - class Foo(util.ComparableMixin): - compare_attrs = ["a", "b"] - def __init__(self, a, b, c): - self.a, self.b, self.c = a,b,c - - class Bar(Foo, util.ComparableMixin): - compare_attrs = ["b", "c"] - - def setUp(self): - self.f123 = self.Foo(1, 2, 3) - self.f124 = self.Foo(1, 2, 4) - self.f134 = self.Foo(1, 3, 4) - self.b123 = self.Bar(1, 2, 3) - self.b223 = self.Bar(2, 2, 3) - self.b213 = self.Bar(2, 1, 3) - - def test_equality_identity(self): - self.assertEqual(self.f123, self.f123) - - def test_equality_same(self): - another_f123 = self.Foo(1, 2, 3) - self.assertEqual(self.f123, another_f123) - - def test_equality_unimportantDifferences(self): - self.assertEqual(self.f123, self.f124) - - def test_equality_unimportantDifferences_subclass(self): - # verify that the parent class's compare_attrs doesn't - # affect the subclass - self.assertEqual(self.b123, self.b223) - - def test_inequality_importantDifferences(self): - self.assertNotEqual(self.f123, self.f134) - - def test_inequality_importantDifferences_subclass(self): - self.assertNotEqual(self.b123, self.b213) - - def test_inequality_differentClasses(self): - self.assertNotEqual(self.f123, self.b123) - - def test_inequality_sameClass_differentCompareAttrs(self): - another_f123 = self.Foo(1, 2, 3) - another_f123.compare_attrs = ["b", "a"] - self.assertNotEqual(self.f123, another_f123) - - def test_lt_importantDifferences(self): - assert self.f123 < self.f134 - - def test_lt_differentClasses(self): - assert self.b123 < self.f123 diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_bbcollections.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_bbcollections.py deleted file mode 100644 index de3ede52..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_bbcollections.py +++ /dev/null @@ -1,69 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.util import bbcollections - -class KeyedSets(unittest.TestCase): - - def setUp(self): - self.ks = bbcollections.KeyedSets() - - def test_getitem_default(self): - self.assertEqual(self.ks['x'], set()) - # remaining tests effectively cover __getitem__ - - def test_add(self): - self.ks.add('y', 2) - self.assertEqual(self.ks['y'], set([2])) - - def test_add_twice(self): - self.ks.add('z', 2) - self.ks.add('z', 4) - self.assertEqual(self.ks['z'], set([2, 4])) - - def test_discard_noError(self): - self.ks.add('full', 12) - self.ks.discard('empty', 13) # should not fail - self.ks.discard('full', 13) # nor this - self.assertEqual(self.ks['full'], set([12])) - - def test_discard_existing(self): - self.ks.add('yarn', 'red') - self.ks.discard('yarn', 'red') - self.assertEqual(self.ks['yarn'], set([])) - - def test_contains_true(self): - self.ks.add('yarn', 'red') - self.assertTrue('yarn' in self.ks) - - def test_contains_false(self): - self.assertFalse('yarn' in self.ks) - - def test_contains_setNamesNotContents(self): - self.ks.add('yarn', 'red') - self.assertFalse('red' in self.ks) - - def test_pop_exists(self): - self.ks.add('names', 'pop') - self.ks.add('names', 'coke') - self.ks.add('names', 'soda') - popped = self.ks.pop('names') - remaining = self.ks['names'] - self.assertEqual((popped, remaining), - (set(['pop', 'coke', 'soda']), set())) - - def test_pop_missing(self): - self.assertEqual(self.ks.pop('flavors'), set()) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_eventual.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_eventual.py deleted file mode 100644 index fa37ec29..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_eventual.py +++ /dev/null @@ -1,108 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from twisted.internet import defer -from twisted.python import log - -from buildbot.util import eventual - -class Eventually(unittest.TestCase): - - def setUp(self): - # reset the queue to its base state - eventual._theSimpleQueue = eventual._SimpleCallQueue() - self.old_log_err = log.err - self.results = [] - - def tearDown(self): - log.err = self.old_log_err - return eventual.flushEventualQueue() - - # utility callback - def cb(self, *args, **kwargs): - r = args - if kwargs: r = r + (kwargs,) - self.results.append(r) - - # flush the queue and assert results - def assertResults(self, exp): - d = eventual.flushEventualQueue() - def cb(_): - self.assertEqual(self.results, exp) - d.addCallback(cb) - return d - - ## tests - - def test_eventually_calls(self): - eventual.eventually(self.cb) - return self.assertResults([()]) - - def test_eventually_args(self): - eventual.eventually(self.cb, 1, 2, a='a') - return self.assertResults([(1, 2, dict(a='a'))]) - - def test_eventually_err(self): - # monkey-patch log.err; this is restored by tearDown - log.err = lambda : self.results.append("err") - def cb_fails(): - raise RuntimeError("should not cause test failure") - eventual.eventually(cb_fails) - return self.assertResults(['err']) - - def test_eventually_butNotNow(self): - eventual.eventually(self.cb, 1) - self.failIf(self.results != []) - return self.assertResults([(1,)]) - - def test_eventually_order(self): - eventual.eventually(self.cb, 1) - eventual.eventually(self.cb, 2) - eventual.eventually(self.cb, 3) - return self.assertResults([(1,), (2,), (3,)]) - - def test_flush_waitForChainedEventuallies(self): - def chain(n): - self.results.append(n) - if n <= 0: return - eventual.eventually(chain, n-1) - chain(3) - # (the flush this tests is implicit in assertResults) - return self.assertResults([3, 2, 1, 0]) - - def test_flush_waitForTreeEventuallies(self): - # a more complex set of eventualities - def tree(n): - self.results.append(n) - if n <= 0: return - eventual.eventually(tree, n-1) - eventual.eventually(tree, n-1) - tree(2) - # (the flush this tests is implicit in assertResults) - return self.assertResults([2, 1, 1, 0, 0, 0, 0]) - - def test_flush_duringTurn(self): - testd = defer.Deferred() - def cb(): - d = eventual.flushEventualQueue() - d.addCallback(testd.callback) - eventual.eventually(cb) - return testd - - def test_fireEventually_call(self): - d = eventual.fireEventually(13) - d.addCallback(self.cb) - return self.assertResults([(13,)]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_lru.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_lru.py deleted file mode 100644 index d67e90d8..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_lru.py +++ /dev/null @@ -1,576 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -import string -import random -import gc -from twisted.trial import unittest -from twisted.internet import defer, reactor -from twisted.python import failure -from buildbot.util import lru - -# construct weakref-able objects for particular keys -def short(k): - return set([k.upper() * 3]) -def long(k): - return set([k.upper() * 6]) - -class LRUCacheTest(unittest.TestCase): - - def setUp(self): - lru.inv_failed = False - self.lru = lru.LRUCache(short, 3) - - def tearDown(self): - self.assertFalse(lru.inv_failed, "invariant failed; see logs") - - def check_result(self, r, exp, exp_hits=None, exp_misses=None, - exp_refhits=None): - self.assertEqual(r, exp) - if exp_hits is not None: - self.assertEqual(self.lru.hits, exp_hits) - if exp_misses is not None: - self.assertEqual(self.lru.misses, exp_misses) - if exp_refhits is not None: - self.assertEqual(self.lru.refhits, exp_refhits) - - def test_single_key(self): - # just get an item - val = self.lru.get('a') - self.check_result(val, short('a'), 0, 1) - - # second time, it should be cached.. - self.lru.miss_fn = long - val = self.lru.get('a') - self.check_result(val, short('a'), 1, 1) - - def test_simple_lru_expulsion(self): - val = self.lru.get('a') - self.check_result(val, short('a'), 0, 1) - val = self.lru.get('b') - self.check_result(val, short('b'), 0, 2) - val = self.lru.get('c') - self.check_result(val, short('c'), 0, 3) - val = self.lru.get('d') - self.check_result(val, short('d'), 0, 4) - del(val) - gc.collect() - - # now try 'a' again - it should be a miss - self.lru.miss_fn = long - val = self.lru.get('a') - self.check_result(val, long('a'), 0, 5) - - # ..and that expelled B, but C is still in the cache - val = self.lru.get('c') - self.check_result(val, short('c'), 1, 5) - - def test_simple_lru_expulsion_maxsize_1(self): - self.lru = lru.LRUCache(short, 1) - val = self.lru.get('a') - self.check_result(val, short('a'), 0, 1) - val = self.lru.get('a') - self.check_result(val, short('a'), 1, 1) - val = self.lru.get('b') - self.check_result(val, short('b'), 1, 2) - del(val) - gc.collect() - - # now try 'a' again - it should be a miss - self.lru.miss_fn = long - val = self.lru.get('a') - self.check_result(val, long('a'), 1, 3) - del(val) - gc.collect() - - # ..and that expelled B - val = self.lru.get('b') - self.check_result(val, long('b'), 1, 4) - - def test_simple_lru_expulsion_maxsize_1_null_result(self): - # a regression test for #2011 - def miss_fn(k): - if k == 'b': - return None - else: - return short(k) - self.lru = lru.LRUCache(miss_fn, 1) - val = self.lru.get('a') - self.check_result(val, short('a'), 0, 1) - val = self.lru.get('b') - self.check_result(val, None, 0, 2) - del(val) - - # 'a' was not expelled since 'b' was None - self.lru.miss_fn = long - val = self.lru.get('a') - self.check_result(val, short('a'), 1, 2) - - def test_queue_collapsing(self): - # just to check that we're practicing with the right queue size (so - # QUEUE_SIZE_FACTOR is 10) - self.assertEqual(self.lru.max_queue, 30) - - for c in 'a' + 'x' * 27 + 'ab': - res = self.lru.get(c) - self.check_result(res, short('b'), 27, 3) - - # at this point, we should have 'x', 'a', and 'b' in the cache, and - # 'axx..xxab' in the queue. - self.assertEqual(len(self.lru.queue), 30) - - # This 'get' operation for an existing key should cause compaction - res = self.lru.get('b') - self.check_result(res, short('b'), 28, 3) - - self.assertEqual(len(self.lru.queue), 3) - - # expect a cached short('a') - self.lru.miss_fn = long - res = self.lru.get('a') - self.check_result(res, short('a'), 29, 3) - - def test_all_misses(self): - for i, c in enumerate(string.lowercase + string.uppercase): - res = self.lru.get(c) - self.check_result(res, short(c), 0, i+1) - - def test_get_exception(self): - def fail_miss_fn(k): - raise RuntimeError("oh noes") - self.lru.miss_fn = fail_miss_fn - - got_exc = False - try: - self.lru.get('abc') - except RuntimeError: - got_exc = True - - self.assertEqual(got_exc, True) - - def test_all_hits(self): - res = self.lru.get('a') - self.check_result(res, short('a'), 0, 1) - - self.lru.miss_fn = long - for i in xrange(100): - res = self.lru.get('a') - self.check_result(res, short('a'), i+1, 1) - - def test_weakrefs(self): - res_a = self.lru.get('a') - self.check_result(res_a, short('a')) - # note that res_a keeps a reference to this value - - res_b = self.lru.get('b') - self.check_result(res_b, short('b')) - del res_b # discard reference to b - - # blow out the cache and the queue - self.lru.miss_fn = long - for c in (string.lowercase[2:] * 5): - self.lru.get(c) - - # and fetch a again, expecting the cached value - res = self.lru.get('a') - self.check_result(res, res_a, exp_refhits=1) - - # but 'b' should give us a new value - res = self.lru.get('b') - self.check_result(res, long('b'), exp_refhits=1) - - def test_fuzz(self): - chars = list(string.lowercase * 40) - random.shuffle(chars) - for i, c in enumerate(chars): - res = self.lru.get(c) - self.check_result(res, short(c)) - - def test_set_max_size(self): - # load up the cache with three items - for c in 'abc': - res = self.lru.get(c) - self.check_result(res, short(c)) - del(res) - - # reset the size to 1 - self.lru.set_max_size(1) - gc.collect() - - # and then expect that 'b' is no longer in the cache - self.lru.miss_fn = long - res = self.lru.get('b') - self.check_result(res, long('b')) - - def test_miss_fn_kwargs(self): - def keep_kwargs_miss_fn(k, **kwargs): - return set(kwargs.keys()) - self.lru.miss_fn = keep_kwargs_miss_fn - - val = self.lru.get('a', a=1, b=2) - self.check_result(val, set(['a', 'b']), 0, 1) - - def test_miss_fn_returns_none(self): - calls = [] - def none_miss_fn(k): - calls.append(k) - return None - self.lru.miss_fn = none_miss_fn - - for i in range(2): - self.assertEqual(self.lru.get('a'), None) - - # check that the miss_fn was called twice - self.assertEqual(calls, ['a', 'a']) - - def test_put(self): - self.assertEqual(self.lru.get('p'), short('p')) - self.lru.put('p', set(['P2P2'])) - self.assertEqual(self.lru.get('p'), set(['P2P2'])) - - def test_put_nonexistent_key(self): - self.assertEqual(self.lru.get('p'), short('p')) - self.lru.put('q', set(['new-q'])) - self.assertEqual(self.lru.get('p'), set(['PPP'])) - self.assertEqual(self.lru.get('q'), set(['QQQ'])) # not updated - - -class AsyncLRUCacheTest(unittest.TestCase): - - def setUp(self): - lru.inv_failed = False - self.lru = lru.AsyncLRUCache(self.short_miss_fn, 3) - - def tearDown(self): - self.assertFalse(lru.inv_failed, "invariant failed; see logs") - - def short_miss_fn(self, key): - return defer.succeed(short(key)) - - def long_miss_fn(self, key): - return defer.succeed(long(key)) - - def failure_miss_fn(self, key): - return defer.succeed(None) - - def check_result(self, r, exp, exp_hits=None, exp_misses=None, - exp_refhits=None): - self.assertEqual(r, exp) - if exp_hits is not None: - self.assertEqual(self.lru.hits, exp_hits) - if exp_misses is not None: - self.assertEqual(self.lru.misses, exp_misses) - if exp_refhits is not None: - self.assertEqual(self.lru.refhits, exp_refhits) - - # tests - - def test_single_key(self): - # just get an item - d = self.lru.get('a') - d.addCallback(self.check_result, short('a'), 0, 1) - - # second time, it should be cached.. - self.lru.miss_fn = self.long_miss_fn - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 1, 1) - return d - - def test_simple_lru_expulsion(self): - d = defer.succeed(None) - - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 0, 1) - d.addCallback(lambda _ : - self.lru.get('b')) - d.addCallback(self.check_result, short('b'), 0, 2) - d.addCallback(lambda _ : - self.lru.get('c')) - d.addCallback(self.check_result, short('c'), 0, 3) - d.addCallback(lambda _ : - self.lru.get('d')) - d.addCallback(self.check_result, short('d'), 0, 4) - - gc.collect() - - # now try 'a' again - it should be a miss - self.lru.miss_fn = self.long_miss_fn - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, long('a'), 0, 5) - - # ..and that expelled B, but C is still in the cache - d.addCallback(lambda _ : - self.lru.get('c')) - d.addCallback(self.check_result, short('c'), 1, 5) - return d - - def test_simple_lru_expulsion_maxsize_1(self): - self.lru = lru.AsyncLRUCache(self.short_miss_fn, 1) - d = defer.succeed(None) - - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 0, 1) - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 1, 1) - d.addCallback(lambda _ : - self.lru.get('b')) - d.addCallback(self.check_result, short('b'), 1, 2) - - gc.collect() - - # now try 'a' again - it should be a miss - self.lru.miss_fn = self.long_miss_fn - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, long('a'), 1, 3) - - gc.collect() - - # ..and that expelled B - d.addCallback(lambda _ : - self.lru.get('b')) - d.addCallback(self.check_result, long('b'), 1, 4) - return d - - def test_simple_lru_expulsion_maxsize_1_null_result(self): - # a regression test for #2011 - def miss_fn(k): - if k == 'b': - return defer.succeed(None) - else: - return defer.succeed(short(k)) - self.lru = lru.AsyncLRUCache(miss_fn, 1) - d = defer.succeed(None) - - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 0, 1) - d.addCallback(lambda _ : - self.lru.get('b')) - d.addCallback(self.check_result, None, 0, 2) - - # 'a' was not expelled since 'b' was None - self.lru.miss_fn = self.long_miss_fn - d.addCallback(lambda _ : - self.lru.get('a')) - d.addCallback(self.check_result, short('a'), 1, 2) - - return d - - @defer.inlineCallbacks - def test_queue_collapsing(self): - # just to check that we're practicing with the right queue size (so - # QUEUE_SIZE_FACTOR is 10) - self.assertEqual(self.lru.max_queue, 30) - - for c in 'a' + 'x' * 27 + 'ab': - res = yield self.lru.get(c) - self.check_result(res, short('b'), 27, 3) - - # at this point, we should have 'x', 'a', and 'b' in the cache, and - # 'axx..xxab' in the queue. - self.assertEqual(len(self.lru.queue), 30) - - # This 'get' operation for an existing key should cause compaction - res = yield self.lru.get('b') - self.check_result(res, short('b'), 28, 3) - - self.assertEqual(len(self.lru.queue), 3) - - # expect a cached short('a') - self.lru.miss_fn = self.long_miss_fn - res = yield self.lru.get('a') - self.check_result(res, short('a'), 29, 3) - - @defer.inlineCallbacks - def test_all_misses(self): - for i, c in enumerate(string.lowercase + string.uppercase): - res = yield self.lru.get(c) - self.check_result(res, short(c), 0, i+1) - - @defer.inlineCallbacks - def test_get_exception(self): - def fail_miss_fn(k): - return defer.fail(RuntimeError("oh noes")) - self.lru.miss_fn = fail_miss_fn - - got_exc = False - try: - yield self.lru.get('abc') - except RuntimeError: - got_exc = True - - self.assertEqual(got_exc, True) - - @defer.inlineCallbacks - def test_all_hits(self): - res = yield self.lru.get('a') - self.check_result(res, short('a'), 0, 1) - - self.lru.miss_fn = self.long_miss_fn - for i in xrange(100): - res = yield self.lru.get('a') - self.check_result(res, short('a'), i+1, 1) - - @defer.inlineCallbacks - def test_weakrefs(self): - res_a = yield self.lru.get('a') - self.check_result(res_a, short('a')) - # note that res_a keeps a reference to this value - - res_b = yield self.lru.get('b') - self.check_result(res_b, short('b')) - del res_b # discard reference to b - - # blow out the cache and the queue - self.lru.miss_fn = self.long_miss_fn - for c in (string.lowercase[2:] * 5): - yield self.lru.get(c) - - # and fetch a again, expecting the cached value - res = yield self.lru.get('a') - self.check_result(res, res_a, exp_refhits=1) - - # but 'b' should give us a new value - res = yield self.lru.get('b') - self.check_result(res, long('b'), exp_refhits=1) - - @defer.inlineCallbacks - def test_fuzz(self): - chars = list(string.lowercase * 40) - random.shuffle(chars) - for i, c in enumerate(chars): - res = yield self.lru.get(c) - self.check_result(res, short(c)) - - def test_massively_parallel(self): - chars = list(string.lowercase * 5) - - misses = [ 0 ] - def slow_short_miss_fn(key): - d = defer.Deferred() - misses[0] += 1 - reactor.callLater(0, lambda : d.callback(short(key))) - return d - self.lru.miss_fn = slow_short_miss_fn - - def check(c, d): - d.addCallback(self.check_result, short(c)) - return d - d = defer.gatherResults([ - check(c, self.lru.get(c)) - for c in chars ]) - def post_check(_): - self.assertEqual(misses[0], 26) - self.assertEqual(self.lru.misses, 26) - self.assertEqual(self.lru.hits, 4*26) - d.addCallback(post_check) - return d - - def test_slow_fetch(self): - def slower_miss_fn(k): - d = defer.Deferred() - reactor.callLater(0.05, lambda : d.callback(short(k))) - return d - self.lru.miss_fn = slower_miss_fn - - def do_get(test_d, k): - d = self.lru.get(k) - d.addCallback(self.check_result, short(k)) - d.addCallbacks(test_d.callback, test_d.errback) - - ds = [] - for i in range(8): - d = defer.Deferred() - reactor.callLater(0.02*i, do_get, d, 'x') - ds.append(d) - - d = defer.gatherResults(ds) - def check(_): - self.assertEqual((self.lru.hits, self.lru.misses), (7, 1)) - d.addCallback(check) - return d - - def test_slow_failure(self): - def slow_fail_miss_fn(k): - d = defer.Deferred() - reactor.callLater(0.05, - lambda : d.errback(failure.Failure(RuntimeError("oh noes")))) - return d - self.lru.miss_fn = slow_fail_miss_fn - - def do_get(test_d, k): - d = self.lru.get(k) - self.assertFailure(d, RuntimeError) - d.addCallbacks(test_d.callback, test_d.errback) - - ds = [] - for i in range(8): - d = defer.Deferred() - reactor.callLater(0.02*i, do_get, d, 'x') - ds.append(d) - - d = defer.gatherResults(ds) - return d - - @defer.inlineCallbacks - def test_set_max_size(self): - # load up the cache with three items - for c in 'abc': - res = yield self.lru.get(c) - self.check_result(res, short(c)) - - # reset the size to 1 - self.lru.set_max_size(1) - gc.collect() - - # and then expect that 'b' is no longer in the cache - self.lru.miss_fn = self.long_miss_fn - res = yield self.lru.get('b') - self.check_result(res, long('b')) - - def test_miss_fn_kwargs(self): - def keep_kwargs_miss_fn(k, **kwargs): - return defer.succeed(set(kwargs.keys())) - self.lru.miss_fn = keep_kwargs_miss_fn - - d = self.lru.get('a', a=1, b=2) - d.addCallback(self.check_result, set(['a', 'b']), 0, 1) - return d - - @defer.inlineCallbacks - def test_miss_fn_returns_none(self): - calls = [] - def none_miss_fn(k): - calls.append(k) - return defer.succeed(None) - self.lru.miss_fn = none_miss_fn - - for i in range(2): - self.assertEqual((yield self.lru.get('a')), None) - - # check that the miss_fn was called twice - self.assertEqual(calls, ['a', 'a']) - - @defer.inlineCallbacks - def test_put(self): - self.assertEqual((yield self.lru.get('p')), short('p')) - self.lru.put('p', set(['P2P2'])) - self.assertEqual((yield self.lru.get('p')), set(['P2P2'])) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_maildir.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_maildir.py deleted file mode 100644 index 419ae448..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_maildir.py +++ /dev/null @@ -1,88 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from __future__ import with_statement - -import os -from twisted.trial import unittest -from twisted.internet import defer -from buildbot.util import maildir -from buildbot.test.util import dirs - -class TestMaildirService(dirs.DirsMixin, unittest.TestCase): - def setUp(self): - self.maildir = os.path.abspath("maildir") - self.newdir = os.path.join(self.maildir, "new") - self.curdir = os.path.join(self.maildir, "cur") - self.tmpdir = os.path.join(self.maildir, "tmp") - self.setUpDirs(self.maildir, self.newdir, self.curdir, self.tmpdir) - - self.svc = None - - def tearDown(self): - if self.svc and self.svc.running: - self.svc.stopService() - self.tearDownDirs() - - # tests - - @defer.inlineCallbacks - def test_start_stop_repeatedly(self): - self.svc = maildir.MaildirService(self.maildir) - self.svc.startService() - yield self.svc.stopService() - self.svc.startService() - yield self.svc.stopService() - self.assertEqual(len(list(self.svc)), 0) - - - def test_messageReceived(self): - self.svc = maildir.MaildirService(self.maildir) - - # add a fake messageReceived method - messagesReceived = [] - def messageReceived(filename): - messagesReceived.append(filename) - return defer.succeed(None) - self.svc.messageReceived = messageReceived - d = defer.maybeDeferred(self.svc.startService) - def check_empty(_): - self.assertEqual(messagesReceived, []) - d.addCallback(check_empty) - def add_msg(_): - tmpfile = os.path.join(self.tmpdir, "newmsg") - newfile = os.path.join(self.newdir, "newmsg") - open(tmpfile, "w").close() - os.rename(tmpfile, newfile) - d.addCallback(add_msg) - def trigger(_): - # TODO: can we wait for a dnotify somehow, if enabled? - return self.svc.poll() - d.addCallback(trigger) - def check_nonempty(_): - self.assertEqual(messagesReceived, [ 'newmsg' ]) - d.addCallback(check_nonempty) - return d - - def test_moveToCurDir(self): - self.svc = maildir.MaildirService(self.maildir) - tmpfile = os.path.join(self.tmpdir, "newmsg") - newfile = os.path.join(self.newdir, "newmsg") - open(tmpfile, "w").close() - os.rename(tmpfile, newfile) - self.svc.moveToCurDir("newmsg") - self.assertEqual([ os.path.exists(os.path.join(d, "newmsg")) - for d in (self.newdir, self.curdir, self.tmpdir) ], - [ False, True, False ]) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_misc.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_misc.py deleted file mode 100644 index 78f38144..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_misc.py +++ /dev/null @@ -1,130 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.util import misc -from buildbot import util -from twisted.python import failure -from twisted.internet import defer, reactor -from buildbot.test.util import compat -from buildbot.util.eventual import eventually - -class deferredLocked(unittest.TestCase): - def test_name(self): - self.assertEqual(util.deferredLocked, misc.deferredLocked) - - def test_fn(self): - l = defer.DeferredLock() - @util.deferredLocked(l) - def check_locked(arg1, arg2): - self.assertEqual([l.locked, arg1, arg2], [True, 1, 2]) - return defer.succeed(None) - d = check_locked(1, 2) - def check_unlocked(_): - self.assertFalse(l.locked) - d.addCallback(check_unlocked) - return d - - def test_fn_fails(self): - l = defer.DeferredLock() - @util.deferredLocked(l) - def do_fail(): - return defer.fail(RuntimeError("oh noes")) - d = do_fail() - def check_unlocked(_): - self.assertFalse(l.locked) - d.addCallbacks(lambda _ : self.fail("didn't errback"), - lambda _ : self.assertFalse(l.locked)) - return d - - def test_fn_exception(self): - l = defer.DeferredLock() - @util.deferredLocked(l) - def do_fail(): - raise RuntimeError("oh noes") - d = do_fail() - def check_unlocked(_): - self.assertFalse(l.locked) - d.addCallbacks(lambda _ : self.fail("didn't errback"), - lambda _ : self.assertFalse(l.locked)) - return d - - def test_method(self): - testcase = self - class C: - @util.deferredLocked('aLock') - def check_locked(self, arg1, arg2): - testcase.assertEqual([self.aLock.locked, arg1, arg2], [True, 1, 2]) - return defer.succeed(None) - obj = C() - obj.aLock = defer.DeferredLock() - d = obj.check_locked(1, 2) - def check_unlocked(_): - self.assertFalse(obj.aLock.locked) - d.addCallback(check_unlocked) - return d - -class SerializedInvocation(unittest.TestCase): - - def waitForQuiet(self, si): - d = defer.Deferred() - si._quiet = lambda : d.callback(None) - return d - - # tests - - def test_name(self): - self.assertEqual(util.SerializedInvocation, misc.SerializedInvocation) - - def testCallFolding(self): - events = [] - def testfn(): - d = defer.Deferred() - def done(): - events.append('TM') - d.callback(None) - eventually(done) - return d - si = misc.SerializedInvocation(testfn) - - # run three times - the first starts testfn, the second - # requires a second run, and the third is folded. - d1 = si() - d2 = si() - d3 = si() - - dq = self.waitForQuiet(si) - d = defer.gatherResults([d1, d2, d3, dq]) - def check(_): - self.assertEqual(events, [ 'TM', 'TM' ]) - d.addCallback(check) - return d - - @compat.usesFlushLoggedErrors - def testException(self): - def testfn(): - d = defer.Deferred() - reactor.callLater(0, d.errback, - failure.Failure(RuntimeError("oh noes"))) - return d - si = misc.SerializedInvocation(testfn) - - d = si() - - def check(_): - self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) - d.addCallback(check) - return d - diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_netstrings.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_netstrings.py deleted file mode 100644 index 87173e5d..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_netstrings.py +++ /dev/null @@ -1,42 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.protocols import basic -from twisted.trial import unittest -from buildbot.util import netstrings - -class NetstringParser(unittest.TestCase): - - def test_valid_netstrings(self): - p = netstrings.NetstringParser() - p.feed("5:hello,5:world,") - self.assertEqual(p.strings, ['hello', 'world']) - - def test_valid_netstrings_byte_by_byte(self): - # (this is really testing twisted's support, but oh well) - p = netstrings.NetstringParser() - [ p.feed(c) for c in "5:hello,5:world," ] - self.assertEqual(p.strings, ['hello', 'world']) - - def test_invalid_netstring(self): - p = netstrings.NetstringParser() - self.assertRaises(basic.NetstringParseError, - lambda : p.feed("5-hello!")) - - def test_incomplete_netstring(self): - p = netstrings.NetstringParser() - p.feed("11:hello world,6:foob") - # note that the incomplete 'foobar' does not appear here - self.assertEqual(p.strings, ['hello world']) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_sautils.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_sautils.py deleted file mode 100644 index 6c77e49a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_sautils.py +++ /dev/null @@ -1,22 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.util import sautils - -class SAVersion(unittest.TestCase): - - def test_sa_version(self): - self.failUnless(sautils.sa_version() > (0,5,0)) diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_state.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_state.py deleted file mode 100644 index 8e7adca2..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_state.py +++ /dev/null @@ -1,77 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest -from buildbot.util import state -from buildbot.test.fake.fakemaster import make_master - -class FakeObject(state.StateMixin): - name = "fake-name" - - def __init__(self, master): - self.master = master - -class TestStateMixin(unittest.TestCase): - - OBJECTID = 19 - - def setUp(self): - self.master = make_master(wantDb=True, testcase=self) - self.object = FakeObject(self.master) - - def test_getState(self): - self.master.db.state.fakeState('fake-name', 'FakeObject', - fav_color=['red','purple']) - d = self.object.getState('fav_color') - def check(res): - self.assertEqual(res, ['red', 'purple']) - d.addCallback(check) - return d - - def test_getState_default(self): - d = self.object.getState('fav_color', 'black') - def check(res): - self.assertEqual(res, 'black') - d.addCallback(check) - return d - - def test_getState_KeyError(self): - self.master.db.state.fakeState('fake-name', 'FakeObject', - fav_color=['red','purple']) - d = self.object.getState('fav_book') - def cb(_): - self.fail("should not succeed") - def check_exc(f): - f.trap(KeyError) - pass - d.addCallbacks(cb, check_exc) - return d - - def test_setState(self): - d = self.object.setState('y', 14) - def check(_): - self.master.db.state.assertStateByClass('fake-name', 'FakeObject', - y=14) - d.addCallback(check) - return d - - def test_setState_existing(self): - self.master.db.state.fakeState('fake-name', 'FakeObject', x=13) - d = self.object.setState('x', 14) - def check(_): - self.master.db.state.assertStateByClass('fake-name', 'FakeObject', - x=14) - d.addCallback(check) - return d diff --git a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_subscriptions.py b/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_subscriptions.py deleted file mode 100644 index 0defb18a..00000000 --- a/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/test/unit/test_util_subscriptions.py +++ /dev/null @@ -1,64 +0,0 @@ -# This file is part of Buildbot. Buildbot is free software: you can -# redistribute it and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation, version 2. -# -# This program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -# details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, write to the Free Software Foundation, Inc., 51 -# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Copyright Buildbot Team Members - -from twisted.trial import unittest - -from buildbot.util import subscription -from buildbot.test.util import compat - -class subscriptions(unittest.TestCase): - - def setUp(self): - self.subpt = subscription.SubscriptionPoint('test_sub') - - def test_str(self): - self.assertIn('test_sub', str(self.subpt)) - - def test_subscribe_unsubscribe(self): - state = [] - def cb(*args, **kwargs): - state.append((args, kwargs)) - - # subscribe - sub = self.subpt.subscribe(cb) - self.assertTrue(isinstance(sub, subscription.Subscription)) - self.assertEqual(state, []) - - # deliver - self.subpt.deliver(1, 2, a=3, b=4) - self.assertEqual(state, [((1,2), dict(a=3, b=4))]) - state.pop() - - # unsubscribe - sub.unsubscribe() - - # don't receive events anymore - self.subpt.deliver(3, 4) - self.assertEqual(state, []) - - @compat.usesFlushLoggedErrors - def test_exception(self): - def cb(*args, **kwargs): - raise RuntimeError('mah bucket!') - - # subscribe - self.subpt.subscribe(cb) - try: - self.subpt.deliver() - except RuntimeError: - self.fail("should not have seen exception here!") - # log.err will cause Trial to complain about this error anyway, unless - # we clean it up - self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError))) |