id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
4,600
test_versions_063_add_steps_locks_acquired_at.py
buildbot_buildbot/master/buildbot/test/unit/db_migrate/test_versions_063_add_steps_locks_acquired_at.py
# 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 from buildbot.util import sautils 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 # buildid foreign key is removed for the purposes of the test steps = sautils.Table( 'steps', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('number', sa.Integer, nullable=False), sa.Column('name', sa.String(50), nullable=False), sa.Column('buildid', sa.Integer, nullable=True), sa.Column('started_at', sa.Integer), sa.Column('complete_at', sa.Integer), sa.Column('state_string', sa.Text, nullable=False), sa.Column('results', sa.Integer), sa.Column('urls_json', sa.Text, nullable=False), sa.Column('hidden', sa.SmallInteger, nullable=False, server_default='0'), ) steps.create(bind=conn) conn.execute( steps.insert(), [ { "id": 4, "number": 123, "name": "step", "buildid": 12, "started_at": 1690848000, "complete_at": 1690848030, "state_string": "state", "results": 0, "urls_json": "", "hidden": 0, } ], ) conn.commit() def test_update(self): def setup_thd(conn): self.create_tables_thd(conn) def verify_thd(conn): metadata = sa.MetaData() metadata.bind = conn steps = sautils.Table('steps', metadata, autoload_with=conn) self.assertIsInstance(steps.c.locks_acquired_at.type, sa.Integer) q = sa.select( steps.c.name, steps.c.locks_acquired_at, ) num_rows = 0 for row in conn.execute(q): self.assertEqual(row.name, "step") self.assertEqual(row.locks_acquired_at, 1690848000) num_rows += 1 self.assertEqual(num_rows, 1) return self.do_test_migration('062', '063', setup_thd, verify_thd)
3,246
Python
.py
79
30.544304
85
0.589597
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,601
test_upgrade.py
buildbot_buildbot/master/buildbot/test/integration/test_upgrade.py
# 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 annotations import locale import os import pprint import shutil import sqlite3 import tarfile import sqlalchemy as sa from alembic.autogenerate import compare_metadata from alembic.migration import MigrationContext from sqlalchemy.exc import DatabaseError from twisted.internet import defer from twisted.python import util from twisted.trial import unittest from buildbot.db import connector from buildbot.db.model import UpgradeFromBefore0p9Error from buildbot.db.model import UpgradeFromBefore3p0Error from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import db from buildbot.test.util import querylog class UpgradeTestMixin(db.RealDatabaseMixin, TestReactorMixin): """Supporting code to test upgrading from older versions by untarring a basedir tarball and then checking that the results are as expected.""" # class variables to set in subclasses # filename of the tarball (sibling to this file) source_tarball: None | str = None # set to true in subclasses to set up and use a real DB use_real_db = False # db URL to use, if not using a real db db_url = "sqlite:///state.sqlite" # these tests take a long time on platforms where sqlite is slow # (e.g., lion, see #2256) timeout = 1200 @defer.inlineCallbacks def setUpUpgradeTest(self): # set up the "real" db if desired if self.use_real_db: # note this changes self.db_url yield self.setUpRealDatabase(sqlite_memory=False) self.basedir = None if self.source_tarball: tarball = util.sibpath(__file__, self.source_tarball) if not os.path.exists(tarball): raise unittest.SkipTest( f"'{tarball}' not found (normal when not building from Git)" ) with tarfile.open(tarball) as tf: prefixes = set() for inf in tf: if hasattr(tarfile, 'data_filter'): tf.extract(inf, filter='data') else: tf.extract(inf) prefixes.add(inf.name.split('/', 1)[0]) # get the top-level dir from the tarball assert len(prefixes) == 1, "tarball has multiple top-level dirs!" self.basedir = prefixes.pop() else: if not os.path.exists("basedir"): os.makedirs("basedir") self.basedir = os.path.abspath("basedir") self.master = master = yield fakemaster.make_master(self) master.config.db['db_url'] = self.db_url self.db = connector.DBConnector(self.basedir) yield self.db.setServiceParent(master) yield self.db.setup(check_version=False) self._sql_log_handler = querylog.start_log_queries() @defer.inlineCallbacks def tearDownUpgradeTest(self): querylog.stop_log_queries(self._sql_log_handler) if self.use_real_db: yield self.tearDownRealDatabase() if self.basedir: shutil.rmtree(self.basedir) # save subclasses the trouble of calling our setUp and tearDown methods def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setUpUpgradeTest() @defer.inlineCallbacks def tearDown(self): yield self.tearDownUpgradeTest() yield self.tear_down_test_reactor() @defer.inlineCallbacks def assertModelMatches(self): def comp(engine): # use compare_model_to_db, which gets everything but indexes with engine.connect() as conn: opts = None if engine.dialect.name == 'mysql': # Disable type comparisons for mysql. Since 1.12.0 it is enabled by default. # https://alembic.sqlalchemy.org/en/latest/changelog.html#change-1.12.0 # There is issue with comparison MEDIUMBLOB() vs LargeBinary(length=65536) in logchunks table. opts = {"compare_type": False} diff = compare_metadata( MigrationContext.configure(conn, opts=opts), self.db.model.metadata ) if engine.dialect.name == 'mysql': # MySQL/MyISAM does not support foreign keys, which is expected. diff = [d for d in diff if d[0] != 'add_fk'] if diff: return diff # check indexes manually insp = sa.inspect(engine) # unique, name, column_names diff = [] for tbl in self.db.model.metadata.sorted_tables: exp = sorted( [ { "name": idx.name, "unique": idx.unique and 1 or 0, "column_names": sorted([c.name for c in idx.columns]), } for idx in tbl.indexes ], key=lambda x: x['name'], ) # include implied indexes on postgres and mysql if engine.dialect.name == 'mysql': implied = [ idx for (tname, idx) in self.db.model.implied_indexes if tname == tbl.name ] exp = sorted(exp + implied, key=lambda k: k["name"]) got = sorted(insp.get_indexes(tbl.name), key=lambda x: x['name']) if exp != got: got_names = {idx['name'] for idx in got} exp_names = {idx['name'] for idx in exp} got_info = dict((idx['name'], idx) for idx in got) exp_info = dict((idx['name'], idx) for idx in exp) for name in got_names - exp_names: diff.append( f"got unexpected index {name} on table {tbl.name}: " f"{got_info[name]!r}" ) for name in exp_names - got_names: diff.append(f"missing index {name} on table {tbl.name}") for name in got_names & exp_names: gi = { "name": name, "unique": got_info[name]['unique'] and 1 or 0, "column_names": sorted(got_info[name]['column_names']), } ei = exp_info[name] if gi != ei: diff.append( f"index {name} on table {tbl.name} differs: got {gi}; exp {ei}" ) if diff: return "\n".join(diff) return None try: diff = yield self.db.pool.do_with_engine(comp) except TypeError as e: # older sqlites cause failures in reflection, which manifest as a # TypeError. Reflection is only used for tests, so we can just skip # this test on such platforms. We still get the advantage of trying # the upgrade, at any rate. raise unittest.SkipTest( "model comparison skipped: bugs in schema reflection on this sqlite version" ) from e if diff: self.fail("\n" + pprint.pformat(diff)) def gotError(self, e): if isinstance(e, (sqlite3.DatabaseError, DatabaseError)): if "file is encrypted or is not a database" in str(e): self.flushLoggedErrors(sqlite3.DatabaseError) self.flushLoggedErrors(DatabaseError) raise unittest.SkipTest(f"sqlite dump not readable on this machine {e!s}") @defer.inlineCallbacks def do_test_upgrade(self, pre_callbacks=None): if pre_callbacks is None: pre_callbacks = [] yield from pre_callbacks try: yield self.db.model.upgrade() except Exception as e: self.gotError(e) yield self.db.pool.do(self.verify_thd) yield self.assertModelMatches() class UpgradeTestEmpty(UpgradeTestMixin, unittest.TestCase): use_real_db = True @defer.inlineCallbacks def test_emptydb_modelmatches(self): os_encoding = locale.getpreferredencoding() try: '\N{SNOWMAN}'.encode(os_encoding) except UnicodeEncodeError as e: # Default encoding of Windows console is 'cp1252' # which cannot encode the snowman. raise unittest.SkipTest( "Cannot encode weird unicode " f"on this platform with {os_encoding}" ) from e yield self.db.model.upgrade() yield self.assertModelMatches() class UpgradeTestV2_10_5(UpgradeTestMixin, unittest.TestCase): source_tarball = "v2.10.5.tgz" def test_upgrade(self): return self.do_test_upgrade() def verify_thd(self, conn): pass @defer.inlineCallbacks def test_got_invalid_sqlite_file(self): def upgrade(): return defer.fail(sqlite3.DatabaseError('file is encrypted or is not a database')) self.db.model.upgrade = upgrade with self.assertRaises(unittest.SkipTest): yield self.do_test_upgrade() @defer.inlineCallbacks def test_got_invalid_sqlite_file2(self): def upgrade(): return defer.fail(DatabaseError('file is encrypted or is not a database', None, None)) self.db.model.upgrade = upgrade with self.assertRaises(unittest.SkipTest): yield self.do_test_upgrade() class UpgradeTestV090b4(UpgradeTestMixin, unittest.TestCase): source_tarball = "v090b4.tgz" def gotError(self, e): self.flushLoggedErrors(UpgradeFromBefore3p0Error) def test_upgrade(self): return self.do_test_upgrade() def verify_thd(self, conn): r = conn.execute(sa.text("select version from migrate_version limit 1")) version = r.scalar() self.assertEqual(version, 44) def assertModelMatches(self): pass class UpgradeTestV087p1(UpgradeTestMixin, unittest.TestCase): source_tarball = "v087p1.tgz" def gotError(self, e): self.flushLoggedErrors(UpgradeFromBefore0p9Error) def verify_thd(self, conn): r = conn.execute(sa.text("select version from migrate_version limit 1")) version = r.scalar() self.assertEqual(version, 22) def assertModelMatches(self): pass def test_upgrade(self): return self.do_test_upgrade()
11,403
Python
.py
253
33.604743
114
0.603246
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,602
test_customservices.py
buildbot_buildbot/master/buildbot/test/integration/test_customservices.py
# 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.internet import defer from buildbot.test.util.integration import RunFakeMasterTestCase # This integration test creates a master and worker environment, # with one builder and a custom step # The custom step is using a CustomService, in order to calculate its result # we make sure that we can reconfigure the master while build is running class CustomServiceMaster(RunFakeMasterTestCase): def setUp(self): super().setUp() self.num_reconfig = 0 def create_master_config(self): self.num_reconfig += 1 from buildbot.config import BuilderConfig from buildbot.process.factory import BuildFactory from buildbot.steps.shell import ShellCommand from buildbot.util.service import BuildbotService class MyShellCommand(ShellCommand): def getResultSummary(self): service = self.master.service_manager.namedServices['myService'] return {"step": f'num reconfig: {service.num_reconfig}'} class MyService(BuildbotService): name = "myService" def reconfigService(self, num_reconfig): self.num_reconfig = num_reconfig return defer.succeed(None) config_dict = { 'builders': [ BuilderConfig( name="builder", workernames=["worker1"], factory=BuildFactory([MyShellCommand(command='echo hei')]), ), ], 'workers': [self.createLocalWorker('worker1')], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, 'db_url': 'sqlite://', # we need to make sure reconfiguration uses the same URL 'services': [MyService(num_reconfig=self.num_reconfig)], } if self.num_reconfig == 3: config_dict['services'].append( MyService(name="myService2", num_reconfig=self.num_reconfig) ) return config_dict @defer.inlineCallbacks def test_custom_service(self): yield self.setup_master(self.create_master_config()) yield self.do_test_build_by_name('builder') self.assertStepStateString(1, 'worker worker1 ready') self.assertStepStateString(2, 'num reconfig: 1') myService = self.master.service_manager.namedServices['myService'] self.assertEqual(myService.num_reconfig, 1) self.assertTrue(myService.running) # We do several reconfig, and make sure the service # are reconfigured as expected yield self.reconfig_master(self.create_master_config()) yield self.do_test_build_by_name('builder') self.assertEqual(myService.num_reconfig, 2) self.assertStepStateString(1, 'worker worker1 ready') self.assertStepStateString(2, 'num reconfig: 1') yield self.reconfig_master(self.create_master_config()) myService2 = self.master.service_manager.namedServices['myService2'] self.assertTrue(myService2.running) self.assertEqual(myService2.num_reconfig, 3) self.assertEqual(myService.num_reconfig, 3) yield self.reconfig_master(self.create_master_config()) # second service removed self.assertNotIn('myService2', self.master.service_manager.namedServices) self.assertFalse(myService2.running) self.assertEqual(myService2.num_reconfig, 3) self.assertEqual(myService.num_reconfig, 4)
4,249
Python
.py
86
40.593023
92
0.682049
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,603
test_integration_mastershell.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_mastershell.py
# 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 twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.test.util.integration import RunMasterBase from buildbot.util import asyncSleep # This integration test creates a master and worker environment, # with one builders and a shellcommand step # meant to be a template for integration steps class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config_for_master_command(self, **kwargs): c = {} c['schedulers'] = [schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"])] f = BuildFactory() f.addStep(steps.MasterShellCommand(**kwargs)) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) def get_change(self): return { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } @defer.inlineCallbacks def test_shell(self): yield self.setup_config_for_master_command(command='echo hello') build = yield self.doForceBuild(wantSteps=True, useChange=self.get_change(), wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['steps'][1]['state_string'], 'Ran') @defer.inlineCallbacks def test_logs(self): yield self.setup_config_for_master_command(command=[sys.executable, '-c', 'print("hello")']) build = yield self.doForceBuild(wantSteps=True, useChange=self.get_change(), wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "hello") self.assertTrue(res) self.assertEqual(build['steps'][1]['state_string'], 'Ran') @defer.inlineCallbacks def test_fails(self): yield self.setup_config_for_master_command(command=[sys.executable, '-c', 'exit(1)']) build = yield self.doForceBuild(wantSteps=True, useChange=self.get_change(), wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['steps'][1]['state_string'], 'failed (1) (failure)') @defer.inlineCallbacks def test_interrupt(self): yield self.setup_config_for_master_command( name='sleep', command=[sys.executable, '-c', "while True: pass"] ) d = self.doForceBuild(wantSteps=True, useChange=self.get_change(), wantLogs=True) @defer.inlineCallbacks def on_new_step(_, data): if data['name'] == 'sleep': # wait until the step really starts yield asyncSleep(1) brs = yield self.master.data.get(('buildrequests',)) brid = brs[-1]['buildrequestid'] self.master.data.control( 'cancel', {'reason': 'cancelled by test'}, ('buildrequests', brid) ) yield self.master.mq.startConsuming(on_new_step, ('steps', None, 'new')) build = yield d self.assertEqual(build['buildid'], 1) if sys.platform == 'win32': self.assertEqual(build['steps'][1]['state_string'], 'failed (1) (exception)') else: self.assertEqual(build['steps'][1]['state_string'], 'killed (9) (exception)')
4,215
Python
.py
87
40.91954
100
0.666504
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,604
test_try_client_e2e.py
buildbot_buildbot/master/buildbot/test/integration/test_try_client_e2e.py
# 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.internet import defer from twisted.internet import reactor from buildbot.test.util.decorators import flaky from buildbot.test.util.integration import RunMasterBase # This integration test tests that the try command line works end2end class TryClientE2E(RunMasterBase): timeout = 15 @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.Try_Userpass( name="try", builderNames=["testy"], port='tcp:0', userpass=[("alice", "pw1")] ) ] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @flaky(bugNumber=7084) @defer.inlineCallbacks def test_shell(self): yield self.setup_config() def trigger_callback(): port = self.master.pbmanager.dispatchers['tcp:0'].port.getHost().port def thd(): os.system( f"buildbot try --connect=pb --master=127.0.0.1:{port} -b testy " "--property=foo:bar --username=alice --passwd=pw1 --vc=none" ) reactor.callInThread(thd) build = yield self.doForceBuild( wantSteps=True, triggerCallback=trigger_callback, wantLogs=True, wantProperties=True ) self.assertEqual(build['buildid'], 1)
2,384
Python
.py
54
37.12963
96
0.686664
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,605
test_process_botmaster.py
buildbot_buildbot/master/buildbot/test/integration/test_process_botmaster.py
# 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 annotations from typing import TYPE_CHECKING from twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.data import resultspec from buildbot.process.factory import BuildFactory from buildbot.process.results import SUCCESS from buildbot.process.workerforbuilder import PingException from buildbot.schedulers import triggerable from buildbot.steps import trigger from buildbot.test.fake.worker import WorkerController from buildbot.test.util.integration import RunFakeMasterTestCase from buildbot.util.twisted import async_to_deferred if TYPE_CHECKING: from typing import Any from typing import Callable from typing import Coroutine from typing import TypeVar from typing_extensions import ParamSpec _T = TypeVar('_T') _P = ParamSpec('_P') class Tests(RunFakeMasterTestCase): @defer.inlineCallbacks def do_terminates_ping_on_shutdown(self, quick_mode): """ During shutdown we want to terminate any outstanding pings. """ controller = WorkerController(self, 'local') config_dict = { 'builders': [ BuilderConfig(name="testy", workernames=['local'], factory=BuildFactory()), ], 'workers': [controller.worker], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('testy') yield controller.connect_worker() controller.sever_connection() yield self.create_build_request([builder_id]) # give time for any delayed actions to complete self.reactor.advance(1) yield self.master.botmaster.cleanShutdown(quickMode=quick_mode, stopReactor=False) self.flushLoggedErrors(PingException) def test_terminates_ping_on_shutdown_quick_mode(self): return self.do_terminates_ping_on_shutdown(quick_mode=True) def test_terminates_ping_on_shutdown_slow_mode(self): return self.do_terminates_ping_on_shutdown(quick_mode=False) def _wait_step(self, wait_step: float = 0.1, timeout_seconds: float = 5.0): for _ in range(0, int(timeout_seconds * 1000), int(wait_step * 1000)): self.reactor.advance(wait_step) yield async def _query_until_result( self, fn: Callable[_P, Coroutine[Any, Any, _T]], *args: _P.args, **kwargs: _P.kwargs, ) -> _T: for _ in self._wait_step(): result = await fn(*args, **kwargs) if result: return result self.fail('Fail to get result in appropriate timeout') @async_to_deferred async def test_shutdown_busy_with_child(self) -> None: """ Test that clean shutdown complete correctly even when a running Build trigger another and wait for it's completion """ parent_controller = WorkerController(self, 'parent_worker') child_controller = WorkerController(self, 'child_worker') config_dict = { 'builders': [ BuilderConfig( name="parent", workernames=[parent_controller.worker.name], factory=BuildFactory([ trigger.Trigger(schedulerNames=['triggerable'], waitForFinish=True) ]), ), BuilderConfig( name="child", workernames=[child_controller.worker.name], factory=BuildFactory() ), ], 'workers': [parent_controller.worker, child_controller.worker], 'schedulers': [triggerable.Triggerable(name='triggerable', builderNames=['child'])], 'protocols': {'null': {}}, 'multiMaster': True, 'collapseRequests': False, } await self.setup_master(config_dict) parent_builder_id = await self.master.data.updates.findBuilderId('parent') child_builder_id = await self.master.data.updates.findBuilderId('child') await parent_controller.connect_worker() # Pause worker of Child builder so we know the build won't start before we start shutdown await child_controller.disconnect_worker() # Create a Child build without Parent so we can later make sure it was not executed _, first_child_brids = await self.create_build_request([child_builder_id]) self.assertEqual(len(first_child_brids), 1) _, _parent_brids = await self.create_build_request([parent_builder_id]) self.assertEqual(len(_parent_brids), 1) parent_brid = _parent_brids[parent_builder_id] # wait until Parent trigger it's Child build parent_buildid = ( await self._query_until_result( self.master.data.get, ("builds",), filters=[resultspec.Filter('buildrequestid', 'eq', [parent_brid])], ) )[0]['buildid'] # now get the child_buildset child_buildsetid = ( await self._query_until_result( self.master.data.get, ("buildsets",), filters=[resultspec.Filter('parent_buildid', 'eq', [parent_buildid])], ) )[0]['bsid'] # and finally, the child BuildReques child_buildrequest = ( await self._query_until_result( self.master.data.get, ("buildrequests",), filters=[resultspec.Filter('buildsetid', 'eq', [child_buildsetid])], ) )[0] # now we know the Parent's Child BuildRequest exists, # create a second Child without Parent for good measure _, second_child_brids = await self.create_build_request([child_builder_id]) self.assertEqual(len(second_child_brids), 1) # Now start the clean shutdown shutdown_deferred: defer.Deferred[None] = self.master.botmaster.cleanShutdown( quickMode=False, stopReactor=False, ) # Connect back Child worker so the build can happen await child_controller.connect_worker() # wait for the child request to be claimed, and completed for _ in self._wait_step(): if child_buildrequest['claimed'] and child_buildrequest['complete']: break child_buildrequest = await self.master.data.get( ("buildrequests", child_buildrequest['buildrequestid']), ) self.assertIsNotNone(child_buildrequest) self.assertEqual(child_buildrequest['results'], SUCCESS) # make sure parent-less BuildRequest weren't built first_child_request = await self.master.data.get( ("buildrequests", first_child_brids[child_builder_id]), ) self.assertIsNotNone(first_child_request) self.assertFalse(first_child_request['claimed']) self.assertFalse(first_child_request['complete']) second_child_request = await self.master.data.get( ("buildrequests", second_child_brids[child_builder_id]), ) self.assertIsNotNone(second_child_request) self.assertFalse(second_child_request['claimed']) self.assertFalse(second_child_request['complete']) # confirm Master shutdown await shutdown_deferred self.assertTrue(shutdown_deferred.called)
8,184
Python
.py
178
36.58427
100
0.649147
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,606
test_download_secret_to_worker.py
buildbot_buildbot/master/buildbot/test/integration/test_download_secret_to_worker.py
# 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 parameterized import parameterized from twisted.internet import defer from twisted.trial.unittest import SkipTest from buildbot.config import BuilderConfig from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.steps.download_secret_to_worker import DownloadSecretsToWorker from buildbot.steps.download_secret_to_worker import RemoveWorkerFileSecret from buildbot.test.util.integration import RunMasterBase class DownloadSecretsBase(RunMasterBase): def setUp(self): self.temp_dir = os.path.abspath(self.mktemp()) os.mkdir(self.temp_dir) @defer.inlineCallbacks def setup_config(self, path, data, remove=False): c = {} c['schedulers'] = [ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() f.addStep(DownloadSecretsToWorker([(path, data)])) if remove: f.addStep(RemoveWorkerFileSecret([(path, data)])) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) def get_homedir(self): path = os.path.expanduser('~') if path == '~': return None return path @parameterized.expand([ ('simple', False, True), ('relative_to_home', True, True), ('simple_remove', False, True), ('relative_to_home_remove', True, True), ]) @defer.inlineCallbacks def test_transfer_secrets(self, name, relative_to_home, remove): bb_path = self.temp_dir if relative_to_home: homedir = self.get_homedir() if homedir is None: raise SkipTest("Home directory is not known") try: bb_path = os.path.join('~', os.path.relpath(bb_path, homedir)) except ValueError as e: raise SkipTest("Can't get relative path from home directory to test files") from e if not os.path.isdir(os.path.expanduser(bb_path)): raise SkipTest("Unknown error preparing test paths") path = os.path.join(bb_path, 'secret_path') data = 'some data' yield self.setup_config(path, data, remove=remove) yield self.doForceBuild() if remove: self.assertFalse(os.path.exists(path)) else: self.assertTrue(os.path.isfile(path)) with open(path, encoding='utf-8') as f: self.assertEqual(f.read(), data) class DownloadSecretsBasePb(DownloadSecretsBase): proto = "pb" class DownloadSecretsBaseMsgPack(DownloadSecretsBase): proto = "msgpack"
3,371
Python
.py
76
37.407895
98
0.688244
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,607
test_graphql.py
buildbot_buildbot/master/buildbot/test/integration/test_graphql.py
# 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 annotations import json import os from twisted.internet import defer from twisted.trial import unittest from buildbot.data import connector as dataconnector from buildbot.data.graphql import GraphQLConnector from buildbot.mq import connector as mqconnector from buildbot.process.results import SUCCESS from buildbot.schedulers.forcesched import ForceScheduler from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util import toJson try: from ruamel.yaml import YAML except ImportError: YAML = None # type: ignore[assignment,misc] try: import graphql as graphql_core except ImportError: graphql_core = None # type: ignore[assignment,misc] class GraphQL(unittest.TestCase, TestReactorMixin): if not graphql_core: skip = "graphql-core is required for GraphQL integration tests" master = None def load_yaml(self, f): if YAML is None: # for running the test ruamel is not needed (to avoid a build dependency for distros) import yaml return yaml.safe_load(f) self.yaml = YAML() self.yaml.default_flow_style = False # default is round-trip return self.yaml.load(f) def save_yaml(self, data, f): if YAML is None: raise ImportError("please install ruamel.yaml for test regeneration") self.yaml.dump(data, f) @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(use_asyncio=True) master = yield fakemaster.make_master(self, wantDb=True) master.config.mq = {'type': "simple"} master.mq = mqconnector.MQConnector() yield master.mq.setServiceParent(master) yield master.mq.setup() master.data = dataconnector.DataConnector() yield master.data.setServiceParent(master) master.graphql = GraphQLConnector() yield master.graphql.setServiceParent(master) master.config.www = {'graphql': {"debug": True}} master.graphql.reconfigServiceWithBuildbotConfig(master.config) self.master = master scheds = [ ForceScheduler( name="force", builderNames=["runtests0", "runtests1", "runtests2", "slowruntests"] ) ] self.master.allSchedulers = lambda: scheds yield self.master.startService() yield self.insert_initial_data() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() @defer.inlineCallbacks def insert_initial_data(self): yield self.master.db.insert_test_data([ fakedb.Master(id=1), fakedb.Worker(id=1, name='example-worker'), fakedb.Scheduler(id=1, name='custom', enabled=1), fakedb.Scheduler(id=2, name='all', enabled=2), fakedb.Scheduler(id=3, name='force', enabled=3), fakedb.SchedulerMaster(schedulerid=1, masterid=1), fakedb.SchedulerMaster(schedulerid=2, masterid=1), fakedb.SchedulerMaster(schedulerid=3, masterid=1), fakedb.Builder(id=1, name='runtests1'), fakedb.Builder(id=2, name='runtests2'), fakedb.Builder(id=3, name='runtests3'), fakedb.BuilderMaster(id=1, builderid=1, masterid=1), fakedb.BuilderMaster(id=2, builderid=2, masterid=1), fakedb.BuilderMaster(id=3, builderid=3, masterid=1), fakedb.Tag(id=1, name='tag1'), fakedb.Tag(id=2, name='tag12'), fakedb.Tag(id=3, name='tag23'), fakedb.BuildersTags(id=1, builderid=1, tagid=1), fakedb.BuildersTags(id=2, builderid=1, tagid=2), fakedb.BuildersTags(id=3, builderid=2, tagid=2), fakedb.BuildersTags(id=4, builderid=2, tagid=3), fakedb.BuildersTags(id=5, builderid=3, tagid=3), fakedb.Buildset( id=1, results=SUCCESS, reason="Force reason 1", submitted_at=100000, complete_at=100110, complete=1, ), fakedb.Buildset( id=2, results=SUCCESS, reason="Force reason 2", submitted_at=100200, complete_at=100330, complete=1, ), fakedb.Buildset( id=3, results=SUCCESS, reason="Force reason 3", submitted_at=100400, complete_at=100550, complete=1, ), fakedb.BuildsetProperty( buildsetid=1, property_name='scheduler', property_value='["custom", "Scheduler"]' ), fakedb.BuildsetProperty( buildsetid=2, property_name='scheduler', property_value='["all", "Scheduler"]' ), fakedb.BuildsetProperty( buildsetid=3, property_name='scheduler', property_value='["force", "Scheduler"]' ), fakedb.BuildsetProperty( buildsetid=3, property_name='owner', property_value='["[email protected]", "Force Build Form"]', ), fakedb.SourceStamp(id=1, branch='master', revision='1234abcd'), fakedb.Change(changeid=1, branch='master', revision='1234abcd', sourcestampid=1), fakedb.ChangeProperty( changeid=1, property_name="owner", property_value='["[email protected]", "change"]' ), fakedb.ChangeProperty( changeid=1, property_name="other_prop", property_value='["value", "change"]' ), fakedb.BuildsetSourceStamp(id=1, buildsetid=1, sourcestampid=1), fakedb.BuildsetSourceStamp(id=2, buildsetid=2, sourcestampid=1), fakedb.BuildsetSourceStamp(id=3, buildsetid=3, sourcestampid=1), fakedb.BuildRequest( id=1, buildsetid=1, builderid=1, results=SUCCESS, submitted_at=100001, complete_at=100109, complete=1, ), fakedb.BuildRequest( id=2, buildsetid=2, builderid=1, results=SUCCESS, submitted_at=100201, complete_at=100329, complete=1, ), fakedb.BuildRequest( id=3, buildsetid=3, builderid=2, results=SUCCESS, submitted_at=100401, complete_at=100549, complete=1, ), fakedb.Build( id=1, number=1, buildrequestid=1, builderid=1, workerid=1, masterid=1001, started_at=100002, complete_at=100108, state_string='build successful', results=SUCCESS, ), fakedb.Build( id=2, number=2, buildrequestid=2, builderid=1, workerid=1, masterid=1001, started_at=100202, complete_at=100328, state_string='build successful', results=SUCCESS, ), fakedb.Build( id=3, number=1, buildrequestid=3, builderid=2, workerid=1, masterid=1001, started_at=100402, complete_at=100548, state_string='build successful', results=SUCCESS, ), fakedb.BuildProperty( buildid=3, name='reason', value='"force build"', source="Force Build Form" ), fakedb.BuildProperty( buildid=3, name='owner', value='"[email protected]"', source="Force Build Form" ), fakedb.BuildProperty(buildid=3, name='scheduler', value='"force"', source="Scheduler"), fakedb.BuildProperty( buildid=3, name='buildername', value='"runtests3"', source="Builder" ), fakedb.BuildProperty( buildid=3, name='workername', value='"example-worker"', source="Worker" ), fakedb.Step( id=1, number=1, name='step1', buildid=1, started_at=100010, locks_acquired_at=100012, complete_at=100019, state_string='step1 done', ), fakedb.Step( id=2, number=2, name='step2', buildid=1, started_at=100020, locks_acquired_at=100022, complete_at=100029, state_string='step2 done', ), fakedb.Step( id=3, number=3, name='step3', buildid=1, started_at=100030, locks_acquired_at=100032, complete_at=100039, state_string='step3 done', ), fakedb.Step( id=11, number=1, name='step1', buildid=2, started_at=100210, locks_acquired_at=100212, complete_at=100219, state_string='step1 done', ), fakedb.Step( id=12, number=2, name='step2', buildid=2, started_at=100220, locks_acquired_at=100222, complete_at=100229, state_string='step2 done', ), fakedb.Step( id=13, number=3, name='step3', buildid=2, started_at=100230, locks_acquired_at=100232, complete_at=100239, state_string='step3 done', ), fakedb.Step( id=21, number=1, name='step1', buildid=3, started_at=100410, locks_acquired_at=100412, complete_at=100419, state_string='step1 done', ), fakedb.Step( id=22, number=2, name='step2', buildid=3, started_at=100420, locks_acquired_at=100422, complete_at=100429, state_string='step2 done', ), fakedb.Step( id=23, number=3, name='step3', buildid=3, started_at=100430, locks_acquired_at=100432, complete_at=100439, state_string='step3 done', ), fakedb.Log(id=1, name='stdio', slug='stdio', stepid=1, complete=1, num_lines=10), fakedb.Log(id=2, name='stdio', slug='stdio', stepid=2, complete=1, num_lines=20), fakedb.Log(id=3, name='stdio', slug='stdio', stepid=3, complete=1, num_lines=30), fakedb.Log(id=11, name='stdio', slug='stdio', stepid=11, complete=1, num_lines=30), fakedb.Log(id=12, name='stdio', slug='stdio', stepid=12, complete=1, num_lines=40), fakedb.Log(id=13, name='stdio', slug='stdio', stepid=13, complete=1, num_lines=50), fakedb.Log(id=21, name='stdio', slug='stdio', stepid=21, complete=1, num_lines=50), fakedb.Log(id=22, name='stdio', slug='stdio', stepid=22, complete=1, num_lines=60), fakedb.Log(id=23, name='stdio', slug='stdio', stepid=23, complete=1, num_lines=70), fakedb.LogChunk(logid=1, first_line=0, last_line=2, content='o line1\no line2\n'), fakedb.LogChunk(logid=1, first_line=2, last_line=3, content='o line3\n'), fakedb.LogChunk( logid=2, first_line=0, last_line=4, content='o line1\no line2\no line3\no line4\n' ), ]) @defer.inlineCallbacks def test_examples_from_yaml(self): """This test takes input from yaml file containing queries to execute and expected results. In order to ease writing of tests, if the expected key is not found, it is automatically generated, so developer only has to review results Full regen can still be done with regen local variable just below """ regen = False need_save = False fn = os.path.join(os.path.dirname(__file__), "test_graphql_queries.yaml") with open(fn, encoding='utf-8') as f: data = self.load_yaml(f) focussed_data = [test for test in data if test.get('focus')] if not focussed_data: focussed_data = data for test in focussed_data: query = test['query'] result = yield self.master.graphql.query(query) self.assertIsNone(result.errors) if 'expected' not in test or regen: need_save = True test['expected'] = result.data else: # remove ruamel metadata before compare (it is needed for round-trip regen, # but confuses the comparison) result_data = json.loads(json.dumps(result.data, default=toJson)) expected = json.loads(json.dumps(test['expected'], default=toJson)) self.assertEqual(result_data, expected, f"for {query}") if need_save: with open(fn, 'w', encoding='utf-8') as f: self.save_yaml(data, f) @defer.inlineCallbacks def test_buildrequests_builds(self): data = yield self.master.graphql.query( "{buildrequests{buildrequestid, builds{number, buildrequestid}}}" ) self.assertEqual(data.errors, None) for br in data.data["buildrequests"]: for build in br["builds"]: self.assertEqual(build["buildrequestid"], br["buildrequestid"])
15,112
Python
.py
374
27.518717
99
0.54826
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,608
test_virtual_builder.py
buildbot_buildbot/master/buildbot/test/integration/test_virtual_builder.py
# 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.internet import defer from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builder and a shellcommand step # meant to be a template for integration steps class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) c['builders'] = [ BuilderConfig( name="testy", workernames=["local1"], properties={ 'virtual_builder_name': 'virtual_testy', 'virtual_builder_description': 'I am a virtual builder', 'virtual_builder_project': 'virtual_project', 'virtual_builder_tags': ['virtual'], }, factory=f, ) ] yield self.setup_master(c) @defer.inlineCallbacks def test_shell(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) builders = yield self.master.data.get(("builders",)) self.assertEqual(len(builders), 2) self.assertEqual( builders[1], { 'masterids': [], 'tags': ['virtual', '_virtual_'], 'projectid': 1, 'description': 'I am a virtual builder', 'description_format': None, 'description_html': None, 'name': 'virtual_testy', 'builderid': 2, }, ) self.assertEqual(build['builderid'], builders[1]['builderid'])
2,760
Python
.py
65
33.4
91
0.633048
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,609
test_locks.py
buildbot_buildbot/master/buildbot/test/integration/test_locks.py
# 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 parameterized import parameterized from twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.plugins import util from buildbot.process.factory import BuildFactory from buildbot.process.results import SUCCESS from buildbot.test.fake.step import BuildStepController from buildbot.test.util.integration import RunFakeMasterTestCase from buildbot.util.eventual import flushEventualQueue class Tests(RunFakeMasterTestCase): @defer.inlineCallbacks def create_single_worker_two_builder_lock_config(self, lock_cls, mode): stepcontrollers = [BuildStepController(), BuildStepController()] lock = lock_cls("lock1", maxCount=1) config_dict = { 'builders': [ BuilderConfig( name='builder1', workernames=['worker1'], factory=BuildFactory([stepcontrollers[0].step]), locks=[lock.access(mode)], ), BuilderConfig( name='builder2', workernames=['worker1'], factory=BuildFactory([stepcontrollers[1].step]), locks=[lock.access(mode)], ), ], 'workers': [ self.createLocalWorker('worker1'), ], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('builder1')), (yield self.master.data.updates.findBuilderId('builder2')), ] return stepcontrollers, builder_ids @defer.inlineCallbacks def create_single_worker_two_builder_step_lock_config(self, lock_cls, mode): lock = lock_cls("lock1", maxCount=1) stepcontrollers = [ BuildStepController(locks=[lock.access(mode)]), BuildStepController(locks=[lock.access(mode)]), ] config_dict = { 'builders': [ BuilderConfig( name='builder1', workernames=['worker1'], factory=BuildFactory([stepcontrollers[0].step]), ), BuilderConfig( name='builder2', workernames=['worker1'], factory=BuildFactory([stepcontrollers[1].step]), ), ], 'workers': [ self.createLocalWorker('worker1'), ], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('builder1')), (yield self.master.data.updates.findBuilderId('builder2')), ] return stepcontrollers, builder_ids @defer.inlineCallbacks def create_two_worker_two_builder_lock_config(self, mode): stepcontrollers = [BuildStepController(), BuildStepController()] master_lock = util.MasterLock("lock1", maxCount=1) config_dict = { 'builders': [ BuilderConfig( name='builder1', workernames=['worker1'], factory=BuildFactory([stepcontrollers[0].step]), locks=[master_lock.access(mode)], ), BuilderConfig( name='builder2', workernames=['worker2'], factory=BuildFactory([stepcontrollers[1].step]), locks=[master_lock.access(mode)], ), ], 'workers': [ self.createLocalWorker('worker1'), self.createLocalWorker('worker2'), ], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('builder1')), (yield self.master.data.updates.findBuilderId('builder2')), ] return stepcontrollers, builder_ids @defer.inlineCallbacks def assert_two_builds_created_one_after_another(self, stepcontrollers, builder_ids): # start two builds and verify that a second build starts after the # first is finished yield self.create_build_request([builder_ids[0]]) yield self.create_build_request([builder_ids[1]]) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 1) self.assertEqual(builds[0]['results'], None) self.assertEqual(builds[0]['builderid'], builder_ids[0]) stepcontrollers[0].finish_step(SUCCESS) # execute Build.releaseLocks which is called eventually yield flushEventualQueue() builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) self.assertEqual(builds[0]['results'], SUCCESS) self.assertEqual(builds[1]['results'], None) self.assertEqual(builds[1]['builderid'], builder_ids[1]) stepcontrollers[1].finish_step(SUCCESS) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) self.assertEqual(builds[0]['results'], SUCCESS) self.assertEqual(builds[1]['results'], SUCCESS) @defer.inlineCallbacks def assert_two_steps_created_one_after_another(self, stepcontrollers, builder_ids): # start two builds and verify that a second build starts after the # first is finished yield self.create_build_request([builder_ids[0]]) yield self.create_build_request([builder_ids[1]]) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) self.assertEqual(builds[0]['results'], None) self.assertEqual(builds[0]['builderid'], builder_ids[0]) self.assertEqual(builds[1]['results'], None) self.assertEqual(builds[1]['builderid'], builder_ids[1]) self.assertTrue(stepcontrollers[0].running) self.assertFalse(stepcontrollers[1].running) stepcontrollers[0].finish_step(SUCCESS) yield flushEventualQueue() self.assertFalse(stepcontrollers[0].running) self.assertTrue(stepcontrollers[1].running) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) self.assertEqual(builds[0]['results'], SUCCESS) self.assertEqual(builds[1]['results'], None) stepcontrollers[1].finish_step(SUCCESS) yield flushEventualQueue() builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) self.assertEqual(builds[0]['results'], SUCCESS) self.assertEqual(builds[1]['results'], SUCCESS) @parameterized.expand([ (util.MasterLock, 'counting'), (util.MasterLock, 'exclusive'), (util.WorkerLock, 'counting'), (util.WorkerLock, 'exclusive'), ]) @defer.inlineCallbacks def test_builder_lock_prevents_concurrent_builds(self, lock_cls, mode): """ Tests whether a builder lock works at all in preventing a build when the lock is taken. """ stepcontrollers, builder_ids = yield self.create_single_worker_two_builder_lock_config( lock_cls, mode ) yield self.assert_two_builds_created_one_after_another(stepcontrollers, builder_ids) @parameterized.expand([ (util.MasterLock, 'counting'), (util.MasterLock, 'exclusive'), (util.WorkerLock, 'counting'), (util.WorkerLock, 'exclusive'), ]) @defer.inlineCallbacks def test_step_lock_prevents_concurrent_builds(self, lock_cls, mode): """ Tests whether a builder lock works at all in preventing a build when the lock is taken. """ stepcontrollers, builder_ids = yield self.create_single_worker_two_builder_step_lock_config( lock_cls, mode ) yield self.assert_two_steps_created_one_after_another(stepcontrollers, builder_ids) @parameterized.expand(['counting', 'exclusive']) @defer.inlineCallbacks def test_builder_lock_release_wakes_builds_for_another_builder(self, mode): """ If a builder locks a master lock then the build request distributor must retry running any buildrequests that might have been not scheduled due to unavailability of that lock when the lock becomes available. """ stepcontrollers, builder_ids = yield self.create_two_worker_two_builder_lock_config(mode) yield self.assert_two_builds_created_one_after_another(stepcontrollers, builder_ids) class TestReconfig(RunFakeMasterTestCase): def create_stepcontrollers(self, count, lock, mode): stepcontrollers = [] for _ in range(count): locks = [lock.access(mode)] if lock is not None else [] stepcontrollers.append(BuildStepController(locks=locks)) return stepcontrollers def update_builder_config(self, config_dict, stepcontrollers, lock, mode): config_dict['builders'] = [] for i, stepcontroller in enumerate(stepcontrollers): locks = [lock.access(mode)] if lock is not None else [] b = BuilderConfig( name=f'builder{i}', workernames=['worker1'], factory=BuildFactory([stepcontroller.step]), locks=locks, ) config_dict['builders'].append(b) @defer.inlineCallbacks def create_single_worker_n_builder_lock_config(self, builder_count, lock_cls, max_count, mode): stepcontrollers = self.create_stepcontrollers(builder_count, None, None) lock = lock_cls("lock1", maxCount=max_count) config_dict = { 'builders': [], 'workers': [ self.createLocalWorker('worker1'), ], 'protocols': {'null': {}}, 'multiMaster': True, } self.update_builder_config(config_dict, stepcontrollers, lock, mode) yield self.setup_master(config_dict) builder_ids = [] for i in range(builder_count): builder_ids.append((yield self.master.data.updates.findBuilderId(f'builder{i}'))) return stepcontrollers, config_dict, lock, builder_ids @defer.inlineCallbacks def create_single_worker_n_builder_step_lock_config( self, builder_count, lock_cls, max_count, mode ): lock = lock_cls("lock1", maxCount=max_count) stepcontrollers = self.create_stepcontrollers(builder_count, lock, mode) config_dict = { 'builders': [], 'workers': [ self.createLocalWorker('worker1'), ], 'protocols': {'null': {}}, 'multiMaster': True, } self.update_builder_config(config_dict, stepcontrollers, None, None) yield self.setup_master(config_dict) builder_ids = [] for i in range(builder_count): builder_ids.append((yield self.master.data.updates.findBuilderId(f'builder{i}'))) return stepcontrollers, config_dict, lock, builder_ids @parameterized.expand([ (3, util.MasterLock, 'counting', 1, 2, 1, 2), (3, util.WorkerLock, 'counting', 1, 2, 1, 2), (3, util.MasterLock, 'counting', 2, 1, 2, 2), (3, util.WorkerLock, 'counting', 2, 1, 2, 2), (2, util.MasterLock, 'exclusive', 1, 2, 1, 1), (2, util.WorkerLock, 'exclusive', 1, 2, 1, 1), (2, util.MasterLock, 'exclusive', 2, 1, 1, 1), (2, util.WorkerLock, 'exclusive', 2, 1, 1, 1), ]) @defer.inlineCallbacks def test_changing_max_lock_count_does_not_break_builder_locks( self, builder_count, lock_cls, mode, max_count_before, max_count_after, allowed_builds_before, allowed_builds_after, ): """ Check that Buildbot does not allow extra claims on a claimed lock after a reconfig that changed the maxCount of that lock. Some Buildbot versions created a completely separate real lock after each maxCount change, which allowed to e.g. take an exclusive lock twice. """ ( stepcontrollers, config_dict, lock, builder_ids, ) = yield self.create_single_worker_n_builder_lock_config( builder_count, lock_cls, max_count_before, mode ) # create a number of builds and check that the expected number of them # start for i in range(builder_count): yield self.create_build_request([builder_ids[i]]) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), allowed_builds_before) # update the config and reconfig the master lock = lock_cls(lock.name, maxCount=max_count_after) self.update_builder_config(config_dict, stepcontrollers, lock, mode) yield self.master.reconfig() yield flushEventualQueue() # check that the number of running builds matches expectation builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), allowed_builds_after) # finish the steps and check that builds finished as expected for stepcontroller in stepcontrollers: stepcontroller.finish_step(SUCCESS) yield flushEventualQueue() builds = yield self.master.data.get(("builds",)) for b in builds[allowed_builds_after:]: self.assertEqual(b['results'], SUCCESS) @parameterized.expand([ (3, util.MasterLock, 'counting', 1, 2, 1, 2), (3, util.WorkerLock, 'counting', 1, 2, 1, 2), (3, util.MasterLock, 'counting', 2, 1, 2, 2), (3, util.WorkerLock, 'counting', 2, 1, 2, 2), (2, util.MasterLock, 'exclusive', 1, 2, 1, 1), (2, util.WorkerLock, 'exclusive', 1, 2, 1, 1), (2, util.MasterLock, 'exclusive', 2, 1, 1, 1), (2, util.WorkerLock, 'exclusive', 2, 1, 1, 1), ]) @defer.inlineCallbacks def test_changing_max_lock_count_does_not_break_step_locks( self, builder_count, lock_cls, mode, max_count_before, max_count_after, allowed_steps_before, allowed_steps_after, ): """ Check that Buildbot does not allow extra claims on a claimed lock after a reconfig that changed the maxCount of that lock. Some Buildbot versions created a completely separate real lock after each maxCount change, which allowed to e.g. take an exclusive lock twice. """ ( stepcontrollers, config_dict, lock, builder_ids, ) = yield self.create_single_worker_n_builder_step_lock_config( builder_count, lock_cls, max_count_before, mode ) # create a number of builds and check that the expected number of them # start their steps for i in range(builder_count): yield self.create_build_request([builder_ids[i]]) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), builder_count) self.assertEqual(sum(sc.running for sc in stepcontrollers), allowed_steps_before) # update the config and reconfig the master lock = lock_cls(lock.name, maxCount=max_count_after) new_stepcontrollers = self.create_stepcontrollers(builder_count, lock, mode) self.update_builder_config(config_dict, new_stepcontrollers, lock, mode) yield self.master.reconfig() yield flushEventualQueue() # check that all builds are still running builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), builder_count) # check that the expected number of steps has been started and that # none of the new steps has been started self.assertEqual(sum(sc.running for sc in stepcontrollers), allowed_steps_before) self.assertEqual(sum(sc.running for sc in new_stepcontrollers), 0) # finish the steps and check that builds finished as expected for stepcontroller in stepcontrollers: stepcontroller.finish_step(SUCCESS) yield flushEventualQueue() builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), builder_count) for b in builds: self.assertEqual(b['results'], SUCCESS) self.assertEqual(sum(sc.running for sc in stepcontrollers), 0) self.assertEqual(sum(sc.running for sc in new_stepcontrollers), 0)
17,570
Python
.py
389
35.11054
100
0.624752
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,610
test_setup_entrypoints.py
buildbot_buildbot/master/buildbot/test/integration/test_setup_entrypoints.py
# 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 importlib import inspect import os import warnings import twisted from packaging.version import parse as parse_version from twisted.trial import unittest from twisted.trial.unittest import SkipTest from zope.interface.verify import verifyClass from buildbot.interfaces import IBuildStep from buildbot.interfaces import IChangeSource from buildbot.interfaces import IScheduler from buildbot.interfaces import IWorker from buildbot.plugins.db import get_plugins def get_python_module_contents(package_name): spec = importlib.util.find_spec(package_name) if spec is None or spec.origin is None: return set() pathname = os.path.dirname(spec.origin) result = set() with os.scandir(pathname) as dir_entries: for dir_entry in dir_entries: filename = dir_entry.name if filename.startswith('__'): continue next_package_name = '.'.join((package_name, filename.partition('.')[0])) if dir_entry.is_file() and filename.endswith('.py'): result.add(next_package_name) if dir_entry.is_dir() and not filename.startswith('.'): # Ignore hidden directories added by various tooling an user may have, e.g. # .ropeproject result.add(next_package_name) result |= get_python_module_contents(next_package_name) return result # NOTE: when running this test locally, make sure to reinstall master after every change to pick up # new entry points. class TestSetupPyEntryPoints(unittest.TestCase): def test_changes(self): known_not_exported = { 'buildbot.changes.gerritchangesource.GerritChangeSourceBase', 'buildbot.changes.base.ReconfigurablePollingChangeSource', 'buildbot.changes.base.ChangeSource', } self.verify_plugins_registered( 'changes', 'buildbot.changes', IChangeSource, known_not_exported ) def test_schedulers(self): known_not_exported = { 'buildbot.schedulers.basic.BaseBasicScheduler', 'buildbot.schedulers.timed.Timed', 'buildbot.schedulers.trysched.TryBase', 'buildbot.schedulers.base.BaseScheduler', 'buildbot.schedulers.timed.NightlyBase', 'buildbot.schedulers.basic.Scheduler', } self.verify_plugins_registered( 'schedulers', 'buildbot.schedulers', IScheduler, known_not_exported ) def test_steps(self): known_not_exported = { 'buildbot.steps.download_secret_to_worker.RemoveWorkerFileSecret', 'buildbot.steps.source.base.Source', 'buildbot.steps.download_secret_to_worker.DownloadSecretsToWorker', 'buildbot.steps.worker.WorkerBuildStep', 'buildbot.steps.vstudio.VisualStudio', } self.verify_plugins_registered('steps', 'buildbot.steps', IBuildStep, known_not_exported) def test_util(self): # work around Twisted bug 9384. if parse_version(twisted.__version__) < parse_version("18.9.0"): raise SkipTest('manhole.py can not be imported on old twisted and new python') known_not_exported = { 'buildbot.util._notifier.Notifier', 'buildbot.util.backoff.ExponentialBackoffEngineAsync', 'buildbot.util.backoff.ExponentialBackoffEngineSync', 'buildbot.util.backoff.BackoffTimeoutExceededError', 'buildbot.util.backoff.ExponentialBackoffEngine', 'buildbot.util.bbcollections.KeyedSets', 'buildbot.util.codebase.AbsoluteSourceStampsMixin', 'buildbot.util.config.ConfiguredMixin', 'buildbot.util.debounce.Debouncer', 'buildbot.util.deferwaiter.DeferWaiter', "buildbot.util.deferwaiter.NonRepeatedActionHandler", 'buildbot.util.deferwaiter.RepeatedActionHandler', 'buildbot.util.git.GitMixin', 'buildbot.util.git.GitStepMixin', 'buildbot.util.git.GitServiceAuth', 'buildbot.util.git.AbstractGitAuth', 'buildbot.util.git.GitStepAuth', 'buildbot.util.giturlparse.GitUrl', 'buildbot.util.httpclientservice.HTTPClientService', 'buildbot.util.httpclientservice.HTTPSession', 'buildbot.util.httpclientservice.TreqResponseWrapper', 'buildbot.util.httpclientservice.TxRequestsResponseWrapper', 'buildbot.util.kubeclientservice.KubeClientService', 'buildbot.util.kubeclientservice.KubeConfigLoaderBase', 'buildbot.util.latent.CompatibleLatentWorkerMixin', 'buildbot.util.lineboundaries.LineBoundaryFinder', 'buildbot.util.lru.AsyncLRUCache', 'buildbot.util.lru.LRUCache', 'buildbot.util.maildir.MaildirService', 'buildbot.util.maildir.NoSuchMaildir', 'buildbot.util.netstrings.NetstringParser', 'buildbot.util.netstrings.NullAddress', 'buildbot.util.netstrings.NullTransport', 'buildbot.util.pathmatch.Matcher', 'buildbot.util.poll.Poller', 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', 'buildbot.util.protocol.LineBuffer', 'buildbot.util.protocol.LineProcessProtocol', 'buildbot.util.pullrequest.PullRequestMixin', 'buildbot.util.queue.ConnectableThreadQueue', 'buildbot.util.queue.UndoableQueue', 'buildbot.util.raml.RamlLoader', 'buildbot.util.raml.RamlSpec', 'buildbot.util.runprocess.RunProcessPP', 'buildbot.util.runprocess.RunProcess', 'buildbot.util.sautils.InsertFromSelect', 'buildbot.util.service.AsyncMultiService', 'buildbot.util.service.AsyncService', 'buildbot.util.service.BuildbotService', 'buildbot.util.service.BuildbotServiceManager', 'buildbot.util.service.ClusteredBuildbotService', 'buildbot.util.service.MasterService', 'buildbot.util.service.ReconfigurableServiceMixin', 'buildbot.util.service.SharedService', 'buildbot.util.state.StateMixin', 'buildbot.util.subscription.Subscription', 'buildbot.util.subscription.SubscriptionPoint', 'buildbot.util.test_result_submitter.TestResultSubmitter', "buildbot.util.watchdog.Watchdog", } self.verify_plugins_registered('util', 'buildbot.util', None, known_not_exported) def test_reporters(self): known_not_exported = { 'buildbot.reporters.base.ReporterBase', 'buildbot.reporters.generators.utils.BuildStatusGeneratorMixin', 'buildbot.reporters.gerrit.DEFAULT_REVIEW', 'buildbot.reporters.gerrit.DEFAULT_SUMMARY', 'buildbot.reporters.gerrit.GerritBuildEndStatusGenerator', 'buildbot.reporters.gerrit.GerritBuildSetStatusGenerator', 'buildbot.reporters.gerrit.GerritBuildStartStatusGenerator', 'buildbot.reporters.gerrit.GerritStatusGeneratorBase', 'buildbot.reporters.irc.IRCChannel', 'buildbot.reporters.irc.IRCContact', 'buildbot.reporters.irc.IrcStatusBot', 'buildbot.reporters.irc.IrcStatusFactory', 'buildbot.reporters.irc.UsageError', 'buildbot.reporters.mail.Domain', 'buildbot.reporters.message.MessageFormatterBase', 'buildbot.reporters.message.MessageFormatterBaseJinja', 'buildbot.reporters.telegram.TelegramChannel', 'buildbot.reporters.telegram.TelegramContact', 'buildbot.reporters.telegram.TelegramPollingBot', 'buildbot.reporters.telegram.TelegramStatusBot', 'buildbot.reporters.telegram.TelegramWebhookBot', 'buildbot.reporters.words.Channel', 'buildbot.reporters.words.Contact', 'buildbot.reporters.words.ForceOptions', 'buildbot.reporters.words.StatusBot', 'buildbot.reporters.words.ThrottledClientFactory', 'buildbot.reporters.words.UsageError', 'buildbot.reporters.words.WebhookResource', } self.verify_plugins_registered('reporters', 'buildbot.reporters', None, known_not_exported) def test_secrets(self): known_not_exported = { 'buildbot.secrets.manager.SecretManager', 'buildbot.secrets.providers.base.SecretProviderBase', 'buildbot.secrets.secret.SecretDetails', 'buildbot.secrets.providers.vault_hvac.VaultAuthenticator', } self.verify_plugins_registered('secrets', 'buildbot.secrets', None, known_not_exported) def test_webhooks(self): # in the case of webhooks the entry points list modules, not classes, so # verify_plugins_registered won't work. For now let's ignore this edge case get_plugins('webhooks', None, load_now=True) def test_workers(self): known_not_exported = { 'buildbot.worker.upcloud.UpcloudLatentWorker', 'buildbot.worker.base.AbstractWorker', 'buildbot.worker.latent.AbstractLatentWorker', 'buildbot.worker.latent.LocalLatentWorker', 'buildbot.worker.marathon.MarathonLatentWorker', 'buildbot.worker.docker.DockerBaseWorker', } self.verify_plugins_registered('worker', 'buildbot.worker', IWorker, known_not_exported) def verify_plugins_registered( self, plugin_type, module_name, interface, known_not_exported=None ): # This will verify whether we can load plugins, i.e. whether the entry points are valid. plugins = get_plugins(plugin_type, interface, load_now=True) # Now verify that are no unregistered plugins left. existing_classes = self.get_existing_classes(module_name, interface) exported_classes = { f'{plugins._get_entry(name)._entry.module}.{name}' for name in plugins.names } if known_not_exported is None: known_not_exported = set() not_exported_classes = existing_classes - exported_classes - known_not_exported self.assertEqual(not_exported_classes, set()) self.assertEqual(known_not_exported - existing_classes, set()) def class_provides_iface(self, interface, klass): try: verifyClass(interface, klass) return True except Exception: return False def get_existing_classes(self, module_name, interface): existing_modules = get_python_module_contents(module_name) existing_classes = set() with warnings.catch_warnings(): warnings.simplefilter("ignore") for existing_module in existing_modules: module = importlib.import_module(existing_module) for name, obj in inspect.getmembers(module): if name.startswith('_'): continue if inspect.isclass(obj) and obj.__module__ == existing_module: if interface is not None and not self.class_provides_iface(interface, obj): continue existing_classes.add(f'{existing_module}.{name}') return existing_classes
12,130
Python
.py
237
40.658228
99
0.672454
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,611
test_configs.py
buildbot_buildbot/master/buildbot/test/integration/test_configs.py
# 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.python import util from twisted.trial import unittest from buildbot.config.master import FileLoader from buildbot.scripts import runner from buildbot.test.util import dirs from buildbot.test.util.warnings import assertNotProducesWarnings from buildbot.warnings import DeprecatedApiWarning class RealConfigs(dirs.DirsMixin, unittest.TestCase): def setUp(self): self.setUpDirs('basedir') self.basedir = os.path.abspath('basedir') self.filename = os.path.abspath("test.cfg") def tearDown(self): self.tearDownDirs() def test_sample_config(self): filename = util.sibpath(runner.__file__, 'sample.cfg') with assertNotProducesWarnings(DeprecatedApiWarning): FileLoader(self.basedir, filename).loadConfig() def test_0_9_0b5_api_renamed_config(self): with open(self.filename, "w", encoding='utf-8') as f: f.write(sample_0_9_0b5_api_renamed) FileLoader(self.basedir, self.filename).loadConfig() # sample.cfg from various versions, with comments stripped. Adjustments made # for compatibility are marked with comments # Template for master configuration just after worker renaming. sample_0_9_0b5_api_renamed = """\ from buildbot.plugins import * c = BuildmasterConfig = {} c['workers'] = [worker.Worker("example-worker", "pass")] c['protocols'] = {'pb': {'port': 9989}} c['change_source'] = [] c['change_source'].append(changes.GitPoller( 'https://github.com/buildbot/hello-world.git', workdir='gitpoller-workdir', branch='master', pollInterval=300)) c['schedulers'] = [] c['schedulers'].append(schedulers.SingleBranchScheduler( name="all", change_filter=util.ChangeFilter(branch='master'), treeStableTimer=None, builderNames=["runtests"])) c['schedulers'].append(schedulers.ForceScheduler( name="force", builderNames=["runtests"])) factory = util.BuildFactory() factory.addStep(steps.Git(repourl='https://github.com/buildbot/hello-world.git', mode='incremental')) factory.addStep(steps.ShellCommand(command=["trial", "hello"], env={"PYTHONPATH": "."})) c['builders'] = [] c['builders'].append( util.BuilderConfig(name="runtests", workernames=["example-worker"], factory=factory)) c['title'] = "Pyflakes" c['titleURL'] = "https://launchpad.net/pyflakes" c['buildbotURL'] = "http://localhost:8010/" c['www'] = dict(port=8010, plugins=dict(waterfall_view={}, console_view={})) c['db'] = { 'db_url' : "sqlite:///state.sqlite", } """
3,439
Python
.py
77
38.597403
101
0.689727
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,612
test_master.py
buildbot_buildbot/master/buildbot/test/integration/test_master.py
# 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 annotations from typing import Any from twisted.internet import defer from twisted.internet import reactor from twisted.internet.task import deferLater from buildbot.changes.filter import ChangeFilter from buildbot.changes.pb import PBChangeSource from buildbot.config import BuilderConfig from buildbot.process.factory import BuildFactory from buildbot.schedulers.basic import AnyBranchScheduler from buildbot.schedulers.forcesched import ForceScheduler from buildbot.steps.shell import ShellCommand from buildbot.test.util import www from buildbot.test.util.integration import RunMasterBase from buildbot.worker import Worker class RunMaster(RunMasterBase, www.RequiresWwwMixin): proto = 'pb' @defer.inlineCallbacks def do_test_master(self): yield self.setup_master(BuildmasterConfig, startWorker=False) # hang out for a fraction of a second, to let startup processes run yield deferLater(reactor, 0.01, lambda: None) # run this test twice, to make sure the first time shut everything down # correctly; if this second test fails, but the first succeeds, then # something is not cleaning up correctly in stopService. def test_master1(self): return self.do_test_master() def test_master2(self): return self.do_test_master() # master configuration # Note that the *same* configuration objects are used for both runs of the # master. This is a more strenuous test than strictly required, since a master # will generally re-execute master.cfg on startup. However, it's good form and # will help to flush out any bugs that may otherwise be difficult to find. c: dict[str, Any] = {} BuildmasterConfig = c c['workers'] = [Worker("local1", "localpw")] c['protocols'] = {'pb': {'port': 'tcp:0'}} c['change_source'] = [] c['change_source'] = PBChangeSource() c['schedulers'] = [] c['schedulers'].append( AnyBranchScheduler( name="all", change_filter=ChangeFilter(project_re='^testy/'), treeStableTimer=1 * 60, builderNames=[ 'testy', ], ) ) c['schedulers'].append(ForceScheduler(name="force", builderNames=["testy"])) f1 = BuildFactory() f1.addStep(ShellCommand(command='echo hi')) c['builders'] = [] c['builders'].append(BuilderConfig(name="testy", workernames=["local1"], factory=f1)) c['title'] = "test" c['titleURL'] = "test" c['buildbotURL'] = "http://localhost:8010/"
3,140
Python
.py
73
40.027397
85
0.754748
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,613
test_try_client.py
buildbot_buildbot/master/buildbot/test/integration/test_try_client.py
# 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 unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.python import log from twisted.python.filepath import FilePath from buildbot import util from buildbot.clients import tryclient from buildbot.schedulers import trysched from buildbot.test.util import www from buildbot.test.util.integration import RunMasterBase # wait for some asynchronous result @defer.inlineCallbacks def waitFor(fn): while True: res = yield fn() if res: return res yield util.asyncSleep(0.01) class Schedulers(RunMasterBase, www.RequiresWwwMixin): def setUp(self): self.master = None self.sch = None def spawnProcess(pp, executable, args, environ): tmpfile = os.path.join(self.jobdir, 'tmp', 'testy') newfile = os.path.join(self.jobdir, 'new', 'testy') with open(tmpfile, "w", encoding='utf-8') as f: f.write(pp.job) os.rename(tmpfile, newfile) log.msg(f"wrote jobfile {newfile}") # get the scheduler to poll this directory now d = self.sch.watcher.poll() d.addErrback(log.err, 'while polling') @d.addCallback def finished(_): st = mock.Mock() st.value.signal = None st.value.exitCode = 0 pp.processEnded(st) self.patch(reactor, 'spawnProcess', spawnProcess) self.sourcestamp = tryclient.SourceStamp(branch='br', revision='rr', patch=(0, '++--')) def getSourceStamp(vctype, treetop, branch=None, repository=None): return defer.succeed(self.sourcestamp) self.patch(tryclient, 'getSourceStamp', getSourceStamp) self.output = [] # stub out printStatus, as it's timing-based and thus causes # occasional test failures. self.patch(tryclient.Try, 'printStatus', lambda _: None) def output(*msg): msg = ' '.join(map(str, msg)) log.msg(f"output: {msg}") self.output.append(msg) self.patch(tryclient, 'output', output) def setupJobdir(self): jobdir = FilePath(self.mktemp()) jobdir.createDirectory() self.jobdir = jobdir.path for sub in 'new', 'tmp', 'cur': jobdir.child(sub).createDirectory() return self.jobdir @defer.inlineCallbacks def setup_config(self, extra_config): c = {} from buildbot.config import BuilderConfig from buildbot.process import results from buildbot.process.buildstep import BuildStep from buildbot.process.factory import BuildFactory class MyBuildStep(BuildStep): def run(self): return results.SUCCESS c['change_source'] = [] c['schedulers'] = [] # filled in above f1 = BuildFactory() f1.addStep(MyBuildStep(name='one')) f1.addStep(MyBuildStep(name='two')) c['builders'] = [ BuilderConfig(name="a", workernames=["local1"], factory=f1), ] c['title'] = "test" c['titleURL'] = "test" c['buildbotURL'] = "http://localhost:8010/" c['mq'] = {'debug': True} # test wants to influence the config, but we still return a new config # each time c.update(extra_config) yield self.setup_master(c) @defer.inlineCallbacks def startMaster(self, sch): extra_config = { 'schedulers': [sch], } self.sch = sch yield self.setup_config(extra_config) # wait until the scheduler is active yield waitFor(lambda: self.sch.active) # and, for Try_Userpass, until it's registered its port if isinstance(self.sch, trysched.Try_Userpass): def getSchedulerPort(): if not self.sch.registrations: return None self.serverPort = self.sch.registrations[0].getPort() log.msg(f"Scheduler registered at port {self.serverPort}") return True yield waitFor(getSchedulerPort) def runClient(self, config): self.clt = tryclient.Try(config) return self.clt.run_impl() @defer.inlineCallbacks def test_userpass_no_wait(self): yield self.startMaster(trysched.Try_Userpass('try', ['a'], 0, [('u', b'p')])) yield self.runClient({ 'connect': 'pb', 'master': f'127.0.0.1:{self.serverPort}', 'username': 'u', 'passwd': b'p', }) self.assertEqual( self.output, [ "using 'pb' connect method", 'job created', 'Delivering job; comment= None', 'job has been delivered', 'not waiting for builds to finish', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 1) @defer.inlineCallbacks def test_userpass_wait(self): yield self.startMaster(trysched.Try_Userpass('try', ['a'], 0, [('u', b'p')])) yield self.runClient({ 'connect': 'pb', 'master': f'127.0.0.1:{self.serverPort}', 'username': 'u', 'passwd': b'p', 'wait': True, }) self.assertEqual( self.output, [ "using 'pb' connect method", 'job created', 'Delivering job; comment= None', 'job has been delivered', 'All Builds Complete', 'a: success (build successful)', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 1) @defer.inlineCallbacks def test_userpass_wait_bytes(self): self.sourcestamp = tryclient.SourceStamp(branch=b'br', revision=b'rr', patch=(0, b'++--')) yield self.startMaster(trysched.Try_Userpass('try', ['a'], 0, [('u', b'p')])) yield self.runClient({ 'connect': 'pb', 'master': f'127.0.0.1:{self.serverPort}', 'username': 'u', 'passwd': b'p', 'wait': True, }) self.assertEqual( self.output, [ "using 'pb' connect method", 'job created', 'Delivering job; comment= None', 'job has been delivered', 'All Builds Complete', 'a: success (build successful)', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 1) @defer.inlineCallbacks def test_userpass_wait_dryrun(self): yield self.startMaster(trysched.Try_Userpass('try', ['a'], 0, [('u', b'p')])) yield self.runClient({ 'connect': 'pb', 'master': f'127.0.0.1:{self.serverPort}', 'username': 'u', 'passwd': b'p', 'wait': True, 'dryrun': True, }) self.assertEqual( self.output, [ "using 'pb' connect method", 'job created', 'Job:\n' '\tRepository: \n' '\tProject: \n' '\tBranch: br\n' '\tRevision: rr\n' '\tBuilders: None\n' '++--', 'job has been delivered', 'All Builds Complete', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 0) @defer.inlineCallbacks def test_userpass_list_builders(self): yield self.startMaster(trysched.Try_Userpass('try', ['a'], 0, [('u', b'p')])) yield self.runClient({ 'connect': 'pb', 'get-builder-names': True, 'master': f'127.0.0.1:{self.serverPort}', 'username': 'u', 'passwd': b'p', }) self.assertEqual( self.output, [ "using 'pb' connect method", 'The following builders are available for the try scheduler: ', 'a', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 0) @defer.inlineCallbacks def test_jobdir_no_wait(self): jobdir = self.setupJobdir() yield self.startMaster(trysched.Try_Jobdir('try', ['a'], jobdir)) yield self.runClient({ 'connect': 'ssh', 'master': '127.0.0.1', 'username': 'u', 'passwd': b'p', 'builders': 'a', # appears to be required for ssh }) self.assertEqual( self.output, [ "using 'ssh' connect method", 'job created', 'job has been delivered', 'not waiting for builds to finish', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 1) @defer.inlineCallbacks def test_jobdir_wait(self): jobdir = self.setupJobdir() yield self.startMaster(trysched.Try_Jobdir('try', ['a'], jobdir)) yield self.runClient({ 'connect': 'ssh', 'wait': True, 'host': '127.0.0.1', 'username': 'u', 'passwd': b'p', 'builders': 'a', # appears to be required for ssh }) self.assertEqual( self.output, [ "using 'ssh' connect method", 'job created', 'job has been delivered', 'waiting for builds with ssh is not supported', ], ) buildsets = yield self.master.db.buildsets.getBuildsets() self.assertEqual(len(buildsets), 1)
10,741
Python
.py
283
27.424028
98
0.560791
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,614
test_integration_with_secrets.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_with_secrets.py
# 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.internet import defer from buildbot.process.properties import Interpolate from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.util.integration import RunMasterBase class SecretsConfig(RunMasterBase): @defer.inlineCallbacks def setup_config(self, use_with=False): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] c['secretsProviders'] = [FakeSecretStorage(secretdict={"foo": "bar", "something": "more"})] f = BuildFactory() if use_with: secrets_list = [("pathA", Interpolate('%(secret:something)s'))] with f.withSecrets(secrets_list): f.addStep(steps.ShellCommand(command=Interpolate('echo %(secret:foo)s'))) else: f.addSteps( [steps.ShellCommand(command=Interpolate('echo %(secret:foo)s'))], withSecrets=[("pathA", Interpolate('%(secret:something)s'))], ) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_secret(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "<foo>") self.assertTrue(res) @defer.inlineCallbacks def test_withsecrets(self): yield self.setup_config(use_with=True) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "<foo>") self.assertTrue(res)
2,637
Python
.py
54
42.203704
99
0.702913
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,615
test_trigger.py
buildbot_buildbot/master/buildbot/test/integration/test_trigger.py
# 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 io import StringIO from twisted.internet import defer from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with two builders and a trigger step linking them expectedOutputRegex = r"""\*\*\* BUILD 1 \*\*\* ==> build successful \(success\) \*\*\* STEP worker_preparation \*\*\* ==> worker local1 ready \(success\) \*\*\* STEP shell \*\*\* ==> 'echo hello' \(success\) log:stdio \({loglines}\) \*\*\* STEP trigger \*\*\* ==> triggered trigsched, 1 success \(success\) url:trigsched #2 \(http://localhost:8080/#/buildrequests/2\) url:success: build #1 \(http://localhost:8080/#/builders/(1|2)/builds/1\) \*\*\* STEP shell_1 \*\*\* ==> 'echo world' \(success\) log:stdio \({loglines}\) \*\*\* BUILD 2 \*\*\* ==> build successful \(success\) \*\*\* STEP worker_preparation \*\*\* ==> worker local1 ready \(success\) \*\*\* STEP shell \*\*\* ==> 'echo ola' \(success\) log:stdio \({loglines}\) """ class TriggeringMaster(RunMasterBase): change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } @defer.inlineCallbacks def setup_config(self, addFailure=False): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.Triggerable(name="trigsched", builderNames=["build"]), schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"]), ] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) f.addStep( steps.Trigger(schedulerNames=['trigsched'], waitForFinish=True, updateSourceStamp=True) ) f.addStep(steps.ShellCommand(command='echo world')) f2 = BuildFactory() f2.addStep(steps.ShellCommand(command='echo ola')) c['builders'] = [ BuilderConfig(name="testy", workernames=["local1"], factory=f), BuilderConfig(name="build", workernames=["local1"], factory=f2), ] if addFailure: f3 = BuildFactory() f3.addStep(steps.ShellCommand(command='false')) c['builders'].append(BuilderConfig(name="build2", workernames=["local1"], factory=f3)) c['builders'].append(BuilderConfig(name="build3", workernames=["local1"], factory=f2)) c['schedulers'][0] = schedulers.Triggerable( name="trigsched", builderNames=["build", "build2", "build3"] ) yield self.setup_master(c) @defer.inlineCallbacks def test_trigger(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True, useChange=self.change, wantLogs=True) self.assertEqual(build['steps'][2]['state_string'], 'triggered trigsched, 1 success') builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 2) dump = StringIO() for b in builds: yield self.printBuild(b, dump) # depending on the environment the number of lines is different between # test hosts loglines = builds[1]['steps'][1]['logs'][0]['num_lines'] self.assertRegex(dump.getvalue(), expectedOutputRegex.format(loglines=loglines)) @defer.inlineCallbacks def test_trigger_failure(self): yield self.setup_config(addFailure=True) build = yield self.doForceBuild(wantSteps=True, useChange=self.change, wantLogs=True) self.assertEqual( build['steps'][2]['state_string'], 'triggered trigsched, 2 successes, 1 failure' ) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 4)
4,712
Python
.py
98
40.765306
99
0.649119
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,616
test_integration_secrets_with_vault_hvac.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_secrets_with_vault_hvac.py
# 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 base64 import subprocess import time from unittest.case import SkipTest from parameterized import parameterized from twisted.internet import defer from buildbot.process.properties import Interpolate from buildbot.secrets.providers.vault_hvac import HashiCorpVaultKvSecretProvider from buildbot.secrets.providers.vault_hvac import VaultAuthenticatorToken from buildbot.steps.shell import ShellCommand from buildbot.test.util.decorators import skipUnlessPlatformIs from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builders and a shellcommand step # Test needs to be explicitly disabled on Windows, as docker may be present there, but not able # to properly launch images. @skipUnlessPlatformIs('posix') class TestVaultHvac(RunMasterBase): @defer.inlineCallbacks def setup_config(self, secret_specifier): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] # note that as of August 2021, the vault docker image default to kv # version 2 to be enabled by default c['secretsProviders'] = [ HashiCorpVaultKvSecretProvider( authenticator=VaultAuthenticatorToken('my_vaulttoken'), vault_server="http://localhost:8200", secrets_mount="secret", ) ] f = BuildFactory() f.addStep(ShellCommand(command=Interpolate(f'echo {secret_specifier} | base64'))) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) def start_container(self, image_tag): try: image = f'vault:{image_tag}' subprocess.check_call(['docker', 'pull', image], stdout=subprocess.DEVNULL) subprocess.check_call( [ 'docker', 'run', '-d', '-e', 'SKIP_SETCAP=yes', '-e', 'VAULT_DEV_ROOT_TOKEN_ID=my_vaulttoken', '-e', 'VAULT_TOKEN=my_vaulttoken', '--name=vault_for_buildbot', '-p', '8200:8200', image, ], stdout=subprocess.DEVNULL, ) time.sleep(1) # the container needs a little time to setup itself self.addCleanup(self.remove_container) subprocess.check_call( [ 'docker', 'exec', '-e', 'VAULT_ADDR=http://127.0.0.1:8200/', 'vault_for_buildbot', 'vault', 'kv', 'put', 'secret/key', 'value=word', ], stdout=subprocess.DEVNULL, ) subprocess.check_call( [ 'docker', 'exec', '-e', 'VAULT_ADDR=http://127.0.0.1:8200/', 'vault_for_buildbot', 'vault', 'kv', 'put', 'secret/anykey', 'anyvalue=anyword', ], stdout=subprocess.DEVNULL, ) subprocess.check_call( [ 'docker', 'exec', '-e', 'VAULT_ADDR=http://127.0.0.1:8200/', 'vault_for_buildbot', 'vault', 'kv', 'put', 'secret/key1/key2', 'id=val', ], stdout=subprocess.DEVNULL, ) except (FileNotFoundError, subprocess.CalledProcessError) as e: raise SkipTest("Vault integration needs docker environment to be setup") from e def remove_container(self): subprocess.call(['docker', 'rm', '-f', 'vault_for_buildbot'], stdout=subprocess.DEVNULL) @defer.inlineCallbacks def do_secret_test(self, image_tag, secret_specifier, expected_obfuscation, expected_value): self.start_container(image_tag) yield self.setup_config(secret_specifier=secret_specifier) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) patterns = [ f"echo {expected_obfuscation}", base64.b64encode((expected_value + "\n").encode('utf-8')).decode('utf-8'), ] res = yield self.checkBuildStepLogExist(build, patterns) self.assertTrue(res) all_tags = [ ('1.9.7',), ('1.10.5',), ('1.11.1',), ] @parameterized.expand(all_tags) @defer.inlineCallbacks def test_key(self, image_tag): yield self.do_secret_test(image_tag, '%(secret:key|value)s', '<key|value>', 'word') @parameterized.expand(all_tags) @defer.inlineCallbacks def test_key_any_value(self, image_tag): yield self.do_secret_test( image_tag, '%(secret:anykey|anyvalue)s', '<anykey|anyvalue>', 'anyword' ) @parameterized.expand(all_tags) @defer.inlineCallbacks def test_nested_key(self, image_tag): yield self.do_secret_test(image_tag, '%(secret:key1/key2|id)s', '<key1/key2|id>', 'val')
6,419
Python
.py
156
29.532051
96
0.575894
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,617
test_telegram_bot.py
buildbot_buildbot/master/buildbot/test/integration/test_telegram_bot.py
# 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 json from unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.trial import unittest from twisted.web import client from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer from zope.interface import implementer from buildbot.data import connector as dataconnector from buildbot.mq import connector as mqconnector from buildbot.reporters import telegram from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.util import db from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.www import auth from buildbot.www import authz from buildbot.www import service as wwwservice @implementer(IBodyProducer) class BytesProducer: def __init__(self, body): self.body = body self.length = len(body) def resumeProducing(self) -> None: raise NotImplementedError() def startProducing(self, consumer): consumer.write(self.body) return defer.succeed(None) def pauseProducing(self): pass def stopProducing(self): pass class TelegramBot(db.RealDatabaseWithConnectorMixin, www.RequiresWwwMixin, unittest.TestCase): master = None _commands = [ {'command': command, 'description': doc} for command, doc in telegram.TelegramContact.get_commands() ] @defer.inlineCallbacks def setup_http_service(self, bot_token): base_url = "https://api.telegram.org/bot" + bot_token self.http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, base_url ) def expect_telegram_requests(self, bot_token): self.http.expect( "post", "/getMe", content_json={'ok': 1, 'result': {'username': 'testbot'}} ) self.http.expect( "post", "/setMyCommands", json={'commands': self._commands}, content_json={'ok': 1} ) if bot_token == 'poll': self.http.expect("post", "/deleteWebhook", content_json={'ok': 1}) else: self.http.expect( "post", "/setWebhook", json={'url': bytes2unicode(self.bot_url)}, content_json={'ok': 1}, ) @defer.inlineCallbacks def setUp(self): table_names = [ 'objects', 'object_state', 'masters', 'workers', 'configured_workers', 'connected_workers', 'builder_masters', 'builders', 'projects', ] master = yield fakemaster.make_master(self, wantRealReactor=True) yield self.setUpRealDatabaseWithConnector( master, table_names=table_names, sqlite_memory=False ) master.data = dataconnector.DataConnector() yield master.data.setServiceParent(master) master.config.mq = {"type": 'simple'} master.mq = mqconnector.MQConnector() yield master.mq.setServiceParent(master) yield master.mq.setup() yield master.mq.startService() master.config.www = { "port": 'tcp:0:interface=127.0.0.1', "debug": True, "auth": auth.NoAuth(), "authz": authz.Authz(), "avatar_methods": [], "logfileName": 'http.log', } master.www = wwwservice.WWWService() yield master.www.setServiceParent(master) yield master.www.startService() yield master.www.reconfigServiceWithBuildbotConfig(master.config) session = mock.Mock() session.uid = "0" master.www.site.sessionFactory = mock.Mock(return_value=session) # now that we have a port, construct the real URL and insert it into # the config. The second reconfig isn't really required, but doesn't # hurt. self.url = f'http://127.0.0.1:{master.www.getPortnum()}/' self.url = unicode2bytes(self.url) master.config.buildbotURL = self.url yield master.www.reconfigServiceWithBuildbotConfig(master.config) self.master = master self.agent = client.Agent(reactor) self.bot_url = self.url + b"telegram12345:secret" yield self.setup_http_service('12345:secret') self.expect_telegram_requests('12345:secret') # create a telegram bot service tb = master.config.services['TelegramBot'] = telegram.TelegramBot( bot_token='12345:secret', useWebhook=True, chat_ids=[-123456], notify_events=['worker'] ) yield tb.setServiceParent(self.master) yield tb.startService() self.sent_messages = [] def send_message(chat, message, **kwargs): self.sent_messages.append((chat, message)) tb.bot.send_message = send_message @defer.inlineCallbacks def tearDown(self): if self.master: yield self.master.www.stopService() yield self.master.mq.stopService() yield self.tearDownRealDatabaseWithConnector() @defer.inlineCallbacks def testWebhook(self): payload = unicode2bytes( json.dumps({ "update_id": 12345, "message": { "message_id": 123, "from": { "id": 123456789, "first_name": "Alice", }, "chat": {"id": -12345678, "title": "Wonderlands", "type": "group"}, "date": 1566688888, "text": "/getid", }, }) ) pg = yield self.agent.request( b'POST', self.bot_url, Headers({'Content-Type': ['application/json']}), BytesProducer(payload), ) self.assertEqual( pg.code, 202, f"did not get 202 response for '{bytes2unicode(self.bot_url)}'" ) self.assertIn('123456789', self.sent_messages[0][1]) self.assertIn('-12345678', self.sent_messages[1][1]) @defer.inlineCallbacks def testReconfig(self): # initial config and reconfig will issue requests twice self.expect_telegram_requests('12345:secret') tb = self.master.config.services['TelegramBot'] yield tb.reconfigService( bot_token='12345:secret', useWebhook=True, chat_ids=[-123456], notify_events=['problem'] ) @defer.inlineCallbacks def testLoadState(self): tboid = yield self.master.db.state.getObjectId( 'testbot', 'buildbot.reporters.telegram.TelegramWebhookBot' ) yield self.insert_test_data([ fakedb.ObjectState( objectid=tboid, name='notify_events', value_json='[[123456789, ["started", "finished"]]]', ), fakedb.ObjectState( objectid=tboid, name='missing_workers', value_json='[[123456789, [12]]]' ), ]) tb = self.master.config.services['TelegramBot'] yield tb.bot.loadState() c = tb.bot.getContact({'id': 123456789}, {'id': 123456789}) self.assertEqual(c.channel.notify_events, {'started', 'finished'}) self.assertEqual(c.channel.missing_workers, {12}) @defer.inlineCallbacks def testSaveState(self): tb = self.master.config.services['TelegramBot'] tboid = yield self.master.db.state.getObjectId( 'testbot', 'buildbot.reporters.telegram.TelegramWebhookBot' ) notify_events = yield self.master.db.state.getState(tboid, 'notify_events', ()) missing_workers = yield self.master.db.state.getState(tboid, 'missing_workers', ()) self.assertNotIn([99, ['cancelled']], notify_events) self.assertNotIn([99, [13]], missing_workers) tb.bot.getChannel(98) # this channel should not be saved c = tb.bot.getChannel(99) self.assertIn(98, tb.bot.channels) self.assertIn(99, tb.bot.channels) c.notify_events = {'cancelled'} c.missing_workers = {13} yield tb.bot.saveNotifyEvents() yield tb.bot.saveMissingWorkers() notify_events = yield self.master.db.state.getState(tboid, 'notify_events', ()) missing_workers = yield self.master.db.state.getState(tboid, 'missing_workers', ()) self.assertNotIn(98, (c for c, _ in notify_events)) self.assertIn([99, ['cancelled']], notify_events) self.assertIn([99, [13]], missing_workers) @defer.inlineCallbacks def testMissingWorker(self): yield self.insert_test_data([fakedb.Worker(id=1, name='local1')]) tb = self.master.config.services['TelegramBot'] channel = tb.bot.getChannel(-123456) self.assertEqual(channel.notify_events, {'worker'}) yield self.master.data.updates.workerMissing( workerid=1, masterid=self.master.masterid, last_connection='long time ago', notify=['[email protected]'], ) self.assertEqual( self.sent_messages[0][1], "Worker `local1` is missing. It was seen last on long time ago.", ) yield self.master.data.updates.workerConnected( workerid=1, masterid=self.master.masterid, workerinfo={}, ) self.assertEqual(self.sent_messages[1][1], "Worker `local1` is back online.")
10,319
Python
.py
246
32.861789
100
0.63213
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,618
test_log_finish.py
buildbot_buildbot/master/buildbot/test/integration/test_log_finish.py
# 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.internet import defer from buildbot.plugins import steps from buildbot.process.results import EXCEPTION from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase class TestLog(RunMasterBase): # master configuration @defer.inlineCallbacks def setup_config(self, step): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"])] f = BuildFactory() f.addStep(step) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_shellcommand(self): testcase = self class MyStep(steps.ShellCommand): def _newLog(self, name, type, logid, logEncoding): r = super()._newLog(name, type, logid, logEncoding) testcase.curr_log = r return r step = MyStep(command='echo hello') yield self.setup_config(step) change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['results'], SUCCESS) self.assertTrue(self.curr_log.finished) @defer.inlineCallbacks def test_mastershellcommand(self): testcase = self class MyStep(steps.MasterShellCommand): def _newLog(self, name, type, logid, logEncoding): r = super()._newLog(name, type, logid, logEncoding) testcase.curr_log = r return r step = MyStep(command='echo hello') yield self.setup_config(step) change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['results'], SUCCESS) self.assertTrue(self.curr_log.finished) @defer.inlineCallbacks def test_mastershellcommand_issue(self): testcase = self class MyStep(steps.MasterShellCommand): def _newLog(self, name, type, logid, logEncoding): r = super()._newLog(name, type, logid, logEncoding) testcase.curr_log = r testcase.patch(r, "finish", lambda: defer.fail(RuntimeError('Could not finish'))) return r step = MyStep(command='echo hello') yield self.setup_config(step) change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertFalse(self.curr_log.finished) self.assertEqual(build['results'], EXCEPTION) errors = self.flushLoggedErrors() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.getErrorMessage(), 'Could not finish')
4,535
Python
.py
106
33.754717
97
0.629823
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,619
test_www.py
buildbot_buildbot/master/buildbot/test/integration/test_www.py
# 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 annotations import json import zlib from typing import TYPE_CHECKING from unittest import mock from twisted.internet import defer from twisted.internet import protocol from twisted.internet import reactor from twisted.trial import unittest from twisted.web import client from twisted.web.http_headers import Headers from buildbot.data import connector as dataconnector from buildbot.db import connector as dbconnector from buildbot.mq import connector as mqconnector from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.util import db from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.util.twisted import async_to_deferred from buildbot.www import auth from buildbot.www import authz from buildbot.www import service as wwwservice if TYPE_CHECKING: from typing import Callable SOMETIME = 1348971992 OTHERTIME = 1008971992 class BodyReader(protocol.Protocol): # an IProtocol that reads the entire HTTP body and then calls back # with it def __init__(self, finishedDeferred): self.body = [] self.finishedDeferred = finishedDeferred def dataReceived(self, data): self.body.append(data) def connectionLost(self, reason): if reason.check(client.ResponseDone): self.finishedDeferred.callback(b''.join(self.body)) else: self.finishedDeferred.errback(reason) class Www(db.RealDatabaseMixin, www.RequiresWwwMixin, unittest.TestCase): master = None @defer.inlineCallbacks def setUp(self): # set up a full master serving HTTP yield self.setUpRealDatabase( table_names=['masters', 'objects', 'object_state'], sqlite_memory=False ) master = fakemaster.FakeMaster(reactor) master.config.db = {"db_url": self.db_url} master.db = dbconnector.DBConnector('basedir') yield master.db.setServiceParent(master) yield master.db.setup(check_version=False) master.config.mq = {"type": 'simple'} master.mq = mqconnector.MQConnector() yield master.mq.setServiceParent(master) yield master.mq.setup() master.data = dataconnector.DataConnector() yield master.data.setServiceParent(master) master.config.www = { "port": 'tcp:0:interface=127.0.0.1', "debug": True, "auth": auth.NoAuth(), "authz": authz.Authz(), "avatar_methods": [], "logfileName": 'http.log', } master.www = wwwservice.WWWService() yield master.www.setServiceParent(master) yield master.www.startService() yield master.www.reconfigServiceWithBuildbotConfig(master.config) session = mock.Mock() session.uid = "0" master.www.site.sessionFactory = mock.Mock(return_value=session) # now that we have a port, construct the real URL and insert it into # the config. The second reconfig isn't really required, but doesn't # hurt. self.url = f'http://127.0.0.1:{master.www.getPortnum()}/' self.url = unicode2bytes(self.url) master.config.buildbotURL = self.url yield master.www.reconfigServiceWithBuildbotConfig(master.config) self.master = master # build an HTTP agent, using an explicit connection pool if Twisted # supports it (Twisted 13.0.0 and up) if hasattr(client, 'HTTPConnectionPool'): self.pool = client.HTTPConnectionPool(reactor) self.agent = client.Agent(reactor, pool=self.pool) else: self.pool = None self.agent = client.Agent(reactor) @defer.inlineCallbacks def tearDown(self): if self.pool: yield self.pool.closeCachedConnections() if self.master: yield self.master.www.stopService() yield self.tearDownRealDatabase() @defer.inlineCallbacks def apiGet(self, url, expect200=True): pg = yield self.agent.request(b'GET', url) # this is kind of obscene, but protocols are like that d = defer.Deferred() bodyReader = BodyReader(d) pg.deliverBody(bodyReader) body = yield d # check this *after* reading the body, otherwise Trial will # complain that the response is half-read if expect200 and pg.code != 200: self.fail(f"did not get 200 response for '{url}'") return json.loads(bytes2unicode(body)) def link(self, suffix): return self.url + b'api/v2/' + suffix # tests # There's no need to be exhaustive here. The intent is to test that data # can get all the way from the DB to a real HTTP client, and a few # resources will be sufficient to demonstrate that. @defer.inlineCallbacks def test_masters(self): yield self.insert_test_data([ fakedb.Master(id=7, active=0, last_active=SOMETIME), fakedb.Master(id=8, active=1, last_active=OTHERTIME), ]) res = yield self.apiGet(self.link(b'masters')) self.assertEqual( res, { 'masters': [ { 'active': False, 'masterid': 7, 'name': 'master-7', 'last_active': SOMETIME, }, { 'active': True, 'masterid': 8, 'name': 'master-8', 'last_active': OTHERTIME, }, ], 'meta': { 'total': 2, }, }, ) res = yield self.apiGet(self.link(b'masters/7')) self.assertEqual( res, { 'masters': [ { 'active': False, 'masterid': 7, 'name': 'master-7', 'last_active': SOMETIME, }, ], 'meta': {}, }, ) async def _test_compression( self, encoding: bytes, decompress_fn: Callable[[bytes], bytes], ) -> None: await self.insert_test_data([ fakedb.Master(id=7, active=0, last_active=SOMETIME), ]) pg = await self.agent.request( b'GET', self.link(b'masters/7'), headers=Headers({b'accept-encoding': [encoding]}), ) # this is kind of obscene, but protocols are like that d: defer.Deferred[bytes] = defer.Deferred() bodyReader = BodyReader(d) pg.deliverBody(bodyReader) body = await d self.assertEqual(pg.headers.getRawHeaders(b'content-encoding'), [encoding]) response = json.loads(bytes2unicode(decompress_fn(body))) self.assertEqual( response, { 'masters': [ { 'active': False, 'masterid': 7, 'name': 'master-7', 'last_active': SOMETIME, }, ], 'meta': {}, }, ) @async_to_deferred async def test_gzip_compression(self): await self._test_compression( b'gzip', decompress_fn=lambda body: zlib.decompress( body, # use largest wbits possible as twisted customize it # see: https://docs.python.org/3/library/zlib.html#zlib.decompress wbits=47, ), ) @async_to_deferred async def test_brotli_compression(self): try: import brotli except ImportError as e: raise unittest.SkipTest("brotli not installed, skip the test") from e await self._test_compression(b'br', decompress_fn=brotli.decompress) @async_to_deferred async def test_zstandard_compression(self): try: import zstandard except ImportError as e: raise unittest.SkipTest("zstandard not installed, skip the test") from e def _decompress(data): # zstd cannot decompress data compressed with stream api with a non stream api decompressor = zstandard.ZstdDecompressor() decompressobj = decompressor.decompressobj() return decompressobj.decompress(data) + decompressobj.flush() await self._test_compression(b'zstd', decompress_fn=_decompress)
9,434
Python
.py
239
29.506276
90
0.609375
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,620
test_URLs.py
buildbot_buildbot/master/buildbot/test/integration/test_URLs.py
# 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.internet import defer from twisted.python import runtime from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment # and make sure the UrlForBuild renderable is working class UrlForBuildMaster(RunMasterBase): proto = "null" @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.plugins import util from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() # do a bunch of transfer to exercise the protocol f.addStep(steps.ShellCommand(command=["echo", util.URLForBuild])) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_url(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], SUCCESS) if runtime.platformType == 'win32': command = "echo http://localhost:8080/#/builders/1/builds/1" else: command = "echo 'http://localhost:8080/#/builders/1/builds/1'" self.assertIn(command, build['steps'][1]['logs'][0]['contents']['content'])
2,250
Python
.py
46
43.565217
91
0.728558
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,621
test_integration_template.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_template.py
# 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.internet import defer from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builder and a shellcommand step # meant to be a template for integration steps class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"]), schedulers.ForceScheduler(name="force", builderNames=["testy"]), ] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] c['www'] = {'graphql': True} yield self.setup_master(c) @defer.inlineCallbacks def test_shell(self): yield self.setup_config() # if you don't need change, you can just remove this change, and useChange parameter change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild( wantSteps=True, useChange=change, wantLogs=True, wantProperties=True ) self.assertEqual(build['buildid'], 1) self.assertEqual(build['properties']['owners'], (['[email protected]'], 'Build'))
2,417
Python
.py
54
38.12963
92
0.681529
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,622
test_usePty.py
buildbot_buildbot/master/buildbot/test/integration/test_usePty.py
# 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 packaging.version import parse as parse_version from twisted import __version__ as twistedVersion from twisted.internet import defer from buildbot.test.util.decorators import skipUnlessPlatformIs from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builder and a shellcommand step, which use usePTY class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self, usePTY): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() f.addStep( steps.ShellCommand( command='if [ -t 1 ] ; then echo in a terminal; else echo "not a terminal"; fi', usePTY=usePTY, ) ) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @skipUnlessPlatformIs('posix') @defer.inlineCallbacks def test_usePTY(self): yield self.setup_config(usePTY=True) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "in a terminal", onlyStdout=True) self.assertTrue(res) # Twisted versions less than 17.1.0 would issue a warning: # "Argument strings and environment keys/values passed to reactor.spawnProcess # "should be str, not unicode." # This warning was unnecessary. Even in the old versions of Twisted, the # unicode arguments were encoded. This warning was removed in Twisted here: # # https://github.com/twisted/twisted/commit/23fa3cc05549251ea4118e4e03354d58df87eaaa if parse_version(twistedVersion) < parse_version("17.1.0"): self.flushWarnings() @skipUnlessPlatformIs('posix') @defer.inlineCallbacks def test_NOusePTY(self): yield self.setup_config(usePTY=False) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "not a terminal", onlyStdout=True) self.assertTrue(res)
3,170
Python
.py
64
43.15625
96
0.717518
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,623
test_stop_trigger.py
buildbot_buildbot/master/buildbot/test/integration/test_stop_trigger.py
# 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 textwrap from twisted.internet import defer from twisted.internet import reactor from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.process.results import CANCELLED from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with two builders and a trigger step linking them. the triggered build never ends # so that we can reliably stop it recursively class TriggeringMaster(RunMasterBase): timeout = 120 change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } @defer.inlineCallbacks def setup_trigger_config(self, triggeredFactory, nextBuild=None): c = {} c['schedulers'] = [ schedulers.Triggerable(name="trigsched", builderNames=["triggered"]), schedulers.AnyBranchScheduler(name="sched", builderNames=["main"]), ] f = BuildFactory() f.addStep( steps.Trigger(schedulerNames=['trigsched'], waitForFinish=True, updateSourceStamp=True) ) f.addStep(steps.ShellCommand(command='echo world')) mainBuilder = BuilderConfig(name="main", workernames=["local1"], factory=f) triggeredBuilderKwargs = { 'name': "triggered", 'workernames': ["local1"], 'factory': triggeredFactory, } if nextBuild is not None: triggeredBuilderKwargs['nextBuild'] = nextBuild triggeredBuilder = BuilderConfig(**triggeredBuilderKwargs) c['builders'] = [mainBuilder, triggeredBuilder] yield self.setup_master(c) @defer.inlineCallbacks def setup_config_trigger_runs_forever(self): f2 = BuildFactory() # Infinite sleep command. if sys.platform == 'win32': # Ping localhost infinitely. # There are other options, however they either don't work in # non-interactive mode (e.g. 'pause'), or doesn't available on all # Windows versions (e.g. 'timeout' and 'choice' are available # starting from Windows 7). cmd = 'ping -t 127.0.0.1'.split() else: cmd = textwrap.dedent("""\ while : do echo "sleeping"; sleep 1; done """) f2.addStep(steps.ShellCommand(command=cmd)) yield self.setup_trigger_config(f2) @defer.inlineCallbacks def setup_config_triggered_build_not_created(self): f2 = BuildFactory() f2.addStep(steps.ShellCommand(command="echo 'hello'")) def nextBuild(*args, **kwargs): return defer.succeed(None) yield self.setup_trigger_config(f2, nextBuild=nextBuild) def assertBuildIsCancelled(self, b): self.assertTrue(b['complete']) self.assertEqual(b['results'], CANCELLED, repr(b)) @defer.inlineCallbacks def runTest(self, newBuildCallback, flushErrors=False): newConsumer = yield self.master.mq.startConsuming(newBuildCallback, ('builds', None, 'new')) build = yield self.doForceBuild(wantSteps=True, useChange=self.change, wantLogs=True) self.assertBuildIsCancelled(build) newConsumer.stopConsuming() builds = yield self.master.data.get(("builds",)) for b in builds: self.assertBuildIsCancelled(b) if flushErrors: self.flushLoggedErrors() @defer.inlineCallbacks def testTriggerRunsForever(self): yield self.setup_config_trigger_runs_forever() self.higherBuild = None def newCallback(_, data): if self.higherBuild is None: self.higherBuild = data['buildid'] else: self.master.data.control("stop", {}, ("builds", self.higherBuild)) self.higherBuild = None yield self.runTest(newCallback, flushErrors=True) @defer.inlineCallbacks def testTriggerRunsForeverAfterCmdStarted(self): yield self.setup_config_trigger_runs_forever() self.higherBuild = None def newCallback(_, data): if self.higherBuild is None: self.higherBuild = data['buildid'] else: def f(): self.master.data.control("stop", {}, ("builds", self.higherBuild)) self.higherBuild = None reactor.callLater(5.0, f) yield self.runTest(newCallback, flushErrors=True) @defer.inlineCallbacks def testTriggeredBuildIsNotCreated(self): yield self.setup_config_triggered_build_not_created() def newCallback(_, data): self.master.data.control("stop", {}, ("builds", data['buildid'])) yield self.runTest(newCallback)
5,774
Python
.py
133
34.789474
100
0.656322
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,624
test_steps_configurable.py
buildbot_buildbot/master/buildbot/test/integration/test_steps_configurable.py
# 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 tempfile from twisted.internet import defer from twisted.trial import unittest from buildbot.config import BuilderConfig from buildbot.plugins import changes from buildbot.plugins import schedulers from buildbot.process import factory from buildbot.steps.configurable import BuildbotCiSetupSteps from buildbot.steps.configurable import BuildbotTestCiTrigger from buildbot.steps.source.git import Git from buildbot.test.util.git_repository import TestGitRepository from buildbot.test.util.integration import RunMasterBase from buildbot.worker import Worker buildbot_ci_yml = """\ language: python label_mapping: TWISTED: tw SQLALCHEMY: sqla SQLALCHEMY_MIGRATE: sqlam latest: l python: py python: - "3.8" env: global: - CI=true matrix: include: # Test different versions of SQLAlchemy - python: "3.8" env: TWISTED=12.0.0 SQLALCHEMY=0.6.0 SQLALCHEMY_MIGRATE=0.7.1 - python: "3.8" env: TWISTED=13.0.0 SQLALCHEMY=0.6.8 SQLALCHEMY_MIGRATE=0.7.1 - python: "3.8" env: TWISTED=14.0.0 SQLALCHEMY=0.6.8 SQLALCHEMY_MIGRATE=0.7.1 - python: "3.8" env: TWISTED=15.0.0 SQLALCHEMY=0.6.8 SQLALCHEMY_MIGRATE=0.7.1 before_install: - echo doing before install - echo doing before install 2nd command install: - echo doing install script: - echo doing scripts - echo Ran 10 tests with 0 failures and 0 errors after_success: - echo doing after success notifications: email: false """ class BuildbotTestCiTest(RunMasterBase): timeout = 300 @defer.inlineCallbacks def setUp(self): yield super().setUp() try: self.repo = TestGitRepository( repository_path=tempfile.mkdtemp( prefix="TestRepository_", dir=os.getcwd(), ) ) except FileNotFoundError as e: raise unittest.SkipTest("Can't find git binary") from e self.prepare_repository() def prepare_repository(self): self.repo.create_file_text('.bbtravis.yml', buildbot_ci_yml) self.repo.exec_git(['add', '.bbtravis.yml']) self.repo.commit(message='Initial commit', files=['.bbtravis.yml']) @defer.inlineCallbacks def setup_config(self): c = { 'workers': [Worker("local1", "p")], 'services': [ changes.GitPoller( repourl=str(self.repo.repository_path), project='buildbot', branch='main' ) ], 'builders': [], 'schedulers': [], 'multiMaster': True, } repository = str(self.repo.repository_path) job_name = "buildbot-job" try_name = "buildbot-try" spawner_name = "buildbot" codebases = {spawner_name: {'repository': repository}} # main job f = factory.BuildFactory() f.addStep(Git(repourl=repository, codebase=spawner_name, mode='incremental')) f.addStep(BuildbotCiSetupSteps()) c['builders'].append( BuilderConfig( name=job_name, workernames=['local1'], collapseRequests=False, tags=["job", 'buildbot'], factory=f, ) ) c['schedulers'].append( schedulers.Triggerable(name=job_name, builderNames=[job_name], codebases=codebases) ) # spawner f = factory.BuildFactory() f.addStep(Git(repourl=repository, codebase=spawner_name, mode='incremental')) f.addStep(BuildbotTestCiTrigger(scheduler=job_name)) c['builders'].append( BuilderConfig( name=spawner_name, workernames=['local1'], properties={'BUILDBOT_PULL_REQUEST': True}, tags=["spawner", 'buildbot'], factory=f, ) ) c['schedulers'].append( schedulers.AnyBranchScheduler( name=spawner_name, builderNames=[spawner_name], codebases=codebases ) ) # try job f = factory.BuildFactory() f.addStep(Git(repourl=repository, codebase=spawner_name, mode='incremental')) f.addStep(BuildbotTestCiTrigger(scheduler=job_name)) c['builders'].append( BuilderConfig( name=try_name, workernames=['local1'], properties={'BUILDBOT_PULL_REQUEST': True}, tags=["try", 'buildbot'], factory=f, ) ) yield self.setup_master(c) @defer.inlineCallbacks def test_buildbot_ci(self): yield self.setup_config() change = dict( branch="main", files=["foo.c"], author="[email protected]", comments="good stuff", revision="HEAD", repository=str(self.repo.repository_path), codebase='buildbot', project="buildbot", ) build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) if 'worker local1 ready' in build['steps'][0]['state_string']: build['steps'] = build['steps'][1:] self.assertEqual(build['steps'][0]['state_string'], 'update buildbot') self.assertEqual(build['steps'][0]['name'], 'git-buildbot') self.assertEqual( build['steps'][1]['state_string'], 'triggered ' + ", ".join(["buildbot-job"] * 4) + ', 4 successes', ) url_names = [url['name'] for url in build['steps'][1]['urls']] url_urls = [url['url'] for url in build['steps'][1]['urls']] self.assertIn('http://localhost:8080/#/builders/4/builds/1', url_urls) self.assertIn('success: buildbot py:3.8 sqla:0.6.0 sqlam:0.7.1 tw:12.0.0 #1', url_names) self.assertEqual(build['steps'][1]['logs'][0]['contents']['content'], buildbot_ci_yml) builds = yield self.master.data.get(("builds",)) self.assertEqual(len(builds), 5) props = {} buildernames = {} labels = {} for build in builds: build['properties'] = yield self.master.data.get(( "builds", build['buildid'], 'properties', )) props[build['buildid']] = { k: v[0] for k, v in build['properties'].items() if v[1] == 'BuildbotTestCiTrigger' } buildernames[build['buildid']] = build['properties'].get('virtual_builder_name') labels[build['buildid']] = build['properties'].get('matrix_label') self.assertEqual( props, { 1: {}, 2: { 'python': '3.8', 'CI': 'true', 'TWISTED': '12.0.0', 'SQLALCHEMY': '0.6.0', 'SQLALCHEMY_MIGRATE': '0.7.1', 'virtual_builder_name': 'buildbot py:3.8 sqla:0.6.0 sqlam:0.7.1 tw:12.0.0', 'virtual_builder_tags': [ 'buildbot', 'py:3.8', 'sqla:0.6.0', 'sqlam:0.7.1', 'tw:12.0.0', '_virtual_', ], 'matrix_label': 'py:3.8/sqla:0.6.0/sqlam:0.7.1/tw:12.0.0', }, 3: { 'python': '3.8', 'CI': 'true', 'TWISTED': '13.0.0', 'SQLALCHEMY': '0.6.8', 'SQLALCHEMY_MIGRATE': '0.7.1', 'virtual_builder_name': 'buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:13.0.0', 'virtual_builder_tags': [ 'buildbot', 'py:3.8', 'sqla:0.6.8', 'sqlam:0.7.1', 'tw:13.0.0', '_virtual_', ], 'matrix_label': 'py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:13.0.0', }, 4: { 'python': '3.8', 'CI': 'true', 'TWISTED': '14.0.0', 'SQLALCHEMY': '0.6.8', 'SQLALCHEMY_MIGRATE': '0.7.1', 'virtual_builder_name': 'buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:14.0.0', 'virtual_builder_tags': [ 'buildbot', 'py:3.8', 'sqla:0.6.8', 'sqlam:0.7.1', 'tw:14.0.0', '_virtual_', ], 'matrix_label': 'py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:14.0.0', }, 5: { 'python': '3.8', 'CI': 'true', 'TWISTED': '15.0.0', 'SQLALCHEMY': '0.6.8', 'SQLALCHEMY_MIGRATE': '0.7.1', 'virtual_builder_name': 'buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:15.0.0', 'virtual_builder_tags': [ 'buildbot', 'py:3.8', 'sqla:0.6.8', 'sqlam:0.7.1', 'tw:15.0.0', '_virtual_', ], 'matrix_label': 'py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:15.0.0', }, }, ) # global env CI should not be there self.assertEqual( buildernames, { 1: None, 2: ('buildbot py:3.8 sqla:0.6.0 sqlam:0.7.1 tw:12.0.0', 'BuildbotTestCiTrigger'), 3: ('buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:13.0.0', 'BuildbotTestCiTrigger'), 4: ('buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:14.0.0', 'BuildbotTestCiTrigger'), 5: ('buildbot py:3.8 sqla:0.6.8 sqlam:0.7.1 tw:15.0.0', 'BuildbotTestCiTrigger'), }, ) self.assertEqual( labels, { 1: None, 2: ('py:3.8/sqla:0.6.0/sqlam:0.7.1/tw:12.0.0', 'BuildbotTestCiTrigger'), 3: ('py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:13.0.0', 'BuildbotTestCiTrigger'), 4: ('py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:14.0.0', 'BuildbotTestCiTrigger'), 5: ('py:3.8/sqla:0.6.8/sqlam:0.7.1/tw:15.0.0', 'BuildbotTestCiTrigger'), }, )
11,292
Python
.py
288
27.020833
98
0.518856
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,625
test_notifier.py
buildbot_buildbot/master/buildbot/test/integration/test_notifier.py
# 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 base64 from twisted.internet import defer from buildbot.reporters.generators.build import BuildStatusGenerator from buildbot.reporters.generators.buildset import BuildSetStatusGenerator from buildbot.reporters.generators.worker import WorkerMissingGenerator from buildbot.reporters.mail import ESMTPSenderFactory from buildbot.reporters.mail import MailNotifier from buildbot.reporters.message import MessageFormatter from buildbot.reporters.message import MessageFormatterMissingWorker from buildbot.reporters.pushover import PushoverNotifier from buildbot.test.util.integration import RunMasterBase from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes # This integration test creates a master and worker environment, # with one builders and a shellcommand step, and a MailNotifier class NotifierMaster(RunMasterBase): if not ESMTPSenderFactory: skip = "twisted-mail unavailable, see: https://twistedmatrix.com/trac/ticket/8770" @defer.inlineCallbacks def create_master_config(self, build_set_summary=False): from buildbot.config import BuilderConfig from buildbot.plugins import reporters from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory self.mailDeferred = defer.Deferred() # patch MailNotifier.sendmail to know when the mail has been sent def sendMail(_, mail, recipients): self.mailDeferred.callback((mail.as_string(), recipients)) self.patch(MailNotifier, "sendMail", sendMail) self.notification = defer.Deferred() def sendNotification(_, params): self.notification.callback(params) self.patch(PushoverNotifier, "sendNotification", sendNotification) c = {} c['schedulers'] = [schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"])] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] formatter = MessageFormatter(template='This is a message.') formatter_worker = MessageFormatterMissingWorker(template='No worker.') if build_set_summary: generators_mail = [ BuildSetStatusGenerator(mode='all'), WorkerMissingGenerator(workers='all'), ] generators_pushover = [ BuildSetStatusGenerator(mode='all', message_formatter=formatter), WorkerMissingGenerator(workers=['local1'], message_formatter=formatter_worker), ] else: generators_mail = [ BuildStatusGenerator(mode='all'), WorkerMissingGenerator(workers='all'), ] generators_pushover = [ BuildStatusGenerator(mode='all', message_formatter=formatter), WorkerMissingGenerator(workers=['local1'], message_formatter=formatter_worker), ] c['services'] = [ reporters.MailNotifier("[email protected]", generators=generators_mail), reporters.PushoverNotifier('1234', 'abcd', generators=generators_pushover), ] yield self.setup_master(c) @defer.inlineCallbacks def doTest(self, what): change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "projectname", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) mail, recipients = yield self.mailDeferred self.assertEqual(recipients, ["[email protected]"]) self.assertIn("From: [email protected]", mail) self.assertIn( f"Subject: =?utf-8?q?=E2=98=BA_Buildbot_=28Buildbot=29=3A_{what}_-_build_successful_=28master=29?=\n", mail, ) self.assertEncodedIn("A passing build has been detected on builder testy while", mail) params = yield self.notification self.assertEqual(build['buildid'], 1) self.assertEqual( params, { 'title': f"☺ Buildbot (Buildbot): {what} - build successful (master)", 'message': "This is a message.", }, ) def assertEncodedIn(self, text, mail): # The default transfer encoding is base64 for utf-8 even when it could be represented # accurately by quoted 7bit encoding. TODO: it is possible to override it, # see https://bugs.python.org/issue12552 if "base64" not in mail: self.assertIn(text, mail) else: # b64encode and remove '=' padding (hence [:-1]) encodedBytes = base64.b64encode(unicode2bytes(text)).rstrip(b"=") encodedText = bytes2unicode(encodedBytes) self.assertIn(encodedText, mail) @defer.inlineCallbacks def test_notifiy_for_build(self): yield self.create_master_config(build_set_summary=False) yield self.doTest('testy') @defer.inlineCallbacks def test_notifiy_for_buildset(self): yield self.create_master_config(build_set_summary=True) yield self.doTest('projectname') @defer.inlineCallbacks def test_missing_worker(self): yield self.create_master_config(build_set_summary=False) yield self.master.data.updates.workerMissing( workerid='local1', masterid=self.master.masterid, last_connection='long time ago', notify=['[email protected]'], ) mail, recipients = yield self.mailDeferred self.assertIn("From: [email protected]", mail) self.assertEqual(recipients, ['[email protected]']) self.assertIn("Subject: Buildbot Buildbot worker local1 missing", mail) self.assertIn("disconnected at long time ago", mail) self.assertEncodedIn("worker named local1 went away", mail) params = yield self.notification self.assertEqual( params, {'title': "Buildbot Buildbot worker local1 missing", 'message': b"No worker."} )
7,021
Python
.py
145
39.786207
114
0.678681
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,626
test_integration_force_with_patch.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_force_with_patch.py
# 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.internet import defer from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.steps.source.base import Source from buildbot.test.util.decorators import skipUnlessPlatformIs from buildbot.test.util.integration import RunMasterBase # a simple patch which adds a Makefile PATCH = b"""diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8a5cf80 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +all: +\techo OK """ class MySource(Source): """A source class which only applies the patch""" @defer.inlineCallbacks def run_vc(self, branch, revision, patch): self.stdio_log = yield self.addLogForRemoteCommands("stdio") if patch: yield self.patch(patch) return SUCCESS class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.plugins import util from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.ForceScheduler( name="force", codebases=[util.CodebaseParameter("foo", patch=util.PatchParameter())], builderNames=["testy"], ) ] f = BuildFactory() f.addStep(MySource(codebase='foo')) # if the patch was applied correctly, then make will work! f.addStep(steps.ShellCommand(command=["make"])) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @skipUnlessPlatformIs("posix") # make is not installed on windows @defer.inlineCallbacks def test_shell(self): yield self.setup_config() build = yield self.doForceBuild( wantSteps=True, wantLogs=True, forceParams={'foo_patch_body': PATCH} ) self.assertEqual(build['buildid'], 1) # if makefile was not properly created, we would have a failure self.assertEqual(build['results'], SUCCESS) @defer.inlineCallbacks def test_shell_no_patch(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) # if no patch, the source step is happy, but the make step cannot find makefile self.assertEqual(build['steps'][1]['results'], SUCCESS) self.assertEqual(build['steps'][2]['results'], FAILURE) self.assertEqual(build['results'], FAILURE)
3,355
Python
.py
79
36.531646
88
0.702943
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,627
test_custom_buildstep.py
buildbot_buildbot/master/buildbot/test/integration/test_custom_buildstep.py
# 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.internet import defer from twisted.internet import error from buildbot.config import BuilderConfig from buildbot.process import buildstep from buildbot.process import logobserver from buildbot.process import results from buildbot.process.factory import BuildFactory from buildbot.process.project import Project from buildbot.test.util.integration import RunFakeMasterTestCase class TestLogObserver(logobserver.LogObserver): def __init__(self): self.observed = [] def outReceived(self, data): self.observed.append(data) class Latin1ProducingCustomBuildStep(buildstep.BuildStep): @defer.inlineCallbacks def run(self): _log = yield self.addLog('xx') output_str = '\N{CENT SIGN}' yield _log.addStdout(output_str) yield _log.finish() return results.SUCCESS class BuildStepWithFailingLogObserver(buildstep.BuildStep): @defer.inlineCallbacks def run(self): self.addLogObserver('xx', logobserver.LineConsumerLogObserver(self.log_consumer)) _log = yield self.addLog('xx') yield _log.addStdout('line1\nline2\n') yield _log.finish() return results.SUCCESS def log_consumer(self): _, _ = yield raise RuntimeError('fail') class SucceedingCustomStep(buildstep.BuildStep): flunkOnFailure = True def run(self): return defer.succeed(results.SUCCESS) class FailingCustomStep(buildstep.BuildStep): flunkOnFailure = True def __init__(self, exception=buildstep.BuildStepFailed, *args, **kwargs): super().__init__(*args, **kwargs) self.exception = exception @defer.inlineCallbacks def run(self): yield defer.succeed(None) raise self.exception() class RunSteps(RunFakeMasterTestCase): @defer.inlineCallbacks def create_config_for_step(self, step): config_dict = { 'builders': [ BuilderConfig( name="builder", workernames=["worker1"], factory=BuildFactory([step]) ), ], 'workers': [self.createLocalWorker('worker1')], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('builder') return builder_id @defer.inlineCallbacks def create_config_for_step_project(self, step): config_dict = { 'builders': [ BuilderConfig( name="builder", workernames=["worker1"], factory=BuildFactory([step]), project='project1', ), ], 'workers': [self.createLocalWorker('worker1')], 'projects': [Project(name='project1')], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('builder') return builder_id @defer.inlineCallbacks def test_step_raising_buildstepfailed_in_start(self): builder_id = yield self.create_config_for_step(FailingCustomStep()) yield self.do_test_build(builder_id) yield self.assertBuildResults(1, results.FAILURE) @defer.inlineCallbacks def test_step_raising_exception_in_start(self): builder_id = yield self.create_config_for_step(FailingCustomStep(exception=ValueError)) yield self.do_test_build(builder_id) yield self.assertBuildResults(1, results.EXCEPTION) self.assertEqual(len(self.flushLoggedErrors(ValueError)), 1) @defer.inlineCallbacks def test_step_raising_connectionlost_in_start(self): """Check whether we can recover from raising ConnectionLost from a step if the worker did not actually disconnect """ step = FailingCustomStep(exception=error.ConnectionLost) builder_id = yield self.create_config_for_step(step) yield self.do_test_build(builder_id) yield self.assertBuildResults(1, results.EXCEPTION) test_step_raising_connectionlost_in_start.skip = "Results in infinite loop" # type: ignore[attr-defined] @defer.inlineCallbacks def test_step_raising_in_log_observer(self): step = BuildStepWithFailingLogObserver() builder_id = yield self.create_config_for_step(step) yield self.do_test_build(builder_id) yield self.assertBuildResults(1, results.EXCEPTION) yield self.assertStepStateString(2, "finished (exception)") self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) @defer.inlineCallbacks def test_Latin1ProducingCustomBuildStep(self): step = Latin1ProducingCustomBuildStep(logEncoding='latin-1') builder_id = yield self.create_config_for_step(step) yield self.do_test_build(builder_id) yield self.assertLogs( 1, { 'xx': 'o\N{CENT SIGN}\n', }, ) def _check_and_pop_dynamic_properties(self, properties): for property in ('builddir', 'basedir'): self.assertIn(property, properties) properties.pop(property) @defer.inlineCallbacks def test_all_properties(self): builder_id = yield self.create_config_for_step(SucceedingCustomStep()) yield self.do_test_build(builder_id) properties = yield self.master.data.get(("builds", 1, "properties")) self._check_and_pop_dynamic_properties(properties) self.assertEqual( properties, { "buildername": ("builder", "Builder"), "builderid": (1, "Builder"), "workername": ("worker1", "Worker"), "buildnumber": (1, "Build"), "branch": (None, "Build"), "revision": (None, "Build"), "repository": ("", "Build"), "codebase": ("", "Build"), "project": ("", "Build"), }, ) @defer.inlineCallbacks def test_all_properties_project(self): builder_id = yield self.create_config_for_step_project(SucceedingCustomStep()) yield self.do_test_build(builder_id) properties = yield self.master.data.get(('builds', 1, 'properties')) self._check_and_pop_dynamic_properties(properties) self.assertEqual( properties, { 'buildername': ('builder', 'Builder'), 'builderid': (1, 'Builder'), 'workername': ('worker1', 'Worker'), 'buildnumber': (1, 'Build'), 'branch': (None, 'Build'), 'projectid': (1, 'Builder'), 'projectname': ('project1', 'Builder'), 'revision': (None, 'Build'), 'repository': ('', 'Build'), 'codebase': ('', 'Build'), 'project': ('', 'Build'), }, )
7,865
Python
.py
183
33.781421
109
0.637209
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,628
test_integration_scheduler_reconfigure.py
buildbot_buildbot/master/buildbot/test/integration/test_integration_scheduler_reconfigure.py
# 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.internet import defer from buildbot.plugins import schedulers from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # with one builders and a shellcommand step # meant to be a template for integration steps class ShellMaster(RunMasterBase): def create_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.AnyBranchScheduler(name="sched1", builderNames=["testy1"]), schedulers.ForceScheduler(name="sched2", builderNames=["testy2"]), ] f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) c['builders'] = [ BuilderConfig(name=name, workernames=["local1"], factory=f) for name in ['testy1', 'testy2'] ] return c @defer.inlineCallbacks def test_shell(self): cfg = self.create_config() yield self.setup_master(cfg) change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } # switch the configuration of the scheduler, and make sure the correct builder is run cfg['schedulers'] = [ schedulers.AnyBranchScheduler(name="sched1", builderNames=["testy2"]), schedulers.ForceScheduler(name="sched2", builderNames=["testy1"]), ] yield self.master.reconfig() build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) builder = yield self.master.data.get(('builders', build['builderid'])) self.assertEqual(builder['name'], 'testy2')
2,680
Python
.py
60
37.666667
93
0.676493
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,629
test_stop_build.py
buildbot_buildbot/master/buildbot/test/integration/test_stop_build.py
# 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.internet import defer from buildbot.test.util.integration import RunMasterBase class ShellMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"]), schedulers.ForceScheduler(name="force", builderNames=["testy"]), ] f = BuildFactory() f.addStep(steps.ShellCommand(command='sleep 100', name='sleep')) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_shell(self): yield self.setup_config() @defer.inlineCallbacks def newStepCallback(_, data): # when the sleep step start, we kill it if data['name'] == 'sleep': brs = yield self.master.data.get(('buildrequests',)) brid = brs[-1]['buildrequestid'] self.master.data.control( 'cancel', {'reason': 'cancelled by test'}, ('buildrequests', brid) ) yield self.master.mq.startConsuming(newStepCallback, ('steps', None, 'new')) build = yield self.doForceBuild(wantSteps=True, wantLogs=True, wantProperties=True) self.assertEqual(build['buildid'], 1) # make sure the cancel reason is transferred all the way to the step log cancel_logs = [log for log in build['steps'][1]["logs"] if log["name"] == "cancelled"] self.assertEqual(len(cancel_logs), 1) self.assertIn('cancelled by test', cancel_logs[0]['contents']['content'])
2,572
Python
.py
51
43
94
0.680749
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,630
test_setpropertyfromcommand.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_setpropertyfromcommand.py
# 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.internet import defer from twisted.internet import reactor from twisted.internet import task from buildbot.test.util.integration import RunMasterBase # This integration test helps reproduce http://trac.buildbot.net/ticket/3024 # we make sure that we can reconfigure the master while build is running class SetPropertyFromCommand(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.plugins import util c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = util.BuildFactory() f.addStep(steps.SetPropertyFromCommand(property="test", command=["echo", "foo"])) c['builders'] = [util.BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_setProp(self): yield self.setup_config() oldNewLog = self.master.data.updates.addLog @defer.inlineCallbacks def newLog(*arg, **kw): # Simulate db delay. We usually don't test race conditions # with delays, but in integrations test, that would be pretty # tricky yield task.deferLater(reactor, 0.1, lambda: None) res = yield oldNewLog(*arg, **kw) return res self.master.data.updates.addLog = newLog build = yield self.doForceBuild(wantProperties=True) self.assertEqual(build['properties']['test'], ('foo', 'SetPropertyFromCommand Step')) class SetPropertyFromCommandPB(SetPropertyFromCommand): proto = "pb" class SetPropertyFromCommandMsgPack(SetPropertyFromCommand): proto = "msgpack"
2,486
Python
.py
51
43.039216
93
0.7284
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,631
test_transfer.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_transfer.py
# 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 shutil from twisted.internet import defer from buildbot.process.buildstep import BuildStep from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.steps.transfer import DirectoryUpload from buildbot.steps.transfer import FileDownload from buildbot.steps.transfer import FileUpload from buildbot.steps.transfer import MultipleFileUpload from buildbot.steps.transfer import StringDownload from buildbot.steps.worker import CompositeStepMixin from buildbot.test.util.decorators import flaky from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment # and make sure the transfer steps are working # When new protocols are added, make sure you update this test to exercise # your proto implementation class TransferStepsMasterPb(RunMasterBase): proto = "pb" @defer.inlineCallbacks def setup_config(self, bigfilename): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() # do a bunch of transfer to exercise the protocol f.addStep(StringDownload("filecontent", workerdest="dir/file1.txt")) f.addStep(StringDownload("filecontent2", workerdest="dir/file2.txt")) # create 8 MB file with open(bigfilename, 'w', encoding='utf-8') as o: buf = "xxxxxxxx" * 1024 for _ in range(1000): o.write(buf) f.addStep(FileDownload(mastersrc=bigfilename, workerdest="bigfile.txt")) f.addStep(FileUpload(workersrc="dir/file2.txt", masterdest="master.txt")) f.addStep(FileDownload(mastersrc="master.txt", workerdest="dir/file3.txt")) f.addStep(DirectoryUpload(workersrc="dir", masterdest="dir")) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def setup_config_glob(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory class CustomStep(BuildStep, CompositeStepMixin): @defer.inlineCallbacks def run(self): content = yield self.getFileContentFromWorker( "dir/file1.txt", abandonOnFailure=True ) assert content == "filecontent" return SUCCESS c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() f.addStep(StringDownload("filecontent", workerdest="dir/file1.txt")) f.addStep(StringDownload("filecontent2", workerdest="dir/notafile1.txt")) f.addStep(StringDownload("filecontent2", workerdest="dir/only1.txt")) f.addStep( MultipleFileUpload( workersrcs=["dir/file*.txt", "dir/not*.txt", "dir/only?.txt"], masterdest="dest/", glob=True, ) ) f.addStep(CustomStep()) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def setup_config_single_step(self, step): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = BuildFactory() f.addStep(step) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) def readMasterDirContents(self, top): contents = {} for root, _, files in os.walk(top): for name in files: fn = os.path.join(root, name) with open(fn, encoding='utf-8') as f: contents[fn] = f.read() return contents @flaky(bugNumber=4407, onPlatform='win32') @defer.inlineCallbacks def test_transfer(self): yield self.setup_config(bigfilename=self.mktemp()) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], SUCCESS) dirContents = self.readMasterDirContents("dir") self.assertEqual( dirContents, { os.path.join('dir', 'file1.txt'): 'filecontent', os.path.join('dir', 'file2.txt'): 'filecontent2', os.path.join('dir', 'file3.txt'): 'filecontent2', }, ) # cleanup our mess (worker is cleaned up by parent class) shutil.rmtree("dir") os.unlink("master.txt") @defer.inlineCallbacks def test_globTransfer(self): yield self.setup_config_glob() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], SUCCESS) dirContents = self.readMasterDirContents("dest") self.assertEqual( dirContents, { os.path.join('dest', 'file1.txt'): 'filecontent', os.path.join('dest', 'notafile1.txt'): 'filecontent2', os.path.join('dest', 'only1.txt'): 'filecontent2', }, ) # cleanup shutil.rmtree("dest") @defer.inlineCallbacks def test_no_exist_file_upload(self): step = FileUpload(workersrc="dir/noexist_path", masterdest="master_dest") yield self.setup_config_single_step(step) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], FAILURE) res = yield self.checkBuildStepLogExist(build, "Cannot open file") self.assertTrue(res) self.assertFalse(os.path.exists("master_dest")) @defer.inlineCallbacks def test_no_exist_directory_upload(self): step = DirectoryUpload(workersrc="dir/noexist_path", masterdest="master_dest") yield self.setup_config_single_step(step) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], FAILURE) res = yield self.checkBuildStepLogExist(build, "Cannot read directory") self.assertTrue(res) self.assertFalse(os.path.exists("master_dest")) @defer.inlineCallbacks def test_no_exist_multiple_file_upload(self): step = MultipleFileUpload(workersrcs=["dir/noexist_path"], masterdest="master_dest") yield self.setup_config_single_step(step) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['results'], FAILURE) res = yield self.checkBuildStepLogExist(build, "not available at worker") self.assertTrue(res) self.assertEqual(self.readMasterDirContents("master_dest"), {}) class TransferStepsMasterNull(TransferStepsMasterPb): proto = "null"
7,893
Python
.py
167
38.952096
92
0.676069
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,632
test_interruptcommand.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_interruptcommand.py
# 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.internet import defer from buildbot.process.results import CANCELLED from buildbot.test.util.decorators import flaky from buildbot.test.util.integration import RunMasterBase from buildbot.util import asyncSleep class InterruptCommand(RunMasterBase): """Make sure we can interrupt a command""" @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.plugins import util class SleepAndInterrupt(steps.ShellSequence): @defer.inlineCallbacks def run(self): if self.worker.worker_system == "nt": sleep = "waitfor SomethingThatIsNeverHappening /t 100 >nul 2>&1" else: sleep = ["sleep", "100"] d = self.runShellSequence([util.ShellArg(sleep)]) yield asyncSleep(1) self.interrupt("just testing") res = yield d return res c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] f = util.BuildFactory() f.addStep(SleepAndInterrupt()) c['builders'] = [util.BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @flaky(bugNumber=4404, onPlatform='win32') @defer.inlineCallbacks def test_interrupt(self): yield self.setup_config() build = yield self.doForceBuild(wantSteps=True) self.assertEqual(build['steps'][-1]['results'], CANCELLED) class InterruptCommandPb(InterruptCommand): proto = "pb" class InterruptCommandMsgPack(InterruptCommand): proto = "msgpack"
2,446
Python
.py
54
38.240741
93
0.696256
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,633
test_compositestepmixin.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_compositestepmixin.py
# 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.internet import defer from buildbot.process import results from buildbot.process.buildstep import BuildStep from buildbot.steps.worker import CompositeStepMixin from buildbot.test.util.integration import RunMasterBase class TestCompositeMixinStep(BuildStep, CompositeStepMixin): def __init__(self, is_list_mkdir, is_list_rmdir): super().__init__() self.logEnviron = False self.is_list_mkdir = is_list_mkdir self.is_list_rmdir = is_list_rmdir @defer.inlineCallbacks def run(self): contents = yield self.runGlob('*') if contents != []: return results.FAILURE paths = ['composite_mixin_test_1', 'composite_mixin_test_2'] for path in paths: has_path = yield self.pathExists(path) if has_path: return results.FAILURE if self.is_list_mkdir: yield self.runMkdir(paths) else: for path in paths: yield self.runMkdir(path) for path in paths: has_path = yield self.pathExists(path) if not has_path: return results.FAILURE contents = yield self.runGlob('*') contents.sort() for i, path in enumerate(paths): if not contents[i].endswith(path): return results.FAILURE if self.is_list_rmdir: yield self.runRmdir(paths) else: for path in paths: yield self.runRmdir(path) for path in paths: has_path = yield self.pathExists(path) if has_path: return results.FAILURE return results.SUCCESS # This integration test creates a master and worker environment, # and makes sure the composite step mixin is working. class CompositeStepMixinMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self, is_list_mkdir=True, is_list_rmdir=True): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"])] f = BuildFactory() f.addStep(TestCompositeMixinStep(is_list_mkdir=is_list_mkdir, is_list_rmdir=is_list_rmdir)) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_compositemixin_rmdir_list(self): yield self.do_compositemixin_test(is_list_mkdir=False, is_list_rmdir=True) @defer.inlineCallbacks def test_compositemixin(self): yield self.do_compositemixin_test(is_list_mkdir=False, is_list_rmdir=False) @defer.inlineCallbacks def do_compositemixin_test(self, is_list_mkdir, is_list_rmdir): yield self.setup_config(is_list_mkdir=is_list_mkdir, is_list_rmdir=is_list_rmdir) change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['results'], results.SUCCESS) class CompositeStepMixinMasterPb(CompositeStepMixinMaster): proto = "pb" class CompositeStepMixinMasterMsgPack(CompositeStepMixinMaster): proto = "msgpack" @defer.inlineCallbacks def test_compositemixin_mkdir_rmdir_lists(self): yield self.do_compositemixin_test(is_list_mkdir=True, is_list_rmdir=True)
4,470
Python
.py
101
36.316832
99
0.676267
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,634
test_commandmixin.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_commandmixin.py
# 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.internet import defer from buildbot.process import results from buildbot.process.buildstep import BuildStep from buildbot.process.buildstep import CommandMixin from buildbot.test.util.integration import RunMasterBase # This integration test creates a master and worker environment, # and makes sure the command mixin is working. class CommandMixinMaster(RunMasterBase): @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"])] f = BuildFactory() f.addStep(TestCommandMixinStep()) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_commandmixin(self): yield self.setup_config() change = { "branch": "master", "files": ["foo.c"], "author": "[email protected]", "committer": "[email protected]", "comments": "good stuff", "revision": "HEAD", "project": "none", } build = yield self.doForceBuild(wantSteps=True, useChange=change, wantLogs=True) self.assertEqual(build['buildid'], 1) self.assertEqual(build['results'], results.SUCCESS) class CommandMixinMasterPB(CommandMixinMaster): proto = "pb" class CommandMixinMasterMsgPack(CommandMixinMaster): proto = "msgpack" class TestCommandMixinStep(BuildStep, CommandMixin): @defer.inlineCallbacks def run(self): contents = yield self.runGlob('*') if contents != []: return results.FAILURE hasPath = yield self.pathExists('composite_mixin_test') if hasPath: return results.FAILURE yield self.runMkdir('composite_mixin_test') hasPath = yield self.pathExists('composite_mixin_test') if not hasPath: return results.FAILURE contents = yield self.runGlob('*') if not contents[0].endswith('composite_mixin_test'): return results.FAILURE yield self.runRmdir('composite_mixin_test') hasPath = yield self.pathExists('composite_mixin_test') if hasPath: return results.FAILURE return results.SUCCESS
3,162
Python
.py
73
36.534247
95
0.698076
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,635
__init__.py
buildbot_buildbot/master/buildbot/test/integration/interop/__init__.py
# 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 """Tests in this module are meant to be used for interoperability between different version of worker vs master (e.g py2 vs py3) """
839
Python
.py
17
48.294118
79
0.786845
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,636
test_integration_secrets.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_integration_secrets.py
# 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 parameterized import parameterized from twisted.internet import defer from buildbot.process.properties import Interpolate from buildbot.reporters.http import HttpStatusPush from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.util.integration import RunMasterBase class FakeSecretReporter(HttpStatusPush): def sendMessage(self, reports): assert self.auth == ('user', 'myhttppasswd') self.reported = True class SecretsConfig(RunMasterBase): @defer.inlineCallbacks def setup_config(self, use_interpolation): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.plugins import util from buildbot.process.factory import BuildFactory fake_reporter = FakeSecretReporter( 'http://example.com/hook', auth=('user', Interpolate('%(secret:httppasswd)s')) ) c['services'] = [fake_reporter] c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] c['secretsProviders'] = [ FakeSecretStorage( secretdict={"foo": "secretvalue", "something": "more", 'httppasswd': 'myhttppasswd'} ) ] f = BuildFactory() if use_interpolation: if os.name == "posix": # on posix we can also check whether the password was passed to the command command = Interpolate( 'echo %(secret:foo)s | ' + 'sed "s/secretvalue/The password was there/"' ) else: command = Interpolate('echo %(secret:foo)s') else: command = ['echo', util.Secret('foo')] f.addStep(steps.ShellCommand(command=command)) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) return fake_reporter # Note that the secret name must be long enough so that it does not crash with random directory # or file names in the build dictionary. @parameterized.expand([ ('with_interpolation', True), ('plain_command', False), ]) @defer.inlineCallbacks def test_secret(self, name, use_interpolation): fake_reporter = yield self.setup_config(use_interpolation) build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) # check the command line res = yield self.checkBuildStepLogExist(build, "echo <foo>") # also check the secrets are replaced in argv yield self.checkBuildStepLogExist(build, "argv:.*echo.*<foo>", regex=True) # also check that the correct value goes to the command if os.name == "posix" and use_interpolation: res &= yield self.checkBuildStepLogExist(build, "The password was there") self.assertTrue(res) # at this point, build contains all the log and steps info that is in the db # we check that our secret is not in there! self.assertNotIn("secretvalue", repr(build)) self.assertTrue(fake_reporter.reported) @parameterized.expand([ ('with_interpolation', True), ('plain_command', False), ]) @defer.inlineCallbacks def test_secretReconfig(self, name, use_interpolation): yield self.setup_config(use_interpolation) self.master_config_dict['secretsProviders'] = [ FakeSecretStorage(secretdict={"foo": "different_value", "something": "more"}) ] yield self.master.reconfig() build = yield self.doForceBuild(wantSteps=True, wantLogs=True) self.assertEqual(build['buildid'], 1) res = yield self.checkBuildStepLogExist(build, "echo <foo>") self.assertTrue(res) # at this point, build contains all the log and steps info that is in the db # we check that our secret is not in there! self.assertNotIn("different_value", repr(build)) class SecretsConfigPB(SecretsConfig): proto = "pb" class SecretsConfigMsgPack(SecretsConfig): proto = "msgpack"
4,902
Python
.py
104
39.586538
100
0.681961
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,637
test_worker_reconnect.py
buildbot_buildbot/master/buildbot/test/integration/interop/test_worker_reconnect.py
# 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 annotations from twisted.internet import defer from buildbot.process.buildstep import BuildStep from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase class DisconnectingStep(BuildStep): disconnection_list: list[DisconnectingStep] = [] def run(self): self.disconnection_list.append(self) assert self.worker.conn.get_peer().startswith("127.0.0.1:") if len(self.disconnection_list) < 2: self.worker.disconnect() return SUCCESS class WorkerReconnectPb(RunMasterBase): """integration test for testing worker disconnection and reconnection""" proto = "pb" @defer.inlineCallbacks def setup_config(self): c = {} from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.process.factory import BuildFactory c['schedulers'] = [ schedulers.AnyBranchScheduler(name="sched", builderNames=["testy"]), schedulers.ForceScheduler(name="force", builderNames=["testy"]), ] f = BuildFactory() f.addStep(DisconnectingStep()) c['builders'] = [BuilderConfig(name="testy", workernames=["local1"], factory=f)] yield self.setup_master(c) @defer.inlineCallbacks def test_eventually_reconnect(self): DisconnectingStep.disconnection_list = [] yield self.setup_config() build = yield self.doForceBuild() self.assertEqual(build['buildid'], 2) self.assertEqual(len(DisconnectingStep.disconnection_list), 2) class WorkerReconnectMsgPack(WorkerReconnectPb): proto = "msgpack"
2,395
Python
.py
53
39.679245
88
0.730554
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,638
test_marathon.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_marathon.py
# 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 unittest.case import SkipTest from twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase from buildbot.worker.marathon import MarathonLatentWorker # This integration test creates a master and marathon worker environment, # It requires environment variable set to your marathon hosting. # you can use the mesos-compose to create a marathon environment for development: # git clone https://github.com/bobrik/mesos-compose.git # cd mesos-compose # make run # then set the environment variable to run the test: # export BBTEST_MARATHON_URL=http://localhost:8080 # following environment variable can be used to stress concurrent worker startup NUM_CONCURRENT = int(os.environ.get("MARATHON_TEST_NUM_CONCURRENT_BUILD", 1)) # if you run the stress test against a real mesos deployment, you want to also use https and basic # credentials export BBTEST_MARATHON_CREDS=login:passwd class MarathonMaster(RunMasterBase): def setUp(self): if "BBTEST_MARATHON_URL" not in os.environ: raise SkipTest( "marathon integration tests only run when environment variable BBTEST_MARATHON_URL" " is with url to Marathon api " ) @defer.inlineCallbacks def setup_config(self, num_concurrent, extra_steps=None): if extra_steps is None: extra_steps = [] c = {} c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] triggereables = [] for i in range(num_concurrent): c['schedulers'].append( schedulers.Triggerable(name="trigsched" + str(i), builderNames=["build"]) ) triggereables.append("trigsched" + str(i)) f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) f.addStep( steps.Trigger(schedulerNames=triggereables, waitForFinish=True, updateSourceStamp=True) ) f.addStep(steps.ShellCommand(command='echo world')) f2 = BuildFactory() f2.addStep(steps.ShellCommand(command='echo ola')) for step in extra_steps: f2.addStep(step) c['builders'] = [ BuilderConfig(name="testy", workernames=["marathon0"], factory=f), BuilderConfig( name="build", workernames=["marathon" + str(i) for i in range(num_concurrent)], factory=f2, ), ] url = os.environ.get('BBTEST_MARATHON_URL') creds = os.environ.get('BBTEST_MARATHON_CREDS') if creds is not None: user, password = creds.split(":") else: user = password = None masterFQDN = os.environ.get('masterFQDN') marathon_extra_config = {} c['workers'] = [ MarathonLatentWorker( 'marathon' + str(i), url, user, password, 'buildbot/buildbot-worker:master', marathon_extra_config=marathon_extra_config, masterFQDN=masterFQDN, ) for i in range(num_concurrent) ] # un comment for debugging what happens if things looks locked. # c['www'] = {'port': 8080} # if the masterFQDN is forced (proxy case), then we use 9989 default port # else, we try to find a free port if masterFQDN is not None: c['protocols'] = {"pb": {"port": "tcp:9989"}} else: c['protocols'] = {"pb": {"port": "tcp:0"}} yield self.setup_master(c, startWorker=False) @defer.inlineCallbacks def test_trigger(self): yield self.setup_master(num_concurrent=NUM_CONCURRENT) yield self.doForceBuild() builds = yield self.master.data.get(("builds",)) # if there are some retry, there will be more builds self.assertEqual(len(builds), 1 + NUM_CONCURRENT) for b in builds: self.assertEqual(b['results'], SUCCESS)
4,950
Python
.py
111
36.666667
99
0.665077
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,639
test_comm.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_comm.py
# 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.cred import credentials from twisted.internet import defer from twisted.internet import reactor from twisted.internet.endpoints import clientFromString from twisted.python import log from twisted.python import util from twisted.spread import pb from twisted.trial import unittest import buildbot from buildbot import config from buildbot import worker from buildbot.process import botmaster from buildbot.process import builder from buildbot.process import factory from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util.eventual import eventually from buildbot.worker import manager as workermanager from buildbot.worker.protocols.manager.pb import PBManager PKI_DIR = util.sibpath(__file__, 'pki') class FakeWorkerForBuilder(pb.Referenceable): """ Fake worker-side WorkerForBuilder object """ class FakeWorkerWorker(pb.Referenceable): """ Fake worker-side Worker object @ivar master_persp: remote perspective on the master """ def __init__(self, callWhenBuilderListSet): self.callWhenBuilderListSet = callWhenBuilderListSet self.master_persp = None self._detach_deferreds = [] self._detached = False def waitForDetach(self): if self._detached: return defer.succeed(None) d = defer.Deferred() self._detach_deferreds.append(d) return d def setMasterPerspective(self, persp): self.master_persp = persp # clear out master_persp on disconnect def clear_persp(): self.master_persp = None persp.broker.notifyOnDisconnect(clear_persp) def fire_deferreds(): self._detached = True deferreds = self._detach_deferreds self._detach_deferreds = None for d in deferreds: d.callback(None) persp.broker.notifyOnDisconnect(fire_deferreds) def remote_print(self, message): log.msg(f"WORKER-SIDE: remote_print({message!r})") def remote_getWorkerInfo(self): return { 'info': 'here', 'worker_commands': { 'x': 1, }, 'numcpus': 1, 'none': None, 'os_release': b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(), b'\xe3\x83\xaa\xe3\x83\xaa\xe3\x83\xbc\xe3\x82\xb9\xe3' b'\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(): b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(), } def remote_getVersion(self): return buildbot.version def remote_getCommands(self): return {'x': 1} def remote_setBuilderList(self, builder_info): builder_names = [n for n, dir in builder_info] slbuilders = [FakeWorkerForBuilder() for n in builder_names] eventually(self.callWhenBuilderListSet) return dict(zip(builder_names, slbuilders)) class FakeBuilder(builder.Builder): def attached(self, worker, commands): return defer.succeed(None) def detached(self, worker): pass def getOldestRequestTime(self): return 0 def maybeStartBuild(self): return defer.succeed(None) class MyWorker(worker.Worker): def attached(self, conn): self.detach_d = defer.Deferred() return super().attached(conn) def detached(self): super().detached() d = self.detach_d self.detach_d = None d.callback(None) class TestWorkerComm(unittest.TestCase, TestReactorMixin): """ Test handling of connections from workers as integrated with - Twisted Spread - real TCP connections. - PBManager @ivar master: fake build master @ivar pbamanger: L{PBManager} instance @ivar botmaster: L{BotMaster} instance @ivar worker: master-side L{Worker} instance @ivar workerworker: worker-side L{FakeWorkerWorker} instance @ivar port: TCP port to connect to @ivar server_connection_string: description string for the server endpoint @ivar client_connection_string_tpl: description string template for the client endpoint (expects to passed 'port') @ivar endpoint: endpoint controlling the outbound connection from worker to master """ @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantData=True, wantDb=True) # set the worker port to a loopback address with unspecified # port self.pbmanager = self.master.pbmanager = PBManager() yield self.pbmanager.setServiceParent(self.master) # remove the fakeServiceParent from fake service hierarchy, and replace # by a real one yield self.master.workers.disownServiceParent() self.workers = self.master.workers = workermanager.WorkerManager(self.master) yield self.workers.setServiceParent(self.master) self.botmaster = botmaster.BotMaster() yield self.botmaster.setServiceParent(self.master) self.master.botmaster = self.botmaster self.master.data.updates.workerConfigured = lambda *a, **k: None yield self.master.startService() self.buildworker = None self.port = None self.workerworker = None self.endpoint = None self.broker = None self._detach_deferreds = [] # patch in our FakeBuilder for the regular Builder class self.patch(botmaster, 'Builder', FakeBuilder) self.server_connection_string = "tcp:0:interface=127.0.0.1" self.client_connection_string_tpl = "tcp:host=127.0.0.1:port={port}" @defer.inlineCallbacks def tearDown(self): if self.broker: del self.broker if self.endpoint: del self.endpoint deferreds = [ *self._detach_deferreds, self.pbmanager.stopService(), self.botmaster.stopService(), self.workers.stopService(), ] # if the worker is still attached, wait for it to detach, too if self.buildworker and self.buildworker.detach_d: deferreds.append(self.buildworker.detach_d) yield defer.gatherResults(deferreds) yield self.tear_down_test_reactor() @defer.inlineCallbacks def addWorker(self, **kwargs): """ Create a master-side worker instance and add it to the BotMaster @param **kwargs: arguments to pass to the L{Worker} constructor. """ self.buildworker = MyWorker("testworker", "pw", **kwargs) # reconfig the master to get it set up new_config = self.master.config new_config.protocols = {"pb": {"port": self.server_connection_string}} new_config.workers = [self.buildworker] new_config.builders = [ config.BuilderConfig( name='bldr', workername='testworker', factory=factory.BuildFactory() ) ] yield self.botmaster.reconfigServiceWithBuildbotConfig(new_config) yield self.workers.reconfigServiceWithBuildbotConfig(new_config) # as part of the reconfig, the worker registered with the pbmanager, so # get the port it was assigned self.port = self.buildworker.registration.getPBPort() def connectWorker(self, waitForBuilderList=True): """ Connect a worker the master via PB @param waitForBuilderList: don't return until the setBuilderList has been called @returns: L{FakeWorkerWorker} and a Deferred that will fire when it is detached; via deferred """ factory = pb.PBClientFactory() creds = credentials.UsernamePassword(b"testworker", b"pw") setBuilderList_d = defer.Deferred() workerworker = FakeWorkerWorker(lambda: setBuilderList_d.callback(None)) login_d = factory.login(creds, workerworker) @login_d.addCallback def logged_in(persp): workerworker.setMasterPerspective(persp) # set up to hear when the worker side disconnects workerworker.detach_d = defer.Deferred() persp.broker.notifyOnDisconnect(lambda: workerworker.detach_d.callback(None)) self._detach_deferreds.append(workerworker.detach_d) return workerworker self.endpoint = clientFromString( reactor, self.client_connection_string_tpl.format(port=self.port) ) connected_d = self.endpoint.connect(factory) dlist = [connected_d, login_d] if waitForBuilderList: dlist.append(setBuilderList_d) d = defer.DeferredList(dlist, consumeErrors=True, fireOnOneErrback=True) d.addCallback(lambda _: workerworker) return d def workerSideDisconnect(self, worker): """Disconnect from the worker side""" worker.master_persp.broker.transport.loseConnection() @defer.inlineCallbacks def test_connect_disconnect(self): """Test a single worker connecting and disconnecting.""" yield self.addWorker() # connect worker = yield self.connectWorker() # disconnect self.workerSideDisconnect(worker) # wait for the resulting detach yield worker.waitForDetach() @defer.inlineCallbacks def test_tls_connect_disconnect(self): """Test with TLS or SSL endpoint. According to the deprecation note for the SSL client endpoint, the TLS endpoint is supported from Twistd 16.0. TODO add certificate verification (also will require some conditionals on various versions, including PyOpenSSL, service_identity. The CA used to generate the testing cert is in ``PKI_DIR/ca`` """ def escape_colon(path): # on windows we can't have \ as it serves as the escape character for : return path.replace('\\', '/').replace(':', '\\:') self.server_connection_string = ( "ssl:port=0:certKey={pub}:privateKey={priv}:" + "interface=127.0.0.1" ).format( pub=escape_colon(os.path.join(PKI_DIR, '127.0.0.1.crt')), priv=escape_colon(os.path.join(PKI_DIR, '127.0.0.1.key')), ) self.client_connection_string_tpl = "ssl:host=127.0.0.1:port={port}" yield self.addWorker() # connect worker = yield self.connectWorker() # disconnect self.workerSideDisconnect(worker) # wait for the resulting detach yield worker.waitForDetach() @defer.inlineCallbacks def test_worker_info(self): yield self.addWorker() worker = yield self.connectWorker() props = self.buildworker.info # check worker info passing self.assertEqual(props.getProperty("info"), "here") # check worker info passing with UTF-8 self.assertEqual( props.getProperty("os_release"), b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode() ) self.assertEqual( props.getProperty( b'\xe3\x83\xaa\xe3\x83\xaa\xe3\x83\xbc\xe3\x82' b'\xb9\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode() ), b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(), ) self.assertEqual(props.getProperty("none"), None) self.assertEqual(props.getProperty("numcpus"), 1) self.workerSideDisconnect(worker) yield worker.waitForDetach() @defer.inlineCallbacks def _test_duplicate_worker(self): yield self.addWorker() # connect first worker worker1 = yield self.connectWorker() # connect second worker; this should fail try: yield self.connectWorker(waitForBuilderList=False) connect_failed = False except Exception: connect_failed = True self.assertTrue(connect_failed) # disconnect both and wait for that to percolate self.workerSideDisconnect(worker1) yield worker1.waitForDetach() # flush the exception logged for this on the master self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) @defer.inlineCallbacks def _test_duplicate_worker_old_dead(self): yield self.addWorker() # connect first worker worker1 = yield self.connectWorker() # monkeypatch that worker to fail with PBConnectionLost when its # remote_print method is called def remote_print(message): worker1.master_persp.broker.transport.loseConnection() raise pb.PBConnectionLost("fake!") worker1.remote_print = remote_print # connect second worker; this should succeed, and the old worker # should be disconnected. worker2 = yield self.connectWorker() # disconnect both and wait for that to percolate self.workerSideDisconnect(worker2) yield worker1.waitForDetach() # flush the exception logged for this on the worker self.assertEqual(len(self.flushLoggedErrors(pb.PBConnectionLost)), 1)
13,892
Python
.py
321
34.866044
107
0.671067
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,640
test_misc.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_misc.py
# 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 annotations from twisted.internet import defer from zope.interface import implementer from buildbot.config import BuilderConfig from buildbot.interfaces import IBuildStepFactory from buildbot.machine.base import Machine from buildbot.process.buildstep import BuildStep from buildbot.process.buildstep import create_step_from_step_or_factory from buildbot.process.factory import BuildFactory from buildbot.process.properties import Interpolate from buildbot.process.results import CANCELLED from buildbot.process.results import RETRY from buildbot.test.fake.latent import LatentController from buildbot.test.fake.step import BuildStepController from buildbot.test.fake.worker import WorkerController from buildbot.test.util.integration import RunFakeMasterTestCase RemoteWorker: type | None = None try: from buildbot_worker.bot import LocalWorker as RemoteWorker except ImportError: pass @implementer(IBuildStepFactory) class StepController: def __init__(self, **kwargs): self.kwargs = kwargs self.steps = [] def buildStep(self): step_deferred = defer.Deferred() step = create_step_from_step_or_factory(ControllableStep(step_deferred, **self.kwargs)) self.steps.append((step, step_deferred)) return step class ControllableStep(BuildStep): def run(self): return self._step_deferred def __init__(self, step_deferred, **kwargs): super().__init__(**kwargs) self._step_deferred = step_deferred def interrupt(self, reason): self._step_deferred.callback(CANCELLED) class Tests(RunFakeMasterTestCase): @defer.inlineCallbacks def test_latent_max_builds(self): """ If max_builds is set, only one build is started on a latent worker at a time. """ controller = LatentController(self, 'local', max_builds=1) step_controller = StepController() config_dict = { 'builders': [ BuilderConfig( name="testy-1", workernames=["local"], factory=BuildFactory([step_controller]), ), BuilderConfig( name="testy-2", workernames=["local"], factory=BuildFactory([step_controller]), ), ], 'workers': [controller.worker], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('testy-1')), (yield self.master.data.updates.findBuilderId('testy-2')), ] started_builds = [] yield self.master.mq.startConsuming( lambda key, build: started_builds.append(build), ('builds', None, 'new') ) # Trigger a buildrequest yield self.master.data.updates.addBuildset( waited_for=False, builderids=builder_ids, sourcestamps=[ {'codebase': '', 'repository': '', 'branch': None, 'revision': None, 'project': ''}, ], ) # The worker fails to substantiate. controller.start_instance(True) yield controller.connect_worker() self.assertEqual(len(started_builds), 1) yield controller.auto_stop(True) @defer.inlineCallbacks def test_local_worker_max_builds(self): """ If max_builds is set, only one build is started on a worker at a time. """ step_controller = StepController() config_dict = { 'builders': [ BuilderConfig( name="testy-1", workernames=["local"], factory=BuildFactory([step_controller]), ), BuilderConfig( name="testy-2", workernames=["local"], factory=BuildFactory([step_controller]), ), ], 'workers': [self.createLocalWorker('local', max_builds=1)], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('testy-1')), (yield self.master.data.updates.findBuilderId('testy-2')), ] started_builds = [] yield self.master.mq.startConsuming( lambda key, build: started_builds.append(build), ('builds', None, 'new') ) # Trigger a buildrequest yield self.master.data.updates.addBuildset( waited_for=False, builderids=builder_ids, sourcestamps=[ {'codebase': '', 'repository': '', 'branch': None, 'revision': None, 'project': ''}, ], ) self.assertEqual(len(started_builds), 1) @defer.inlineCallbacks def test_worker_registered_to_machine(self): worker = self.createLocalWorker('worker1', machine_name='machine1') machine = Machine('machine1') config_dict = { 'builders': [ BuilderConfig( name="builder1", workernames=["worker1"], factory=BuildFactory(), ), ], 'workers': [worker], 'machines': [machine], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) self.assertIs(worker.machine, machine) @defer.inlineCallbacks def test_worker_reconfigure_with_new_builder(self): """ Checks if we can successfully reconfigure if we add new builders to worker. """ config_dict = { 'builders': [ BuilderConfig(name="builder1", workernames=['local1'], factory=BuildFactory()), ], 'workers': [self.createLocalWorker('local1', max_builds=1)], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) config_dict['builders'] += [ BuilderConfig(name="builder2", workernames=['local1'], factory=BuildFactory()), ] config_dict['workers'] = [self.createLocalWorker('local1', max_builds=2)] # reconfig should succeed yield self.reconfig_master(config_dict) @defer.inlineCallbacks def test_step_with_worker_build_props_during_worker_disconnect(self): """ We need to handle worker disconnection and steps with worker build properties gracefully """ controller = WorkerController(self, 'local') stepcontroller = BuildStepController() config_dict = { 'builders': [ BuilderConfig( name="builder", workernames=['local'], properties={'worker': Interpolate("%(worker:numcpus)s")}, factory=BuildFactory([stepcontroller.step]), ), ], 'workers': [controller.worker], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('builder') yield self.create_build_request([builder_id]) yield controller.connect_worker() self.reactor.advance(1) yield controller.disconnect_worker() self.reactor.advance(1) yield self.assertBuildResults(1, RETRY) @defer.inlineCallbacks def test_worker_os_release_info_roundtrip(self): """ Checks if we can successfully get information about the platform the worker is running on. This is very similar to test_worker_comm.TestWorkerComm.test_worker_info, except that we check details such as whether the information is passed in correct encoding. """ worker = self.createLocalWorker('local1') config_dict = { 'builders': [ BuilderConfig(name="builder1", workernames=['local1'], factory=BuildFactory()), ], 'workers': [worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) props = worker.info from buildbot_worker.base import BotBase expected_props_dict = {} BotBase._read_os_release(BotBase.os_release_file, expected_props_dict) for key, value in expected_props_dict.items(): self.assertTrue(isinstance(key, str)) self.assertTrue(isinstance(value, str)) self.assertEqual(props.getProperty(key), value) if RemoteWorker is None: skip = "buildbot-worker package is not installed"
9,754
Python
.py
239
30.870293
100
0.611146
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,641
test_upcloud.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_upcloud.py
# 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 unittest.case import SkipTest from twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase from buildbot.worker.upcloud import UpcloudLatentWorker # This integration test creates a master and upcloud worker environment. You # need to have upcloud account for this to work. Running this will cost money. # If you want to run this, # export BBTEST_UPCLOUD_CREDS=username:password # following environment variable can be used to stress concurrent worker startup NUM_CONCURRENT = int(os.environ.get("BUILDBOT_TEST_NUM_CONCURRENT_BUILD", 1)) class UpcloudMaster(RunMasterBase): # wait 5 minutes. timeout = 300 def setUp(self): if "BBTEST_UPCLOUD_CREDS" not in os.environ: raise SkipTest( "upcloud integration tests only run when environment variable BBTEST_UPCLOUD_CREDS" " is set to valid upcloud credentials " ) @defer.inlineCallbacks def test_trigger(self): yield self.setup_master(masterConfig(num_concurrent=1), startWorker=False) yield self.doForceBuild() builds = yield self.master.data.get(("builds",)) # if there are some retry, there will be more builds self.assertEqual(len(builds), 1 + NUM_CONCURRENT) for b in builds: self.assertEqual(b['results'], SUCCESS) # master configuration def masterConfig(num_concurrent, extra_steps=None): if extra_steps is None: extra_steps = [] c = {} c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] triggereables = [] for i in range(num_concurrent): c['schedulers'].append( schedulers.Triggerable(name="trigsched" + str(i), builderNames=["build"]) ) triggereables.append("trigsched" + str(i)) f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) f.addStep( steps.Trigger(schedulerNames=triggereables, waitForFinish=True, updateSourceStamp=True) ) f.addStep(steps.ShellCommand(command='echo world')) f2 = BuildFactory() f2.addStep(steps.ShellCommand(command='echo ola')) for step in extra_steps: f2.addStep(step) c['builders'] = [ BuilderConfig(name="testy", workernames=["upcloud0"], factory=f), BuilderConfig( name="build", workernames=["upcloud" + str(i) for i in range(num_concurrent)], factory=f2, ), ] creds = os.environ.get('BBTEST_UPCLOUD_CREDS') if creds is not None: user, password = creds.split(":") else: raise RuntimeError("Cannot run this test without credentials") masterFQDN = os.environ.get('masterFQDN', 'localhost') c['workers'] = [] for i in range(num_concurrent): upcloud_host_config = { "user_data": f""" #!/usr/bin/env bash groupadd -g 999 buildbot useradd -u 999 -g buildbot -s /bin/bash -d /buildworker -m buildbot passwd -l buildbot apt update apt install -y git python3 python3-dev python3-pip sudo gnupg curl pip3 install buildbot-worker service_identity chown -R buildbot:buildbot /buildworker cat <<EOF >> /etc/hosts 127.0.1.1 upcloud{i} EOF cat <<EOF >/etc/sudoers.d/buildbot buidbot ALL=(ALL) NOPASSWD:ALL EOF sudo -H -u buildbot bash -c "buildbot-worker create-worker /buildworker {masterFQDN} upcloud{i} pass" sudo -H -u buildbot bash -c "buildbot-worker start /buildworker" """ } c['workers'].append( UpcloudLatentWorker( 'upcloud' + str(i), api_username=user, api_password=password, image='Debian GNU/Linux 9 (Stretch)', hostconfig=upcloud_host_config, masterFQDN=masterFQDN, ) ) # un comment for debugging what happens if things looks locked. # c['www'] = {'port': 8080} # if the masterFQDN is forced (proxy case), then we use 9989 default port # else, we try to find a free port if masterFQDN is not None: c['protocols'] = {"pb": {"port": "tcp:9989"}} else: c['protocols'] = {"pb": {"port": "tcp:0"}} return c
5,094
Python
.py
125
35.04
101
0.692447
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,642
test_workerside.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_workerside.py
# 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 shutil import tempfile import time from twisted.cred.error import UnauthorizedLogin from twisted.internet import defer from twisted.internet import reactor from twisted.python import util from twisted.trial import unittest import buildbot_worker.bot from buildbot import config from buildbot import worker from buildbot.process import botmaster from buildbot.process import builder from buildbot.process import factory from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.worker import manager as workermanager from buildbot.worker.protocols.manager.pb import PBManager PKI_DIR = util.sibpath(__file__, 'pki') # listening on port 0 says to the kernel to choose any free port (race-free) # the environment variable is handy for repetitive test launching with # introspecting tools (tcpdump, wireshark...) DEFAULT_PORT = os.environ.get("BUILDBOT_TEST_DEFAULT_PORT", "0") class FakeBuilder(builder.Builder): def attached(self, worker, commands): return defer.succeed(None) def detached(self, worker): pass def getOldestRequestTime(self): return 0 def maybeStartBuild(self): return defer.succeed(None) class TestingWorker(buildbot_worker.bot.Worker): """Add more introspection and scheduling hooks to the real Worker class. @ivar tests_connected: a ``Deferred`` that's called back once the PB connection is operational (``gotPerspective``). Callbacks receive the ``Perspective`` object. @ivar tests_disconnected: a ``Deferred`` that's called back upon disconnections. yielding these in an inlineCallbacks has the effect to wait on the corresponding conditions, actually allowing the services to fulfill them. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.tests_disconnected = defer.Deferred() self.tests_connected = defer.Deferred() self.tests_login_failed = defer.Deferred() self.master_perspective = None orig_got_persp = self.bf.gotPerspective orig_failed_get_persp = self.bf.failedToGetPerspective def gotPerspective(persp): orig_got_persp(persp) self.master_perspective = persp self.tests_connected.callback(persp) persp.broker.notifyOnDisconnect(lambda: self.tests_disconnected.callback(None)) def failedToGetPerspective(why, broker): orig_failed_get_persp(why, broker) self.tests_login_failed.callback((why, broker)) self.bf.gotPerspective = gotPerspective self.bf.failedToGetPerspective = failedToGetPerspective class TestWorkerConnection(unittest.TestCase, TestReactorMixin): """ Test handling of connections from real worker code This is meant primarily to test the worker itself. @ivar master: fake build master @ivar pbmanager: L{PBManager} instance @ivar botmaster: L{BotMaster} instance @ivar buildworker: L{worker.Worker} instance @ivar port: actual TCP port of the master PB service (fixed after call to ``addMasterSideWorker``) """ timeout = 30 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantData=True, wantDb=True) # set the worker port to a loopback address with unspecified # port self.pbmanager = self.master.pbmanager = PBManager() yield self.pbmanager.setServiceParent(self.master) # remove the fakeServiceParent from fake service hierarchy, and replace # by a real one yield self.master.workers.disownServiceParent() self.workers = self.master.workers = workermanager.WorkerManager(self.master) yield self.workers.setServiceParent(self.master) self.botmaster = botmaster.BotMaster() yield self.botmaster.setServiceParent(self.master) self.master.botmaster = self.botmaster self.master.data.updates.workerConfigured = lambda *a, **k: None yield self.master.startService() self.buildworker = None self.port = None self.workerworker = None # patch in our FakeBuilder for the regular Builder class self.patch(botmaster, 'Builder', FakeBuilder) self.client_connection_string_tpl = r"tcp:host=127.0.0.1:port={port}" self.tmpdirs = set() @defer.inlineCallbacks def tearDown(self): for tmp in self.tmpdirs: if os.path.exists(tmp): shutil.rmtree(tmp) yield self.pbmanager.stopService() yield self.botmaster.stopService() yield self.workers.stopService() # if the worker is still attached, wait for it to detach, too if self.buildworker: yield self.buildworker.waitForCompleteShutdown() yield self.tear_down_test_reactor() @defer.inlineCallbacks def addMasterSideWorker( self, connection_string=f"tcp:{DEFAULT_PORT}:interface=127.0.0.1", name="testworker", password="pw", update_port=True, **kwargs, ): """ Create a master-side worker instance and add it to the BotMaster @param **kwargs: arguments to pass to the L{Worker} constructor. """ self.buildworker = worker.Worker(name, password, **kwargs) # reconfig the master to get it set up new_config = self.master.config new_config.protocols = {"pb": {"port": connection_string}} new_config.workers = [self.buildworker] new_config.builders = [ config.BuilderConfig( name='bldr', workername='testworker', factory=factory.BuildFactory() ) ] yield self.botmaster.reconfigServiceWithBuildbotConfig(new_config) yield self.workers.reconfigServiceWithBuildbotConfig(new_config) if update_port: # as part of the reconfig, the worker registered with the # pbmanager, so get the port it was assigned self.port = self.buildworker.registration.getPBPort() def workerSideDisconnect(self, worker): """Disconnect from the worker side This seems a good way to simulate a broken connection. Returns a Deferred """ return worker.bf.disconnect() def addWorker( self, connection_string_tpl=r"tcp:host=127.0.0.1:port={port}", password="pw", name="testworker", keepalive=None, ): """Add a true Worker object to the services.""" wdir = tempfile.mkdtemp() self.tmpdirs.add(wdir) return TestingWorker( None, None, name, password, wdir, keepalive, protocol='pb', connection_string=connection_string_tpl.format(port=self.port), ) @defer.inlineCallbacks def test_connect_disconnect(self): yield self.addMasterSideWorker() def could_not_connect(): self.fail("Worker never got connected to master") timeout = reactor.callLater(self.timeout, could_not_connect) worker = self.addWorker() yield worker.startService() yield worker.tests_connected timeout.cancel() self.assertTrue('bldr' in worker.bot.builders) yield worker.stopService() yield worker.tests_disconnected @defer.inlineCallbacks def test_reconnect_network(self): yield self.addMasterSideWorker() def could_not_connect(): self.fail("Worker did not reconnect in time to master") worker = self.addWorker(r"tcp:host=127.0.0.1:port={port}") yield worker.startService() yield worker.tests_connected self.assertTrue('bldr' in worker.bot.builders) timeout = reactor.callLater(self.timeout, could_not_connect) yield self.workerSideDisconnect(worker) yield worker.tests_connected timeout.cancel() yield worker.stopService() yield worker.tests_disconnected @defer.inlineCallbacks def test_applicative_reconnection(self): """Test reconnection on PB errors. The worker starts with a password that the master does not accept at first, and then the master gets reconfigured to accept it. """ yield self.addMasterSideWorker() worker = self.addWorker(password="pw2") yield worker.startService() yield worker.tests_login_failed self.assertEqual(1, len(self.flushLoggedErrors(UnauthorizedLogin))) def could_not_connect(): self.fail("Worker did not reconnect in time to master") # we have two reasons to call that again: # - we really need to instantiate a new one master-side worker, # just changing its password has it simply ignored # - we need to fix the port yield self.addMasterSideWorker( password='pw2', update_port=False, # don't know why, but it'd fail connection_string=f"tcp:{self.port}:interface=127.0.0.1", ) timeout = reactor.callLater(self.timeout, could_not_connect) yield worker.tests_connected timeout.cancel() self.assertTrue('bldr' in worker.bot.builders) yield worker.stopService() yield worker.tests_disconnected @defer.inlineCallbacks def test_pb_keepalive(self): """Test applicative (PB) keepalives. This works by patching the master to callback a deferred on which the test waits. """ def perspective_keepalive(Connection_self): waiter = worker.keepalive_waiter if waiter is not None: waiter.callback(time.time()) worker.keepalive_waiter = None from buildbot.worker.protocols.pb import Connection self.patch(Connection, 'perspective_keepalive', perspective_keepalive) yield self.addMasterSideWorker() # short keepalive to make the test bearable to run worker = self.addWorker(keepalive=0.1) waiter = worker.keepalive_waiter = defer.Deferred() yield worker.startService() yield worker.tests_connected first = yield waiter yield worker.bf.currentKeepaliveWaiter waiter = worker.keepalive_waiter = defer.Deferred() second = yield waiter yield worker.bf.currentKeepaliveWaiter self.assertGreater(second, first) self.assertLess(second, first + 1) # seems safe enough yield worker.stopService() yield worker.tests_disconnected
11,532
Python
.py
262
35.778626
97
0.681664
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,643
test_proxy.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_proxy.py
# 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 asyncio import multiprocessing import os import signal import socket import sys from twisted.internet import defer from buildbot.test.util.integration import RunMasterBase from ..interop import test_commandmixin from ..interop import test_compositestepmixin from ..interop import test_integration_secrets from ..interop import test_interruptcommand from ..interop import test_setpropertyfromcommand from ..interop import test_transfer from ..interop import test_worker_reconnect # This integration test puts HTTP proxy in between the master and worker. def get_log_path(): return f'test_worker_proxy_stdout_{os.getpid()}.txt' def write_to_log(msg, with_traceback=False): with open(get_log_path(), 'a', encoding='utf-8') as outfile: outfile.write(msg) if with_traceback: import traceback traceback.print_exc(file=outfile) async def handle_client(local_reader, local_writer): async def pipe(reader, writer): try: while not reader.at_eof(): writer.write(await reader.read(2048)) except ConnectionResetError: pass finally: writer.close() try: request = await local_reader.read(2048) lines = request.split(b"\r\n") if not lines[0].startswith(b"CONNECT "): write_to_log(f"bad request {request.decode()}\n") local_writer.write(b"HTTP/1.1 407 Only CONNECT allowed\r\n\r\n") return host, port = lines[0].split(b" ")[1].split(b":") try: remote_reader, remote_writer = await asyncio.open_connection(host.decode(), int(port)) except socket.gaierror: write_to_log(f"failed to relay to {host} {port}\n") local_writer.write(b"HTTP/1.1 404 Not Found\r\n\r\n") return write_to_log(f"relaying to {host} {port}\n") local_writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n") pipe1 = pipe(local_reader, remote_writer) pipe2 = pipe(remote_reader, local_writer) await asyncio.gather(pipe1, pipe2) finally: local_writer.close() def run_proxy(queue): write_to_log("run_proxy\n") try: try: loop = asyncio.get_running_loop() except RuntimeError: # https://github.com/python/cpython/issues/83710 if sys.version_info <= (3, 10, 8): # Workaround for bugs.python.org/issue39529. try: loop = asyncio.get_event_loop_policy().get_event_loop() except RuntimeError: # We can get RuntimeError due to current thread being not main thread # on Python 3.8. It's not clear why that happens, so work around it. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) else: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) coro = asyncio.start_server(handle_client, host="127.0.0.1") server = loop.run_until_complete(coro) host, port = server.sockets[0].getsockname() queue.put(port) def signal_handler(sig, trace): raise KeyboardInterrupt signal.signal(signal.SIGTERM, signal_handler) write_to_log(f"Serving on {host}:{port}\n") try: write_to_log("Running forever\n") loop.run_forever() except KeyboardInterrupt: write_to_log("End\n") server.close() loop.run_until_complete(server.wait_closed()) loop.close() except BaseException as e: write_to_log(f"Exception Raised: {e!s}\n", with_traceback=True) finally: queue.put(get_log_path()) class RunMasterBehindProxy(RunMasterBase): # we need slightly longer timeout for proxy related tests timeout = 30 enable_debug = False def setUp(self): write_to_log("setUp\n") self.queue = multiprocessing.Queue() self.proxy_process = multiprocessing.Process(target=run_proxy, args=(self.queue,)) self.proxy_process.start() self.target_port = self.queue.get() write_to_log(f"got target_port {self.target_port}\n") def tearDown(self): write_to_log("tearDown\n") self.proxy_process.terminate() self.proxy_process.join() if self.enable_debug: print("---- stdout ----") with open(get_log_path(), encoding='utf-8') as file: print(file.read()) print("---- ------ ----") with open(self.queue.get(), encoding='utf-8') as file: print(file.read()) print("---- ------ ----") os.unlink(get_log_path()) @defer.inlineCallbacks def setup_master(self, config_dict, startWorker=True): proxy_connection_string = f"tcp:127.0.0.1:{self.target_port}" yield super().setup_master( config_dict, startWorker, proxy_connection_string=proxy_connection_string ) # Use interoperability test cases to test the HTTP proxy tunneling. class ProxyCommandMixinMasterPB(RunMasterBehindProxy, test_commandmixin.CommandMixinMasterPB): pass class ProxyCompositeStepMixinMasterPb( RunMasterBehindProxy, test_compositestepmixin.CompositeStepMixinMasterPb ): pass class ProxyInterruptCommandPb(RunMasterBehindProxy, test_interruptcommand.InterruptCommandPb): pass class ProxySecretsConfigPB(RunMasterBehindProxy, test_integration_secrets.SecretsConfigPB): pass class ProxySetPropertyFromCommandPB( RunMasterBehindProxy, test_setpropertyfromcommand.SetPropertyFromCommandPB ): pass class ProxyTransferStepsMasterPb(RunMasterBehindProxy, test_transfer.TransferStepsMasterPb): pass class ProxyWorkerReconnect(RunMasterBehindProxy, test_worker_reconnect.WorkerReconnectPb): pass
6,630
Python
.py
156
34.653846
98
0.669157
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,644
test_latent.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_latent.py
# 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 parameterized import parameterized from twisted.internet import defer from twisted.python.failure import Failure from twisted.spread import pb from buildbot.config import BuilderConfig from buildbot.config.master import MasterConfig from buildbot.interfaces import LatentWorkerCannotSubstantiate from buildbot.interfaces import LatentWorkerFailedToSubstantiate from buildbot.interfaces import LatentWorkerSubstantiatiationCancelled from buildbot.machine.latent import States as MachineStates from buildbot.process.factory import BuildFactory from buildbot.process.properties import Interpolate from buildbot.process.properties import Properties from buildbot.process.results import CANCELLED from buildbot.process.results import EXCEPTION from buildbot.process.results import FAILURE from buildbot.process.results import RETRY from buildbot.process.results import SUCCESS from buildbot.test.fake.latent import ControllableLatentWorker from buildbot.test.fake.latent import LatentController from buildbot.test.fake.machine import LatentMachineController from buildbot.test.fake.step import BuildStepController from buildbot.test.util.integration import RunFakeMasterTestCase from buildbot.test.util.misc import TimeoutableTestCase from buildbot.test.util.patch_delay import patchForDelay from buildbot.worker import manager from buildbot.worker.latent import States class TestException(Exception): """ An exception thrown in tests. """ class Latent(TimeoutableTestCase, RunFakeMasterTestCase): def tearDown(self): # Flush the errors logged by the master stop cancelling the builds. self.flushLoggedErrors(LatentWorkerSubstantiatiationCancelled) super().tearDown() @defer.inlineCallbacks def create_single_worker_config(self, controller_kwargs=None): if not controller_kwargs: controller_kwargs = {} controller = LatentController(self, 'local', **controller_kwargs) config_dict = { 'builders': [ BuilderConfig( name="testy", workernames=["local"], factory=BuildFactory(), ), ], 'workers': [controller.worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('testy') return controller, builder_id @defer.inlineCallbacks def create_single_worker_config_with_step(self, controller_kwargs=None): if not controller_kwargs: controller_kwargs = {} controller = LatentController(self, 'local', **controller_kwargs) stepcontroller = BuildStepController() config_dict = { 'builders': [ BuilderConfig( name="testy", workernames=["local"], factory=BuildFactory([stepcontroller.step]), ), ], 'workers': [controller.worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('testy') return controller, stepcontroller, builder_id @defer.inlineCallbacks def create_single_worker_two_builder_config(self, controller_kwargs=None): if not controller_kwargs: controller_kwargs = {} controller = LatentController(self, 'local', **controller_kwargs) config_dict = { 'builders': [ BuilderConfig( name="testy-1", workernames=["local"], factory=BuildFactory(), ), BuilderConfig( name="testy-2", workernames=["local"], factory=BuildFactory(), ), ], 'workers': [controller.worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_ids = [ (yield self.master.data.updates.findBuilderId('testy-1')), (yield self.master.data.updates.findBuilderId('testy-2')), ] return controller, builder_ids @defer.inlineCallbacks def reconfig_workers_remove_all(self): config_dict = {'workers': [], 'multiMaster': True} config = MasterConfig.loadFromDict(config_dict, '<dict>') yield self.master.workers.reconfigServiceWithBuildbotConfig(config) def stop_first_build(self, results): stopped_d = defer.Deferred() def new_callback(_, data): if stopped_d.called: return # Stop the build buildid = data['buildid'] self.master.mq.produce( ('control', 'builds', str(buildid), 'stop'), {'reason': 'no reason', 'results': results}, ) stopped_d.callback(None) consumed_d = self.master.mq.startConsuming(new_callback, ('builds', None, 'new')) return consumed_d, stopped_d @defer.inlineCallbacks def test_latent_workers_start_in_parallel(self): """ If there are two latent workers configured, and two build requests for them, both workers will start substantiating concurrently. """ controllers = [ LatentController(self, 'local1'), LatentController(self, 'local2'), ] config_dict = { 'builders': [ BuilderConfig( name="testy", workernames=["local1", "local2"], factory=BuildFactory() ), ], 'workers': [controller.worker for controller in controllers], 'protocols': {'null': {}}, 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('testy') # Request two builds. for _ in range(2): yield self.create_build_request([builder_id]) # Check that both workers were requested to start. self.assertEqual(controllers[0].starting, True) self.assertEqual(controllers[1].starting, True) for controller in controllers: yield controller.start_instance(True) yield controller.auto_stop(True) @defer.inlineCallbacks def test_refused_substantiations_get_requeued(self): """ If a latent worker refuses to substantiate, the build request becomes unclaimed. """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) # Indicate that the worker can't start an instance. yield controller.start_instance(False) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) yield self.assertBuildResults(1, RETRY) yield controller.auto_stop(True) self.flushLoggedErrors(LatentWorkerFailedToSubstantiate) @defer.inlineCallbacks def test_failed_substantiations_get_requeued(self): """ If a latent worker fails to substantiate, the build request becomes unclaimed. """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) # The worker fails to substantiate. yield controller.start_instance(Failure(TestException("substantiation failed"))) # Flush the errors logged by the failure. self.flushLoggedErrors(TestException) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) yield self.assertBuildResults(1, RETRY) yield controller.auto_stop(True) @defer.inlineCallbacks def test_failed_substantiations_get_exception(self): """ If a latent worker fails to substantiate, the result is an exception. """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest yield self.create_build_request([builder_id]) # The worker fails to substantiate. yield controller.start_instance( Failure(LatentWorkerCannotSubstantiate("substantiation failed")) ) # Flush the errors logged by the failure. self.flushLoggedErrors(LatentWorkerCannotSubstantiate) # When the substantiation fails, the result is an exception. yield self.assertBuildResults(1, EXCEPTION) yield controller.auto_stop(True) @defer.inlineCallbacks def test_worker_accepts_builds_after_failure(self): """ If a latent worker fails to substantiate, the worker is still able to accept jobs. """ controller, builder_id = yield self.create_single_worker_config() yield controller.auto_stop(True) # Trigger a buildrequest yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) # The worker fails to substantiate. yield controller.start_instance(Failure(TestException("substantiation failed"))) # Flush the errors logged by the failure. self.flushLoggedErrors(TestException) # The retry logic should only trigger after a exponential backoff self.assertEqual(controller.starting, False) # advance the time to the point where we should retry self.reactor.advance(controller.worker.quarantine_initial_timeout) # If the worker started again after the failure, then the retry logic will have # already kicked in to start a new build on this (the only) worker. We check that # a new instance was requested, which indicates that the worker # accepted the build. self.assertEqual(controller.starting, True) # The worker fails to substantiate(again). yield controller.start_instance(Failure(TestException("substantiation failed"))) # Flush the errors logged by the failure. self.flushLoggedErrors(TestException) yield self.assertBuildResults(1, RETRY) # advance the time to the point where we should not retry self.reactor.advance(controller.worker.quarantine_initial_timeout) self.assertEqual(controller.starting, False) # advance the time to the point where we should retry self.reactor.advance(controller.worker.quarantine_initial_timeout) self.assertEqual(controller.starting, True) controller.auto_start(True) controller.auto_stop(True) @defer.inlineCallbacks def test_worker_multiple_substantiations_succeed(self): """ If multiple builders trigger try to substantiate a worker at the same time, if the substantiation succeeds then all of the builds proceed. """ controller, builder_ids = yield self.create_single_worker_two_builder_config() # Trigger a buildrequest yield self.create_build_request(builder_ids) # The worker succeeds to substantiate. yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) yield self.assertBuildResults(2, SUCCESS) yield controller.auto_stop(True) @defer.inlineCallbacks def test_very_late_detached_after_substantiation(self): """ A latent worker may detach at any time after stop_instance() call. Make sure it works at the most late detachment point, i.e. when we're substantiating again. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) yield self.create_build_request([builder_id]) self.assertTrue(controller.starting) controller.auto_disconnect_worker = False yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.reactor.advance(1) # stop the instance, but don't disconnect the worker up to until just # before we complete start_instance() self.assertTrue(controller.stopping) yield controller.stop_instance(True) self.assertTrue(controller.stopped) yield self.create_build_request([builder_id]) self.assertTrue(controller.starting) yield controller.disconnect_worker() yield controller.start_instance(True) yield self.assertBuildResults(2, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) yield controller.disconnect_worker() @defer.inlineCallbacks def test_substantiation_during_stop_instance(self): """ If a latent worker detaches before stop_instance() completes and we start a build then it should start successfully without causing an erroneous cancellation of the substantiation request. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) # Trigger a single buildrequest yield self.create_build_request([builder_id]) self.assertEqual(True, controller.starting) # start instance controller.auto_disconnect_worker = False yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.reactor.advance(1) self.assertTrue(controller.stopping) yield controller.disconnect_worker() # now create a buildrequest that will substantiate the build. It should # either not start at all until the instance finished substantiating, # or the substantiation request needs to be recorded and start # immediately after stop_instance completes. yield self.create_build_request([builder_id]) yield controller.stop_instance(True) yield controller.start_instance(True) yield self.assertBuildResults(2, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) yield controller.disconnect_worker() @defer.inlineCallbacks def test_substantiation_during_stop_instance_canStartBuild_race(self): """ If build attempts substantiation after the latent worker detaches, but stop_instance() is not completed yet, then we should successfully complete substantiation without causing an erroneous cancellation. The above sequence of events was possible even if canStartBuild checked for a in-progress insubstantiation, as if the build is scheduled before insubstantiation, its start could be delayed until when stop_instance() is in progress. """ controller, builder_ids = yield self.create_single_worker_two_builder_config( controller_kwargs={"build_wait_timeout": 1} ) # Trigger a single buildrequest yield self.create_build_request([builder_ids[0]]) self.assertEqual(True, controller.starting) # start instance yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) with patchForDelay('buildbot.process.builder.Builder.maybeStartBuild') as delay: # create a build request which will result in a build, but it won't # attempt to substantiate until after stop_instance() is in progress yield self.create_build_request([builder_ids[1]]) self.assertEqual(len(delay), 1) self.reactor.advance(1) self.assertTrue(controller.stopping) delay.fire() yield controller.stop_instance(True) self.assertTrue(controller.starting) yield controller.start_instance(True) yield self.assertBuildResults(2, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) @defer.inlineCallbacks def test_insubstantiation_during_substantiation_refuses_substantiation(self): """ If a latent worker gets insubstantiation() during substantiation, then it should refuse to substantiate. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) # insubstantiate during start_instance(). Note that failed substantiation is notified only # after the latent workers completes start-stop cycle. yield self.create_build_request([builder_id]) d = controller.worker.insubstantiate() yield controller.start_instance(False) yield controller.stop_instance(True) yield d yield self.assertBuildResults(1, RETRY) @defer.inlineCallbacks def test_stopservice_during_insubstantiation_completes(self): """ When stopService is called and a worker is insubstantiating, we should wait for this process to complete. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.assertTrue(controller.started) # Wait until worker starts insubstantiation and then shutdown worker self.reactor.advance(1) self.assertTrue(controller.stopping) d = self.reconfig_workers_remove_all() self.assertFalse(d.called) yield controller.stop_instance(True) yield d @parameterized.expand([ ('with_substantiation_failure', False, False), ('without_worker_connecting', True, False), ('with_worker_connecting', True, True), ]) @defer.inlineCallbacks def test_stopservice_during_substantiation_completes( self, name, subst_success, worker_connects ): """ When stopService is called and a worker is substantiating, we should wait for this process to complete. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) controller.auto_connect_worker = worker_connects # Substantiate worker via a build yield self.create_build_request([builder_id]) self.assertTrue(controller.starting) d = self.reconfig_workers_remove_all() self.assertFalse(d.called) yield controller.start_instance(subst_success) # we should stop the instance immediately after it substantiates regardless of the result self.assertTrue(controller.stopping) yield controller.stop_instance(True) yield d @defer.inlineCallbacks def test_substantiation_is_cancelled_by_build_stop(self): """ Stopping a build during substantiation should cancel the substantiation itself. Otherwise we will be left with a substantiating worker without a corresponding build which means that master shutdown may not work correctly. """ controller, builder_id = yield self.create_single_worker_config() controller.auto_connect_worker = False controller.auto_stop(True) # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) self.master.mq.produce(('control', 'builds', '1', 'stop'), {'reason': 'no reason'}) self.reactor.advance(1) # force build to actually execute the stop instruction self.assertTrue(controller.stopped) @parameterized.expand([ ('after_start_instance_no_worker', False, False), ('after_start_instance_with_worker', True, False), ('before_start_instance_no_worker', False, True), ('before_start_instance_with_worker', True, True), ]) @defer.inlineCallbacks def test_reconfigservice_during_substantiation_clean_shutdown_after( self, name, worker_connects, before_start_service ): """ When stopService is called and a worker is substantiating, we should wait for this process to complete. """ registered_workers = [] def registration_updates(reg, worker_config, global_config): registered_workers.append((worker_config.workername, worker_config.password)) self.patch(manager.WorkerRegistration, 'update', registration_updates) controller, builder_id = yield self.create_single_worker_config() controller.auto_connect_worker = worker_connects controller.auto_stop(True) # Substantiate worker via a build yield self.create_build_request([builder_id]) self.assertTrue(controller.starting) # change some unimportant property of the worker to force configuration self.master.config_loader.config_dict['workers'] = [ ControllableLatentWorker('local', controller, max_builds=3) ] if before_start_service: yield self.reconfig_master() yield controller.start_instance(True) else: yield controller.start_instance(True) yield self.reconfig_master() yield self.clean_master_shutdown(quick=True) self.assertEqual(registered_workers, [('local', 'password_1'), ('local', 'password_1')]) @defer.inlineCallbacks def test_substantiation_cancelled_by_insubstantiation_when_waiting_for_insubstantiation(self): """ We should cancel substantiation if we insubstantiate when that substantiation is waiting on current insubstantiation to finish """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) yield self.create_build_request([builder_id]) # put the worker into insubstantiation phase yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.reactor.advance(1) self.assertTrue(controller.stopping) # build should wait on the insubstantiation yield self.create_build_request([builder_id]) self.assertEqual(controller.worker.state, States.INSUBSTANTIATING_SUBSTANTIATING) # build should be requeued if we insubstantiate. d = controller.worker.insubstantiate() yield controller.stop_instance(True) yield d yield self.assertBuildResults(2, RETRY) @defer.inlineCallbacks def test_stalled_substantiation_then_timeout_get_requeued(self): """ If a latent worker substantiate, but not connect, and then be unsubstantiated, the build request becomes unclaimed. """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) # We never start the worker, rather timeout it. self.reactor.advance(controller.worker.missing_timeout) # Flush the errors logged by the failure. self.flushLoggedErrors(defer.TimeoutError) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) yield controller.start_instance(False) yield controller.auto_stop(True) @defer.inlineCallbacks def test_stalled_substantiation_then_check_instance_fails_get_requeued(self): """ If a latent worker substantiate, but not connect and check_instance() indicates a crash, the build request should become unclaimed as soon as check_instance_interval passes """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={'check_instance_interval': 10} ) controller.auto_connect_worker = False # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) # The worker startup succeeds, but it doe not connect and check_instance() later # indicates a crash. yield controller.start_instance(True) self.reactor.advance(10) controller.has_crashed = True self.reactor.advance(10) # Flush the errors logged by the failure. self.flushLoggedErrors(LatentWorkerFailedToSubstantiate) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) yield controller.auto_stop(True) @defer.inlineCallbacks def test_sever_connection_before_ping_then_timeout_get_requeued(self): """ If a latent worker connects, but its connection is severed without notification in the TCP layer, we successfully wait until TCP times out and requeue the build. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) yield self.create_build_request([builder_id]) # sever connection just before ping() with patchForDelay( 'buildbot.process.workerforbuilder.AbstractWorkerForBuilder.ping' ) as delay: yield controller.start_instance(True) controller.sever_connection() delay.fire() # lose connection after TCP times out self.reactor.advance(100) yield controller.disconnect_worker() yield self.assertBuildResults(1, RETRY) # the worker will be put into quarantine self.reactor.advance(controller.worker.quarantine_initial_timeout) yield controller.stop_instance(True) yield controller.start_instance(True) yield self.assertBuildResults(2, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) self.flushLoggedErrors(pb.PBConnectionLost) @defer.inlineCallbacks def test_failed_sendBuilderList_get_requeued(self): """ sendBuilderList can fail due to missing permissions on the workdir, the build request becomes unclaimed """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) logs = [] yield self.master.mq.startConsuming( lambda key, log: logs.append(log), ('logs', None, 'new') ) # The worker succeed to substantiate def remote_setBuilderList(self, dirs): raise TestException("can't create dir") controller.patchBot(self, 'remote_setBuilderList', remote_setBuilderList) yield controller.start_instance(True) # Flush the errors logged by the failure. self.flushLoggedErrors(TestException) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) # should get 2 logs (html and txt) with proper information in there self.assertEqual(len(logs), 2) logs_by_name = {} for _log in logs: fulllog = yield self.master.data.get(("logs", str(_log['logid']), "raw")) logs_by_name[fulllog['filename']] = fulllog['raw'] for i in [ 'testy_build_1_step_worker_preparation_log_err_text', "testy_build_1_step_worker_preparation_log_err_html", ]: self.assertIn("can't create dir", logs_by_name[i]) # make sure stacktrace is present in html self.assertIn( "buildbot.test.integration.test_worker_latent.TestException", logs_by_name[i] ) yield controller.auto_stop(True) @defer.inlineCallbacks def test_failed_ping_get_requeued(self): """ sendBuilderList can fail due to missing permissions on the workdir, the build request becomes unclaimed """ controller, builder_id = yield self.create_single_worker_config() # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) logs = [] yield self.master.mq.startConsuming( lambda key, log: logs.append(log), ('logs', None, 'new') ) # The worker succeed to substantiate def remote_print(self, msg): if msg == "ping": raise TestException("can't ping") controller.patchBot(self, 'remote_print', remote_print) yield controller.start_instance(True) # Flush the errors logged by the failure. self.flushLoggedErrors(TestException) # When the substantiation fails, the buildrequest becomes unclaimed. self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) # should get 2 logs (html and txt) with proper information in there self.assertEqual(len(logs), 2) logs_by_name = {} for _log in logs: fulllog = yield self.master.data.get(("logs", str(_log['logid']), "raw")) logs_by_name[fulllog['filename']] = fulllog['raw'] for i in [ 'testy_build_1_step_worker_preparation_log_err_text', "testy_build_1_step_worker_preparation_log_err_html", ]: self.assertIn("can't ping", logs_by_name[i]) # make sure stacktrace is present in html self.assertIn( "buildbot.test.integration.test_worker_latent.TestException", logs_by_name[i] ) yield controller.auto_stop(True) @defer.inlineCallbacks def test_worker_close_connection_while_building(self): """ If the worker close connection in the middle of the build, the next build can start correctly """ controller, stepcontroller, builder_id = yield self.create_single_worker_config_with_step( controller_kwargs={"build_wait_timeout": 0} ) # Request a build and disconnect midway controller.auto_disconnect_worker = False yield self.create_build_request([builder_id]) yield controller.auto_stop(True) self.assertTrue(controller.starting) yield controller.start_instance(True) yield self.assertBuildResults(1, None) yield controller.disconnect_worker() yield self.assertBuildResults(1, RETRY) # Now check that the build requeued and finished with success yield controller.start_instance(True) yield self.assertBuildResults(2, None) stepcontroller.finish_step(SUCCESS) yield self.assertBuildResults(2, SUCCESS) yield controller.disconnect_worker() @defer.inlineCallbacks def test_negative_build_timeout_reattach_substantiated(self): """ When build_wait_timeout is negative, we don't disconnect the worker from our side. We should still support accidental disconnections from worker side due to, e.g. network problems. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": -1} ) controller.auto_disconnect_worker = False controller.auto_connect_worker = False # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield controller.connect_worker() yield self.assertBuildResults(1, SUCCESS) self.assertTrue(controller.started) # Now disconnect and reconnect worker and check whether we can still # build. This should not change the worker state from our side. yield controller.disconnect_worker() self.assertTrue(controller.started) yield controller.connect_worker() self.assertTrue(controller.started) yield self.create_build_request([builder_id]) yield self.assertBuildResults(1, SUCCESS) # The only way to stop worker with negative build timeout is to # insubstantiate explicitly yield controller.auto_stop(True) yield controller.worker.insubstantiate() yield controller.disconnect_worker() @defer.inlineCallbacks def test_sever_connection_while_building(self): """ If the connection to worker is severed without TCP notification in the middle of the build, the build is re-queued and successfully restarted. """ controller, stepcontroller, builder_id = yield self.create_single_worker_config_with_step( controller_kwargs={"build_wait_timeout": 0} ) # Request a build and disconnect midway yield self.create_build_request([builder_id]) yield controller.auto_stop(True) self.assertTrue(controller.starting) yield controller.start_instance(True) yield self.assertBuildResults(1, None) # sever connection and lose it after TCP times out controller.sever_connection() self.reactor.advance(100) yield controller.disconnect_worker() yield self.assertBuildResults(1, RETRY) # Request one build. yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(2, None) stepcontroller.finish_step(SUCCESS) yield self.assertBuildResults(2, SUCCESS) @defer.inlineCallbacks def test_sever_connection_during_insubstantiation(self): """ If latent worker connection is severed without notification in the TCP layer, we successfully wait until TCP times out, insubstantiate and can substantiate after that. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) # sever connection just before insubstantiation and lose it after TCP # times out with patchForDelay('buildbot.worker.base.AbstractWorker.disconnect') as delay: self.reactor.advance(1) self.assertTrue(controller.stopping) controller.sever_connection() delay.fire() yield controller.stop_instance(True) self.reactor.advance(100) yield controller.disconnect_worker() # create new build request and verify it works yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) self.flushLoggedErrors(pb.PBConnectionLost) @defer.inlineCallbacks def test_sever_connection_during_insubstantiation_and_buildrequest(self): """ If latent worker connection is severed without notification in the TCP layer, we successfully wait until TCP times out, insubstantiate and can substantiate after that. In this the subsequent build request is created during insubstantiation """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) # sever connection just before insubstantiation and lose it after TCP # times out with patchForDelay('buildbot.worker.base.AbstractWorker.disconnect') as delay: self.reactor.advance(1) self.assertTrue(controller.stopping) yield self.create_build_request([builder_id]) controller.sever_connection() delay.fire() yield controller.stop_instance(True) self.reactor.advance(100) yield controller.disconnect_worker() # verify the previously created build successfully completes yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) self.flushLoggedErrors(pb.PBConnectionLost) @defer.inlineCallbacks def test_negative_build_timeout_reattach_insubstantiating(self): """ When build_wait_timeout is negative, we don't disconnect the worker from our side, but it can disconnect and reattach from worker side due to, e.g. network problems. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": -1} ) controller.auto_disconnect_worker = False controller.auto_connect_worker = False # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield controller.connect_worker() yield self.assertBuildResults(1, SUCCESS) self.assertTrue(controller.started) # Now start insubstantiation and disconnect and reconnect the worker. # It should not change worker state from master side. d = controller.worker.insubstantiate() self.assertTrue(controller.stopping) yield controller.disconnect_worker() self.assertTrue(controller.stopping) yield controller.connect_worker() self.assertTrue(controller.stopping) yield controller.stop_instance(True) yield d self.assertTrue(controller.stopped) yield controller.disconnect_worker() # Now substantiate the worker and verify build succeeds yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield controller.connect_worker() yield self.assertBuildResults(1, SUCCESS) controller.auto_disconnect_worker = True yield controller.auto_stop(True) @defer.inlineCallbacks def test_negative_build_timeout_no_disconnect_insubstantiating(self): """ When build_wait_timeout is negative, we don't disconnect the worker from our side, so it should be possible to insubstantiate and substantiate it without problems if the worker does not disconnect either. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": -1} ) controller.auto_disconnect_worker = False controller.auto_connect_worker = False # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield controller.connect_worker() yield self.assertBuildResults(1, SUCCESS) self.assertTrue(controller.started) # Insubstantiate worker without disconnecting it d = controller.worker.insubstantiate() self.assertTrue(controller.stopping) yield controller.stop_instance(True) yield d self.assertTrue(controller.stopped) # Now substantiate the worker without connecting it yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) controller.auto_disconnect_worker = True yield controller.auto_stop(True) @defer.inlineCallbacks def test_negative_build_timeout_insubstantiates_on_master_shutdown(self): """ When build_wait_timeout is negative, we should still insubstantiate when master shuts down. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": -1} ) # Substantiate worker via a build yield self.create_build_request([builder_id]) yield controller.start_instance(True) yield self.assertBuildResults(1, SUCCESS) self.assertTrue(controller.started) # Shutdown master d = self.master.stopService() yield controller.stop_instance(True) yield d @defer.inlineCallbacks def test_stop_instance_synchronous_exception(self): """ Throwing a synchronous exception from stop_instance should allow subsequent build to start. """ controller, builder_id = yield self.create_single_worker_config( controller_kwargs={"build_wait_timeout": 1} ) controller.auto_stop(True) # patch stop_instance() to raise exception synchronously def raise_stop_instance(fast): raise TestException() real_stop_instance = controller.worker.stop_instance controller.worker.stop_instance = raise_stop_instance # create a build and wait for stop yield self.create_build_request([builder_id]) yield controller.start_instance(True) self.reactor.advance(1) yield self.assertBuildResults(1, SUCCESS) self.flushLoggedErrors(TestException) # unpatch stop_instance() and call it to cleanup state of fake worker controller controller.worker.stop_instance = real_stop_instance yield controller.worker.stop_instance(False) self.reactor.advance(1) # subsequent build should succeed yield self.create_build_request([builder_id]) yield controller.start_instance(True) self.reactor.advance(1) yield self.assertBuildResults(2, SUCCESS) @defer.inlineCallbacks def test_build_stop_with_cancelled_during_substantiation(self): """ If a build is stopping during latent worker substantiating, the build becomes cancelled """ controller, builder_id = yield self.create_single_worker_config() consumed_d, stopped_d = self.stop_first_build(CANCELLED) yield consumed_d # Trigger a buildrequest yield self.create_build_request([builder_id]) yield stopped_d # Indicate that the worker can't start an instance. yield controller.start_instance(False) yield self.assertBuildResults(1, CANCELLED) yield controller.auto_stop(True) self.flushLoggedErrors(LatentWorkerFailedToSubstantiate) @defer.inlineCallbacks def test_build_stop_with_retry_during_substantiation(self): """ If master is shutting down during latent worker substantiating, the build becomes retry. """ controller, builder_id = yield self.create_single_worker_config() consumed_d, stopped_d = self.stop_first_build(RETRY) yield consumed_d # Trigger a buildrequest _, brids = yield self.create_build_request([builder_id]) unclaimed_build_requests = [] yield self.master.mq.startConsuming( lambda key, request: unclaimed_build_requests.append(request), ('buildrequests', None, 'unclaimed'), ) yield stopped_d # Indicate that the worker can't start an instance. yield controller.start_instance(False) yield self.assertBuildResults(1, RETRY) self.assertEqual(set(brids), {req['buildrequestid'] for req in unclaimed_build_requests}) yield controller.auto_stop(True) self.flushLoggedErrors(LatentWorkerFailedToSubstantiate) @defer.inlineCallbacks def test_rejects_build_on_instance_with_different_type_timeout_zero(self): """ If latent worker supports getting its instance type from properties that are rendered from build then the buildrequestdistributor must not schedule any builds on workers that are running different instance type than what these builds will require. """ controller, stepcontroller, builder_id = yield self.create_single_worker_config_with_step( controller_kwargs={"kind": Interpolate('%(prop:worker_kind)s'), "build_wait_timeout": 0} ) # create build request yield self.create_build_request([builder_id], properties=Properties(worker_kind='a')) # start the build and verify the kind of the worker. Note that the # buildmaster needs to restart the worker in order to change the worker # kind, so we allow it both to auto start and stop self.assertEqual(True, controller.starting) controller.auto_start(True) yield controller.auto_stop(True) self.assertEqual((yield controller.get_started_kind()), 'a') # before the other build finished, create another build request yield self.create_build_request([builder_id], properties=Properties(worker_kind='b')) stepcontroller.finish_step(SUCCESS) # give the botmaster chance to insubstantiate the worker and # maybe substantiate it for the pending build the builds on worker self.reactor.advance(0.1) # verify that the second build restarted with the expected instance # kind self.assertEqual((yield controller.get_started_kind()), 'b') stepcontroller.finish_step(SUCCESS) yield self.assertBuildResults(1, SUCCESS) yield self.assertBuildResults(2, SUCCESS) @defer.inlineCallbacks def test_rejects_build_on_instance_with_different_type_timeout_nonzero(self): """ If latent worker supports getting its instance type from properties that are rendered from build then the buildrequestdistributor must not schedule any builds on workers that are running different instance type than what these builds will require. """ controller, stepcontroller, builder_id = yield self.create_single_worker_config_with_step( controller_kwargs={"kind": Interpolate('%(prop:worker_kind)s'), "build_wait_timeout": 5} ) # create build request yield self.create_build_request([builder_id], properties=Properties(worker_kind='a')) # start the build and verify the kind of the worker. Note that the # buildmaster needs to restart the worker in order to change the worker # kind, so we allow it both to auto start and stop self.assertEqual(True, controller.starting) controller.auto_start(True) yield controller.auto_stop(True) self.assertEqual((yield controller.get_started_kind()), 'a') # before the other build finished, create another build request yield self.create_build_request([builder_id], properties=Properties(worker_kind='b')) stepcontroller.finish_step(SUCCESS) # give the botmaster chance to insubstantiate the worker and # maybe substantiate it for the pending build the builds on worker self.reactor.advance(0.1) # verify build has not started, even though the worker is waiting # for one self.assertIsNone((yield self.master.db.builds.getBuild(2))) self.assertTrue(controller.started) # wait until the latent worker times out, is insubstantiated, # is substantiated because of pending buildrequest and starts the build self.reactor.advance(6) self.assertIsNotNone((yield self.master.db.builds.getBuild(2))) # verify that the second build restarted with the expected instance # kind self.assertEqual((yield controller.get_started_kind()), 'b') stepcontroller.finish_step(SUCCESS) yield self.assertBuildResults(1, SUCCESS) yield self.assertBuildResults(2, SUCCESS) @defer.inlineCallbacks def test_supports_no_build_for_substantiation(self): """ Abstract latent worker should support being substantiated without a build and then insubstantiated. """ controller, _ = yield self.create_single_worker_config() d = controller.worker.substantiate(None, None) yield controller.start_instance(True) self.assertTrue(controller.started) yield d d = controller.worker.insubstantiate() yield controller.stop_instance(True) yield d @defer.inlineCallbacks def test_supports_no_build_for_substantiation_accepts_build_later(self): """ Abstract latent worker should support being substantiated without a build and then accept a build request. """ controller, stepcontroller, builder_id = yield self.create_single_worker_config_with_step( controller_kwargs={"build_wait_timeout": 1} ) d = controller.worker.substantiate(None, None) yield controller.start_instance(True) self.assertTrue(controller.started) yield d self.create_build_request([builder_id]) stepcontroller.finish_step(SUCCESS) self.reactor.advance(1) yield controller.stop_instance(True) class LatentWithLatentMachine(TimeoutableTestCase, RunFakeMasterTestCase): def tearDown(self): # Flush the errors logged by the master stop cancelling the builds. self.flushLoggedErrors(LatentWorkerSubstantiatiationCancelled) super().tearDown() @defer.inlineCallbacks def create_single_worker_config(self, build_wait_timeout=0): machine_controller = LatentMachineController( name='machine1', build_wait_timeout=build_wait_timeout ) worker_controller = LatentController(self, 'worker1', machine_name='machine1') step_controller = BuildStepController() config_dict = { 'machines': [machine_controller.machine], 'builders': [ BuilderConfig( name="builder1", workernames=["worker1"], factory=BuildFactory([step_controller.step]), ), ], 'workers': [worker_controller.worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder_id = yield self.master.data.updates.findBuilderId('builder1') return machine_controller, worker_controller, step_controller, builder_id @defer.inlineCallbacks def create_two_worker_config(self, build_wait_timeout=0, controller_kwargs=None): if not controller_kwargs: controller_kwargs = {} machine_controller = LatentMachineController( name='machine1', build_wait_timeout=build_wait_timeout ) worker1_controller = LatentController( self, 'worker1', machine_name='machine1', **controller_kwargs ) worker2_controller = LatentController( self, 'worker2', machine_name='machine1', **controller_kwargs ) step1_controller = BuildStepController() step2_controller = BuildStepController() config_dict = { 'machines': [machine_controller.machine], 'builders': [ BuilderConfig( name="builder1", workernames=["worker1"], factory=BuildFactory([step1_controller.step]), ), BuilderConfig( name="builder2", workernames=["worker2"], factory=BuildFactory([step2_controller.step]), ), ], 'workers': [worker1_controller.worker, worker2_controller.worker], 'protocols': {'null': {}}, # Disable checks about missing scheduler. 'multiMaster': True, } yield self.setup_master(config_dict) builder1_id = yield self.master.data.updates.findBuilderId('builder1') builder2_id = yield self.master.data.updates.findBuilderId('builder2') return ( machine_controller, [worker1_controller, worker2_controller], [step1_controller, step2_controller], [builder1_id, builder2_id], ) @defer.inlineCallbacks def test_1worker_starts_and_stops_after_single_build_success(self): ( machine_controller, worker_controller, step_controller, builder_id, ) = yield self.create_single_worker_config() worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(True) self.assertTrue(worker_controller.started) step_controller.finish_step(SUCCESS) self.reactor.advance(0) # force deferred suspend call to be executed machine_controller.stop_machine() self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_1worker_starts_and_stops_after_single_build_failure(self): ( machine_controller, worker_controller, step_controller, builder_id, ) = yield self.create_single_worker_config() worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(True) self.assertTrue(worker_controller.started) step_controller.finish_step(FAILURE) self.reactor.advance(0) # force deferred stop call to be executed machine_controller.stop_machine() self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_1worker_stops_machine_after_timeout(self): ( machine_controller, worker_controller, step_controller, builder_id, ) = yield self.create_single_worker_config(build_wait_timeout=5) worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(True) self.reactor.advance(10.0) step_controller.finish_step(SUCCESS) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) self.reactor.advance(4.9) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) # put clock 5s after step finish, machine should start suspending self.reactor.advance(0.1) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPING) machine_controller.stop_machine() self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_1worker_does_not_stop_machine_machine_after_timeout_during_build(self): ( machine_controller, worker_controller, step_controller, builder_id, ) = yield self.create_single_worker_config(build_wait_timeout=5) worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(True) self.reactor.advance(10.0) step_controller.finish_step(SUCCESS) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) # create build request while machine is still awake. It should not # suspend regardless of how much time passes self.reactor.advance(4.9) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) yield self.create_build_request([builder_id]) self.reactor.advance(5.1) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) step_controller.finish_step(SUCCESS) self.reactor.advance(4.9) self.assertEqual(machine_controller.machine.state, MachineStates.STARTED) # put clock 5s after step finish, machine should start suspending self.reactor.advance(0.1) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPING) machine_controller.stop_machine() self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_1worker_insubstantiated_after_start_failure(self): ( machine_controller, worker_controller, _, builder_id, ) = yield self.create_single_worker_config() worker_controller.auto_connect_worker = False worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(False) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) self.assertEqual(worker_controller.started, False) @defer.inlineCallbacks def test_1worker_eats_exception_from_start_machine(self): ( machine_controller, worker_controller, _, builder_id, ) = yield self.create_single_worker_config() worker_controller.auto_connect_worker = False worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) class FakeError(Exception): pass machine_controller.start_machine(FakeError('start error')) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) self.assertEqual(worker_controller.started, False) self.flushLoggedErrors(FakeError) @defer.inlineCallbacks def test_1worker_eats_exception_from_stop_machine(self): ( machine_controller, worker_controller, step_controller, builder_id, ) = yield self.create_single_worker_config() worker_controller.auto_start(True) worker_controller.auto_stop(True) yield self.create_build_request([builder_id]) machine_controller.start_machine(True) step_controller.finish_step(SUCCESS) self.reactor.advance(0) # force deferred suspend call to be executed class FakeError(Exception): pass machine_controller.stop_machine(FakeError('stop error')) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) self.flushLoggedErrors(FakeError) @defer.inlineCallbacks def test_2workers_build_substantiates_insubstantiates_both_workers(self): ( machine_controller, worker_controllers, step_controllers, builder_ids, ) = yield self.create_two_worker_config( controller_kwargs={"starts_without_substantiate": True} ) for wc in worker_controllers: wc.auto_start(True) wc.auto_stop(True) yield self.create_build_request([builder_ids[0]]) machine_controller.start_machine(True) for wc in worker_controllers: self.assertTrue(wc.started) step_controllers[0].finish_step(SUCCESS) self.reactor.advance(0) # force deferred suspend call to be executed machine_controller.stop_machine() for wc in worker_controllers: self.assertFalse(wc.started) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_2workers_two_builds_start_machine_concurrently(self): ( machine_controller, worker_controllers, step_controllers, builder_ids, ) = yield self.create_two_worker_config() for wc in worker_controllers: wc.auto_start(True) wc.auto_stop(True) yield self.create_build_request([builder_ids[0]]) self.assertEqual(machine_controller.machine.state, MachineStates.STARTING) yield self.create_build_request([builder_ids[1]]) machine_controller.start_machine(True) for wc in worker_controllers: self.assertTrue(wc.started) step_controllers[0].finish_step(SUCCESS) step_controllers[1].finish_step(SUCCESS) self.reactor.advance(0) # force deferred suspend call to be executed machine_controller.stop_machine() for wc in worker_controllers: self.assertFalse(wc.started) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) @defer.inlineCallbacks def test_2workers_insubstantiated_after_one_start_failure(self): ( machine_controller, worker_controllers, _, builder_ids, ) = yield self.create_two_worker_config() for wc in worker_controllers: wc.auto_connect_worker = False wc.auto_start(True) wc.auto_stop(True) yield self.create_build_request([builder_ids[0]]) machine_controller.start_machine(False) self.assertEqual(machine_controller.machine.state, MachineStates.STOPPED) for wc in worker_controllers: self.assertEqual(wc.started, False)
64,232
Python
.py
1,361
37.62748
100
0.672545
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,645
test_kubernetes.py
buildbot_buildbot/master/buildbot/test/integration/worker/test_kubernetes.py
# 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 unittest.case import SkipTest from twisted.internet import defer from buildbot.config import BuilderConfig from buildbot.plugins import schedulers from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.process.results import SUCCESS from buildbot.test.util.integration import RunMasterBase from buildbot.util import kubeclientservice from buildbot.worker import kubernetes # This integration test creates a master and kubernetes worker environment, # It requires a kubernetes cluster up and running. It tries to get the config # like loading "~/.kube/config" files or environment variable. # You can use minikube to create a kubernetes environment for development: # # See https://github.com/kubernetes/minikube for full documentation # minikube start # [--vm-driver=kvm] # # export masterFQDN=$(ip route get $(minikube ip)| awk '{ print $5 }') # export KUBE_NAMESPACE=`kubectl config get-contexts \`kubectl config current-context\` # |tail -n1 |awk '{print $5}'` # useful commands: # - 'minikube dashboard' to display WebUI of the kubernetes cluster # - 'minikube ip' to display the IP of the kube-apimaster # - 'minikube ssh' to get a shell into the minikube VM # following environment variable can be used to stress concurrent worker startup NUM_CONCURRENT = int(os.environ.get("KUBE_TEST_NUM_CONCURRENT_BUILD", 1)) class KubernetesMaster(RunMasterBase): timeout = 200 def setUp(self): if "TEST_KUBERNETES" not in os.environ: raise SkipTest( "kubernetes integration tests only run when environment " "variable TEST_KUBERNETES is set" ) if 'masterFQDN' not in os.environ: raise SkipTest( "you need to export masterFQDN. You have example in the test file. " "Make sure that you're spawned worker can callback this IP" ) @defer.inlineCallbacks def setup_config(self, num_concurrent, extra_steps=None): if extra_steps is None: extra_steps = [] c = {} c['schedulers'] = [schedulers.ForceScheduler(name="force", builderNames=["testy"])] triggereables = [] for i in range(num_concurrent): c['schedulers'].append( schedulers.Triggerable(name="trigsched" + str(i), builderNames=["build"]) ) triggereables.append("trigsched" + str(i)) f = BuildFactory() f.addStep(steps.ShellCommand(command='echo hello')) f.addStep( steps.Trigger(schedulerNames=triggereables, waitForFinish=True, updateSourceStamp=True) ) f.addStep(steps.ShellCommand(command='echo world')) f2 = BuildFactory() f2.addStep(steps.ShellCommand(command='echo ola')) for step in extra_steps: f2.addStep(step) c['builders'] = [ BuilderConfig(name="testy", workernames=["kubernetes0"], factory=f), BuilderConfig( name="build", workernames=["kubernetes" + str(i) for i in range(num_concurrent)], factory=f2, ), ] masterFQDN = os.environ.get('masterFQDN') c['workers'] = [ kubernetes.KubeLatentWorker( 'kubernetes' + str(i), 'buildbot/buildbot-worker', kube_config=kubeclientservice.KubeCtlProxyConfigLoader( namespace=os.getenv("KUBE_NAMESPACE", "default") ), masterFQDN=masterFQDN, ) for i in range(num_concurrent) ] # un comment for debugging what happens if things looks locked. # c['www'] = {'port': 8080} c['protocols'] = {"pb": {"port": "tcp:9989"}} yield self.setup_master(c, startWorker=False) @defer.inlineCallbacks def test_trigger(self): yield self.setup_config(num_concurrent=NUM_CONCURRENT) yield self.doForceBuild() builds = yield self.master.data.get(("builds",)) # if there are some retry, there will be more builds self.assertEqual(len(builds), 1 + NUM_CONCURRENT) for b in builds: self.assertEqual(b['results'], SUCCESS) class KubernetesMasterTReq(KubernetesMaster): def setup(self): super().setUp() self.patch(kubernetes.KubeClientService, 'PREFER_TREQ', True)
5,134
Python
.py
113
37.938053
99
0.674995
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,646
users.py
buildbot_buildbot/master/buildbot/test/fakedb/users.py
# 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 annotations from buildbot.test.fakedb.row import Row class User(Row): table = "users" id_column = 'uid' def __init__(self, uid=None, identifier='soap', bb_username=None, bb_password=None): super().__init__( uid=uid, identifier=identifier, bb_username=bb_username, bb_password=bb_password ) class UserInfo(Row): table = "users_info" foreignKeys = ('uid',) required_columns = ('uid',) def __init__(self, uid=None, attr_type='git', attr_data='Tyler Durden <[email protected]>'): super().__init__(uid=uid, attr_type=attr_type, attr_data=attr_data)
1,345
Python
.py
29
42.827586
95
0.723583
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,647
state.py
buildbot_buildbot/master/buildbot/test/fakedb/state.py
# 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.test.fakedb.row import Row class Object(Row): table = "objects" id_column = 'id' def __init__(self, id=None, name='nam', class_name='cls'): super().__init__(id=id, name=name, class_name=class_name) class ObjectState(Row): table = "object_state" required_columns = ('objectid',) def __init__(self, objectid=None, name='nam', value_json='{}'): super().__init__(objectid=objectid, name=name, value_json=value_json)
1,181
Python
.py
25
44.24
79
0.731239
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,648
buildrequests.py
buildbot_buildbot/master/buildbot/test/fakedb/buildrequests.py
# 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 annotations from buildbot.test.fakedb.row import Row class BuildRequest(Row): table = "buildrequests" foreignKeys = ('buildsetid',) id_column = 'id' required_columns = ('buildsetid',) def __init__( self, id=None, buildsetid=None, builderid=None, priority=0, complete=0, results=-1, submitted_at=12345678, complete_at=None, waited_for=0, ): super().__init__( id=id, buildsetid=buildsetid, builderid=builderid, priority=priority, complete=complete, results=results, submitted_at=submitted_at, complete_at=complete_at, waited_for=waited_for, ) class BuildRequestClaim(Row): table = "buildrequest_claims" foreignKeys = ('brid', 'masterid') required_columns = ('brid', 'masterid', 'claimed_at') def __init__(self, brid=None, masterid=None, claimed_at=None): super().__init__(brid=brid, masterid=masterid, claimed_at=claimed_at)
1,815
Python
.py
50
30.02
79
0.668568
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,649
buildsets.py
buildbot_buildbot/master/buildbot/test/fakedb/buildsets.py
# 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 annotations from buildbot.test.fakedb.row import Row class Buildset(Row): table = "buildsets" foreignKeys = ('rebuilt_buildid',) id_column = 'id' def __init__( self, id=None, external_idstring='extid', reason='because', submitted_at=12345678, complete=0, complete_at=None, results=-1, rebuilt_buildid=None, parent_buildid=None, parent_relationship=None, ): super().__init__( id=id, external_idstring=external_idstring, reason=reason, submitted_at=submitted_at, complete=complete, complete_at=complete_at, results=results, rebuilt_buildid=rebuilt_buildid, parent_buildid=parent_buildid, parent_relationship=parent_relationship, ) class BuildsetProperty(Row): table = "buildset_properties" foreignKeys = ('buildsetid',) required_columns = ('buildsetid',) def __init__(self, buildsetid=None, property_name='prop', property_value='[22, "fakedb"]'): super().__init__( buildsetid=buildsetid, property_name=property_name, property_value=property_value ) class BuildsetSourceStamp(Row): table = "buildset_sourcestamps" foreignKeys = ('buildsetid', 'sourcestampid') required_columns = ( 'buildsetid', 'sourcestampid', ) id_column = 'id' def __init__(self, id=None, buildsetid=None, sourcestampid=None): super().__init__(id=id, buildsetid=buildsetid, sourcestampid=sourcestampid)
2,348
Python
.py
63
30.714286
95
0.67063
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,650
connector.py
buildbot_buildbot/master/buildbot/test/fakedb/connector.py
# 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 json from twisted.internet import defer from buildbot.db.connector import DBConnector from buildbot.util.sautils import hash_columns from .build_data import BuildData from .builders import Builder from .builders import BuilderMaster from .builders import BuildersTags from .buildrequests import BuildRequest from .buildrequests import BuildRequestClaim from .builds import Build from .builds import BuildProperty from .buildsets import Buildset from .buildsets import BuildsetProperty from .buildsets import BuildsetSourceStamp from .changes import Change from .changes import ChangeFile from .changes import ChangeProperty from .changes import ChangeUser from .changesources import ChangeSource from .changesources import ChangeSourceMaster from .logs import Log from .logs import LogChunk from .masters import Master from .projects import Project from .schedulers import Scheduler from .schedulers import SchedulerChange from .schedulers import SchedulerMaster from .sourcestamps import Patch from .sourcestamps import SourceStamp from .state import Object from .state import ObjectState from .steps import Step from .tags import Tag from .test_result_sets import TestResultSet from .test_results import TestCodePath from .test_results import TestName from .test_results import TestResult from .users import User from .users import UserInfo from .workers import ConfiguredWorker from .workers import ConnectedWorker from .workers import Worker class FakeDBConnector(DBConnector): """ A stand-in for C{master.db} that operates without an actual database backend. This also implements a test-data interface similar to the L{buildbot.test.util.db.RealDatabaseMixin.insert_test_data} method. The child classes implement various useful assertions and faking methods; see their documentation for more. """ MASTER_ID = 824 def __init__(self, basedir, testcase, auto_upgrade=False): super().__init__(basedir) self.testcase = testcase self.checkForeignKeys = False self.auto_upgrade = auto_upgrade @defer.inlineCallbacks def setup(self): if self.auto_upgrade: yield super().setup(check_version=False) yield self.model.upgrade() else: yield super().setup() def _match_rows(self, rows, type): matched_rows = [r for r in rows if isinstance(r, type)] non_matched_rows = [r for r in rows if r not in matched_rows] return matched_rows, non_matched_rows def _thd_maybe_insert_build_data(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildData) for row in matched_rows: conn.execute( self.model.build_data.insert(), [ { 'id': row.id, 'buildid': row.buildid, 'name': row.name, 'value': row.value, 'length': row.length, 'source': row.source, } ], ) return non_matched_rows def _thd_maybe_insert_builder(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Builder) for row in matched_rows: conn.execute( self.model.builders.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), 'projectid': row.projectid, 'description': row.description, 'description_format': row.description_format, 'description_html': row.description_html, } ], ) return non_matched_rows def _thd_maybe_insert_builder_master(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuilderMaster) for row in matched_rows: conn.execute( self.model.builder_masters.insert(), [{'id': row.id, 'builderid': row.builderid, 'masterid': row.masterid}], ) return non_matched_rows def _thd_maybe_insert_builder_tags(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildersTags) for row in matched_rows: conn.execute( self.model.builders_tags.insert(), [{'builderid': row.builderid, 'tagid': row.tagid}], ) return non_matched_rows def _thd_maybe_insert_buildrequest(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildRequest) for row in matched_rows: conn.execute( self.model.buildrequests.insert(), [ { 'id': row.id, 'buildsetid': row.buildsetid, 'builderid': row.builderid, 'priority': row.priority, 'complete': row.complete, 'results': row.results, 'submitted_at': row.submitted_at, 'complete_at': row.complete_at, 'waited_for': row.waited_for, } ], ) return non_matched_rows def _thd_maybe_insert_buildrequest_claim(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildRequestClaim) for row in matched_rows: conn.execute( self.model.buildrequest_claims.insert(), [ { 'brid': row.brid, 'masterid': row.masterid, 'claimed_at': row.claimed_at, } ], ) return non_matched_rows def _thd_maybe_insert_build(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Build) for row in matched_rows: conn.execute( self.model.builds.insert(), [ { 'id': row.id, 'number': row.number, 'builderid': row.builderid, 'buildrequestid': row.buildrequestid, 'workerid': row.workerid, 'masterid': row.masterid, 'started_at': row.started_at, 'complete_at': row.complete_at, 'locks_duration_s': row.locks_duration_s, 'state_string': row.state_string, 'results': row.results, } ], ) return non_matched_rows def _thd_maybe_insert_build_properties(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildProperty) for row in matched_rows: conn.execute( self.model.build_properties.insert(), [ { 'buildid': row.buildid, 'name': row.name, 'value': json.dumps(row.value), 'source': row.source, } ], ) return non_matched_rows def _thd_maybe_insert_buildset(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Buildset) for row in matched_rows: conn.execute( self.model.buildsets.insert(), [ { 'id': row.id, 'external_idstring': row.external_idstring, 'reason': row.reason, 'submitted_at': row.submitted_at, 'complete': row.complete, 'complete_at': row.complete_at, 'results': row.results, 'parent_buildid': row.parent_buildid, 'parent_relationship': row.parent_relationship, 'rebuilt_buildid': row.rebuilt_buildid, } ], ) return non_matched_rows def _thd_maybe_insert_buildset_property(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildsetProperty) for row in matched_rows: conn.execute( self.model.buildset_properties.insert(), [ { 'buildsetid': row.buildsetid, 'property_name': row.property_name, 'property_value': row.property_value, } ], ) return non_matched_rows def _thd_maybe_insert_buildset_sourcestamp(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, BuildsetSourceStamp) for row in matched_rows: conn.execute( self.model.buildset_sourcestamps.insert(), [ { 'id': row.id, 'buildsetid': row.buildsetid, 'sourcestampid': row.sourcestampid, } ], ) return non_matched_rows def _thd_maybe_insert_change(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Change) for row in matched_rows: conn.execute( self.model.changes.insert(), [ { 'changeid': row.changeid, 'author': row.author, 'committer': row.committer, 'comments': row.comments, 'branch': row.branch, 'revision': row.revision, 'revlink': row.revlink, 'when_timestamp': row.when_timestamp, 'category': row.category, 'repository': row.repository, 'codebase': row.codebase, 'project': row.project, 'sourcestampid': row.sourcestampid, 'parent_changeids': row.parent_changeids, } ], ) return non_matched_rows def _thd_maybe_insert_change_file(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ChangeFile) for row in matched_rows: conn.execute( self.model.change_files.insert(), [{'changeid': row.changeid, 'filename': row.filename}], ) return non_matched_rows def _thd_maybe_insert_change_property(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ChangeProperty) for row in matched_rows: conn.execute( self.model.change_properties.insert(), [ { 'changeid': row.changeid, 'property_name': row.property_name, 'property_value': row.property_value, } ], ) return non_matched_rows def _thd_maybe_insert_change_user(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ChangeUser) for row in matched_rows: conn.execute( self.model.change_users.insert(), [{'changeid': row.changeid, 'uid': row.uid}], ) return non_matched_rows def _thd_maybe_insert_changesource(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ChangeSource) for row in matched_rows: conn.execute( self.model.changesources.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), } ], ) return non_matched_rows def _thd_maybe_insert_changesource_master(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ChangeSourceMaster) for row in matched_rows: conn.execute( self.model.changesource_masters.insert(), [ { 'changesourceid': row.changesourceid, 'masterid': row.masterid, } ], ) return non_matched_rows def _thd_maybe_insert_log(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Log) for row in matched_rows: conn.execute( self.model.logs.insert(), [ { 'id': row.id, 'name': row.name, 'slug': row.slug, 'stepid': row.stepid, 'complete': row.complete, 'num_lines': row.num_lines, 'type': row.type, } ], ) return non_matched_rows def _thd_maybe_insert_log_chunk(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, LogChunk) for row in matched_rows: conn.execute( self.model.logchunks.insert(), [ { 'logid': row.logid, 'first_line': row.first_line, 'last_line': row.last_line, 'content': row.content, 'compressed': row.compressed, } ], ) return non_matched_rows def _thd_maybe_insert_master(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Master) for row in matched_rows: conn.execute( self.model.masters.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), 'active': row.active, 'last_active': row.last_active, } ], ) return non_matched_rows def _thd_maybe_insert_project(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Project) for row in matched_rows: conn.execute( self.model.projects.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), 'slug': row.slug, 'description': row.description, 'description_format': row.description_format, 'description_html': row.description_html, } ], ) return non_matched_rows def _thd_maybe_insert_scheduler_change(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, SchedulerChange) for row in matched_rows: conn.execute( self.model.scheduler_changes.insert(), [ { 'schedulerid': row.schedulerid, 'changeid': row.changeid, 'important': row.important, } ], ) return non_matched_rows def _thd_maybe_insert_scheduler(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Scheduler) for row in matched_rows: conn.execute( self.model.schedulers.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), 'enabled': row.enabled, } ], ) return non_matched_rows def _thd_maybe_insert_scheduler_master(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, SchedulerMaster) for row in matched_rows: conn.execute( self.model.scheduler_masters.insert(), [ { 'schedulerid': row.schedulerid, 'masterid': row.masterid, } ], ) return non_matched_rows def _thd_maybe_insert_patch(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Patch) for row in matched_rows: conn.execute( self.model.patches.insert(), [ { 'id': row.id, 'patchlevel': row.patchlevel, 'patch_base64': row.patch_base64, 'patch_author': row.patch_author, 'patch_comment': row.patch_comment, 'subdir': row.subdir, } ], ) return non_matched_rows def _thd_maybe_insert_sourcestamp(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, SourceStamp) for row in matched_rows: conn.execute( self.model.sourcestamps.insert(), [ { 'id': row.id, 'branch': row.branch, 'revision': row.revision, 'patchid': row.patchid, 'repository': row.repository, 'codebase': row.codebase, 'project': row.project, 'created_at': row.created_at, 'ss_hash': hash_columns( row.branch, row.revision, row.repository, row.project, row.codebase, row.patchid, ), } ], ) return non_matched_rows def _thd_maybe_insert_object(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Object) for row in matched_rows: conn.execute( self.model.objects.insert(), [ { 'id': row.id, 'name': row.name, 'class_name': row.class_name, } ], ) return non_matched_rows def _thd_maybe_insert_object_state(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ObjectState) for row in matched_rows: conn.execute( self.model.object_state.insert(), [ { 'objectid': row.objectid, 'name': row.name, 'value_json': row.value_json, } ], ) return non_matched_rows def _thd_maybe_insert_step(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Step) for row in matched_rows: conn.execute( self.model.steps.insert(), [ { 'id': row.id, 'number': row.number, 'name': row.name, 'buildid': row.buildid, 'started_at': row.started_at, 'locks_acquired_at': row.locks_acquired_at, 'complete_at': row.complete_at, 'state_string': row.state_string, 'results': row.results, 'urls_json': row.urls_json, 'hidden': row.hidden, } ], ) return non_matched_rows def _thd_maybe_insert_tag(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Tag) for row in matched_rows: conn.execute( self.model.tags.insert(), [ { 'id': row.id, 'name': row.name, 'name_hash': hash_columns(row.name), } ], ) return non_matched_rows def _thd_maybe_insert_test_result_set(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, TestResultSet) for row in matched_rows: conn.execute( self.model.test_result_sets.insert(), [ { 'id': row.id, 'builderid': row.builderid, 'buildid': row.buildid, 'stepid': row.stepid, 'description': row.description, 'category': row.category, 'value_unit': row.value_unit, 'tests_passed': row.tests_passed, 'tests_failed': row.tests_failed, 'complete': row.complete, } ], ) return non_matched_rows def _thd_maybe_insert_test_name(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, TestName) for row in matched_rows: conn.execute( self.model.test_names.insert(), [ { 'id': row.id, 'builderid': row.builderid, 'name': row.name, } ], ) return non_matched_rows def _thd_maybe_insert_test_code_path(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, TestCodePath) for row in matched_rows: conn.execute( self.model.test_code_paths.insert(), [ { 'id': row.id, 'builderid': row.builderid, 'path': row.path, } ], ) return non_matched_rows def _thd_maybe_insert_test_result(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, TestResult) for row in matched_rows: conn.execute( self.model.test_results.insert(), [ { 'id': row.id, 'builderid': row.builderid, 'test_result_setid': row.test_result_setid, 'test_nameid': row.test_nameid, 'test_code_pathid': row.test_code_pathid, 'line': row.line, 'duration_ns': row.duration_ns, 'value': row.value, } ], ) return non_matched_rows def _thd_maybe_insert_user(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, User) for row in matched_rows: conn.execute( self.model.users.insert(), [ { 'uid': row.uid, 'identifier': row.identifier, 'bb_username': row.bb_username, 'bb_password': row.bb_password, } ], ) return non_matched_rows def _thd_maybe_insert_user_info(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, UserInfo) for row in matched_rows: conn.execute( self.model.users_info.insert(), [ { 'uid': row.uid, 'attr_type': row.attr_type, 'attr_data': row.attr_data, } ], ) return non_matched_rows def _thd_maybe_insert_worker(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, Worker) for row in matched_rows: conn.execute( self.model.workers.insert(), [ { 'id': row.id, 'name': row.name, 'info': row.info, 'paused': row.paused, 'pause_reason': row.pause_reason, 'graceful': row.graceful, } ], ) return non_matched_rows def _thd_maybe_insert_configured_worker(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ConfiguredWorker) for row in matched_rows: conn.execute( self.model.configured_workers.insert(), [ { 'id': row.id, 'buildermasterid': row.buildermasterid, 'workerid': row.workerid, } ], ) return non_matched_rows def _thd_maybe_insert_connected_worker(self, conn, rows): matched_rows, non_matched_rows = self._match_rows(rows, ConnectedWorker) for row in matched_rows: conn.execute( self.model.connected_workers.insert(), [{'id': row.id, 'masterid': row.masterid, 'workerid': row.workerid}], ) return non_matched_rows @defer.inlineCallbacks def insert_test_data(self, rows): """Insert a list of Row instances into the database""" def thd_insert_rows(conn): remaining = rows remaining = self._thd_maybe_insert_build_data(conn, remaining) remaining = self._thd_maybe_insert_builder(conn, remaining) remaining = self._thd_maybe_insert_builder_master(conn, remaining) remaining = self._thd_maybe_insert_builder_tags(conn, remaining) remaining = self._thd_maybe_insert_buildrequest(conn, remaining) remaining = self._thd_maybe_insert_buildrequest_claim(conn, remaining) remaining = self._thd_maybe_insert_build(conn, remaining) remaining = self._thd_maybe_insert_build_properties(conn, remaining) remaining = self._thd_maybe_insert_buildset(conn, remaining) remaining = self._thd_maybe_insert_buildset_property(conn, remaining) remaining = self._thd_maybe_insert_buildset_sourcestamp(conn, remaining) remaining = self._thd_maybe_insert_change(conn, remaining) remaining = self._thd_maybe_insert_change_file(conn, remaining) remaining = self._thd_maybe_insert_change_property(conn, remaining) remaining = self._thd_maybe_insert_change_user(conn, remaining) remaining = self._thd_maybe_insert_changesource(conn, remaining) remaining = self._thd_maybe_insert_changesource_master(conn, remaining) remaining = self._thd_maybe_insert_log(conn, remaining) remaining = self._thd_maybe_insert_log_chunk(conn, remaining) remaining = self._thd_maybe_insert_master(conn, remaining) remaining = self._thd_maybe_insert_project(conn, remaining) remaining = self._thd_maybe_insert_scheduler_change(conn, remaining) remaining = self._thd_maybe_insert_scheduler(conn, remaining) remaining = self._thd_maybe_insert_scheduler_master(conn, remaining) remaining = self._thd_maybe_insert_patch(conn, remaining) remaining = self._thd_maybe_insert_sourcestamp(conn, remaining) remaining = self._thd_maybe_insert_object(conn, remaining) remaining = self._thd_maybe_insert_object_state(conn, remaining) remaining = self._thd_maybe_insert_step(conn, remaining) remaining = self._thd_maybe_insert_tag(conn, remaining) remaining = self._thd_maybe_insert_test_result_set(conn, remaining) remaining = self._thd_maybe_insert_test_name(conn, remaining) remaining = self._thd_maybe_insert_test_code_path(conn, remaining) remaining = self._thd_maybe_insert_test_result(conn, remaining) remaining = self._thd_maybe_insert_user(conn, remaining) remaining = self._thd_maybe_insert_user_info(conn, remaining) remaining = self._thd_maybe_insert_worker(conn, remaining) remaining = self._thd_maybe_insert_configured_worker(conn, remaining) remaining = self._thd_maybe_insert_connected_worker(conn, remaining) self.testcase.assertEqual(remaining, []) conn.commit() for row in rows: if self.checkForeignKeys: row.checkForeignKeys(self, self.testcase) yield self.pool.do(thd_insert_rows)
30,708
Python
.py
739
26.166441
87
0.500585
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,651
test_results.py
buildbot_buildbot/master/buildbot/test/fakedb/test_results.py
# 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 annotations from buildbot.test.fakedb.row import Row class TestName(Row): table = 'test_names' id_column = 'id' foreignKeys = ('builderid',) required_columns = ('builderid', 'name') def __init__(self, id=None, builderid=None, name='nam'): super().__init__(id=id, builderid=builderid, name=name) class TestCodePath(Row): table = 'test_code_paths' id_column = 'id' foreignKeys = ('builderid',) required_columns = ('builderid', 'path') def __init__(self, id=None, builderid=None, path='path/to/file'): super().__init__(id=id, builderid=builderid, path=path) class TestResult(Row): table = 'test_results' id_column = 'id' foreignKeys = ('builderid', 'test_result_setid', 'test_nameid', 'test_code_pathid') required_columns = ('builderid', 'test_result_setid', 'value') def __init__( self, id=None, builderid=None, test_result_setid=None, test_nameid=None, test_code_pathid=None, line=None, duration_ns=None, value=None, ): super().__init__( id=id, builderid=builderid, test_result_setid=test_result_setid, test_nameid=test_nameid, test_code_pathid=test_code_pathid, line=line, duration_ns=duration_ns, value=value, )
2,119
Python
.py
56
31.875
87
0.661298
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,652
steps.py
buildbot_buildbot/master/buildbot/test/fakedb/steps.py
# 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 annotations from buildbot.test.fakedb.row import Row class Step(Row): table = "steps" id_column = 'id' foreignKeys = ('buildid',) required_columns = ('buildid',) def __init__( self, id=None, number=29, name='step29', buildid=None, started_at=1304262222, locks_acquired_at=None, complete_at=None, state_string='', results=None, urls_json='[]', hidden=0, ): super().__init__( id=id, number=number, name=name, buildid=buildid, started_at=started_at, locks_acquired_at=locks_acquired_at, complete_at=complete_at, state_string=state_string, results=results, urls_json=urls_json, hidden=hidden, )
1,593
Python
.py
48
26.479167
79
0.644574
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,653
changesources.py
buildbot_buildbot/master/buildbot/test/fakedb/changesources.py
# 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.test.fakedb.row import Row class ChangeSource(Row): table = "changesources" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__(self, id=None, name='csname', name_hash=None): super().__init__(id=id, name=name, name_hash=name_hash) class ChangeSourceMaster(Row): table = "changesource_masters" foreignKeys = ('changesourceid', 'masterid') required_columns = ('changesourceid', 'masterid') def __init__(self, changesourceid=None, masterid=None): super().__init__(changesourceid=changesourceid, masterid=masterid)
1,309
Python
.py
27
45.333333
79
0.740566
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,654
tags.py
buildbot_buildbot/master/buildbot/test/fakedb/tags.py
# 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.test.fakedb.row import Row class Tag(Row): table = "tags" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__(self, id=None, name='some:tag', name_hash=None): super().__init__(id=id, name=name, name_hash=name_hash)
985
Python
.py
21
44.47619
79
0.742171
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,655
row.py
buildbot_buildbot/master/buildbot/test/fakedb/row.py
# 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 annotations from typing import Sequence from twisted.internet import defer from buildbot.util import unicode2bytes from buildbot.util.sautils import hash_columns class Row: """ Parent class for row classes, which are used to specify test data for database-related tests. @cvar table: the table name @cvar id_column: specify a column that should be assigned an auto-incremented id. Auto-assigned id's begin at 1000, so any explicitly specified ID's should be less than 1000. @cvar required_columns: a tuple of columns that must be given in the constructor @cvar hashedColumns: a tuple of hash column and source columns designating a hash to work around MySQL's inability to do indexing. @ivar values: the values to be inserted into this row """ id_column: tuple[()] | str = () required_columns: Sequence[str] = () lists: Sequence[str] = () dicts: Sequence[str] = () hashedColumns: Sequence[tuple[str, Sequence[str]]] = () foreignKeys: Sequence[str] = [] # Columns that content is represented as sa.Binary-like type in DB model. # They value is bytestring (in contrast to text-like columns, which are # unicode). binary_columns: Sequence[str] = () _next_id = None def __init__(self, **kwargs): if self.__init__.__func__ is Row.__init__: raise RuntimeError( 'Row.__init__ must be overridden to supply default values for columns' ) self.values = kwargs.copy() if self.id_column: if self.values[self.id_column] is None: self.values[self.id_column] = self.nextId() for col in self.required_columns: assert col in kwargs, f"{col} not specified: {kwargs}" for col in self.lists: setattr(self, col, []) for col in self.dicts: setattr(self, col, {}) # cast to unicode for k, v in self.values.items(): if isinstance(v, str): self.values[k] = str(v) # Binary columns stores either (compressed) binary data or encoded # with utf-8 unicode string. We assume that Row constructor receives # only unicode strings and encode them to utf-8 here. # At this moment there is only one such column: logchunks.contents, # which stores either utf-8 encoded string, or gzip-compressed # utf-8 encoded string. for col in self.binary_columns: self.values[col] = unicode2bytes(self.values[col]) # calculate any necessary hashes for hash_col, src_cols in self.hashedColumns: self.values[hash_col] = hash_columns(*(self.values[c] for c in src_cols)) # make the values appear as attributes self.__dict__.update(self.values) def __eq__(self, other): if self.__class__ != other.__class__: return False return self.values == other.values def __ne__(self, other): if self.__class__ != other.__class__: return True return self.values != other.values def __lt__(self, other): if self.__class__ != other.__class__: raise TypeError(f"Cannot compare {self.__class__} and {other.__class__}") return self.values < other.values def __le__(self, other): if self.__class__ != other.__class__: raise TypeError(f"Cannot compare {self.__class__} and {other.__class__}") return self.values <= other.values def __gt__(self, other): if self.__class__ != other.__class__: raise TypeError(f"Cannot compare {self.__class__} and {other.__class__}") return self.values > other.values def __ge__(self, other): if self.__class__ != other.__class__: raise TypeError(f"Cannot compare {self.__class__} and {other.__class__}") return self.values >= other.values def __repr__(self): return f'{self.__class__.__name__}(**{self.values!r})' @staticmethod def nextId(): id = Row._next_id if Row._next_id is not None else 1 Row._next_id = id + 1 return id @defer.inlineCallbacks def checkForeignKeys(self, db, t): accessors = { "buildsetid": db.buildsets.getBuildset, "workerid": db.workers.getWorker, "builderid": db.builders.getBuilder, "buildid": db.builds.getBuild, "changesourceid": db.changesources.getChangeSource, "changeid": db.changes.getChange, "buildrequestid": db.buildrequests.getBuildRequest, "sourcestampid": db.sourcestamps.getSourceStamp, "schedulerid": db.schedulers.getScheduler, "brid": db.buildrequests.getBuildRequest, "stepid": db.steps.getStep, "masterid": db.masters.getMaster, "rebuilt_buildid": db.builds.getBuild, } for foreign_key in self.foreignKeys: if foreign_key in accessors: key = getattr(self, foreign_key) if key is not None: val = yield accessors[foreign_key](key) t.assertTrue( val is not None, f"in {self!r} foreign key {foreign_key}:{key!r} does not exit", ) else: raise ValueError("warning, unsupported foreign key", foreign_key, self.table)
6,183
Python
.py
135
37.111111
93
0.628197
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,656
workers.py
buildbot_buildbot/master/buildbot/test/fakedb/workers.py
# 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 annotations from buildbot.test.fakedb.row import Row class Worker(Row): table = "workers" id_column = 'id' required_columns = ('name',) def __init__( self, id=None, name='some:worker', info=None, paused=0, pause_reason=None, graceful=0 ): if info is None: info = {"a": "b"} super().__init__( id=id, name=name, info=info, paused=paused, pause_reason=pause_reason, graceful=graceful ) class ConnectedWorker(Row): table = "connected_workers" id_column = 'id' required_columns = ('masterid', 'workerid') def __init__(self, id=None, masterid=None, workerid=None): super().__init__(id=id, masterid=masterid, workerid=workerid) class ConfiguredWorker(Row): table = "configured_workers" id_column = 'id' required_columns = ('buildermasterid', 'workerid') def __init__(self, id=None, buildermasterid=None, workerid=None): super().__init__(id=id, buildermasterid=buildermasterid, workerid=workerid)
1,755
Python
.py
40
39.425
100
0.705467
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,657
schedulers.py
buildbot_buildbot/master/buildbot/test/fakedb/schedulers.py
# 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.test.fakedb.row import Row class Scheduler(Row): table = "schedulers" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__(self, id=None, name='schname', name_hash=None, enabled=1): super().__init__(id=id, name=name, name_hash=name_hash, enabled=enabled) class SchedulerMaster(Row): table = "scheduler_masters" defaults = { "schedulerid": None, "masterid": None, } foreignKeys = ('schedulerid', 'masterid') required_columns = ('schedulerid', 'masterid') def __init__(self, schedulerid=None, masterid=None): super().__init__(schedulerid=schedulerid, masterid=masterid) class SchedulerChange(Row): table = "scheduler_changes" defaults = { "schedulerid": None, "changeid": None, "important": 1, } foreignKeys = ('schedulerid', 'changeid') required_columns = ('schedulerid', 'changeid') def __init__(self, schedulerid=None, changeid=None, important=1): super().__init__(schedulerid=schedulerid, changeid=changeid, important=important)
1,814
Python
.py
42
38.761905
89
0.705581
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,658
logs.py
buildbot_buildbot/master/buildbot/test/fakedb/logs.py
# 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.test.fakedb.row import Row class Log(Row): table = "logs" id_column = 'id' required_columns = ('stepid',) def __init__( self, id=None, name='log29', slug=None, stepid=None, complete=0, num_lines=0, type='s' ): if slug is None: slug = name super().__init__( id=id, name=name, slug=slug, stepid=stepid, complete=complete, num_lines=num_lines, type=type, ) class LogChunk(Row): table = "logchunks" required_columns = ('logid',) # 'content' column is sa.LargeBinary, it's bytestring. binary_columns = ('content',) def __init__(self, logid=None, first_line=0, last_line=0, content='', compressed=0): super().__init__( logid=logid, first_line=first_line, last_line=last_line, content=content, compressed=compressed, )
1,685
Python
.py
46
30.108696
94
0.646409
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,659
projects.py
buildbot_buildbot/master/buildbot/test/fakedb/projects.py
# 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 annotations from buildbot.test.fakedb.row import Row class Project(Row): table = "projects" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__( self, id=None, name='fake_project', name_hash=None, slug=None, description=None, description_format=None, description_html=None, ): if slug is None: slug = name super().__init__( id=id, name=name, name_hash=name_hash, slug=slug, description=description, description_format=description_format, description_html=description_html, )
1,434
Python
.py
41
28.853659
79
0.668349
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,660
masters.py
buildbot_buildbot/master/buildbot/test/fakedb/masters.py
# 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 annotations from buildbot.test.fakedb.row import Row class Master(Row): table = "masters" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__(self, id=None, name=None, name_hash=None, active=1, last_active=9998999): if name is None: name = f'master-{id}' super().__init__( id=id, name=name, name_hash=name_hash, active=active, last_active=last_active )
1,172
Python
.py
26
41.384615
90
0.721053
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,661
__init__.py
buildbot_buildbot/master/buildbot/test/fakedb/__init__.py
# 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 """ A complete re-implementation of the database connector components, but without using a database. These classes should pass the same tests as are applied to the real connector components. """ from .build_data import BuildData from .builders import Builder from .builders import BuilderMaster from .builders import BuildersTags from .buildrequests import BuildRequest from .buildrequests import BuildRequestClaim from .builds import Build from .builds import BuildProperty from .buildsets import Buildset from .buildsets import BuildsetProperty from .buildsets import BuildsetSourceStamp from .changes import Change from .changes import ChangeFile from .changes import ChangeProperty from .changes import ChangeUser from .changesources import ChangeSource from .changesources import ChangeSourceMaster from .connector import FakeDBConnector from .logs import Log from .logs import LogChunk from .masters import Master from .projects import Project from .schedulers import Scheduler from .schedulers import SchedulerChange from .schedulers import SchedulerMaster from .sourcestamps import Patch from .sourcestamps import SourceStamp from .state import Object from .state import ObjectState from .steps import Step from .tags import Tag from .test_result_sets import TestResultSet from .test_results import TestCodePath from .test_results import TestName from .test_results import TestResult from .users import User from .users import UserInfo from .workers import ConfiguredWorker from .workers import ConnectedWorker from .workers import Worker __all__ = [ 'Build', 'BuildData', 'BuildProperty', 'BuildRequest', 'BuildRequestClaim', 'Builder', 'BuilderMaster', 'BuildersTags', 'Buildset', 'BuildsetProperty', 'BuildsetSourceStamp', 'Change', 'ChangeFile', 'ChangeProperty', 'ChangeSource', 'ChangeSourceMaster', 'ChangeUser', 'ConfiguredWorker', 'ConnectedWorker', 'FakeDBConnector', 'Log', 'LogChunk', 'Master', 'Object', 'ObjectState', 'Patch', 'Project', 'Scheduler', 'SchedulerChange', 'SchedulerMaster', 'SourceStamp', 'Step', 'Tag', 'TestCodePath', 'TestName', 'TestResultSet', 'TestResult', 'User', 'UserInfo', 'Worker', ]
3,001
Python
.py
101
27.09901
79
0.780117
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,662
builders.py
buildbot_buildbot/master/buildbot/test/fakedb/builders.py
# 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 annotations from buildbot.test.fakedb.row import Row class Builder(Row): table = "builders" id_column = 'id' hashedColumns = [('name_hash', ('name',))] def __init__( self, id=None, name=None, name_hash=None, projectid=None, description=None, description_format=None, description_html=None, ): if name is None: name = f'builder-{id}' super().__init__( id=id, name=name, name_hash=name_hash, projectid=projectid, description=description, description_format=description_format, description_html=description_html, ) class BuilderMaster(Row): table = "builder_masters" id_column = 'id' required_columns = ('builderid', 'masterid') def __init__(self, id=None, builderid=None, masterid=None): super().__init__(id=id, builderid=builderid, masterid=masterid) class BuildersTags(Row): table = "builders_tags" foreignKeys = ('builderid', 'tagid') required_columns = ( 'builderid', 'tagid', ) id_column = 'id' def __init__(self, id=None, builderid=None, tagid=None): super().__init__(id=id, builderid=builderid, tagid=tagid)
2,031
Python
.py
57
29.54386
79
0.659694
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,663
test_result_sets.py
buildbot_buildbot/master/buildbot/test/fakedb/test_result_sets.py
# 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 annotations from buildbot.test.fakedb.row import Row class TestResultSet(Row): table = 'test_result_sets' id_column = 'id' foreignKeys = ('builderid', 'buildid', 'stepid') required_columns = ('builderid', 'buildid', 'stepid', 'category', 'value_unit', 'complete') def __init__( self, id=None, builderid=None, buildid=None, stepid=None, description=None, category=None, value_unit=None, tests_passed=None, tests_failed=None, complete=None, ): super().__init__( id=id, builderid=builderid, buildid=buildid, stepid=stepid, description=description, category=category, value_unit=value_unit, tests_passed=tests_passed, tests_failed=tests_failed, complete=complete, )
1,644
Python
.py
46
29.217391
95
0.663945
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,664
build_data.py
buildbot_buildbot/master/buildbot/test/fakedb/build_data.py
# 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 annotations from buildbot.test.fakedb.row import Row class BuildData(Row): table = 'build_data' id_column = 'id' foreignKeys = ('buildid',) required_columns = ('buildid', 'name', 'value', 'length', 'source') binary_columns = ('value',) def __init__(self, id=None, buildid=None, name=None, value=None, source=None): super().__init__( id=id, buildid=buildid, name=name, value=value, source=source, length=len(value) )
1,202
Python
.py
26
43
92
0.728205
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,665
builds.py
buildbot_buildbot/master/buildbot/test/fakedb/builds.py
# 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 annotations from buildbot.test.fakedb.row import Row class Build(Row): table = "builds" id_column = 'id' foreignKeys = ('buildrequestid', 'masterid', 'workerid', 'builderid') required_columns = ('buildrequestid', 'masterid', 'workerid') def __init__( self, id=None, number=None, buildrequestid=None, builderid=None, workerid=-1, masterid=None, started_at=1304262222, complete_at=None, state_string="test", results=None, ): if number is None: number = id super().__init__( id=id, number=number, buildrequestid=buildrequestid, builderid=builderid, workerid=workerid, masterid=masterid, started_at=started_at, complete_at=complete_at, locks_duration_s=0, state_string=state_string, results=results, ) class BuildProperty(Row): table = "build_properties" foreignKeys = ('buildid',) required_columns = ('buildid',) def __init__(self, buildid=None, name='prop', value=42, source='fakedb'): super().__init__(buildid=buildid, name=name, value=value, source=source)
1,999
Python
.py
55
29.636364
80
0.65667
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,666
sourcestamps.py
buildbot_buildbot/master/buildbot/test/fakedb/sourcestamps.py
# 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 annotations from buildbot.test.fakedb.row import Row class Patch(Row): table = "patches" id_column = 'id' def __init__( self, id=None, patchlevel=0, patch_base64='aGVsbG8sIHdvcmxk', # 'hello, world', patch_author=None, patch_comment=None, subdir=None, ): super().__init__( id=id, patchlevel=patchlevel, patch_base64=patch_base64, patch_author=patch_author, patch_comment=patch_comment, subdir=subdir, ) class NotSet: pass class SourceStamp(Row): table = "sourcestamps" id_column = 'id' hashedColumns = [ ( 'ss_hash', ( 'branch', 'revision', 'repository', 'project', 'codebase', 'patchid', ), ) ] def __init__( self, id=None, branch='master', revision=NotSet, patchid=None, repository='repo', codebase='', project='proj', created_at=89834834, ss_hash=None, ): if revision is NotSet: revision = f'rev-{id}' super().__init__( id=id, branch=branch, revision=revision, patchid=patchid, repository=repository, codebase=codebase, project=project, created_at=created_at, ss_hash=ss_hash, )
2,283
Python
.py
79
20.658228
79
0.578011
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,667
changes.py
buildbot_buildbot/master/buildbot/test/fakedb/changes.py
# 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 annotations from buildbot.test.fakedb.row import Row class Change(Row): table = "changes" lists = ('files', 'uids') dicts = ('properties',) id_column = 'changeid' def __init__( self, changeid=None, author='frank', committer='steve', comments='test change', branch='master', revision='abcd', revlink='http://vc/abcd', when_timestamp=1200000, category='cat', repository='repo', codebase='', project='proj', sourcestampid=92, parent_changeids=None, ): super().__init__( changeid=changeid, author=author, committer=committer, comments=comments, branch=branch, revision=revision, revlink=revlink, when_timestamp=when_timestamp, category=category, repository=repository, codebase=codebase, project=project, sourcestampid=sourcestampid, parent_changeids=parent_changeids, ) class ChangeFile(Row): table = "change_files" foreignKeys = ('changeid',) required_columns = ('changeid',) def __init__(self, changeid=None, filename=None): super().__init__(changeid=changeid, filename=filename) class ChangeProperty(Row): table = "change_properties" foreignKeys = ('changeid',) required_columns = ('changeid',) def __init__(self, changeid=None, property_name=None, property_value=None): super().__init__( changeid=changeid, property_name=property_name, property_value=property_value ) class ChangeUser(Row): table = "change_users" foreignKeys = ('changeid',) required_columns = ('changeid',) def __init__(self, changeid=None, uid=None): super().__init__(changeid=changeid, uid=uid)
2,632
Python
.py
74
28.648649
89
0.648819
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,668
test_lru.py
buildbot_buildbot/master/buildbot/test/fuzz/test_lru.py
# 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 random from twisted.internet import defer from twisted.internet import reactor from twisted.python import log from buildbot.test.util import fuzz 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]) def deferUntilLater(secs, result=None): d = defer.Deferred() reactor.callLater(secs, d.callback, result) return d class LRUCacheFuzzer(fuzz.FuzzTestCase): FUZZ_TIME = 60 def setUp(self): lru.inv_failed = False def tearDown(self): self.assertFalse(lru.inv_failed, "invariant failed; see logs") if hasattr(self, 'lru'): log.msg( f"hits: {self.lru.hits}; misses: {self.lru.misses}; refhits: {self.lru.refhits}" ) # tests @defer.inlineCallbacks def do_fuzz(self, endTime): lru.inv_failed = False def delayed_miss_fn(key): return deferUntilLater(random.uniform(0.001, 0.002), set([key + 1000])) self.lru = lru.AsyncLRUCache(delayed_miss_fn, 50) keys = list(range(250)) errors = [] # bail out early in the event of an error results = [] # keep references to (most) results # fire off as many requests as we can in one second, with lots of # overlap. while not errors and reactor.seconds() < endTime: key = random.choice(keys) d = self.lru.get(key) def check(result, key): self.assertEqual(result, set([key + 1000])) if random.uniform(0, 1.0) < 0.9: results.append(result) results[:-100] = [] d.addCallback(check, key) @d.addErrback def eb(f): errors.append(f) return f # unhandled error -> in the logs # give the reactor some time to process pending events if random.uniform(0, 1.0) < 0.5: yield deferUntilLater(0) # now wait until all of the pending calls have cleared, noting that # this method will be counted as one delayed call, in the current # implementation while len(reactor.getDelayedCalls()) > 1: # give the reactor some time to process pending events yield deferUntilLater(0.001) self.assertFalse(lru.inv_failed, "invariant failed; see logs") log.msg(f"hits: {self.lru.hits}; misses: {self.lru.misses}; refhits: {self.lru.refhits}")
3,273
Python
.py
75
35.88
97
0.653422
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,669
state.py
buildbot_buildbot/master/buildbot/test/fake/state.py
# 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 class State: """ A simple class you can use to keep track of state throughout a test. Just assign whatever you want to its attributes. Its constructor provides a shortcut to setting initial values for attributes """ def __init__(self, **kwargs): self.__dict__.update(kwargs)
1,021
Python
.py
23
41.695652
79
0.755779
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,670
machine.py
buildbot_buildbot/master/buildbot/test/fake/machine.py
# 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 annotations from twisted.internet import defer from buildbot.machine.latent import AbstractLatentMachine from buildbot.machine.latent import States as MachineStates from buildbot.util import service class FakeMachineManager(service.AsyncMultiService): name: str | None = 'MachineManager' # type: ignore @property def machines(self): return self.namedServices def getMachineByName(self, name): if name in self.machines: return self.machines[name] return None class LatentMachineController: """A controller for ``ControllableLatentMachine``""" def __init__(self, name, **kwargs): self.machine = ControllableLatentMachine(name, self, **kwargs) self._start_deferred = None self._stop_deferred = None def start_machine(self, result): assert self.machine.state == MachineStates.STARTING d = self._start_deferred self._start_deferred = None if isinstance(result, Exception): d.errback(result) else: d.callback(result) def stop_machine(self, result=True): assert self.machine.state == MachineStates.STOPPING d = self._stop_deferred self._stop_deferred = None if isinstance(result, Exception): d.errback(result) else: d.callback(result) class ControllableLatentMachine(AbstractLatentMachine): """A latent machine that can be controlled by tests""" def __init__(self, name, controller, **kwargs): self._controller = controller super().__init__(name, **kwargs) def start_machine(self): d = defer.Deferred() self._controller._start_deferred = d return d def stop_machine(self): d = defer.Deferred() self._controller._stop_deferred = d return d
2,577
Python
.py
63
34.888889
79
0.702562
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,671
httpclientservice.py
buildbot_buildbot/master/buildbot/test/fake/httpclientservice.py
# 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 json as jsonmodule from twisted.internet import defer from twisted.logger import Logger from twisted.python import deprecate from twisted.python import versions from zope.interface import implementer from buildbot import util from buildbot.interfaces import IHttpResponse from buildbot.util import httpclientservice from buildbot.util import service from buildbot.util import toJson from buildbot.util import unicode2bytes log = Logger() @implementer(IHttpResponse) class ResponseWrapper: def __init__(self, code, content, url=None): self._content = content self._code = code self._url = url def content(self): content = unicode2bytes(self._content) return defer.succeed(content) def json(self): return defer.succeed(jsonmodule.loads(self._content)) @property def code(self): return self._code @property def url(self): return self._url class HTTPClientService(service.SharedService): """HTTPClientService is a SharedService class that fakes http requests for buildbot http service testing. This class is named the same as the real HTTPClientService so that it could replace the real class in tests. If a test creates this class earlier than the real one, fake is going to be used until the master is destroyed. Whenever a master wants to create real HTTPClientService, it will find an existing fake service with the same name and use it instead. """ quiet = False def __init__( self, base_url, auth=None, headers=None, debug=False, verify=None, skipEncoding=False ): assert not base_url.endswith("/"), "baseurl should not end with /" super().__init__() self._session = httpclientservice.HTTPSession( self, base_url, auth=auth, headers=headers, debug=debug, verify=verify, skip_encoding=skipEncoding, ) self._expected = [] def updateHeaders(self, headers): self._session.update_headers(headers) @classmethod @defer.inlineCallbacks def getService(cls, master, case, *args, **kwargs): def assertNotCalled(self, *_args, **_kwargs): case.fail( f"HTTPClientService called with *{_args!r}, **{_kwargs!r} " f"while should be called *{args!r} **{kwargs!r}" ) case.patch(httpclientservice.HTTPClientService, "__init__", assertNotCalled) service = yield super().getService(master, *args, **kwargs) service.case = case case.addCleanup(service.assertNoOutstanding) master.httpservice = service return service def expect( self, method, ep, session=None, params=None, headers=None, data=None, json=None, code=200, content=None, content_json=None, files=None, verify=None, cert=None, processing_delay_s=None, ): if content is not None and content_json is not None: return ValueError("content and content_json cannot be both specified") if content_json is not None: content = jsonmodule.dumps(content_json, default=toJson) self._expected.append({ "method": method, "session": session, "ep": ep, "params": params, "headers": headers, "data": data, "json": json, "code": code, "content": content, "files": files, "verify": verify, "cert": cert, "processing_delay_s": processing_delay_s, }) return None def assertNoOutstanding(self): self.case.assertEqual( 0, len(self._expected), f"expected more http requests:\n {self._expected!r}" ) @defer.inlineCallbacks def _do_request( self, session, method, ep, params=None, headers=None, cookies=None, # checks are not implemented data=None, json=None, files=None, auth=None, # checks are not implemented timeout=None, verify=None, cert=None, allow_redirects=None, # checks are not implemented proxies=None, # checks are not implemented ): if ep.startswith('http://') or ep.startswith('https://'): pass else: assert ep == "" or ep.startswith("/"), "ep should start with /: " + ep if not self.quiet: log.debug( "{method} {ep} {params!r} <- {data!r}", method=method, ep=ep, params=params, data=data or json, ) if json is not None: # ensure that the json is really jsonable jsonmodule.dumps(json, default=toJson) if files is not None: files = dict((k, v.read()) for (k, v) in files.items()) if not self._expected: raise AssertionError( f"Not expecting a request, while we got: method={method!r}, ep={ep!r}, " f"params={params!r}, headers={headers!r}, data={data!r}, json={json!r}, " f"files={files!r}" ) expect = self._expected.pop(0) processing_delay_s = expect.pop("processing_delay_s") expect_session = expect["session"] or self._session # pylint: disable=too-many-boolean-expressions if ( expect_session.base_url != session.base_url or expect_session.auth != session.auth or expect_session.headers != session.headers or expect_session.verify != session.verify or expect_session.debug != session.debug or expect_session.skip_encoding != session.skip_encoding or expect["method"] != method or expect["ep"] != ep or expect["params"] != params or expect["headers"] != headers or expect["data"] != data or expect["json"] != json or expect["files"] != files or expect["verify"] != verify or expect["cert"] != cert ): raise AssertionError( "expecting:\n" f"session.base_url={expect_session.base_url!r}, " f"session.auth={expect_session.auth!r}, " f"session.headers={expect_session.headers!r}, " f"session.verify={expect_session.verify!r}, " f"session.debug={expect_session.debug!r}, " f"session.skip_encoding={expect_session.skip_encoding!r}, " f"method={expect['method']!r}, " f"ep={expect['ep']!r}, " f"params={expect['params']!r}, " f"headers={expect['headers']!r}, " f"data={expect['data']!r}, " f"json={expect['json']!r}, " f"files={expect['files']!r}, " f"verify={expect['verify']!r}, " f"cert={expect['cert']!r}" "\ngot :\n" f"session.base_url={session.base_url!r}, " f"session.auth={session.auth!r}, " f"session.headers={session.headers!r}, " f"session.verify={session.verify!r}, " f"session.debug={session.debug!r}, " f"session.skip_encoding={session.skip_encoding!r}, " f"method={method!r}, " f"ep={ep!r}, " f"params={params!r}, " f"headers={headers!r}, " f"data={data!r}, " f"json={json!r}, " f"files={files!r}, " f"verify={verify!r}, " f"cert={cert!r}" ) if not self.quiet: log.debug( "{method} {ep} -> {code} {content!r}", method=method, ep=ep, code=expect['code'], content=expect['content'], ) if processing_delay_s is not None: yield util.asyncSleep(1, reactor=self.master.reactor) return ResponseWrapper(expect['code'], expect['content']) # lets be nice to the auto completers, and don't generate that code @deprecate.deprecated(versions.Version("buildbot", 4, 1, 0)) def get(self, ep, **kwargs): return self._do_request(self._session, 'get', ep, **kwargs) @deprecate.deprecated(versions.Version("buildbot", 4, 1, 0)) def put(self, ep, **kwargs): return self._do_request(self._session, 'put', ep, **kwargs) @deprecate.deprecated(versions.Version("buildbot", 4, 1, 0)) def delete(self, ep, **kwargs): return self._do_request(self._session, 'delete', ep, **kwargs) @deprecate.deprecated(versions.Version("buildbot", 4, 1, 0)) def post(self, ep, **kwargs): return self._do_request(self._session, 'post', ep, **kwargs)
9,783
Python
.py
247
29.631579
96
0.583746
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,672
pbmanager.py
buildbot_buildbot/master/buildbot/test/fake/pbmanager.py
# 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.internet import defer from buildbot.util import service class FakePBManager(service.AsyncMultiService): def __init__(self): super().__init__() self.setName("fake-pbmanager") self._registrations = [] self._unregistrations = [] def register(self, portstr, username, password, pfactory): if (portstr, username) not in self._registrations: reg = FakeRegistration(self, portstr, username) self._registrations.append((portstr, username, password)) return defer.succeed(reg) else: raise KeyError(f"username '{username}' is already registered on port {portstr}") def _unregister(self, portstr, username): self._unregistrations.append((portstr, username)) return defer.succeed(None) class FakeRegistration: def __init__(self, pbmanager, portstr, username): self._portstr = portstr self._username = username self._pbmanager = pbmanager def unregister(self): self._pbmanager._unregister(self._portstr, self._username)
1,799
Python
.py
39
40.666667
92
0.717143
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,673
fakebuild.py
buildbot_buildbot/master/buildbot/test/fake/fakebuild.py
# 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 posixpath from unittest import mock from buildbot import config from buildbot.process import factory from buildbot.process import properties from buildbot.process import workerforbuilder from buildbot.test.fake import fakemaster from buildbot.worker import base class FakeWorkerStatus(properties.PropertiesMixin): def __init__(self, name): self.name = name self.info = properties.Properties() self.info.setProperty("test", "test", "Worker") class FakeBuild(properties.PropertiesMixin): def __init__(self, props=None, master=None): self.builder = fakemaster.FakeBuilder(master) self.workerforbuilder = mock.Mock(spec=workerforbuilder.WorkerForBuilder) self.workerforbuilder.worker = mock.Mock(spec=base.Worker) self.workerforbuilder.worker.info = properties.Properties() self.workerforbuilder.worker.workername = 'workername' self.builder.config = config.BuilderConfig( name='bldr', workernames=['a'], factory=factory.BuildFactory() ) self.path_module = posixpath self.buildid = 92 self.number = 13 self.workdir = 'build' self.locks = [] self._locks_to_acquire = [] self.sources = {} if props is None: props = properties.Properties() props.build = self self.properties = props self.master = None self.config_version = 0 def getProperties(self): return self.properties def getSourceStamp(self, codebase): if codebase in self.sources: return self.sources[codebase] return None def getAllSourceStamps(self): return list(self.sources.values()) def allChanges(self): for s in self.sources.values(): yield from s.changes def allFiles(self): files = [] for c in self.allChanges(): for f in c.files: files.append(f) return files def getBuilder(self): return self.builder def getWorkerInfo(self): return self.workerforbuilder.worker.info def setUniqueStepName(self, step): pass class FakeBuildForRendering: def render(self, r): if isinstance(r, str): return "rendered:" + r if isinstance(r, list): return list(self.render(i) for i in r) if isinstance(r, tuple): return tuple(self.render(i) for i in r) return r
3,182
Python
.py
82
32.085366
81
0.686669
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,674
worker.py
buildbot_buildbot/master/buildbot/test/fake/worker.py
# 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 annotations import os from twisted.internet import defer from twisted.python.filepath import FilePath from twisted.spread import pb from twisted.trial.unittest import SkipTest from buildbot.process import properties from buildbot.test.fake import fakeprotocol from buildbot.worker import Worker RemoteWorker: type | None = None try: from buildbot_worker.bot import LocalWorker as RemoteWorker except ImportError: pass class FakeWorker: workername = 'test' def __init__(self, master): self.master = master self.conn = fakeprotocol.FakeConnection(self) self.info = properties.Properties() self.properties = properties.Properties() self.defaultProperties = properties.Properties() self.workerid = 383 def acquireLocks(self): return True def releaseLocks(self): pass def attached(self, conn): self.worker_system = 'posix' self.path_module = os.path self.workerid = 1234 self.worker_basedir = '/wrk' return defer.succeed(None) def detached(self): pass def messageReceivedFromWorker(self): pass def addWorkerForBuilder(self, wfb): pass def removeWorkerForBuilder(self, wfb): pass def buildFinished(self, wfb): pass def canStartBuild(self): pass def putInQuarantine(self): pass def resetQuarantine(self): pass @defer.inlineCallbacks def disconnect_master_side_worker(worker): # Force disconnection because the LocalWorker does not disconnect itself. Note that # the worker may have already been disconnected by something else (e.g. if it's not # responding). We need to call detached() explicitly because the order in which # disconnection subscriptions are invoked is unspecified. if worker.conn is not None: worker._detached_sub.unsubscribe() conn = worker.conn yield worker.detached() conn.loseConnection() yield worker.waitForCompleteShutdown() class SeverWorkerConnectionMixin: _connection_severed = False _severed_deferreds = None def disconnect_worker(self): if not self._connection_severed: return if self._severed_deferreds is not None: for d in self._severed_deferreds: d.errback(pb.PBConnectionLost('lost connection')) self._connection_severed = False def sever_connection(self): # stubs the worker connection so that it appears that the TCP connection # has been severed in a way that no response is ever received, but # messages don't fail immediately. All callback will be called when # disconnect_worker is called self._connection_severed = True def register_deferred(): d = defer.Deferred() if self._severed_deferreds is None: self._severed_deferreds = [] self._severed_deferreds.append(d) return d def remotePrint(message): return register_deferred() self.worker.conn.remotePrint = remotePrint def remoteGetWorkerInfo(): return register_deferred() self.worker.conn.remoteGetWorkerInfo = remoteGetWorkerInfo def remoteSetBuilderList(builders): return register_deferred() self.worker.conn.remoteSetBuilderList = remoteSetBuilderList def remoteStartCommand(remoteCommand, builderName, commandId, commandName, args): return register_deferred() self.worker.conn.remoteStartCommand = remoteStartCommand def remoteShutdown(): return register_deferred() self.worker.conn.remoteShutdown = remoteShutdown def remoteStartBuild(builderName): return register_deferred() self.worker.conn.remoteStartBuild = remoteStartBuild def remoteInterruptCommand(builderName, commandId, why): return register_deferred() self.worker.conn.remoteInterruptCommand = remoteInterruptCommand class WorkerController(SeverWorkerConnectionMixin): """ A controller for a ``Worker``. https://glyph.twistedmatrix.com/2015/05/separate-your-fakes-and-your-inspectors.html """ def __init__(self, case, name, build_wait_timeout=600, worker_class=None, **kwargs): if worker_class is None: worker_class = Worker self.case = case self.build_wait_timeout = build_wait_timeout self.worker = worker_class(name, self, **kwargs) self.remote_worker = None @defer.inlineCallbacks def connect_worker(self): if self.remote_worker is not None: return if RemoteWorker is None: raise SkipTest("buildbot-worker package is not installed") workdir = FilePath(self.case.mktemp()) workdir.createDirectory() self.remote_worker = RemoteWorker(self.worker.name, workdir.path, False) yield self.remote_worker.setServiceParent(self.worker) @defer.inlineCallbacks def disconnect_worker(self): yield super().disconnect_worker() if self.remote_worker is None: return worker = self.remote_worker self.remote_worker = None disconnect_master_side_worker(self.worker) yield worker.disownServiceParent()
6,109
Python
.py
149
33.671141
89
0.69978
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,675
bworkermanager.py
buildbot_buildbot/master/buildbot/test/fake/bworkermanager.py
# 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.internet import defer from buildbot.util import service class FakeWorkerManager(service.AsyncMultiService): def __init__(self): super().__init__() self.setName('workers') # WorkerRegistration instances keyed by worker name self.registrations = {} # connection objects keyed by worker name self.connections = {} # self.workers contains a ready Worker instance for each # potential worker, i.e. all the ones listed in the config file. # If the worker is connected, self.workers[workername].worker will # contain a RemoteReference to their Bot instance. If it is not # connected, that attribute will hold None. self.workers = {} # maps workername to Worker def register(self, worker): workerName = worker.workername reg = FakeWorkerRegistration(worker) self.registrations[workerName] = reg return defer.succeed(reg) def _unregister(self, registration): del self.registrations[registration.worker.workername] def getWorkerByName(self, workerName): return self.registrations[workerName].worker def newConnection(self, conn, workerName): assert workerName not in self.connections self.connections[workerName] = conn conn.info = {} return defer.succeed(True) class FakeWorkerRegistration: def __init__(self, worker): self.updates = [] self.unregistered = False self.worker = worker def getPBPort(self): return 1234 def unregister(self): assert not self.unregistered, "called twice" self.unregistered = True return defer.succeed(None) def update(self, worker_config, global_config): if worker_config.workername not in self.updates: self.updates.append(worker_config.workername) return defer.succeed(None)
2,629
Python
.py
59
38.254237
79
0.712495
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,676
fakemq.py
buildbot_buildbot/master/buildbot/test/fake/fakemq.py
# 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.internet import defer from buildbot.mq import base from buildbot.test.util import validation from buildbot.util import deferwaiter from buildbot.util import service from buildbot.util import tuplematch class FakeMQConnector(service.AsyncMultiService, base.MQBase): # a fake connector that doesn't actually bridge messages from production to # consumption, and thus doesn't do any topic handling or persistence # note that this *does* verify all messages sent and received, unless this # is set to false: verifyMessages = True def __init__(self, testcase): super().__init__() self.testcase = testcase self.setup_called = False self.productions = [] self.qrefs = [] self._deferwaiter = deferwaiter.DeferWaiter() @defer.inlineCallbacks def stopService(self): yield self._deferwaiter.wait() yield super().stopService() def setup(self): self.setup_called = True return defer.succeed(None) def produce(self, routingKey, data): self.testcase.assertIsInstance(routingKey, tuple) # XXX this is incompatible with the new scheme of sending multiple messages, # since the message type is no longer encoded by the first element of the # routing key # if self.verifyMessages: # validation.verifyMessage(self.testcase, routingKey, data) if any(not isinstance(k, str) for k in routingKey): raise AssertionError(f"{routingKey} is not all str") self.productions.append((routingKey, data)) # note - no consumers are called: IT'S A FAKE def callConsumer(self, routingKey, msg): if self.verifyMessages: validation.verifyMessage(self.testcase, routingKey, msg) matched = False for q in self.qrefs: if tuplematch.matchTuple(routingKey, q.filter): matched = True self._deferwaiter.add(q.callback(routingKey, msg)) if not matched: raise AssertionError("no consumer found") def startConsuming(self, callback, filter, persistent_name=None): if any(not isinstance(k, str) and k is not None for k in filter): raise AssertionError(f"{filter} is not a filter") qref = FakeQueueRef() qref.qrefs = self.qrefs qref.callback = callback qref.filter = filter qref.persistent_name = persistent_name self.qrefs.append(qref) return defer.succeed(qref) def clearProductions(self): "Clear out the cached productions" self.productions = [] def assertProductions(self, exp, orderMatters=True): """Assert that the given messages have been produced, then flush the list of produced messages. If C{orderMatters} is false, then the messages are sorted first; use this in cases where the messages must all be produced, but the order is not specified. """ if orderMatters: self.testcase.assertEqual(self.productions, exp) else: self.testcase.assertEqual(sorted(self.productions), sorted(exp)) self.productions = [] @defer.inlineCallbacks def wait_consumed(self): # waits until all messages have been consumed yield self._deferwaiter.wait() class FakeQueueRef: def stopConsuming(self): if self in self.qrefs: self.qrefs.remove(self)
4,194
Python
.py
94
37.489362
84
0.691422
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,677
secrets.py
buildbot_buildbot/master/buildbot/test/fake/secrets.py
from __future__ import annotations from buildbot.secrets.providers.base import SecretProviderBase class FakeSecretStorage(SecretProviderBase): name: str | None = "SecretsInFake" # type: ignore[assignment] def __init__(self, *args, secretdict: dict | None = None, **kwargs): super().__init__(*args, **kwargs, secretdict=secretdict) self._setup_secrets(secretdict=secretdict) def reconfigService(self, secretdict=None): self._setup_secrets(secretdict=secretdict) def _setup_secrets(self, secretdict: dict | None = None): if secretdict is None: secretdict = {} self.allsecrets = secretdict def get(self, key): if key in self.allsecrets: return self.allsecrets[key] return None
782
Python
.py
17
38.705882
72
0.682058
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,678
libvirt.py
buildbot_buildbot/master/buildbot/test/fake/libvirt.py
# 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 class Domain: def __init__(self, name, conn, libvirt_id): self.conn = conn self._name = name self.running = False self.libvirt_id = libvirt_id self.metadata = {} def ID(self): return self.libvirt_id def name(self): return self._name def create(self): self.running = True def shutdown(self): self.running = False def destroy(self): self.running = False del self.conn[self._name] def setMetadata(self, type, metadata, key, uri, flags): self.metadata[key] = (type, uri, metadata, flags) class Connection: def __init__(self, uri): self.uri = uri self.domains = {} self._next_libvirt_id = 1 def createXML(self, xml, flags): # FIXME: This should really parse the name out of the xml, i guess d = self.fake_add("instance", self._next_libvirt_id) self._next_libvirt_id += 1 d.running = True return d def listDomainsID(self): return list(self.domains) def lookupByName(self, name): return self.domains.get(name, None) def lookupByID(self, ID): for d in self.domains.values(): if d.ID == ID: return d return None def fake_add(self, name, libvirt_id): d = Domain(name, self, libvirt_id) self.domains[name] = d return d def fake_add_domain(self, name, d): self.domains[name] = d def registerCloseCallback(self, c, c2): pass def open(uri): raise NotImplementedError('this must be patched in tests') VIR_DOMAIN_AFFECT_CONFIG = 2 VIR_DOMAIN_METADATA_ELEMENT = 2 class libvirtError(Exception): pass
2,439
Python
.py
68
29.705882
79
0.66184
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,679
fakedata.py
buildbot_buildbot/master/buildbot/test/fake/fakedata.py
# 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 json from twisted.internet import defer from twisted.python import failure from buildbot.data import connector from buildbot.data import resultspec from buildbot.db.buildrequests import AlreadyClaimedError from buildbot.test.util import validation from buildbot.util import service class FakeUpdates(service.AsyncService): # unlike "real" update methods, all of the fake methods are here in a # single class. def __init__(self, testcase): self.testcase = testcase # test cases should assert the values here: self.changesAdded = [] # Changes are numbered starting at 1. # { name : id }; users can add changesources here self.changesourceIds = {} self.buildsetsAdded = [] # Buildsets are numbered starting at 1 self.maybeBuildsetCompleteCalls = 0 self.masterStateChanges = [] # dictionaries self.schedulerIds = {} # { name : id }; users can add schedulers here self.builderIds = {} # { name : id }; users can add builders here self.schedulerMasters = {} # { schedulerid : masterid } self.changesourceMasters = {} # { changesourceid : masterid } self.workerIds = {} # { name : id }; users can add workers here # { logid : {'finished': .., 'name': .., 'type': .., 'content': [ .. ]} } self.logs = {} self.claimedBuildRequests = set([]) self.stepStateString = {} # { stepid : string } self.stepUrls = {} # { stepid : [(name,url)] } self.properties = [] self.missingWorkers = [] # extra assertions def assertProperties(self, sourced, properties): self.testcase.assertIsInstance(properties, dict) for k, v in properties.items(): self.testcase.assertIsInstance(k, str) if sourced: self.testcase.assertIsInstance(v, tuple) self.testcase.assertEqual(len(v), 2) propval, propsrc = v self.testcase.assertIsInstance(propsrc, str) else: propval = v try: json.dumps(propval) except (TypeError, ValueError): self.testcase.fail(f"value for {k} is not JSON-able") # update methods def addChange( self, files=None, comments=None, author=None, committer=None, revision=None, when_timestamp=None, branch=None, category=None, revlink='', properties=None, repository='', codebase=None, project='', src=None, ): if properties is None: properties = {} # double-check args, types, etc. if files is not None: self.testcase.assertIsInstance(files, list) map(lambda f: self.testcase.assertIsInstance(f, str), files) self.testcase.assertIsInstance(comments, (type(None), str)) self.testcase.assertIsInstance(author, (type(None), str)) self.testcase.assertIsInstance(committer, (type(None), str)) self.testcase.assertIsInstance(revision, (type(None), str)) self.testcase.assertIsInstance(when_timestamp, (type(None), int)) self.testcase.assertIsInstance(branch, (type(None), str)) if callable(category): pre_change = self.master.config.preChangeGenerator( author=author, committer=committer, files=files, comments=comments, revision=revision, when_timestamp=when_timestamp, branch=branch, revlink=revlink, properties=properties, repository=repository, project=project, ) category = category(pre_change) self.testcase.assertIsInstance(category, (type(None), str)) self.testcase.assertIsInstance(revlink, (type(None), str)) self.assertProperties(sourced=False, properties=properties) self.testcase.assertIsInstance(repository, str) self.testcase.assertIsInstance(codebase, (type(None), str)) self.testcase.assertIsInstance(project, str) self.testcase.assertIsInstance(src, (type(None), str)) # use locals() to ensure we get all of the args and don't forget if # more are added self.changesAdded.append(locals()) self.changesAdded[-1].pop('self') return defer.succeed(len(self.changesAdded)) def masterActive(self, name, masterid): self.testcase.assertIsInstance(name, str) self.testcase.assertIsInstance(masterid, int) if masterid: self.testcase.assertEqual(masterid, 1) self.thisMasterActive = True return defer.succeed(None) def masterStopped(self, name, masterid): self.testcase.assertIsInstance(name, str) self.testcase.assertEqual(masterid, 1) self.thisMasterActive = False return defer.succeed(None) def expireMasters(self, forceHouseKeeping=False): return defer.succeed(None) @defer.inlineCallbacks def addBuildset( self, waited_for, scheduler=None, sourcestamps=None, reason='', properties=None, builderids=None, external_idstring=None, rebuilt_buildid=None, parent_buildid=None, parent_relationship=None, priority=0, ): if sourcestamps is None: sourcestamps = [] if properties is None: properties = {} if builderids is None: builderids = [] # assert types self.testcase.assertIsInstance(scheduler, str) self.testcase.assertIsInstance(sourcestamps, list) for ss in sourcestamps: if not isinstance(ss, int) and not isinstance(ss, dict): self.testcase.fail(f"{ss} ({type(ss)}) is not an integer or a dictionary") del ss # since we use locals(), below self.testcase.assertIsInstance(reason, str) self.assertProperties(sourced=True, properties=properties) self.testcase.assertIsInstance(builderids, list) self.testcase.assertIsInstance(external_idstring, (type(None), str)) self.buildsetsAdded.append(locals()) self.buildsetsAdded[-1].pop('self') # call through to the db layer, since many scheduler tests expect to # find the buildset in the db later - TODO fix this! bsid, brids = yield self.master.db.buildsets.addBuildset( sourcestamps=sourcestamps, reason=reason, properties=properties, builderids=builderids, waited_for=waited_for, external_idstring=external_idstring, rebuilt_buildid=rebuilt_buildid, parent_buildid=parent_buildid, parent_relationship=parent_relationship, ) return (bsid, brids) def maybeBuildsetComplete(self, bsid): self.maybeBuildsetCompleteCalls += 1 return defer.succeed(None) @defer.inlineCallbacks def claimBuildRequests(self, brids, claimed_at=None): validation.verifyType( self.testcase, 'brids', brids, validation.ListValidator(validation.IntValidator()) ) validation.verifyType( self.testcase, 'claimed_at', claimed_at, validation.NoneOk(validation.DateTimeValidator()), ) if not brids: return True try: yield self.master.db.buildrequests.claimBuildRequests( brids=brids, claimed_at=claimed_at ) except AlreadyClaimedError: return False self.claimedBuildRequests.update(set(brids)) return True @defer.inlineCallbacks def unclaimBuildRequests(self, brids): validation.verifyType( self.testcase, 'brids', brids, validation.ListValidator(validation.IntValidator()) ) self.claimedBuildRequests.difference_update(set(brids)) if brids: yield self.master.db.buildrequests.unclaimBuildRequests(brids) def completeBuildRequests(self, brids, results, complete_at=None): validation.verifyType( self.testcase, 'brids', brids, validation.ListValidator(validation.IntValidator()) ) validation.verifyType(self.testcase, 'results', results, validation.IntValidator()) validation.verifyType( self.testcase, 'complete_at', complete_at, validation.NoneOk(validation.DateTimeValidator()), ) return defer.succeed(True) def rebuildBuildrequest(self, buildrequest): return defer.succeed(None) @defer.inlineCallbacks def update_project_info( self, projectid, slug, description, description_format, description_html, ): yield self.master.db.projects.update_project_info( projectid, slug, description, description_format, description_html ) def find_project_id(self, name): validation.verifyType(self.testcase, 'project name', name, validation.StringValidator()) return self.master.db.projects.find_project_id(name) def updateBuilderList(self, masterid, builderNames): self.testcase.assertEqual(masterid, self.master.masterid) for n in builderNames: self.testcase.assertIsInstance(n, str) self.builderNames = builderNames return defer.succeed(None) @defer.inlineCallbacks def updateBuilderInfo( self, builderid, description, description_format, description_html, projectid, tags ): yield self.master.db.builders.updateBuilderInfo( builderid, description, description_format, description_html, projectid, tags ) def masterDeactivated(self, masterid): return defer.succeed(None) def findSchedulerId(self, name): return self.master.db.schedulers.findSchedulerId(name) def forget_about_it(self, name): validation.verifyType(self.testcase, 'scheduler name', name, validation.StringValidator()) if name not in self.schedulerIds: self.schedulerIds[name] = max([0, *list(self.schedulerIds.values())]) + 1 return defer.succeed(self.schedulerIds[name]) def findChangeSourceId(self, name): validation.verifyType( self.testcase, 'changesource name', name, validation.StringValidator() ) if name not in self.changesourceIds: self.changesourceIds[name] = max([0, *list(self.changesourceIds.values())]) + 1 return defer.succeed(self.changesourceIds[name]) def findBuilderId(self, name): validation.verifyType(self.testcase, 'builder name', name, validation.StringValidator()) return self.master.db.builders.findBuilderId(name) def trySetSchedulerMaster(self, schedulerid, masterid): currentMasterid = self.schedulerMasters.get(schedulerid) if isinstance(currentMasterid, Exception): return defer.fail(failure.Failure(currentMasterid)) if currentMasterid and masterid is not None: return defer.succeed(False) self.schedulerMasters[schedulerid] = masterid return defer.succeed(True) def trySetChangeSourceMaster(self, changesourceid, masterid): currentMasterid = self.changesourceMasters.get(changesourceid) if isinstance(currentMasterid, Exception): return defer.fail(failure.Failure(currentMasterid)) if currentMasterid and masterid is not None: return defer.succeed(False) self.changesourceMasters[changesourceid] = masterid return defer.succeed(True) def addBuild(self, builderid, buildrequestid, workerid): validation.verifyType(self.testcase, 'builderid', builderid, validation.IntValidator()) validation.verifyType( self.testcase, 'buildrequestid', buildrequestid, validation.IntValidator() ) validation.verifyType(self.testcase, 'workerid', workerid, validation.IntValidator()) return defer.succeed((10, 1)) def generateNewBuildEvent(self, buildid): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) return defer.succeed(None) def setBuildStateString(self, buildid, state_string): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType( self.testcase, 'state_string', state_string, validation.StringValidator() ) return defer.succeed(None) def add_build_locks_duration(self, buildid, duration_s): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'duration_s', duration_s, validation.IntValidator()) return defer.succeed(None) def finishBuild(self, buildid, results): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'results', results, validation.IntValidator()) return defer.succeed(None) def setBuildProperty(self, buildid, name, value, source): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'name', name, validation.StringValidator()) try: json.dumps(value) except (TypeError, ValueError): self.testcase.fail(f"Value for {name} is not JSON-able") validation.verifyType(self.testcase, 'source', source, validation.StringValidator()) return defer.succeed(None) @defer.inlineCallbacks def setBuildProperties(self, buildid, properties): for k, v, s in properties.getProperties().asList(): self.properties.append((buildid, k, v, s)) yield self.setBuildProperty(buildid, k, v, s) def addStep(self, buildid, name): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'name', name, validation.IdentifierValidator(50)) return defer.succeed((10, 1, name)) def addStepURL(self, stepid, name, url): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType(self.testcase, 'name', name, validation.StringValidator()) validation.verifyType(self.testcase, 'url', url, validation.StringValidator()) self.stepUrls.setdefault(stepid, []).append((name, url)) return defer.succeed(None) def startStep(self, stepid, started_at=None, locks_acquired=False): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType( self.testcase, "started_at", started_at, validation.NoneOk(validation.IntValidator()) ) validation.verifyType( self.testcase, "locks_acquired", locks_acquired, validation.BooleanValidator() ) return defer.succeed(None) def set_step_locks_acquired_at(self, stepid, locks_acquired_at=None): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType( self.testcase, "locks_acquired_at", locks_acquired_at, validation.NoneOk(validation.IntValidator()), ) return defer.succeed(None) def setStepStateString(self, stepid, state_string): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType( self.testcase, 'state_string', state_string, validation.StringValidator() ) self.stepStateString[stepid] = state_string return defer.succeed(None) def finishStep(self, stepid, results, hidden): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType(self.testcase, 'results', results, validation.IntValidator()) validation.verifyType(self.testcase, 'hidden', hidden, validation.BooleanValidator()) return defer.succeed(None) def addLog(self, stepid, name, type): validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType(self.testcase, 'name', name, validation.StringValidator()) validation.verifyType(self.testcase, 'type', type, validation.IdentifierValidator(1)) logid = max([0, *list(self.logs)]) + 1 self.logs[logid] = {"name": name, "type": type, "content": [], "finished": False} return defer.succeed(logid) def finishLog(self, logid): validation.verifyType(self.testcase, 'logid', logid, validation.IntValidator()) self.logs[logid]['finished'] = True return defer.succeed(None) def compressLog(self, logid): validation.verifyType(self.testcase, 'logid', logid, validation.IntValidator()) return defer.succeed(None) def appendLog(self, logid, content): validation.verifyType(self.testcase, 'logid', logid, validation.IntValidator()) validation.verifyType(self.testcase, 'content', content, validation.StringValidator()) self.testcase.assertEqual(content[-1], '\n') self.logs[logid]['content'].append(content) return defer.succeed(None) def findWorkerId(self, name): validation.verifyType( self.testcase, 'worker name', name, validation.IdentifierValidator(50) ) # this needs to actually get inserted into the db (fake or real) since # getWorker will get called later return self.master.db.workers.findWorkerId(name) def workerConnected(self, workerid, masterid, workerinfo): return self.master.db.workers.workerConnected( workerid=workerid, masterid=masterid, workerinfo=workerinfo ) def workerConfigured(self, workerid, masterid, builderids): return self.master.db.workers.workerConfigured( workerid=workerid, masterid=masterid, builderids=builderids ) def workerDisconnected(self, workerid, masterid): return self.master.db.workers.workerDisconnected(workerid=workerid, masterid=masterid) def deconfigureAllWorkersForMaster(self, masterid): return self.master.db.workers.deconfigureAllWorkersForMaster(masterid=masterid) def workerMissing(self, workerid, masterid, last_connection, notify): self.missingWorkers.append((workerid, masterid, last_connection, notify)) def schedulerEnable(self, schedulerid, v): return self.master.db.schedulers.enable(schedulerid, v) def set_worker_paused(self, workerid, paused, pause_reason=None): return self.master.db.workers.set_worker_paused(workerid, paused, pause_reason=pause_reason) def set_worker_graceful(self, workerid, graceful): return self.master.db.workers.set_worker_graceful(workerid, graceful) # methods form BuildData resource @defer.inlineCallbacks def setBuildData(self, buildid, name, value, source): validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'name', name, validation.StringValidator()) validation.verifyType(self.testcase, 'value', value, validation.BinaryValidator()) validation.verifyType(self.testcase, 'source', source, validation.StringValidator()) yield self.master.db.build_data.setBuildData(buildid, name, value, source) # methods from TestResultSet resource @defer.inlineCallbacks def addTestResultSet(self, builderid, buildid, stepid, description, category, value_unit): validation.verifyType(self.testcase, 'builderid', builderid, validation.IntValidator()) validation.verifyType(self.testcase, 'buildid', buildid, validation.IntValidator()) validation.verifyType(self.testcase, 'stepid', stepid, validation.IntValidator()) validation.verifyType( self.testcase, 'description', description, validation.StringValidator() ) validation.verifyType(self.testcase, 'category', category, validation.StringValidator()) validation.verifyType(self.testcase, 'value_unit', value_unit, validation.StringValidator()) test_result_setid = yield self.master.db.test_result_sets.addTestResultSet( builderid, buildid, stepid, description, category, value_unit ) return test_result_setid @defer.inlineCallbacks def completeTestResultSet(self, test_result_setid, tests_passed=None, tests_failed=None): validation.verifyType( self.testcase, 'test_result_setid', test_result_setid, validation.IntValidator() ) validation.verifyType( self.testcase, 'tests_passed', tests_passed, validation.NoneOk(validation.IntValidator()), ) validation.verifyType( self.testcase, 'tests_failed', tests_failed, validation.NoneOk(validation.IntValidator()), ) yield self.master.db.test_result_sets.completeTestResultSet( test_result_setid, tests_passed, tests_failed ) # methods from TestResult resource @defer.inlineCallbacks def addTestResults(self, builderid, test_result_setid, result_values): yield self.master.db.test_results.addTestResults( builderid, test_result_setid, result_values ) class FakeDataConnector(service.AsyncMultiService): # FakeDataConnector delegates to the real DataConnector so it can get all # of the proper getter and consumer behavior; it overrides all of the # relevant updates with fake methods, though. def __init__(self, master, testcase): super().__init__() self.setServiceParent(master) self.updates = FakeUpdates(testcase) self.updates.setServiceParent(self) # get and control are delegated to a real connector, # after some additional assertions self.realConnector = connector.DataConnector() self.realConnector.setServiceParent(self) self.rtypes = self.realConnector.rtypes self.plural_rtypes = self.realConnector.plural_rtypes def _scanModule(self, mod): return self.realConnector._scanModule(mod) def getEndpoint(self, path): if not isinstance(path, tuple): raise TypeError('path must be a tuple') return self.realConnector.getEndpoint(path) def getResourceType(self, name): return getattr(self.rtypes, name) def get(self, path, filters=None, fields=None, order=None, limit=None, offset=None): if not isinstance(path, tuple): raise TypeError('path must be a tuple') return self.realConnector.get( path, filters=filters, fields=fields, order=order, limit=limit, offset=offset ) def get_with_resultspec(self, path, rspec): if not isinstance(path, tuple): raise TypeError('path must be a tuple') if not isinstance(rspec, resultspec.ResultSpec): raise TypeError('rspec must be ResultSpec') return self.realConnector.get_with_resultspec(path, rspec) def control(self, action, args, path): if not isinstance(path, tuple): raise TypeError('path must be a tuple') return self.realConnector.control(action, args, path) def resultspec_from_jsonapi(self, args, entityType, is_collection): return self.realConnector.resultspec_from_jsonapi(args, entityType, is_collection) def getResourceTypeForGraphQlType(self, type): return self.realConnector.getResourceTypeForGraphQlType(type)
24,667
Python
.py
507
39.542406
100
0.678032
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,680
fakestats.py
buildbot_buildbot/master/buildbot/test/fake/fakestats.py
# 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.process import buildstep from buildbot.process.results import SUCCESS from buildbot.statistics import capture from buildbot.statistics.storage_backends.base import StatsStorageBase class FakeStatsStorageService(StatsStorageBase): """ Fake Storage service used in unit tests """ def __init__(self, stats=None, name='FakeStatsStorageService'): self.stored_data = [] if not stats: self.stats = [capture.CaptureProperty("TestBuilder", 'test')] else: self.stats = stats self.name = name self.captures = [] def thd_postStatsValue(self, post_data, series_name, context=None): if not context: context = {} self.stored_data.append((post_data, series_name, context)) class FakeBuildStep(buildstep.BuildStep): """ A fake build step to be used for testing. """ def doSomething(self): self.setProperty("test", 10, "test") def start(self): self.doSomething() return SUCCESS class FakeInfluxDBClient: """ Fake Influx module for testing on systems that don't have influxdb installed. """ def __init__(self, *args, **kwargs): self.points = [] def write_points(self, points): self.points.extend(points)
2,010
Python
.py
51
34.372549
81
0.711568
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,681
change.py
buildbot_buildbot/master/buildbot/test/fake/change.py
# 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 annotations from buildbot.process.properties import Properties from buildbot.test.fake.state import State class Change(State): project = '' repository = '' branch = '' category = '' codebase = '' properties: dict | Properties = {} def __init__(self, **kw): super().__init__(**kw) # change.properties is a IProperties props = Properties() props.update(self.properties, "test") self.properties = props
1,201
Python
.py
30
36.6
79
0.72813
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,682
endpoint.py
buildbot_buildbot/master/buildbot/test/fake/endpoint.py
# 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 is a static resource type and set of endpoints used as common data by # tests. from twisted.internet import defer from buildbot.data import base from buildbot.data import types testData = { 13: {'testid': 13, 'info': 'ok', 'success': True, 'tags': []}, 14: {'testid': 14, 'info': 'failed', 'success': False, 'tags': []}, 15: { 'testid': 15, 'info': 'warned', 'success': True, 'tags': [ 'a', 'b', ], }, 16: {'testid': 16, 'info': 'skipped', 'success': True, 'tags': ['a']}, 17: {'testid': 17, 'info': 'ignored', 'success': True, 'tags': []}, 18: {'testid': 18, 'info': 'unexp', 'success': False, 'tags': []}, 19: {'testid': 19, 'info': 'todo', 'success': True, 'tags': []}, 20: {'testid': 20, 'info': 'error', 'success': False, 'tags': []}, } stepData = { 13: {'stepid': 13, 'testid': 13, 'info': 'ok'}, 14: {'stepid': 14, 'testid': 13, 'info': 'failed'}, 15: {'stepid': 15, 'testid': 14, 'info': 'failed'}, } class TestsEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = """ /tests /test """ rootLinkName = 'tests' def get(self, resultSpec, kwargs): # results are sorted by ID for test stability return defer.succeed(sorted(testData.values(), key=lambda v: v['testid'])) class RawTestsEndpoint(base.Endpoint): kind = base.EndpointKind.RAW pathPatterns = "/rawtest" def get(self, resultSpec, kwargs): return defer.succeed({"filename": "test.txt", "mime-type": "text/test", 'raw': 'value'}) class FailEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = "/test/fail" def get(self, resultSpec, kwargs): return defer.fail(RuntimeError('oh noes')) class TestEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = """ /tests/n:testid /test/n:testid """ def get(self, resultSpec, kwargs): if kwargs['testid'] == 0: return None return defer.succeed(testData[kwargs['testid']]) def control(self, action, args, kwargs): if action == "fail": return defer.fail(RuntimeError("oh noes")) return defer.succeed({'action': action, 'args': args, 'kwargs': kwargs}) class StepsEndpoint(base.Endpoint): kind = base.EndpointKind.COLLECTION pathPatterns = "/tests/n:testid/steps" def get(self, resultSpec, kwargs): data = [step for step in stepData.values() if step['testid'] == kwargs['testid']] # results are sorted by ID for test stability return defer.succeed(sorted(data, key=lambda v: v['stepid'])) class StepEndpoint(base.Endpoint): kind = base.EndpointKind.SINGLE pathPatterns = "/tests/n:testid/steps/n:stepid" def get(self, resultSpec, kwargs): if kwargs['testid'] == 0: return None return defer.succeed(testData[kwargs['testid']]) class Step(base.ResourceType): name = "step" plural = "steps" endpoints = [StepsEndpoint, StepEndpoint] keyField = "stepid" class EntityType(types.Entity): stepid = types.Integer() testid = types.Integer() info = types.String() entityType = EntityType(name, 'Step') class Test(base.ResourceType): name = "test" plural = "tests" endpoints = [TestsEndpoint, TestEndpoint, FailEndpoint, RawTestsEndpoint] keyField = "testid" subresources = ["Step"] class EntityType(types.Entity): testid = types.Integer() info = types.String() success = types.Boolean() tags = types.List(of=types.String()) entityType = EntityType(name, 'Test') graphql_schema = """ # custom scalar types for buildbot data model scalar Date # stored as utc unix timestamp scalar Binary # arbitrary data stored as base85 scalar JSON # arbitrary json stored as string, mainly used for properties values type Query {{ {queries} }} type Subscription {{ {queries} }} type Test {{ testid: Int! info: String! success: Boolean! tags: [String]! steps(info: String, info__contains: String, info__eq: String, info__ge: String, info__gt: String, info__in: [String], info__le: String, info__lt: String, info__ne: String, info__notin: [String], stepid: Int, stepid__contains: Int, stepid__eq: Int, stepid__ge: Int, stepid__gt: Int, stepid__in: [Int], stepid__le: Int, stepid__lt: Int, stepid__ne: Int, stepid__notin: [Int], testid: Int, testid__contains: Int, testid__eq: Int, testid__ge: Int, testid__gt: Int, testid__in: [Int], testid__le: Int, testid__lt: Int, testid__ne: Int, testid__notin: [Int], order: String, limit: Int, offset: Int): [Step]! step(stepid: Int): Step }} type Step {{ stepid: Int! testid: Int! info: String! }} """.format( queries=""" tests(info: String, info__contains: String, info__eq: String, info__ge: String, info__gt: String, info__in: [String], info__le: String, info__lt: String, info__ne: String, info__notin: [String], success: Boolean, success__contains: Boolean, success__eq: Boolean, success__ge: Boolean, success__gt: Boolean, success__le: Boolean, success__lt: Boolean, success__ne: Boolean, tags: String, tags__contains: String, tags__eq: String, tags__ge: String, tags__gt: String, tags__in: [String], tags__le: String, tags__lt: String, tags__ne: String, tags__notin: [String], testid: Int, testid__contains: Int, testid__eq: Int, testid__ge: Int, testid__gt: Int, testid__in: [Int], testid__le: Int, testid__lt: Int, testid__ne: Int, testid__notin: [Int], order: String, limit: Int, offset: Int): [Test]! test(testid: Int): Test""" )
6,561
Python
.py
212
26.476415
96
0.645243
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,683
msgmanager.py
buildbot_buildbot/master/buildbot/test/fake/msgmanager.py
# 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.internet import defer from buildbot.util import service class FakeMsgManager(service.AsyncMultiService): def __init__(self): super().__init__() self.setName("fake-msgmanager") self._registrations = [] self._unregistrations = [] def register(self, portstr, username, password, pfactory): if (portstr, username) not in self._registrations: reg = FakeRegistration(self, portstr, username) self._registrations.append((portstr, username, password)) return defer.succeed(reg) else: raise KeyError(f"username '{username}' is already registered on port {portstr}") def _unregister(self, portstr, username): self._unregistrations.append((portstr, username)) return defer.succeed(None) class FakeRegistration: def __init__(self, msgmanager, portstr, username): self._portstr = portstr self._username = username self._msgmanager = msgmanager def unregister(self): self._msgmanager._unregister(self._portstr, self._username)
1,805
Python
.py
39
40.820513
92
0.718109
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,684
fakemaster.py
buildbot_buildbot/master/buildbot/test/fake/fakemaster.py
# 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 annotations import weakref from unittest import mock from twisted.internet import defer from twisted.internet import reactor from buildbot.config.master import MasterConfig from buildbot.data.graphql import GraphQLConnector from buildbot.secrets.manager import SecretManager from buildbot.test import fakedb from buildbot.test.fake import bworkermanager from buildbot.test.fake import endpoint from buildbot.test.fake import fakedata from buildbot.test.fake import fakemq from buildbot.test.fake import msgmanager from buildbot.test.fake import pbmanager from buildbot.test.fake.botmaster import FakeBotMaster from buildbot.test.fake.machine import FakeMachineManager from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.util import service class FakeCache: """Emulate an L{AsyncLRUCache}, but without any real caching. This I{does} do the weakref part, to catch un-weakref-able objects.""" def __init__(self, name, miss_fn): self.name = name self.miss_fn = miss_fn def get(self, key, **kwargs): d = self.miss_fn(key, **kwargs) @d.addCallback def mkref(x): if x is not None: weakref.ref(x) return x return d def put(self, key, val): pass class FakeCaches: def get_cache(self, name, miss_fn): return FakeCache(name, miss_fn) class FakeBuilder: def __init__(self, master=None, buildername="Builder"): if master: self.master = master self.botmaster = master.botmaster self.name = buildername class FakeLogRotation: rotateLength = 42 maxRotatedFiles = 42 class FakeMaster(service.MasterService): """ Create a fake Master instance: a Mock with some convenience implementations: - Non-caching implementation for C{self.caches} """ buildbotURL: str mq: fakemq.FakeMQConnector data: fakedata.FakeDataConnector graphql: GraphQLConnector def __init__(self, reactor, master_id=fakedb.FakeDBConnector.MASTER_ID): super().__init__() self._master_id = master_id self.reactor = reactor self.objectids = {} self.config = MasterConfig() self.caches = FakeCaches() self.pbmanager = pbmanager.FakePBManager() self.initLock = defer.DeferredLock() self.basedir = 'basedir' self.botmaster = FakeBotMaster() self.botmaster.setServiceParent(self) self.name = 'fake:/master' self.httpservice = None self.masterid = master_id self.msgmanager = msgmanager.FakeMsgManager() self.workers = bworkermanager.FakeWorkerManager() self.workers.setServiceParent(self) self.machine_manager = FakeMachineManager() self.machine_manager.setServiceParent(self) self.log_rotation = FakeLogRotation() self.db = mock.Mock() self.next_objectid = 0 self.config_version = 0 def getObjectId(sched_name, class_name): k = (sched_name, class_name) try: rv = self.objectids[k] except KeyError: rv = self.objectids[k] = self.next_objectid self.next_objectid += 1 return defer.succeed(rv) self.db.state.getObjectId = getObjectId def getObjectId(self): return defer.succeed(self._master_id) def subscribeToBuildRequests(self, callback): pass # Leave this alias, in case we want to add more behavior later @defer.inlineCallbacks def make_master( testcase, wantMq=False, wantDb=False, wantData=False, wantRealReactor=False, wantGraphql=False, with_secrets: dict | None = None, url=None, **kwargs, ): if wantRealReactor: _reactor = reactor else: assert testcase is not None, "need testcase for fake reactor" # The test case must inherit from TestReactorMixin and setup it. _reactor = testcase.reactor master = FakeMaster(_reactor, **kwargs) if url: master.buildbotURL = url if wantData: wantMq = wantDb = True if wantMq: assert testcase is not None, "need testcase for wantMq" master.mq = fakemq.FakeMQConnector(testcase) yield master.mq.setServiceParent(master) if wantDb: assert testcase is not None, "need testcase for wantDb" master.db = fakedb.FakeDBConnector(master.basedir, testcase) master.db.configured_url = 'sqlite://' yield master.db.setServiceParent(master) yield master.db.setup() testcase.addCleanup(master.db._shutdown) if wantData: master.data = fakedata.FakeDataConnector(master, testcase) if wantGraphql: master.graphql = GraphQLConnector() yield master.graphql.setServiceParent(master) master.graphql.data = master.data.realConnector master.data._scanModule(endpoint) master.config.www = {'graphql': {"debug": True}} try: master.graphql.reconfigServiceWithBuildbotConfig(master.config) except ImportError: pass if with_secrets is not None: secret_service = SecretManager() secret_service.services = [FakeSecretStorage(secretdict=with_secrets)] # This should be awaited, but no other call to `setServiceParent` are awaited here yield secret_service.setServiceParent(master) return master
6,189
Python
.py
161
31.89441
90
0.697415
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,685
reactor.py
buildbot_buildbot/master/buildbot/test/fake/reactor.py
# Copyright Buildbot Team Members # Portions copyright 2015-2016 ClusterHQ Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import annotations from typing import Any from typing import Callable from typing import Sequence from twisted.internet import defer from twisted.internet import reactor from twisted.internet.base import _ThreePhaseEvent from twisted.internet.error import ProcessDone from twisted.internet.interfaces import IReactorCore from twisted.internet.interfaces import IReactorThreads from twisted.internet.task import Clock from twisted.python import log from twisted.python.failure import Failure from zope.interface import implementer # The code here is based on the implementations in # https://twistedmatrix.com/trac/ticket/8295 # https://twistedmatrix.com/trac/ticket/8296 @implementer(IReactorCore) class CoreReactor: """ Partial implementation of ``IReactorCore``. """ def __init__(self): super().__init__() self._triggers = {} def addSystemEventTrigger( self, phase: str, eventType: str, callable: Callable[..., Any], *args, **kw ): event = self._triggers.setdefault(eventType, _ThreePhaseEvent()) return eventType, event.addTrigger(phase, callable, *args, **kw) def removeSystemEventTrigger(self, triggerID): eventType, handle = triggerID event = self._triggers.setdefault(eventType, _ThreePhaseEvent()) event.removeTrigger(handle) def fireSystemEvent(self, eventType): event = self._triggers.get(eventType) if event is not None: event.fireEvent() def callWhenRunning(self, callable: Callable[..., Any], *args, **kwargs): callable(*args, **kwargs) def resolve(self, name: str, timeout: Sequence[int]) -> defer.Deferred[str]: raise NotImplementedError("resolve() is not implemented in this reactor") def stop(self) -> None: raise NotImplementedError("stop() is not implemented in this reactor") def running(self) -> bool: raise NotImplementedError("running() is not implemented in this reactor") def crash(self): raise NotImplementedError("crash() is not implemented in this reactor") def iterate(self, delay=None): raise NotImplementedError("iterate() is not implemented in this reactor") def run(self): raise NotImplementedError("run() is not implemented in this reactor") def runUntilCurrent(self): raise NotImplementedError("runUntilCurrent() is not implemented in this reactor") class NonThreadPool: """ A stand-in for ``twisted.python.threadpool.ThreadPool`` so that the majority of the test suite does not need to use multithreading. This implementation takes the function call which is meant to run in a thread pool and runs it synchronously in the calling thread. :ivar int calls: The number of calls which have been dispatched to this object. """ calls = 0 def __init__(self, **kwargs): pass def callInThreadWithCallback(self, onResult, func, *args, **kw): self.calls += 1 try: result = func(*args, **kw) except: # noqa: E722 # We catch *everything* here, since normally this code would be # running in a thread, where there is nothing that will catch # error. onResult(False, Failure()) else: onResult(True, result) def start(self): pass def stop(self): pass @implementer(IReactorThreads) class NonReactor: """ A partial implementation of ``IReactorThreads`` which fits into the execution model defined by ``NonThreadPool``. """ def suggestThreadPoolSize(self, size: int) -> None: pass def callInThread(self, callable: Callable, *args, **kwargs) -> None: callable(*args, **kwargs) def callFromThread(self, callable: Callable, *args: object, **kwargs: object) -> None: # type: ignore[override] callable(*args, **kwargs) def getThreadPool(self): return NonThreadPool() class ProcessTransport: def __init__(self, pid, reactor): self.pid = pid self.reactor = reactor def signalProcess(self, signal): self.reactor.process_signalProcess(self.pid, signal) def closeChildFD(self, descriptor): self.reactor.process_closeChildFD(self.pid, descriptor) class ProcessReactor: def __init__(self): super().__init__() self._expected_calls = [] self._processes = {} self._next_pid = 0 def _check_call(self, call): function = call["call"] if not self._expected_calls: raise AssertionError(f"Unexpected call to {function}(): {call!r}") expected_call = self._expected_calls.pop(0) self.testcase.assertEqual(call, expected_call, f"when calling to {function}()") def spawnProcess( self, processProtocol, executable, args, env=None, path=None, uid=None, gid=None, usePTY=False, childFDs=None, ): call = { "call": "spawnProcess", "executable": executable, "args": args, "env": env, "path": path, "uid": uid, "gid": gid, "usePTY": usePTY, "childFDs": childFDs, } self._check_call(call) pid = self._next_pid self._next_pid += 1 self._processes[pid] = processProtocol return ProcessTransport(pid, self) def process_signalProcess(self, pid, signal): call = { "call": "signalProcess", "pid": pid, "signal": signal, } self._check_call(call) def process_closeChildFD(self, pid, descriptor): call = { "call": "closeChildFD", "pid": pid, "descriptor": descriptor, } self._check_call(call) def process_done(self, pid, status): reason = ProcessDone(status) self._processes[pid].processEnded(reason) self._processes[pid].processExited(reason) def process_send_stdout(self, pid, data): self._processes[pid].outReceived(data) def process_send_stderr(self, pid, data): self._processes[pid].errReceived(data) def assert_no_remaining_calls(self): if self._expected_calls: msg = "The following expected calls are missing: " for call in self._expected_calls: copy = call.copy() name = copy.pop("call") msg += f"\nTo {name}(): {call!r}" raise AssertionError(msg) def expect_spawn( self, executable, args, env=None, path=None, uid=None, gid=None, usePTY=False, childFDs=None ): self._expected_calls.append({ "call": "spawnProcess", "executable": executable, "args": args, "env": env, "path": path, "uid": uid, "gid": gid, "usePTY": usePTY, "childFDs": childFDs, }) def expect_process_signalProcess(self, pid, signal): self._expected_calls.append({ "call": "signalProcess", "pid": pid, "signal": signal, }) def expect_process_closeChildFD(self, pid, descriptor): self._expected_calls.append({ "call": "closeChildFD", "pid": pid, "descriptor": descriptor, }) class TestReactor(ProcessReactor, NonReactor, CoreReactor, Clock): def __init__(self): super().__init__() # whether there are calls that should run right now self._pendingCurrentCalls = False self.stop_called = False def set_test_case(self, testcase): self.testcase = testcase def _executeCurrentDelayedCalls(self): while self.getDelayedCalls(): first = sorted(self.getDelayedCalls(), key=lambda a: a.getTime())[0] if first.getTime() > self.seconds(): break self.advance(0) self._pendingCurrentCalls = False @defer.inlineCallbacks def _catchPrintExceptions(self, what, *a, **kw): try: r = what(*a, **kw) if isinstance(r, defer.Deferred): yield r except Exception as e: log.msg('Unhandled exception from deferred when doing TestReactor.advance()', e) raise def callLater(self, when, what, *a, **kw): # Buildbot often uses callLater(0, ...) to defer execution of certain # code to the next iteration of the reactor. This means that often # there are pending callbacks registered to the reactor that might # block other code from proceeding unless the test reactor has an # iteration. To avoid deadlocks in tests we give the real reactor a # chance to advance the test reactor whenever we detect that there # are callbacks that should run in the next iteration of the test # reactor. # # Additionally, we wrap all calls with a function that prints any # unhandled exceptions if when <= 0 and not self._pendingCurrentCalls: reactor.callLater(0, self._executeCurrentDelayedCalls) return super().callLater(when, self._catchPrintExceptions, what, *a, **kw) def stop(self): # first fire pending calls until the current time. Note that the real # reactor only advances until the current time in the case of shutdown. self.advance(0) # then, fire the shutdown event self.fireSystemEvent('shutdown') self.stop_called = True
10,813
Python
.py
266
32.81203
116
0.649466
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,686
openstack.py
buildbot_buildbot/master/buildbot/test/fake/openstack.py
# 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. from __future__ import annotations import uuid ACTIVE = 'ACTIVE' BUILD = 'BUILD' DELETED = 'DELETED' ERROR = 'ERROR' UNKNOWN = 'UNKNOWN' TEST_UUIDS = { 'image': '28a65eb4-f354-4420-97dc-253b826547f7', 'volume': '65fbb9f1-c4d5-40a8-a233-ad47c52bb837', 'snapshot': 'ab89152d-3c26-4d30-9ae5-65b705f874b7', 'flavor': '853774a1-459f-4f1f-907e-c96f62472531', } class FakeNovaClient: region_name = "" # Parts used from novaclient class Client: def __init__(self, version, session): self.glance = ItemManager() self.glance._add_items([Image(TEST_UUIDS['image'], 'CirrOS 0.3.4', 13287936)]) self.volumes = ItemManager() self.volumes._add_items([Volume(TEST_UUIDS['volume'], 'CirrOS 0.3.4', 4)]) self.volume_snapshots = ItemManager() self.volume_snapshots._add_items([Snapshot(TEST_UUIDS['snapshot'], 'CirrOS 0.3.4', 2)]) self.flavors = ItemManager() self.flavors._add_items([Flavor(TEST_UUIDS['flavor'], 'm1.small', 0)]) self.servers = Servers() self.session = session self.client = FakeNovaClient() class ItemManager: def __init__(self): self._items = {} def _add_items(self, new_items): for item in new_items: self._items[item.id] = item def list(self): return self._items.values() def get(self, uuid): if uuid in self._items: return self._items[uuid] else: raise NotFound def find_image(self, name): for item in self.list(): if name in (item.name, item.id): return item raise NotFound # This exists because Image needs an attribute that isn't supported by # namedtuple. And once the base code is there might as well have Volume and # Snapshot use it too. class Item: def __init__(self, id, name, size): self.id = id self.name = name self.size = size class Image(Item): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) setattr(self, 'OS-EXT-IMG-SIZE:size', self.size) class Flavor(Item): pass class Volume(Item): pass class Snapshot(Item): pass class Servers: fail_to_get = False fail_to_start = False gets_until_active = 3 gets_until_disappears = 1 instances: dict[uuid.UUID, Instance] = {} def create(self, *boot_args, **boot_kwargs): instance_id = uuid.uuid4() instance = Instance(instance_id, self, boot_args, boot_kwargs) self.instances[instance_id] = instance return instance def get(self, instance_id): if instance_id not in self.instances: raise NotFound inst = self.instances[instance_id] if not self.fail_to_get or inst.gets < self.gets_until_disappears: if not inst.status.startswith('BUILD'): return inst inst.gets += 1 if inst.gets >= self.gets_until_active: if not self.fail_to_start: inst.status = ACTIVE else: inst.status = ERROR return inst else: raise NotFound def delete(self, instance_id): if instance_id in self.instances: del self.instances[instance_id] def findall(self, **kwargs): name = kwargs.get('name', None) if name: return list(filter(lambda item: item.name == name, self.instances.values())) return [] def find(self, **kwargs): result = self.findall(**kwargs) if len(result) > 0: raise NoUniqueMatch if len(result) == 0: raise NotFound return result[0] # This is returned by Servers.create(). class Instance: def __init__(self, id, servers, boot_args, boot_kwargs): self.id = id self.servers = servers self.boot_args = boot_args self.boot_kwargs = boot_kwargs self.gets = 0 self.status = 'BUILD(networking)' self.metadata = boot_kwargs.get('meta', {}) try: self.name = boot_args[0] except IndexError: self.name = 'name' def delete(self): self.servers.delete(self.id) # Parts used from novaclient.exceptions. class NotFound(Exception): pass class NoUniqueMatch(Exception): pass # Parts used from keystoneauth1. def get_plugin_loader(plugin_type): if plugin_type == 'password': return PasswordLoader() if plugin_type == 'token': return TokenLoader() raise ValueError(f"plugin_type '{plugin_type}' is not supported") class PasswordLoader: def load_from_options(self, **kwargs): return PasswordAuth(**kwargs) class TokenLoader: def load_from_options(self, **kwargs): return TokenAuth(**kwargs) class PasswordAuth: def __init__( self, auth_url, password, project_name, username, user_domain_name=None, project_domain_name=None, ): self.auth_url = auth_url self.password = password self.project_name = project_name self.username = username self.user_domain_name = user_domain_name self.project_domain_name = project_domain_name class TokenAuth: def __init__(self, auth_url, token): self.auth_url = auth_url self.token = token self.project_name = 'tenant' self.username = 'testuser' self.user_domain_name = 'token' self.project_domain_name = 'token' class Session: def __init__(self, auth): self.auth = auth
6,386
Python
.py
183
27.945355
95
0.636423
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,687
botmaster.py
buildbot_buildbot/master/buildbot/test/fake/botmaster.py
# 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.internet import defer from buildbot.process import botmaster from buildbot.util import service class FakeBotMaster(service.AsyncMultiService, botmaster.LockRetrieverMixin): def __init__(self): super().__init__() self.setName("fake-botmaster") self.builders = {} # dictionary mapping worker names to builders self.buildsStartedForWorkers = [] self.delayShutdown = False self._starting_brid_to_cancel = {} def getBuildersForWorker(self, workername): return self.builders.get(workername, []) def maybeStartBuildsForWorker(self, workername): self.buildsStartedForWorkers.append(workername) def maybeStartBuildsForAllBuilders(self): self.buildsStartedForWorkers += self.builders.keys() def workerLost(self, bot): pass def cleanShutdown(self, quickMode=False, stopReactor=True): self.shuttingDown = True if self.delayShutdown: self.shutdownDeferred = defer.Deferred() return self.shutdownDeferred return None def add_in_progress_buildrequest(self, brid): self._starting_brid_to_cancel[brid] = False def remove_in_progress_buildrequest(self, brid): return self._starting_brid_to_cancel.pop(brid, None) def maybe_cancel_in_progress_buildrequest(self, brid, reason): if brid in self._starting_brid_to_cancel: self._starting_brid_to_cancel[brid] = reason
2,177
Python
.py
46
41.695652
79
0.733239
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,688
step.py
buildbot_buildbot/master/buildbot/test/fake/step.py
# 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.internet import defer from buildbot.process.buildstep import BuildStep from buildbot.process.results import CANCELLED class BuildStepController: """ A controller for ``ControllableBuildStep``. https://glyph.twistedmatrix.com/2015/05/separate-your-fakes-and-your-inspectors.html """ def __init__(self, **kwargs): self.step = ControllableBuildStep(self, **kwargs) self.running = False self.auto_finish_results = None self._run_deferred = None def finish_step(self, result): assert self.running self.running = False d = self._run_deferred self._run_deferred = None d.callback(result) def auto_finish_step(self, result): self.auto_finish_results = result if self.running: self.finish_step(result) class ControllableBuildStep(BuildStep): """ A latent worker that can be controlled by tests. """ name = "controllableStep" def __init__(self, controller, **kwargs): super().__init__(**kwargs) self._controller = controller def run(self): if self._controller.auto_finish_results is not None: return defer.succeed(self._controller.auto_finish_results) assert not self._controller.running self._controller.running = True self._controller._run_deferred = defer.Deferred() return self._controller._run_deferred def interrupt(self, reason): self._controller.finish_step(CANCELLED)
2,232
Python
.py
54
35.759259
88
0.710587
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,689
logfile.py
buildbot_buildbot/master/buildbot/test/fake/logfile.py
# 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.internet import defer from buildbot import util from buildbot.util import lineboundaries class FakeLogFile: def __init__(self, name): self.name = name self.header = '' self.stdout = '' self.stderr = '' self.lbfs = {} self.finished = False self._finish_waiters = [] self._had_errors = False self.subPoint = util.subscription.SubscriptionPoint(f"{name!r} log") def getName(self): return self.name def subscribe(self, callback): return self.subPoint.subscribe(callback) def _getLbf(self, stream): try: return self.lbfs[stream] except KeyError: lbf = self.lbfs[stream] = lineboundaries.LineBoundaryFinder() return lbf def _on_whole_lines(self, stream, lines): self.subPoint.deliver(stream, lines) assert not self.finished def _split_lines(self, stream, text): lbf = self._getLbf(stream) lines = lbf.append(text) if lines is None: return self._on_whole_lines(stream, lines) def addHeader(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.header += text self._split_lines('h', text) return defer.succeed(None) def addStdout(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.stdout += text self._split_lines('o', text) return defer.succeed(None) def addStderr(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.stderr += text self._split_lines('e', text) return defer.succeed(None) def add_header_lines(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.header += text self._on_whole_lines('h', text) return defer.succeed(None) def add_stdout_lines(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.stdout += text self._on_whole_lines('o', text) return defer.succeed(None) def add_stderr_lines(self, text): if not isinstance(text, str): text = text.decode('utf-8') self.stderr += text self._on_whole_lines('e', text) return defer.succeed(None) def isFinished(self): return self.finished def waitUntilFinished(self): d = defer.Deferred() if self.finished: d.succeed(None) else: self._finish_waiters.append(d) return d def flushFakeLogfile(self): for stream, lbf in self.lbfs.items(): lines = lbf.flush() if lines is not None: self.subPoint.deliver(stream, lines) def had_errors(self): return self._had_errors @defer.inlineCallbacks def finish(self): assert not self.finished self.flushFakeLogfile() self.finished = True # notify subscribers *after* finishing the log self.subPoint.deliver(None, None) yield self.subPoint.waitForDeliveriesToFinish() self._had_errors = len(self.subPoint.pop_exceptions()) > 0 # notify those waiting for finish for d in self._finish_waiters: d.callback(None) def fakeData(self, header='', stdout='', stderr=''): if header: self.header += header if stdout: self.stdout += stdout if stderr: self.stderr += stderr
4,309
Python
.py
118
28.491525
79
0.62578
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,690
latent.py
buildbot_buildbot/master/buildbot/test/fake/latent.py
# 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 annotations import enum from twisted.internet import defer from twisted.python.filepath import FilePath from twisted.trial.unittest import SkipTest from buildbot.test.fake.worker import SeverWorkerConnectionMixin from buildbot.test.fake.worker import disconnect_master_side_worker from buildbot.worker import AbstractLatentWorker RemoteWorker: type | None = None try: from buildbot_worker.bot import LocalWorker as RemoteWorker from buildbot_worker.pb import BotPbLike except ImportError: pass class States(enum.Enum): STOPPED = 0 STARTING = 1 STARTED = 2 STOPPING = 3 class LatentController(SeverWorkerConnectionMixin): """ A controller for ``ControllableLatentWorker``. https://glyph.twistedmatrix.com/2015/05/separate-your-fakes-and-your-inspectors.html Note that by default workers will connect automatically if True is passed to start_instance(). Also by default workers will disconnect automatically just as stop_instance() is executed. """ def __init__( self, case, name, kind=None, build_wait_timeout=600, starts_without_substantiate=None, **kwargs, ): self.case = case self.build_wait_timeout = build_wait_timeout self.has_crashed = False self.worker = ControllableLatentWorker(name, self, **kwargs) self.remote_worker = None if starts_without_substantiate is not None: self.worker.starts_without_substantiate = starts_without_substantiate self.state = States.STOPPED self.auto_stop_flag = False self.auto_start_flag = False self.auto_connect_worker = True self.auto_disconnect_worker = True self._start_deferred = None self._stop_deferred = None self.kind = kind self._started_kind = None self._started_kind_deferred = None @property def starting(self): return self.state == States.STARTING @property def started(self): return self.state == States.STARTED @property def stopping(self): return self.state == States.STOPPING @property def stopped(self): return self.state == States.STOPPED def auto_start(self, result): self.auto_start_flag = result if self.auto_start_flag and self.state == States.STARTING: self.start_instance(True) @defer.inlineCallbacks def start_instance(self, result): yield self.do_start_instance(result) d = self._start_deferred self._start_deferred = None d.callback(result) @defer.inlineCallbacks def do_start_instance(self, result): assert self.state == States.STARTING self.state = States.STARTED if self.auto_connect_worker and result is True: yield self.connect_worker() @defer.inlineCallbacks def auto_stop(self, result): self.auto_stop_flag = result if self.auto_stop_flag and self.state == States.STOPPING: yield self.stop_instance(True) @defer.inlineCallbacks def stop_instance(self, result): yield self.do_stop_instance() d = self._stop_deferred self._stop_deferred = None d.callback(result) @defer.inlineCallbacks def do_stop_instance(self): assert self.state == States.STOPPING self.state = States.STOPPED self._started_kind = None if self.auto_disconnect_worker: yield self.disconnect_worker() @defer.inlineCallbacks def connect_worker(self): if self.remote_worker is not None: return if RemoteWorker is None: raise SkipTest("buildbot-worker package is not installed") workdir = FilePath(self.case.mktemp()) workdir.createDirectory() self.remote_worker = RemoteWorker(self.worker.name, workdir.path, False) yield self.remote_worker.setServiceParent(self.worker) @defer.inlineCallbacks def disconnect_worker(self): yield super().disconnect_worker() if self.remote_worker is None: return self.remote_worker, worker = None, self.remote_worker disconnect_master_side_worker(self.worker) yield worker.disownServiceParent() def setup_kind(self, build): if build: self._started_kind_deferred = build.render(self.kind) else: self._started_kind_deferred = self.kind @defer.inlineCallbacks def get_started_kind(self): if self._started_kind_deferred: self._started_kind = yield self._started_kind_deferred self._started_kind_deferred = None return self._started_kind def patchBot(self, case, remoteMethod, patch): case.patch(BotPbLike, remoteMethod, patch) class ControllableLatentWorker(AbstractLatentWorker): """ A latent worker that can be controlled by tests. """ builds_may_be_incompatible = True def __init__(self, name, controller, **kwargs): self._controller = controller self._random_password_id = 0 AbstractLatentWorker.__init__(self, name, None, **kwargs) def checkConfig(self, name, _, **kwargs): AbstractLatentWorker.checkConfig( self, name, None, build_wait_timeout=self._controller.build_wait_timeout, **kwargs ) def reconfigService(self, name, _, **kwargs): return super().reconfigService( name, self.getRandomPass(), build_wait_timeout=self._controller.build_wait_timeout, **kwargs, ) def _generate_random_password(self): self._random_password_id += 1 return f'password_{self._random_password_id}' @defer.inlineCallbacks def isCompatibleWithBuild(self, build_props): if self._controller.state == States.STOPPED: return True requested_kind = yield build_props.render(self._controller.kind) curr_kind = yield self._controller.get_started_kind() return requested_kind == curr_kind def start_instance(self, build): self._controller.setup_kind(build) assert self._controller.state == States.STOPPED self._controller.state = States.STARTING if self._controller.auto_start_flag: self._controller.do_start_instance(True) return defer.succeed(True) self._controller._start_deferred = defer.Deferred() return self._controller._start_deferred @defer.inlineCallbacks def stop_instance(self, fast): assert self._controller.state == States.STARTED self._controller.state = States.STOPPING if self._controller.auto_stop_flag: yield self._controller.do_stop_instance() return True self._controller._stop_deferred = defer.Deferred() return (yield self._controller._stop_deferred) def check_instance(self): return (not self._controller.has_crashed, "")
7,758
Python
.py
195
32.415385
94
0.681086
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,691
private_tempdir.py
buildbot_buildbot/master/buildbot/test/fake/private_tempdir.py
# 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 class FakePrivateTemporaryDirectory: def __init__(self, suffix=None, prefix=None, dir=None, mode=0o700): dir = dir or '/' prefix = prefix or '' suffix = suffix or '' self.name = os.path.join(dir, prefix + '@@@' + suffix) self.mode = mode def __enter__(self): return self.name def __exit__(self, exc, value, tb): pass def cleanup(self): pass class MockPrivateTemporaryDirectory: def __init__(self): self.dirs = [] def __call__(self, *args, **kwargs): ret = FakePrivateTemporaryDirectory(*args, **kwargs) self.dirs.append((ret.name, ret.mode)) return ret
1,398
Python
.py
35
35.228571
79
0.692535
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,692
connection.py
buildbot_buildbot/master/buildbot/test/fake/connection.py
# 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.internet import defer class FakeConnection: is_fake_test_connection = True _waiting_for_interrupt = False def __init__(self, testcase, name, step, commands_numbers_to_interrupt): self.testcase = testcase self.name = name self.step = step self._commands_numbers_to_interrupt = commands_numbers_to_interrupt self._block_on_interrupt = False self._next_command_number = 0 self._blocked_deferreds = [] @defer.inlineCallbacks def remoteStartCommand(self, remote_command, builder_name, command_id, command_name, args): self._waiting_for_interrupt = False if self._next_command_number in self._commands_numbers_to_interrupt: self._waiting_for_interrupt = True yield self.step.interrupt('interrupt reason') if self._waiting_for_interrupt: raise RuntimeError("Interrupted step, but command was not interrupted") self._next_command_number += 1 yield self.testcase._connection_remote_start_command(remote_command, self, builder_name) # running behaviors may still attempt interrupt the command if self._waiting_for_interrupt: raise RuntimeError("Interrupted step, but command was not interrupted") def remoteInterruptCommand(self, builder_name, command_id, why): if not self._waiting_for_interrupt: raise RuntimeError("Got interrupt, but FakeConnection was not expecting it") self._waiting_for_interrupt = False if self._block_on_interrupt: d = defer.Deferred() self._blocked_deferreds.append(d) return d else: return defer.succeed(None) def set_expect_interrupt(self): if self._waiting_for_interrupt: raise RuntimeError("Already expecting interrupt but got additional request") self._waiting_for_interrupt = True def set_block_on_interrupt(self): self._block_on_interrupt = True def unblock_waiters(self): for d in self._blocked_deferreds: d.callback(None)
2,832
Python
.py
58
41.5
96
0.700979
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,693
web.py
buildbot_buildbot/master/buildbot/test/fake/web.py
# 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 io import BytesIO from unittest.mock import Mock from twisted.internet import defer from twisted.web import server from buildbot.test.fake import fakemaster @defer.inlineCallbacks def fakeMasterForHooks(testcase): # testcase must derive from TestReactorMixin and setup_test_reactor() # must be called before calling this function. master = yield fakemaster.make_master(testcase, wantData=True) master.www = Mock() return master class FakeRequest(Mock): """ A fake Twisted Web Request object, including some pointers to the buildmaster and an addChange method on that master which will append its arguments to self.addedChanges. """ written = b'' finished = False redirected_to = None failure = None def __init__(self, args=None, content=b''): super().__init__() if args is None: args = {} self.args = args self.content = BytesIO(content) self.site = Mock() self.site.buildbot_service = Mock() self.uri = b'/' self.prepath = [] self.method = b'GET' self.received_headers = {} self.deferred = defer.Deferred() def getHeader(self, key): return self.received_headers.get(key) def write(self, data): self.written = self.written + data def redirect(self, url): self.redirected_to = url def finish(self): self.finished = True self.deferred.callback(None) def processingFailed(self, f): self.deferred.errback(f) # work around http://code.google.com/p/mock/issues/detail?id=105 def _get_child_mock(self, **kw): return Mock(**kw) # cribed from twisted.web.test._util._render def test_render(self, resource): for arg in self.args: if not isinstance(arg, bytes): raise ValueError(f"self.args: {self.args!r}, contains values which are not bytes") if self.uri and not isinstance(self.uri, bytes): raise ValueError(f"self.uri: {self.uri!r} is {type(self.uri)}, not bytes") if self.method and not isinstance(self.method, bytes): raise ValueError(f"self.method: {self.method!r} is {type(self.method)}, not bytes") result = resource.render(self) if isinstance(result, bytes): self.write(result) self.finish() return self.deferred elif isinstance(result, str): raise ValueError( f"{resource.render!r} should return bytes, not {type(result)}: {result!r}" ) elif result is server.NOT_DONE_YET: return self.deferred else: raise ValueError(f"Unexpected return value: {result!r}")
3,459
Python
.py
85
33.917647
99
0.672337
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,694
docker.py
buildbot_buildbot/master/buildbot/test/fake/docker.py
# 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 __version__ = "4.0" class Client: latest = None containerCreated = False start_exception = None def __init__(self, base_url): self.base_url = base_url self.call_args_create_container = [] self.call_args_create_host_config = [] self._images = [{'RepoTags': ['busybox:latest', 'worker:latest', 'tester:latest']}] self._pullable = ['alpine:latest', 'tester:latest'] self._pullCount = 0 self._containers = {} if Client.containerCreated: self.create_container("some-default-image") def images(self): return self._images def start(self, container): if self.start_exception is not None: raise self.start_exception # pylint: disable=raising-bad-type def stop(self, id): pass def wait(self, id): return 0 def build(self, fileobj, tag, pull, target): if fileobj.read() == b'BUG': pass elif pull != bool(pull): pass elif target != "": pass else: logs = [] yield from logs self._images.append({'RepoTags': [tag + ':latest']}) def pull(self, image, *args, **kwargs): if image in self._pullable: self._pullCount += 1 self._images.append({'RepoTags': [image]}) def containers(self, filters=None, *args, **kwargs): if filters is not None: if 'existing' in filters.get('name', ''): self.create_container(image='busybox:latest', name="buildbot-existing-87de7e") self.create_container(image='busybox:latest', name="buildbot-existing-87de7ef") return [c for c in self._containers.values() if c['name'].startswith(filters['name'])] return self._containers.values() def create_host_config(self, *args, **kwargs): self.call_args_create_host_config.append(kwargs) def create_container(self, image, *args, **kwargs): self.call_args_create_container.append(kwargs) name = kwargs.get('name', None) if 'buggy' in image: raise RuntimeError('we could not create this container') for c in self._containers.values(): if c['name'] == name: raise RuntimeError('cannot create with same name') ret = { 'Id': '8a61192da2b3bb2d922875585e29b74ec0dc4e0117fcbf84c962204e97564cd7', 'Warnings': None, } self._containers[ret['Id']] = { 'started': False, 'image': image, 'Id': ret['Id'], 'name': name, # docker does not return this 'Names': ["/" + name], # this what docker returns "State": "running", } return ret def remove_container(self, id, **kwargs): del self._containers[id] def logs(self, id, tail=None): return f"log for {id}\n1\n2\n3\nend\n".encode() def close(self): # dummy close, no connection to cleanup pass class APIClient(Client): pass class errors: class APIError(Exception): pass
3,841
Python
.py
95
32.284211
98
0.619124
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,695
fakeprotocol.py
buildbot_buildbot/master/buildbot/test/fake/fakeprotocol.py
# 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 annotations from typing import Any from twisted.internet import defer from buildbot.worker.protocols import base class FakeTrivialConnection(base.Connection): info: dict[str, Any] = {} def __init__(self): super().__init__("Fake") def loseConnection(self): self.notifyDisconnected() def remoteSetBuilderList(self, builders): return defer.succeed(None) class FakeConnection(base.Connection): def __init__(self, worker): super().__init__(worker.workername) self._connected = True self.remoteCalls = [] self.builders = {} # { name : isBusy } # users of the fake can add to this as desired self.info = { 'worker_commands': [], 'version': '0.9.0', 'basedir': '/w', 'system': 'nt', } def loseConnection(self): self.notifyDisconnected() def remotePrint(self, message): self.remoteCalls.append(('remotePrint', message)) return defer.succeed(None) def remoteGetWorkerInfo(self): self.remoteCalls.append(('remoteGetWorkerInfo',)) return defer.succeed(self.info) def remoteSetBuilderList(self, builders): self.remoteCalls.append(('remoteSetBuilderList', builders[:])) self.builders = dict((b, False) for b in builders) return defer.succeed(None) def remoteStartCommand(self, remoteCommand, builderName, commandId, commandName, args): self.remoteCalls.append(( 'remoteStartCommand', remoteCommand, builderName, commandId, commandName, args, )) return defer.succeed(None) def remoteShutdown(self): self.remoteCalls.append(('remoteShutdown',)) return defer.succeed(None) def remoteStartBuild(self, builderName): self.remoteCalls.append(('remoteStartBuild', builderName)) return defer.succeed(None) def remoteInterruptCommand(self, builderName, commandId, why): self.remoteCalls.append(('remoteInterruptCommand', builderName, commandId, why)) return defer.succeed(None) def get_peer(self): if self._connected: return "fake_peer" return None
2,994
Python
.py
74
33.513514
91
0.678621
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,696
test_bad_change_properties_rows.py
buildbot_buildbot/master/buildbot/test/regressions/test_bad_change_properties_rows.py
# 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.internet import defer from twisted.trial import unittest from buildbot.db import changes from buildbot.test import fakedb from buildbot.test.util import connector_component class TestBadRows(connector_component.ConnectorComponentMixin, unittest.TestCase): # See bug #1952 for details. This checks that users who used a development # version between 0.8.3 and 0.8.4 get reasonable behavior even though some # rows in the change_properties database do not contain a proper [value, # source] tuple. @defer.inlineCallbacks def setUp(self): yield self.setUpConnectorComponent( table_names=['patches', 'sourcestamps', 'changes', 'change_properties', 'change_files'] ) self.db.changes = changes.ChangesConnectorComponent(self.db) def tearDown(self): return self.tearDownConnectorComponent() @defer.inlineCallbacks def test_bogus_row_no_source(self): yield self.insert_test_data([ fakedb.SourceStamp(id=10), fakedb.ChangeProperty(changeid=13, property_name='devel', property_value='"no source"'), fakedb.Change(changeid=13, sourcestampid=10), ]) c = yield self.db.changes.getChange(13) self.assertEqual(c.properties, {"devel": ('no source', 'Change')}) @defer.inlineCallbacks def test_bogus_row_jsoned_list(self): yield self.insert_test_data([ fakedb.SourceStamp(id=10), fakedb.ChangeProperty(changeid=13, property_name='devel', property_value='[1, 2]'), fakedb.Change(changeid=13, sourcestampid=10), ]) c = yield self.db.changes.getChange(13) self.assertEqual(c.properties, {"devel": ([1, 2], 'Change')})
2,455
Python
.py
50
43.34
100
0.720201
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,697
test_oldpaths.py
buildbot_buildbot/master/buildbot/test/regressions/test_oldpaths.py
# 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.warnings import DeprecatedApiWarning def deprecatedImport(fn): def wrapper(self): fn(self) warnings = self.flushWarnings() # on older Pythons, this warning appears twice, so use collapse it if len(warnings) == 2 and warnings[0] == warnings[1]: del warnings[1] self.assertEqual(len(warnings), 1, f"got: {warnings!r}") self.assertEqual(warnings[0]['category'], DeprecatedApiWarning) return wrapper class OldImportPaths(unittest.TestCase): """ Test that old, deprecated import paths still work. """ def test_scheduler_Scheduler(self): from buildbot.scheduler import Scheduler # noqa: F401 def test_schedulers_basic_Scheduler(self): # renamed to basic.SingleBranchScheduler from buildbot.schedulers.basic import Scheduler # noqa: F401 def test_scheduler_AnyBranchScheduler(self): from buildbot.scheduler import AnyBranchScheduler # noqa: F401 def test_scheduler_basic_Dependent(self): from buildbot.schedulers.basic import Dependent # noqa: F401 def test_scheduler_Dependent(self): from buildbot.scheduler import Dependent # noqa: F401 def test_scheduler_Periodic(self): from buildbot.scheduler import Periodic # noqa: F401 def test_scheduler_Nightly(self): from buildbot.scheduler import Nightly # noqa: F401 def test_scheduler_Triggerable(self): from buildbot.scheduler import Triggerable # noqa: F401 def test_scheduler_Try_Jobdir(self): from buildbot.scheduler import Try_Jobdir # noqa: F401 def test_scheduler_Try_Userpass(self): from buildbot.scheduler import Try_Userpass # noqa: F401 def test_schedulers_filter_ChangeFilter(self): # this was the location of ChangeFilter until 0.8.4 from buildbot.schedulers.filter import ChangeFilter # noqa: F401 def test_process_base_Build(self): from buildbot.process.base import Build # noqa: F401 def test_buildrequest_BuildRequest(self): from buildbot.buildrequest import BuildRequest # noqa: F401 def test_process_subunitlogobserver_SubunitShellCommand(self): from buildbot.process.subunitlogobserver import SubunitShellCommand # noqa: F401 def test_steps_source_Source(self): from buildbot.steps.source import Source # noqa: F401
3,144
Python
.py
62
44.887097
89
0.73815
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,698
test_steps_shell_WarningCountingShellCommand.py
buildbot_buildbot/master/buildbot/test/regressions/test_steps_shell_WarningCountingShellCommand.py
# 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.steps.shell import WarningCountingShellCommand class TestWarningCountingShellCommand(unittest.TestCase): # Makes sure that it is possible to suppress warnings even if the # warning extractor does not provide line information def testSuppressingLinelessWarningsPossible(self): # Use a warningExtractor that does not provide line # information w = WarningCountingShellCommand( warningExtractor=WarningCountingShellCommand.warnExtractWholeLine, command="echo" ) # Add suppression manually instead of using suppressionFile fileRe = None warnRe = ".*SUPPRESS.*" start = None end = None suppression = (fileRe, warnRe, start, end) w.addSuppression([suppression]) # Now call maybeAddWarning warnings = [] line = "this warning should be SUPPRESSed" match = re.match(".*warning.*", line) w.maybeAddWarning(warnings, line, match) # Finally make the suppressed warning was *not* added to the # list of warnings expectedWarnings = 0 self.assertEqual(len(warnings), expectedWarnings)
1,928
Python
.py
42
40.285714
93
0.732942
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,699
state.py
buildbot_buildbot/master/buildbot/test/util/state.py
# 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.internet import defer class StateTestMixin: @defer.inlineCallbacks def set_fake_state(self, object, name, value): objectid = yield self.master.db.state.getObjectId(object.name, object.__class__.__name__) yield self.master.db.state.setState(objectid, name, value) @defer.inlineCallbacks def assert_state(self, objectid, **kwargs): for k, v in kwargs.items(): value = yield self.master.db.state.getState(objectid, k) self.assertEqual(value, v, f"state for {k!r} is {v!r}") @defer.inlineCallbacks def assert_state_by_class(self, name, class_name, **kwargs): objectid = yield self.master.db.state.getObjectId(name, class_name) yield self.assert_state(objectid, **kwargs)
1,479
Python
.py
29
46.758621
97
0.73615
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)