Пример #1
0
class TestBot(unittest.TestCase):

    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        self.real_bot = base.BotBase(self.basedir, False)
        self.real_bot.startService()

        self.bot = FakeRemote(self.real_bot)

    def tearDown(self):
        d = defer.succeed(None)
        if self.real_bot and self.real_bot.running:
            d.addCallback(lambda _: self.real_bot.stopService())
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        return d

    def test_getCommands(self):
        d = self.bot.callRemote("getCommands")

        def check(cmds):
            # just check that 'shell' is present..
            self.assertTrue('shell' in cmds)
        d.addCallback(check)
        return d

    def test_getVersion(self):
        d = self.bot.callRemote("getVersion")

        def check(vers):
            self.assertEqual(vers, buildbot_worker.version)
        d.addCallback(check)
        return d

    def test_getWorkerInfo(self):
        infodir = os.path.join(self.basedir, "info")
        os.makedirs(infodir)
        open(os.path.join(infodir, "admin"), "w").write("testy!")
        open(os.path.join(infodir, "foo"), "w").write("bar")
        open(os.path.join(infodir, "environ"), "w").write("something else")

        d = self.bot.callRemote("getWorkerInfo")

        def check(info):
            self.assertEqual(info, dict(
                admin='testy!', foo='bar',
                environ=os.environ, system=os.name, basedir=self.basedir,
                worker_commands=self.real_bot.remote_getCommands(),
                version=self.real_bot.remote_getVersion(),
                numcpus=multiprocessing.cpu_count()))
        d.addCallback(check)
        return d

    def test_getWorkerInfo_nodir(self):
        d = self.bot.callRemote("getWorkerInfo")

        def check(info):
            self.assertEqual(set(info.keys()), set(
                ['environ', 'system', 'numcpus', 'basedir', 'worker_commands', 'version']))
        d.addCallback(check)
        return d

    def test_setBuilderList_empty(self):
        d = self.bot.callRemote("setBuilderList", [])

        def check(builders):
            self.assertEqual(builders, {})
        d.addCallback(check)
        return d

    def test_setBuilderList_single(self):
        d = self.bot.callRemote("setBuilderList", [('mybld', 'myblddir')])

        def check(builders):
            self.assertEqual(list(builders), ['mybld'])
            self.assertTrue(
                os.path.exists(os.path.join(self.basedir, 'myblddir')))
            # note that we test the WorkerForBuilder instance below
        d.addCallback(check)
        return d

    def test_setBuilderList_updates(self):
        d = defer.succeed(None)

        workerforbuilders = {}

        def add_my(_):
            d = self.bot.callRemote("setBuilderList", [
                ('mybld', 'myblddir')])

            def check(builders):
                self.assertEqual(list(builders), ['mybld'])
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                workerforbuilders['my'] = builders['mybld']
            d.addCallback(check)
            return d
        d.addCallback(add_my)

        def add_your(_):
            d = self.bot.callRemote("setBuilderList", [
                ('mybld', 'myblddir'), ('yourbld', 'yourblddir')])

            def check(builders):
                self.assertEqual(
                    sorted(builders.keys()), sorted(['mybld', 'yourbld']))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                # 'my' should still be the same WorkerForBuilder object
                self.assertEqual(
                    id(workerforbuilders['my']), id(builders['mybld']))
                workerforbuilders['your'] = builders['yourbld']
            d.addCallback(check)
            return d
        d.addCallback(add_your)

        def remove_my(_):
            d = self.bot.callRemote("setBuilderList", [
                ('yourbld', 'yourblddir2')])  # note new builddir

            def check(builders):
                self.assertEqual(sorted(builders.keys()), sorted(['yourbld']))
                # note that build dirs are not deleted..
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir2')))
                # 'your' should still be the same WorkerForBuilder object
                self.assertEqual(
                    id(workerforbuilders['your']), id(builders['yourbld']))
            d.addCallback(check)
            return d
        d.addCallback(remove_my)

        def add_and_remove(_):
            d = self.bot.callRemote("setBuilderList", [
                ('theirbld', 'theirblddir')])

            def check(builders):
                self.assertEqual(sorted(builders.keys()), sorted(['theirbld']))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'theirblddir')))
            d.addCallback(check)
            return d
        d.addCallback(add_and_remove)

        return d

    def test_shutdown(self):
        d1 = defer.Deferred()
        self.patch(reactor, "stop", lambda: d1.callback(None))
        d2 = self.bot.callRemote("shutdown")
        # don't return until both the shutdown method has returned, and
        # reactor.stop has been called
        return defer.gatherResults([d1, d2])
Пример #2
0
class TestWorkerForBuilder(command.CommandTestMixin, unittest.TestCase):

    @defer.inlineCallbacks
    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        self.bot = base.BotBase(self.basedir, False)
        self.bot.startService()

        # get a WorkerForBuilder object from the bot and wrap it as a fake
        # remote
        builders = yield self.bot.remote_setBuilderList([('wfb', 'wfb')])
        self.wfb = FakeRemote(builders['wfb'])

        self.setUpCommand()

    def tearDown(self):
        self.tearDownCommand()

        d = defer.succeed(None)
        if self.bot and self.bot.running:
            d.addCallback(lambda _: self.bot.stopService())
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        return d

    def test_print(self):
        return self.wfb.callRemote("print", "Hello, WorkerForBuilder.")

    def test_setMaster(self):
        # not much to check here - what the WorkerForBuilder does with the
        # master is not part of the interface (and, in fact, it does very
        # little)
        return self.wfb.callRemote("setMaster", mock.Mock())

    def test_startBuild(self):
        return self.wfb.callRemote("startBuild")

    def test_startCommand(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to handle the 'echo', below
        self.patch_runprocess(
            Expect(['echo', 'hello'], os.path.join(
                self.basedir, 'wfb', 'workdir')) +
            {'hdr': 'headers'} +
            {'stdout': 'hello\n'} +
            {'rc': 0} +
            0,
        )

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote("startCommand", FakeRemote(st),
                                       "13", "shell", dict(
                command=['echo', 'hello'],
                workdir='workdir'))
        d.addCallback(do_start)
        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions, [
                ['update', [[{'hdr': 'headers'}, 0]]],
                ['update', [[{'stdout': 'hello\n'}, 0]]],
                ['update', [[{'rc': 0}, 0]]],
                ['update', [[{'elapsed': 1}, 0]]],
                ['complete', None],
            ])
        d.addCallback(check)
        return d

    def test_startCommand_interruptCommand(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to pretend to sleep (it will really just hang forever,
        # except that we interrupt it)
        self.patch_runprocess(
            Expect(['sleep', '10'], os.path.join(
                self.basedir, 'wfb', 'workdir')) +
            {'hdr': 'headers'} +
            {'wait': True}
        )

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote("startCommand", FakeRemote(st),
                                       "13", "shell", dict(
                command=['sleep', '10'],
                workdir='workdir'))
        d.addCallback(do_start)

        # wait a jiffy..
        def do_wait(_):
            d = defer.Deferred()
            reactor.callLater(0.01, d.callback, None)
            return d
        d.addCallback(do_wait)

        # and then interrupt the step
        def do_interrupt(_):
            return self.wfb.callRemote("interruptCommand", "13", "tl/dr")
        d.addCallback(do_interrupt)

        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions, [
                ['update', [[{'hdr': 'headers'}, 0]]],
                ['update', [[{'hdr': 'killing'}, 0]]],
                ['update', [[{'rc': -1}, 0]]],
                ['complete', None],
            ])
        d.addCallback(check)
        return d

    def test_startCommand_failure(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to generate a failure
        self.patch_runprocess(
            Expect(['sleep', '10'], os.path.join(
                self.basedir, 'wfb', 'workdir')) +
            failure.Failure(Exception("Oops"))
        )
        # patch the log.err, otherwise trial will think something *actually*
        # failed
        self.patch(log, "err", lambda f: None)

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote("startCommand", FakeRemote(st),
                                       "13", "shell", dict(
                command=['sleep', '10'],
                workdir='workdir'))
        d.addCallback(do_start)
        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions[1][0], 'complete')
            self.assertTrue(isinstance(st.actions[1][1], failure.Failure))
        d.addCallback(check)
        return d

    @defer.inlineCallbacks
    def test_startCommand_missing_args(self):
        # set up a fake step to receive updates
        st = FakeStep()

        def do_start():
            return self.wfb.callRemote("startCommand", FakeRemote(st),
                                       "13", "shell", dict())

        yield self.assertFailure(do_start(), ValueError)
Пример #3
0
class TestBot(unittest.TestCase):
    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        self.real_bot = base.BotBase(self.basedir, False)
        self.real_bot.startService()

        self.bot = FakeRemote(self.real_bot)

    def tearDown(self):
        d = defer.succeed(None)
        if self.real_bot and self.real_bot.running:
            d.addCallback(lambda _: self.real_bot.stopService())
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        return d

    def test_getCommands(self):
        d = self.bot.callRemote("getCommands")

        def check(cmds):
            # just check that 'shell' is present..
            self.assertTrue('shell' in cmds)

        d.addCallback(check)
        return d

    def test_getVersion(self):
        d = self.bot.callRemote("getVersion")

        def check(vers):
            self.assertEqual(vers, buildbot_worker.version)

        d.addCallback(check)
        return d

    def test_getWorkerInfo(self):
        infodir = os.path.join(self.basedir, "info")
        os.makedirs(infodir)
        with open(os.path.join(infodir, "admin"), "w") as f:
            f.write("testy!")
        with open(os.path.join(infodir, "foo"), "w") as f:
            f.write("bar")
        with open(os.path.join(infodir, "environ"), "w") as f:
            f.write("something else")

        d = self.bot.callRemote("getWorkerInfo")

        def check(info):
            self.assertEqual(
                info,
                dict(admin='testy!',
                     foo='bar',
                     environ=os.environ,
                     system=os.name,
                     basedir=self.basedir,
                     worker_commands=self.real_bot.remote_getCommands(),
                     version=self.real_bot.remote_getVersion(),
                     numcpus=multiprocessing.cpu_count()))

        d.addCallback(check)
        return d

    def test_getWorkerInfo_nodir(self):
        d = self.bot.callRemote("getWorkerInfo")

        def check(info):
            self.assertEqual(
                set(info.keys()),
                set([
                    'environ', 'system', 'numcpus', 'basedir',
                    'worker_commands', 'version'
                ]))

        d.addCallback(check)
        return d

    def test_setBuilderList_empty(self):
        d = self.bot.callRemote("setBuilderList", [])

        def check(builders):
            self.assertEqual(builders, {})

        d.addCallback(check)
        return d

    def test_setBuilderList_single(self):
        d = self.bot.callRemote("setBuilderList", [('mybld', 'myblddir')])

        def check(builders):
            self.assertEqual(list(builders), ['mybld'])
            self.assertTrue(
                os.path.exists(os.path.join(self.basedir, 'myblddir')))
            # note that we test the WorkerForBuilder instance below

        d.addCallback(check)
        return d

    def test_setBuilderList_updates(self):
        d = defer.succeed(None)

        workerforbuilders = {}

        def add_my(_):
            d = self.bot.callRemote("setBuilderList", [('mybld', 'myblddir')])

            def check(builders):
                self.assertEqual(list(builders), ['mybld'])
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                workerforbuilders['my'] = builders['mybld']

            d.addCallback(check)
            return d

        d.addCallback(add_my)

        def add_your(_):
            d = self.bot.callRemote("setBuilderList",
                                    [('mybld', 'myblddir'),
                                     ('yourbld', 'yourblddir')])

            def check(builders):
                self.assertEqual(sorted(builders.keys()),
                                 sorted(['mybld', 'yourbld']))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                # 'my' should still be the same WorkerForBuilder object
                self.assertEqual(id(workerforbuilders['my']),
                                 id(builders['mybld']))
                workerforbuilders['your'] = builders['yourbld']
                self.assertTrue(
                    repr(workerforbuilders['your']).startswith(
                        "<WorkerForBuilder 'yourbld' at "))

            d.addCallback(check)
            return d

        d.addCallback(add_your)

        def remove_my(_):
            d = self.bot.callRemote(
                "setBuilderList",
                [('yourbld', 'yourblddir2')])  # note new builddir

            def check(builders):
                self.assertEqual(sorted(builders.keys()), sorted(['yourbld']))
                # note that build dirs are not deleted..
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir2')))
                # 'your' should still be the same WorkerForBuilder object
                self.assertEqual(id(workerforbuilders['your']),
                                 id(builders['yourbld']))

            d.addCallback(check)
            return d

        d.addCallback(remove_my)

        def add_and_remove(_):
            d = self.bot.callRemote("setBuilderList",
                                    [('theirbld', 'theirblddir')])

            def check(builders):
                self.assertEqual(sorted(builders.keys()), sorted(['theirbld']))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'myblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'yourblddir')))
                self.assertTrue(
                    os.path.exists(os.path.join(self.basedir, 'theirblddir')))

            d.addCallback(check)
            return d

        d.addCallback(add_and_remove)

        return d

    def test_shutdown(self):
        d1 = defer.Deferred()
        self.patch(reactor, "stop", lambda: d1.callback(None))
        d2 = self.bot.callRemote("shutdown")
        # don't return until both the shutdown method has returned, and
        # reactor.stop has been called
        return defer.gatherResults([d1, d2])
Пример #4
0
class TestWorkerForBuilder(command.CommandTestMixin, unittest.TestCase):
    @defer.inlineCallbacks
    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        self.bot = base.BotBase(self.basedir, False)
        self.bot.startService()

        # get a WorkerForBuilder object from the bot and wrap it as a fake
        # remote
        builders = yield self.bot.remote_setBuilderList([('wfb', 'wfb')])
        self.wfb = FakeRemote(builders['wfb'])

        self.setUpCommand()

    def tearDown(self):
        self.tearDownCommand()

        d = defer.succeed(None)
        if self.bot and self.bot.running:
            d.addCallback(lambda _: self.bot.stopService())
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        return d

    def test_print(self):
        return self.wfb.callRemote("print", "Hello, WorkerForBuilder.")

    def test_printWithCommand(self):
        self.wfb.original.command = Command("builder", "1", ["arg1", "arg2"])
        return self.wfb.callRemote("print", "Hello again, WorkerForBuilder.")

    def test_setMaster(self):
        # not much to check here - what the WorkerForBuilder does with the
        # master is not part of the interface (and, in fact, it does very
        # little)
        return self.wfb.callRemote("setMaster", mock.Mock())

    def test_startBuild(self):
        return self.wfb.callRemote("startBuild")

    def test_startCommand(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to handle the 'echo', below
        self.patch_runprocess(
            Expect(['echo', 'hello'],
                   os.path.join(self.basedir, 'wfb', 'workdir')) +
            {'hdr': 'headers'} + {'stdout': 'hello\n'} + {'rc': 0} + 0, )

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote(
                "startCommand", FakeRemote(st), "13", "shell",
                dict(command=['echo', 'hello'], workdir='workdir'))

        d.addCallback(do_start)
        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions, [
                ['update', [[{
                    'hdr': 'headers'
                }, 0]]],
                ['update', [[{
                    'stdout': 'hello\n'
                }, 0]]],
                ['update', [[{
                    'rc': 0
                }, 0]]],
                ['update', [[{
                    'elapsed': 1
                }, 0]]],
                ['complete', None],
            ])

        d.addCallback(check)
        return d

    def test_startCommand_interruptCommand(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to pretend to sleep (it will really just hang forever,
        # except that we interrupt it)
        self.patch_runprocess(
            Expect(['sleep', '10'], os.path.join(
                self.basedir, 'wfb', 'workdir')) + {'hdr': 'headers'} +
            {'wait': True})

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote(
                "startCommand", FakeRemote(st), "13", "shell",
                dict(command=['sleep', '10'], workdir='workdir'))

        d.addCallback(do_start)

        # wait a jiffy..
        def do_wait(_):
            d = defer.Deferred()
            reactor.callLater(0.01, d.callback, None)
            return d

        d.addCallback(do_wait)

        # and then interrupt the step
        def do_interrupt(_):
            return self.wfb.callRemote("interruptCommand", "13", "tl/dr")

        d.addCallback(do_interrupt)

        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions, [
                ['update', [[{
                    'hdr': 'headers'
                }, 0]]],
                ['update', [[{
                    'hdr': 'killing'
                }, 0]]],
                ['update', [[{
                    'rc': -1
                }, 0]]],
                ['complete', None],
            ])

        d.addCallback(check)
        return d

    def test_startCommand_failure(self):
        # set up a fake step to receive updates
        st = FakeStep()

        # patch runprocess to generate a failure
        self.patch_runprocess(
            Expect(['sleep', '10'], os.path.join(self.basedir, 'wfb',
                                                 'workdir')) +
            failure.Failure(Exception("Oops")))
        # patch the log.err, otherwise trial will think something *actually*
        # failed
        self.patch(log, "err", lambda f: None)

        d = defer.succeed(None)

        def do_start(_):
            return self.wfb.callRemote(
                "startCommand", FakeRemote(st), "13", "shell",
                dict(command=['sleep', '10'], workdir='workdir'))

        d.addCallback(do_start)
        d.addCallback(lambda _: st.wait_for_finish())

        def check(_):
            self.assertEqual(st.actions[1][0], 'complete')
            self.assertTrue(isinstance(st.actions[1][1], failure.Failure))

        d.addCallback(check)
        return d

    @defer.inlineCallbacks
    def test_startCommand_missing_args(self):
        # set up a fake step to receive updates
        st = FakeStep()

        def do_start():
            return self.wfb.callRemote("startCommand", FakeRemote(st), "13",
                                       "shell", dict())

        yield self.assertFailure(do_start(), ValueError)

    @defer.inlineCallbacks
    def test_startCommand_invalid_command(self):
        # set up a fake step to receive updates
        st = FakeStep()

        def do_start():
            return self.wfb.callRemote("startCommand", FakeRemote(st), "13",
                                       "invalid command", dict())

        unknownCommand = yield self.assertFailure(do_start(),
                                                  base.UnknownCommand)
        self.assertEqual(str(unknownCommand),
                         "unrecognized WorkerCommand 'invalid command'")
Пример #5
0
class TestBot(unittest.TestCase):
    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        # create test-release-file
        with open("{}/test-release-file".format(self.basedir), "w") as fout:
            fout.write("""
# unit test release file
OS_NAME="Test"
VERSION="1.0"
ID=test
ID_LIKE=generic
PRETTY_NAME="Test 1.0 Generic"
VERSION_ID="1"
""")
        self.real_bot = base.BotBase(self.basedir, False)
        self.real_bot.setOsReleaseFile("{}/test-release-file".format(
            self.basedir))
        self.real_bot.startService()

        self.bot = FakeRemote(self.real_bot)

    @defer.inlineCallbacks
    def tearDown(self):
        if self.real_bot and self.real_bot.running:
            yield self.real_bot.stopService()
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)

    @defer.inlineCallbacks
    def test_getCommands(self):
        cmds = yield self.bot.callRemote("getCommands")

        # just check that 'shell' is present..
        self.assertTrue('shell' in cmds)

    @defer.inlineCallbacks
    def test_getVersion(self):
        vers = yield self.bot.callRemote("getVersion")

        self.assertEqual(vers, buildbot_worker.version)

    @defer.inlineCallbacks
    def test_getWorkerInfo(self):
        infodir = os.path.join(self.basedir, "info")
        os.makedirs(infodir)
        with open(os.path.join(infodir, "admin"), "w") as f:
            f.write("testy!")
        with open(os.path.join(infodir, "foo"), "w") as f:
            f.write("bar")
        with open(os.path.join(infodir, "environ"), "w") as f:
            f.write("something else")

        info = yield self.bot.callRemote("getWorkerInfo")

        # remove any os_ fields as they are dependent on the test environment
        info = {k: v for k, v in info.items() if not k.startswith("os_")}

        self.assertEqual(
            info,
            dict(admin='testy!',
                 foo='bar',
                 environ=os.environ,
                 system=os.name,
                 basedir=self.basedir,
                 worker_commands=self.real_bot.remote_getCommands(),
                 version=self.real_bot.remote_getVersion(),
                 numcpus=multiprocessing.cpu_count()))

    @defer.inlineCallbacks
    def test_getWorkerInfo_nodir(self):
        info = yield self.bot.callRemote("getWorkerInfo")

        info = {k: v for k, v in info.items() if not k.startswith("os_")}

        self.assertEqual(
            set(info.keys()),
            set([
                'environ', 'system', 'numcpus', 'basedir', 'worker_commands',
                'version'
            ]))

    @defer.inlineCallbacks
    def test_setBuilderList_empty(self):
        builders = yield self.bot.callRemote("setBuilderList", [])

        self.assertEqual(builders, {})

    @defer.inlineCallbacks
    def test_setBuilderList_single(self):
        builders = yield self.bot.callRemote("setBuilderList",
                                             [('mybld', 'myblddir')])

        self.assertEqual(list(builders), ['mybld'])
        self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir')))
        # note that we test the WorkerForBuilder instance below

    @defer.inlineCallbacks
    def test_setBuilderList_updates(self):

        workerforbuilders = {}

        builders = yield self.bot.callRemote("setBuilderList",
                                             [('mybld', 'myblddir')])

        self.assertEqual(list(builders), ['mybld'])
        self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir')))
        workerforbuilders['my'] = builders['mybld']

        builders = yield self.bot.callRemote("setBuilderList",
                                             [('mybld', 'myblddir'),
                                              ('yourbld', 'yourblddir')])

        self.assertEqual(sorted(builders.keys()), sorted(['mybld', 'yourbld']))
        self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir')))
        self.assertTrue(
            os.path.exists(os.path.join(self.basedir, 'yourblddir')))
        # 'my' should still be the same WorkerForBuilder object
        self.assertEqual(id(workerforbuilders['my']), id(builders['mybld']))
        workerforbuilders['your'] = builders['yourbld']
        self.assertTrue(
            repr(workerforbuilders['your']).startswith(
                "<WorkerForBuilder 'yourbld' at "))

        builders = yield self.bot.callRemote(
            "setBuilderList",
            [('yourbld', 'yourblddir2')])  # note new builddir

        self.assertEqual(sorted(builders.keys()), sorted(['yourbld']))
        # note that build dirs are not deleted..
        self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir')))
        self.assertTrue(
            os.path.exists(os.path.join(self.basedir, 'yourblddir')))
        self.assertTrue(
            os.path.exists(os.path.join(self.basedir, 'yourblddir2')))
        # 'your' should still be the same WorkerForBuilder object
        self.assertEqual(id(workerforbuilders['your']),
                         id(builders['yourbld']))

        builders = yield self.bot.callRemote("setBuilderList",
                                             [('theirbld', 'theirblddir')])

        self.assertEqual(sorted(builders.keys()), sorted(['theirbld']))
        self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir')))
        self.assertTrue(
            os.path.exists(os.path.join(self.basedir, 'yourblddir')))
        self.assertTrue(
            os.path.exists(os.path.join(self.basedir, 'theirblddir')))

    def test_shutdown(self):
        d1 = defer.Deferred()
        self.patch(reactor, "stop", lambda: d1.callback(None))
        d2 = self.bot.callRemote("shutdown")
        # don't return until both the shutdown method has returned, and
        # reactor.stop has been called
        return defer.gatherResults([d1, d2])
Пример #6
0
class TestBot(unittest.TestCase):
    def setUp(self):
        self.basedir = os.path.abspath("basedir")
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)
        os.makedirs(self.basedir)

        # create test-release-file
        with open("{}/test-release-file".format(self.basedir), "w") as fout:
            fout.write("""
# unit test release file
OS_NAME="Test"
VERSION="1.0"
ID=test
ID_LIKE=generic
PRETTY_NAME="Test 1.0 Generic"
VERSION_ID="1"
""")
        self.real_bot = pb.BotPbLike(self.basedir, False)
        self.real_bot.setOsReleaseFile("{}/test-release-file".format(
            self.basedir))
        self.real_bot.startService()

        self.bot = FakeRemote(self.real_bot)

    @defer.inlineCallbacks
    def tearDown(self):
        if self.real_bot and self.real_bot.running:
            yield self.real_bot.stopService()
        if os.path.exists(self.basedir):
            shutil.rmtree(self.basedir)

    @defer.inlineCallbacks
    def test_getCommands(self):
        cmds = yield self.bot.callRemote("getCommands")

        # just check that 'shell' is present..
        self.assertTrue('shell' in cmds)

    @defer.inlineCallbacks
    def test_getVersion(self):
        vers = yield self.bot.callRemote("getVersion")

        self.assertEqual(vers, buildbot_worker.version)

    @defer.inlineCallbacks
    def test_getWorkerInfo(self):
        infodir = os.path.join(self.basedir, "info")
        os.makedirs(infodir)
        with open(os.path.join(infodir, "admin"), "w") as f:
            f.write("testy!")
        with open(os.path.join(infodir, "foo"), "w") as f:
            f.write("bar")
        with open(os.path.join(infodir, "environ"), "w") as f:
            f.write("something else")

        info = yield self.bot.callRemote("getWorkerInfo")

        # remove any os_ fields as they are dependent on the test environment
        info = {k: v for k, v in info.items() if not k.startswith("os_")}

        self.assertEqual(
            info,
            dict(admin='testy!',
                 foo='bar',
                 environ=os.environ,
                 system=os.name,
                 basedir=self.basedir,
                 worker_commands=self.real_bot.remote_getCommands(),
                 version=self.real_bot.remote_getVersion(),
                 numcpus=multiprocessing.cpu_count(),
                 delete_leftover_dirs=False))

    @defer.inlineCallbacks
    def test_getWorkerInfo_nodir(self):
        info = yield self.bot.callRemote("getWorkerInfo")

        info = {k: v for k, v in info.items() if not k.startswith("os_")}

        self.assertEqual(
            set(info.keys()),
            set([
                'environ', 'system', 'numcpus', 'basedir', 'worker_commands',
                'version', 'delete_leftover_dirs'
            ]))

    def test_shutdown(self):
        d1 = defer.Deferred()
        self.patch(reactor, "stop", lambda: d1.callback(None))
        d2 = self.bot.callRemote("shutdown")
        # don't return until both the shutdown method has returned, and
        # reactor.stop has been called
        return defer.gatherResults([d1, d2])