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,300
steps.py
buildbot_buildbot/master/buildbot/test/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 import stat import tarfile from io import BytesIO from unittest import mock from twisted.internet import defer from twisted.python import log from twisted.python.reflect import namedModule from buildbot.process import buildstep from buildbot.process.results import EXCEPTION from buildbot.process.results import statusToString from buildbot.test.fake import connection from buildbot.test.fake import fakebuild from buildbot.test.fake import fakemaster from buildbot.test.fake import logfile from buildbot.test.fake import worker from buildbot.util import bytes2unicode from buildbot.util import runprocess from buildbot.util import unicode2bytes from buildbot.warnings import warn_deprecated def _dict_diff(d1, d2): """ Given two dictionaries describe their difference For nested dictionaries, key-paths are concatenated with the '.' operator @return The list of keys missing in d1, the list of keys missing in d2, and the differences in any nested keys """ d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) both = d1_keys & d2_keys missing_in_d1 = {} missing_in_d2 = {} different = [] for k in both: if isinstance(d1[k], dict) and isinstance(d2[k], dict): missing_in_v1, missing_in_v2, different_in_v = _dict_diff(d1[k], d2[k]) for sub_key in missing_in_v1: missing_in_d1[f'{k}.{sub_key}'] = d2[k][sub_key] for sub_key in missing_in_v2: missing_in_d2[f'{k}.{sub_key}'] = d1[k][sub_key] for child_k, left, right in different_in_v: different.append((f'{k}.{child_k}', left, right)) continue if d1[k] != d2[k]: different.append((k, d1[k], d2[k])) for k in d2_keys - both: missing_in_d1[k] = d2[k] for k in d1_keys - both: missing_in_d2[k] = d1[k] return missing_in_d1, missing_in_d2, different def _describe_cmd_difference(exp_command, exp_args, got_command, got_args): if exp_command != got_command: return f'Expected command type {exp_command} got {got_command}. Expected args {exp_args!r}' if exp_args == got_args: return "" text = "" missing_in_exp, missing_in_cmd, diff = _dict_diff(exp_args, got_args) if missing_in_exp: text += f'Keys in command missing from expectation: {missing_in_exp!r}\n' if missing_in_cmd: text += f'Keys in expectation missing from command: {missing_in_cmd!r}\n' if diff: formatted_diff = [f'"{d[0]}":\nexpected: {d[1]!r}\ngot: {d[2]!r}\n' for d in diff] text += 'Key differences between expectation and command: {}\n'.format( '\n'.join(formatted_diff) ) return text class ExpectRemoteRef: """ Define an expected RemoteReference in the args to an L{Expect} class """ def __init__(self, rrclass): self.rrclass = rrclass def __eq__(self, other): return isinstance(other, self.rrclass) class Expect: """ Define an expected L{RemoteCommand}, with the same arguments Extra behaviors of the remote command can be added to the instance, using class methods. Use L{Expect.log} to add a logfile, L{Expect.update} to add an arbitrary update, or add an integer to specify the return code (rc), or add a Failure instance to raise an exception. Additionally, use L{Expect.behavior}, passing a callable that will be invoked with the real command and can do what it likes: def custom_behavior(command): ... Expect('somecommand', { args='foo' }) + Expect.behavior(custom_behavior), ... Expect('somecommand', { args='foo' }) + Expect.log('stdio', stdout='foo!') + Expect.log('config.log', stdout='some info') + Expect.update('status', 'running').add(0), # (specifies the rc) ... """ def __init__(self, remote_command, args, interrupted=False): """ Expect a command named C{remote_command}, with args C{args}. """ self.remote_command = remote_command self.args = args self.result = None self.interrupted = interrupted self.connection_broken = False self.behaviors = [] def behavior(self, callable): self.behaviors.append(('callable', callable)) return self def error(self, error): self.behaviors.append(('err', error)) return self def log(self, name, **streams): self.behaviors.append(('log', name, streams)) return self def update(self, name, value): self.behaviors.append(('update', name, value)) return self def stdout(self, output): self.behaviors.append(('log', 'stdio', {'stdout': output})) return self def stderr(self, output): self.behaviors.append(('log', 'stdio', {'stderr': output})) return self def exit(self, code): self.behaviors.append(('rc', code)) return self def break_connection(self): self.connection_broken = True return self @defer.inlineCallbacks def runBehavior(self, behavior, args, command): """ Implement the given behavior. Returns a Deferred. """ if behavior == 'rc': yield command.remoteUpdate('rc', args[0], False) elif behavior == 'err': raise args[0] elif behavior == 'update': yield command.remoteUpdate(args[0], args[1], False) elif behavior == 'log': name, streams = args for stream in streams: if stream not in ['header', 'stdout', 'stderr']: raise RuntimeError(f'Log stream {stream} is not recognized') if name == command.stdioLogName: if 'header' in streams: command.remote_update([({"header": streams['header']}, 0)]) if 'stdout' in streams: command.remote_update([({"stdout": streams['stdout']}, 0)]) if 'stderr' in streams: command.remote_update([({"stderr": streams['stderr']}, 0)]) else: if 'header' in streams or 'stderr' in streams: raise RuntimeError('Non stdio streams only support stdout') yield command.addToLog(name, streams['stdout']) if name not in command.logs: raise RuntimeError(f"{command}.addToLog: no such log {name}") elif behavior == 'callable': yield args[0](command) else: raise AssertionError(f'invalid behavior {behavior}') return None @defer.inlineCallbacks def runBehaviors(self, command): """ Run all expected behaviors for this command """ for behavior in self.behaviors: yield self.runBehavior(behavior[0], behavior[1:], command) def _cleanup_args(self, args): # we temporarily disable checking of sigtermTime and interruptSignal due to currently # ongoing changes to how step testing works. Once all tests are updated for stricter # checking this will be removed. args = args.copy() args.pop('sigtermTime', None) args.pop('interruptSignal', None) args.pop('usePTY', None) env = args.pop('env', None) if env is None: env = {} args['env'] = env return args def _check(self, case, command): case.assertEqual(self.interrupted, command.interrupted) if command.remote_command == self.remote_command and self._cleanup_args( command.args ) == self._cleanup_args(self.args): return cmd_dif = _describe_cmd_difference( self.remote_command, self.args, command.remote_command, command.args ) msg = ( "Command contents different from expected (command index: " f"{case._expected_commands_popped}):\n{cmd_dif}" ) raise AssertionError(msg) def __repr__(self): return "Expect(" + repr(self.remote_command) + ")" class ExpectShell(Expect): """ Define an expected L{RemoteShellCommand}, with the same arguments Any non-default arguments must be specified explicitly (e.g., usePTY). """ class NotSet: pass def __init__( self, workdir, command, env=NotSet, want_stdout=1, want_stderr=1, initial_stdin=None, timeout=20 * 60, max_time=None, max_lines=None, sigterm_time=None, logfiles=None, use_pty=False, log_environ=True, interrupt_signal='KILL', ): if env is self.NotSet: env = {} if logfiles is None: logfiles = {} args = { 'workdir': workdir, 'command': command, 'env': env, 'want_stdout': want_stdout, 'want_stderr': want_stderr, 'initial_stdin': initial_stdin, 'timeout': timeout, 'maxTime': max_time, 'max_lines': max_lines, 'logfiles': logfiles, 'usePTY': use_pty, 'logEnviron': log_environ, } if sigterm_time is not self.NotSet: args['sigtermTime'] = sigterm_time if interrupt_signal is not None: args['interruptSignal'] = interrupt_signal super().__init__("shell", args) def __repr__(self): return "ExpectShell(" + repr(self.remote_command) + repr(self.args['command']) + ")" class ExpectStat(Expect): def __init__(self, file, workdir=None, log_environ=None): args = {'file': file} if workdir is not None: args['workdir'] = workdir if log_environ is not None: args['logEnviron'] = log_environ super().__init__('stat', args) def stat( self, mode, inode=99, dev=99, nlink=1, uid=0, gid=0, size=99, atime=0, mtime=0, ctime=0 ): self.update('stat', [mode, inode, dev, nlink, uid, gid, size, atime, mtime, ctime]) return self def stat_file(self, mode=0, size=99, atime=0, mtime=0, ctime=0): self.stat(stat.S_IFREG, size=size, atime=atime, mtime=mtime, ctime=ctime) return self def stat_dir(self, mode=0, size=99, atime=0, mtime=0, ctime=0): self.stat(stat.S_IFDIR, size=size, atime=atime, mtime=mtime, ctime=ctime) return self def __repr__(self): return "ExpectStat(" + repr(self.args['file']) + ")" class ExpectUploadFile(Expect): def __init__( self, blocksize=None, maxsize=None, workersrc=None, workdir=None, writer=None, keepstamp=None, slavesrc=None, interrupted=False, ): args = {'workdir': workdir, 'writer': writer, 'blocksize': blocksize, 'maxsize': maxsize} if keepstamp is not None: args['keepstamp'] = keepstamp if slavesrc is not None: args['slavesrc'] = slavesrc if workersrc is not None: args['workersrc'] = workersrc super().__init__('uploadFile', args, interrupted=interrupted) def upload_string(self, string, timestamp=None, out_writers=None, error=None): def behavior(command): writer = command.args['writer'] if out_writers is not None: out_writers.append(writer) writer.remote_write(string) writer.remote_close() if timestamp: writer.remote_utime(timestamp) if error is not None: writer.cancel = mock.Mock(wraps=writer.cancel) raise error self.behavior(behavior) return self def __repr__(self): return f"ExpectUploadFile({self.args['workdir']!r},{self.args['workersrc']!r})" class ExpectUploadDirectory(Expect): def __init__( self, compress=None, blocksize=None, maxsize=None, workersrc=None, workdir=None, writer=None, keepstamp=None, slavesrc=None, interrupted=False, ): args = { 'compress': compress, 'workdir': workdir, 'writer': writer, 'blocksize': blocksize, 'maxsize': maxsize, } if keepstamp is not None: args['keepstamp'] = keepstamp if slavesrc is not None: args['slavesrc'] = slavesrc if workersrc is not None: args['workersrc'] = workersrc super().__init__('uploadDirectory', args, interrupted=interrupted) def upload_tar_file(self, filename, members, error=None, out_writers=None): def behavior(command): f = BytesIO() archive = tarfile.TarFile(fileobj=f, name=filename, mode='w') for name, content in members.items(): content = unicode2bytes(content) archive.addfile(tarfile.TarInfo(name), BytesIO(content)) writer = command.args['writer'] if out_writers is not None: out_writers.append(writer) writer.remote_write(f.getvalue()) writer.remote_unpack() if error is not None: writer.cancel = mock.Mock(wraps=writer.cancel) raise error self.behavior(behavior) return self def __repr__(self): return f"ExpectUploadDirectory({self.args['workdir']!r}, " f"{self.args['workersrc']!r})" class ExpectDownloadFile(Expect): def __init__( self, blocksize=None, maxsize=None, workerdest=None, workdir=None, reader=None, mode=None, interrupted=False, slavesrc=None, slavedest=None, ): args = { 'workdir': workdir, 'reader': reader, 'mode': mode, 'blocksize': blocksize, 'maxsize': maxsize, } if slavesrc is not None: args['slavesrc'] = slavesrc if slavedest is not None: args['slavedest'] = slavedest if workerdest is not None: args['workerdest'] = workerdest super().__init__('downloadFile', args, interrupted=interrupted) def download_string(self, dest_callable, size=1000, timestamp=None): def behavior(command): reader = command.args['reader'] read = reader.remote_read(size) dest_callable(read) reader.remote_close() if timestamp: reader.remote_utime(timestamp) return read self.behavior(behavior) return self def __repr__(self): return f"ExpectUploadDirectory({self.args['workdir']!r}, " f"{self.args['workerdest']!r})" class ExpectMkdir(Expect): def __init__(self, dir=None, log_environ=None): args = {'dir': dir} if log_environ is not None: args['logEnviron'] = log_environ super().__init__('mkdir', args) def __repr__(self): return f"ExpectMkdir({self.args['dir']!r})" class ExpectRmdir(Expect): def __init__(self, dir=None, log_environ=None, timeout=None, path=None): args = {'dir': dir} if log_environ is not None: args['logEnviron'] = log_environ if timeout is not None: args['timeout'] = timeout if path is not None: args['path'] = path super().__init__('rmdir', args) def __repr__(self): return f"ExpectRmdir({self.args['dir']!r})" class ExpectCpdir(Expect): def __init__(self, fromdir=None, todir=None, log_environ=None, timeout=None, max_time=None): args = {'fromdir': fromdir, 'todir': todir} if log_environ is not None: args['logEnviron'] = log_environ if timeout is not None: args['timeout'] = timeout if max_time is not None: args['maxTime'] = max_time super().__init__('cpdir', args) def __repr__(self): return f"ExpectCpdir({self.args['fromdir']!r}, {self.args['todir']!r})" class ExpectGlob(Expect): def __init__(self, path=None, log_environ=None): args = {'path': path} if log_environ is not None: args['logEnviron'] = log_environ super().__init__('glob', args) def files(self, files=None): if files is None: files = [] self.update('files', files) return self def __repr__(self): return f"ExpectGlob({self.args['path']!r})" class ExpectListdir(Expect): def __init__(self, dir=None): args = {'dir': dir} super().__init__('listdir', args) def files(self, files=None): if files is None: files = [] self.update('files', files) return self def __repr__(self): return f"ExpectListdir({self.args['dir']!r})" class ExpectRmfile(Expect): def __init__(self, path=None, log_environ=None): args = {'path': path} if log_environ is not None: args['logEnviron'] = log_environ super().__init__('rmfile', args) def __repr__(self): return f"ExpectRmfile({self.args['path']!r})" def _check_env_is_expected(test, expected_env, env): if expected_env is None: return env = env or {} for var, value in expected_env.items(): test.assertEqual(env.get(var), value, f'Expected environment to have {var} = {value!r}') class ExpectMasterShell: _stdout = b"" _stderr = b"" _exit = 0 _workdir = None _env = None def __init__(self, command): self._command = command def stdout(self, stdout): assert isinstance(stdout, bytes) self._stdout = stdout return self def stderr(self, stderr): assert isinstance(stderr, bytes) self._stderr = stderr return self def exit(self, exit): self._exit = exit return self def workdir(self, workdir): self._workdir = workdir return self def env(self, env): self._env = env return self def _check(self, test, command, workdir, env): test.assertDictEqual( {'command': command, 'workdir': workdir}, {'command': self._command, 'workdir': self._workdir}, "unexpected command run", ) _check_env_is_expected(test, self._env, env) return (self._exit, self._stdout, self._stderr) def __repr__(self): return f"<ExpectMasterShell(command={self._command})>" class FakeRunProcess: def __init__(self, start_retval, result_rc): self.start_retval = start_retval self.result_rc = result_rc self.result_signal = None def start(self): return defer.succeed(self.start_retval) def interrupt(self, signal_name): pass class TestBuildStepMixin: """ @ivar build: the fake build containing the step @ivar progress: mock progress object @ivar worker: mock worker object @ivar properties: build properties (L{Properties} instance) """ @defer.inlineCallbacks def setup_test_build_step( self, want_data=True, want_db=False, want_mq=False, with_secrets: dict | None = None, ): if not hasattr(self, 'reactor'): raise RuntimeError('Reactor has not yet been setup for step') self._interrupt_remote_command_numbers: list[int] = [] self._expected_commands: list[Expect] = [] self._expected_commands_popped = 0 self.master = yield fakemaster.make_master( self, wantData=want_data, wantDb=want_db, wantMq=want_mq, with_secrets=with_secrets, ) self.patch(runprocess, "create_process", self._patched_create_process) # type: ignore[attr-defined] self._master_run_process_expect_env: dict[str, str] = {} self._worker_version = None self._worker_env = None self._build_files = None self.worker = worker.FakeWorker(self.master) self.worker.attached(None) self._steps: list[buildstep.BuildStep] = [] self.build = None # expectations self._exp_results: list[tuple[int, str | None]] = [] self.exp_properties: dict[str, tuple[object, str | None]] = {} self.exp_missing_properties: list[str] = [] self._exp_logfiles: dict[int, dict[str, bytes]] = {} self._exp_logfiles_stderr: dict[int, dict[str, bytes]] = {} self.exp_hidden = False self.exp_exception = None self._exp_test_result_sets: list[tuple[str, str, str]] = [] self._exp_test_results: list[tuple[int, object, str, str, int, int]] = [] self._exp_build_data: dict[str, tuple[object, str]] = {} self._exp_result_summaries: list[str] = [] self._exp_build_result_summaries: list[str] = [] def tear_down_test_build_step(self): pass def _setup_fake_build(self, worker_version, worker_env, build_files): if worker_version is None: worker_version = {'*': '99.99'} if worker_env is None: worker_env = {} if build_files is None: build_files = [] build = fakebuild.FakeBuild(master=self.master) build.allFiles = lambda: build_files build.master = self.master def getWorkerVersion(cmd, oldversion): if cmd in worker_version: return worker_version[cmd] if '*' in worker_version: return worker_version['*'] return oldversion build.getWorkerCommandVersion = getWorkerVersion build.workerEnvironment = worker_env.copy() build.builder.config.env = worker_env.copy() return build def setup_build(self, worker_version=None, worker_env=None, build_files=None): self._worker_version = worker_version self._worker_env = worker_env self._build_files = build_files def setup_step( self, step, worker_version=None, worker_env=None, build_files=None, want_default_work_dir=True, ): if worker_version is not None: warn_deprecated( "4.1.0", "worker_version has been deprecated, use setup_build() to pass this information", ) if worker_env is not None: warn_deprecated( "4.1.0", "worker_env has been deprecated, use setup_build() to pass this information", ) if build_files is not None: warn_deprecated( "4.1.0", "build_files has been deprecated, use setup_build() to pass this information", ) if worker_version is not None or worker_env is not None or build_files is not None: self.setup_build( worker_version=worker_version, worker_env=worker_env, build_files=build_files ) step = buildstep.create_step_from_step_or_factory(step) # set defaults if want_default_work_dir: step.workdir = step._workdir or 'wkdir' if self.build is None: self.build = self._setup_fake_build( self._worker_version, self._worker_env, self._build_files ) step.setBuild(self.build) step.progress = mock.Mock(name="progress") step.worker = self.worker # step overrides def addLog(name, type='s', logEncoding=None): _log = logfile.FakeLogFile(name) step.logs[name] = _log step._connectPendingLogObservers() return defer.succeed(_log) step.addLog = addLog def addHTMLLog(name, html): _log = logfile.FakeLogFile(name) html = bytes2unicode(html) _log.addStdout(html) return defer.succeed(None) step.addHTMLLog = addHTMLLog def addCompleteLog(name, text): _log = logfile.FakeLogFile(name) if name in step.logs: raise RuntimeError(f'Attempt to add log {name} twice to the logs') step.logs[name] = _log _log.addStdout(text) return defer.succeed(None) step.addCompleteLog = addCompleteLog self._got_test_result_sets = [] self._next_test_result_set_id = 1000 def add_test_result_set(description, category, value_unit): self._got_test_result_sets.append((description, category, value_unit)) setid = self._next_test_result_set_id self._next_test_result_set_id += 1 return defer.succeed(setid) step.addTestResultSet = add_test_result_set self._got_test_results = [] def add_test_result( setid, value, test_name=None, test_code_path=None, line=None, duration_ns=None ): self._got_test_results.append(( setid, value, test_name, test_code_path, line, duration_ns, )) step.addTestResult = add_test_result self._got_build_data = {} def set_build_data(name, value, source): self._got_build_data[name] = (value, source) return defer.succeed(None) step.setBuildData = set_build_data # check that the step's name is not None self.assertNotEqual(step.name, None) self._steps.append(step) return step @property def step(self): warn_deprecated( "4.1.0", "step attribute has been deprecated, use get_nth_step(0) as a replacement", ) return self.get_nth_step(0) def get_nth_step(self, index): return self._steps[index] def expect_commands(self, *exp): self._expected_commands.extend(exp) def expect_outcome(self, result, state_string=None): self._exp_results.append((result, state_string)) def expect_property(self, property, value, source=None): self.exp_properties[property] = (value, source) def expect_no_property(self, property): self.exp_missing_properties.append(property) def expect_log_file(self, logfile, contents, step_index=0): self._exp_logfiles.setdefault(step_index, {})[logfile] = contents def expect_log_file_stderr(self, logfile, contents, step_index=0): self._exp_logfiles_stderr.setdefault(step_index, {})[logfile] = contents def expect_build_data(self, name, value, source): self._exp_build_data[name] = (value, source) def expect_hidden(self, hidden=True): self.exp_hidden = hidden def expect_exception(self, exception_class): self.exp_exception = exception_class self.expect_outcome(EXCEPTION) def expect_test_result_sets(self, sets): self._exp_test_result_sets = sets def expect_test_results(self, results): self._exp_test_results = results def expect_result_summary(self, *summaries): self._exp_result_summaries.extend(summaries) def expect_build_result_summary(self, *summaries): self._exp_build_result_summaries.extend(summaries) def add_run_process_expect_env(self, d): self._master_run_process_expect_env.update(d) def _dump_logs(self, step): for l in step.logs.values(): if l.stdout: log.msg(f"{l.name} stdout:\n{l.stdout}") if l.stderr: log.msg(f"{l.name} stderr:\n{l.stderr}") @defer.inlineCallbacks def run_step(self): """ Run the step set up with L{setup_step}, and check the results. @returns: Deferred """ for step_i, step in enumerate(self._steps): self.conn = connection.FakeConnection( self, "WorkerForBuilder(connection)", step, self._interrupt_remote_command_numbers ) step.setupProgress() result = yield step.startStep(self.conn) # finish up the debounced updateSummary before checking self.reactor.advance(1) exp_result, exp_state_string = self._exp_results.pop(0) # in case of unexpected result, display logs in stdout for # debugging failing tests if result != exp_result: msg = ( "unexpected result from step; " f"expected {exp_result} ({statusToString(exp_result)}), " f"got {result} ({statusToString(result)})" ) log.msg(f"{msg}; dumping logs") self._dump_logs(step) raise AssertionError(f"{msg}; see logs") if exp_state_string: stepStateString = self.master.data.updates.stepStateString stepids = list(stepStateString) assert stepids, "no step state strings were set" self.assertEqual( exp_state_string, stepStateString[stepids[0]], f"expected state_string {exp_state_string!r}, got " f"{stepStateString[stepids[0]]!r}", ) if self._exp_result_summaries and (exp_summary := self._exp_result_summaries.pop(0)): step_result_summary = yield step.getResultSummary() self.assertEqual(exp_summary, step_result_summary) if self._exp_build_result_summaries and ( exp_build_summary := self._exp_build_result_summaries.pop(0) ): step_build_result_summary = yield step.getBuildResultSummary() self.assertEqual(exp_build_summary, step_build_result_summary) properties = self.build.getProperties() for pn, (pv, ps) in self.exp_properties.items(): self.assertTrue(properties.hasProperty(pn), f"missing property '{pn}'") self.assertEqual(properties.getProperty(pn), pv, f"property '{pn}'") if ps is not None: self.assertEqual( properties.getPropertySource(pn), ps, f"property {pn!r} source has source {properties.getPropertySource(pn)!r}", ) for pn in self.exp_missing_properties: self.assertFalse(properties.hasProperty(pn), f"unexpected property '{pn}'") if step_i in self._exp_logfiles: for l, exp in self._exp_logfiles[step_i].items(): got = step.logs[l].stdout self._match_log(exp, got, 'stdout') if step_i in self._exp_logfiles_stderr: for l, exp in self._exp_logfiles_stderr[step_i].items(): got = step.logs[l].stderr self._match_log(exp, got, 'stderr') if self._expected_commands: log.msg("un-executed remote commands:") for rc in self._expected_commands: log.msg(repr(rc)) raise AssertionError("un-executed remote commands; see logs") if self.exp_exception: self.assertEqual(len(self.flushLoggedErrors(self.exp_exception)), 1) self.assertEqual(self._exp_test_result_sets, self._got_test_result_sets) self.assertEqual(self._exp_test_results, self._got_test_results) self.assertEqual(self._exp_build_data, self._got_build_data) # XXX TODO: hidden # self.step_status.setHidden.assert_called_once_with(self.exp_hidden) def _match_log(self, exp, got, log_type): if hasattr(exp, 'match'): if exp.match(got) is None: log.msg(f"Unexpected {log_type} log output:\n{exp}") log.msg(f"Expected {log_type} to match:\n{got}") raise AssertionError(f"Unexpected {log_type} log output; see logs") else: if got != exp: log.msg(f"Unexpected {log_type} log output:\n{exp}") log.msg(f"Expected {log_type} log output:\n{got}") raise AssertionError(f"Unexpected {log_type} log output; see logs") # callbacks from the running step @defer.inlineCallbacks def _connection_remote_start_command(self, command, conn, builder_name): self.assertEqual(conn, self.conn) exp = None if self._expected_commands: exp = self._expected_commands.pop(0) self._expected_commands_popped += 1 else: self.fail( f"got remote command {command.remote_command} {command.args!r} when no " "further commands were expected" ) if not isinstance(exp, Expect): self.fail( f"got command {command.remote_command} {command.args!r} but the " f"expectation is not instance of Expect: {exp!r}" ) try: exp._check(self, command) yield exp.runBehaviors(command) except AssertionError as e: # log this error, as the step may swallow the AssertionError or # otherwise obscure the failure. Trial will see the exception in # the log and print an [ERROR]. This may result in # double-reporting, but that's better than non-reporting! log.err() raise e if not exp.connection_broken: command.remote_complete() def _patched_create_process( self, reactor, command, workdir=None, env=None, collect_stdout=True, collect_stderr=True, stderr_is_error=False, io_timeout=300, runtime_timeout=3600, sigterm_timeout=5, initial_stdin=None, use_pty=False, ): _check_env_is_expected(self, self._master_run_process_expect_env, env) exp = None if self._expected_commands: exp = self._expected_commands.pop(0) self._expected_commands_popped += 1 else: self.fail( f"got master command {command!r} at {workdir} ({env!r}) when no " "further commands were expected" ) if not isinstance(exp, ExpectMasterShell): self.fail( f"got command {command!r} at {workdir} ({env!r}) but the " f"expectation is not instance of ExpectMasterShell: {exp!r}" ) try: rc, stdout, stderr = exp._check(self, command, workdir, env) result_rc = rc except AssertionError as e: # log this error, as the step may swallow the AssertionError or # otherwise obscure the failure. Trial will see the exception in # the log and print an [ERROR]. This may result in # double-reporting, but that's better than non-reporting! log.err() raise e if stderr_is_error and stderr: rc = -1 return_stdout = None if collect_stdout is True: return_stdout = stdout elif callable(collect_stdout): collect_stdout(stdout) return_stderr = None if collect_stderr is True: return_stderr = stderr elif callable(collect_stderr): collect_stderr(stderr) if return_stdout is not None and return_stderr is not None: start_retval = (rc, return_stdout, return_stderr) elif return_stdout is not None: start_retval = (rc, return_stdout) elif return_stderr is not None: start_retval = (rc, return_stderr) else: start_retval = rc return FakeRunProcess(start_retval, result_rc) def change_worker_system(self, system): self.worker.worker_system = system if system in ['nt', 'win32']: self.build.path_module = namedModule('ntpath') self.worker.worker_basedir = '\\wrk' else: self.build.path_module = namedModule('posixpath') self.worker.worker_basedir = '/wrk' def interrupt_nth_remote_command(self, number): self._interrupt_remote_command_numbers.append(number)
37,283
Python
.py
915
30.736612
108
0.592851
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,301
__init__.py
buildbot_buildbot/master/buildbot/test/__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 import warnings from unittest import mock import setuptools # force import setuptools before any other distutils imports from buildbot import monkeypatches from buildbot.test.util.warnings import assertProducesWarning # noqa: F401 from buildbot.test.util.warnings import assertProducesWarnings # noqa: F401 from buildbot.warnings import DeprecatedApiWarning # noqa: F401 _ = mock # apply the same patches the buildmaster does when it starts monkeypatches.patch_all() # enable deprecation warnings warnings.filterwarnings('always', category=DeprecationWarning) _ = setuptools # force use for pylint # This is where we load deprecated module-level APIs to ignore warning produced by importing them. # After the deprecated API has been removed, leave at least one instance of the import in a # commented state as reference. # with assertProducesWarnings(DeprecatedApiWarning, # messages_patterns=[ # r" buildbot\.status\.base has been deprecated", # ]): # import buildbot.status.base as _ # All deprecated modules should be loaded, consider future warnings in tests as errors. # In order to not pollute the test outputs, # warnings in tests shall be forcefully tested with assertProducesWarning, # or shutdown using the warning module warnings.filterwarnings('error') # if buildbot_worker is installed in pip install -e mode, then the docker directory will # match "import docker", and produce a warning. # We just suppress this warning instead of doing silly workaround. warnings.filterwarnings( 'ignore', "Not importing directory.*docker': missing __init__.py", category=ImportWarning ) # autobahn is not updated for Twisted 22.04 and newer warnings.filterwarnings( "ignore", "twisted.web.resource.NoResource was deprecated in", category=DeprecationWarning ) # When using Python 3.12, this generates some dependent package warnings.filterwarnings( 'ignore', r"datetime.datetime.utcnow\(\) is deprecated and scheduled for " r"removal in a future version. Use timezone-aware objects to represent " r"datetimes in UTC: datetime.datetime.now\(datetime.UTC\).", category=DeprecationWarning, ) # Python3.12 generates deprecation warnings like: # "This process (pid=6558) is multi-threaded, use of fork() may lead to deadlocks in the child." # Tracked in https://github.com/buildbot/buildbot/issues/7276 warnings.filterwarnings( "ignore", r"This process \(pid=\d+\) is multi-threaded, use of fork\(\) may lead " r"to deadlocks in the child\.", category=DeprecationWarning, ) # Warnings comes from attr 24.1.0 because of automat warnings.filterwarnings( "ignore", r"The `hash` argument is deprecated in favor of `unsafe_hash` " r"and will be removed in or after August 2025\.", category=DeprecationWarning, ) warnings.filterwarnings( "ignore", r"twisted.web.resource._UnsafeErrorPage.__init__ was deprecated in " r"Twisted 22.10.0; please use Use twisted.web.pages.errorPage instead, " r"which properly escapes HTML. instead", category=DeprecationWarning, ) warnings.filterwarnings( "ignore", r"twisted.web.resource._UnsafeNoResource.__init__ was deprecated in " r"Twisted 22.10.0; please use Use twisted.web.pages.notFound instead, " r"which properly escapes HTML. instead", category=DeprecationWarning, ) warnings.filterwarnings( "ignore", r"twisted.web.resource._UnsafeForbiddenResource.__init__ was deprecated in " r"Twisted 22.10.0; please use Use twisted.web.pages.forbidden instead, " r"which properly escapes HTML. instead", category=DeprecationWarning, )
4,394
Python
.py
95
43.810526
98
0.762494
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,302
reactor.py
buildbot_buildbot/master/buildbot/test/reactor.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 from twisted.internet import defer from twisted.internet import threads from twisted.python import threadpool from buildbot.asyncio import AsyncIOLoopWithTwisted from buildbot.test.fake.reactor import NonThreadPool from buildbot.test.fake.reactor import TestReactor from buildbot.util.eventual import _setReactor class TestReactorMixin: """ Mix this in to get TestReactor as self.reactor which is correctly cleaned up at the end """ def setup_test_reactor(self, use_asyncio=False, auto_tear_down=True): self.patch(threadpool, 'ThreadPool', NonThreadPool) self.reactor = TestReactor() self.reactor.set_test_case(self) _setReactor(self.reactor) def deferToThread(f, *args, **kwargs): return threads.deferToThreadPool( self.reactor, self.reactor.getThreadPool(), f, *args, **kwargs ) self.patch(threads, 'deferToThread', deferToThread) self._reactor_use_asyncio = use_asyncio if use_asyncio: self.asyncio_loop = AsyncIOLoopWithTwisted(self.reactor) asyncio.set_event_loop(self.asyncio_loop) self.asyncio_loop.start() if auto_tear_down: self.addCleanup(self.tear_down_test_reactor) self._reactor_tear_down_called = False def tear_down_test_reactor(self): if self._reactor_tear_down_called: return self._reactor_tear_down_called = True if self._reactor_use_asyncio: self.asyncio_loop.stop() self.asyncio_loop.close() asyncio.set_event_loop(None) # During shutdown sequence we must first stop the reactor and only then set unset the # reactor used for eventually() because any callbacks that are run during reactor.stop() # may use eventually() themselves. self.reactor.stop() self.reactor.assert_no_remaining_calls() _setReactor(None) return defer.succeed(None)
2,713
Python
.py
60
38.616667
96
0.712931
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,303
runprocess.py
buildbot_buildbot/master/buildbot/test/runprocess.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.test.steps import ExpectMasterShell from buildbot.test.steps import _check_env_is_expected from buildbot.util import runprocess class MasterRunProcessMixin: long_message = True def setup_master_run_process(self): self._master_run_process_patched = False self._expected_master_commands = [] self._master_run_process_expect_env = {} def assert_all_commands_ran(self): self.assertEqual( self._expected_master_commands, [], "assert all expected commands were run" ) def patched_run_process( self, reactor, command, workdir=None, env=None, collect_stdout=True, collect_stderr=True, stderr_is_error=False, io_timeout=300, runtime_timeout=3600, sigterm_timeout=5, initial_stdin=None, use_pty=False, ) -> defer.Deferred: _check_env_is_expected(self, self._master_run_process_expect_env, env) if not self._expected_master_commands: self.fail(f"got command {command} when no further commands were expected") # type: ignore[attr-defined] expect = self._expected_master_commands.pop(0) rc, stdout, stderr = expect._check(self, command, workdir, env) if not collect_stderr and stderr_is_error and stderr: rc = -1 if collect_stdout and collect_stderr: return defer.succeed((rc, stdout, stderr)) if collect_stdout: return defer.succeed((rc, stdout)) if collect_stderr: return defer.succeed((rc, stderr)) return defer.succeed(rc) def _patch_runprocess(self): if not self._master_run_process_patched: self.patch(runprocess, "run_process", self.patched_run_process) self._master_run_process_patched = True def add_run_process_expect_env(self, d): self._master_run_process_expect_env.update(d) def expect_commands(self, *exp): for e in exp: if not isinstance(e, ExpectMasterShell): raise RuntimeError('All expectation must be an instance of ExpectMasterShell') self._patch_runprocess() self._expected_master_commands.extend(exp)
3,028
Python
.py
70
36.142857
116
0.685588
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,304
test_extra_coverage.py
buildbot_buildbot/master/buildbot/test/test_extra_coverage.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 file imports a number of source files that are not # included in the coverage because none of the tests import # them; this results in a more accurate total coverage percent. from buildbot import worker from buildbot.changes import p4poller from buildbot.changes import svnpoller from buildbot.clients import sendchange from buildbot.clients import tryclient from buildbot.process import subunitlogobserver from buildbot.scripts import checkconfig from buildbot.scripts import logwatcher from buildbot.scripts import reconfig from buildbot.scripts import runner from buildbot.steps import master from buildbot.steps import maxq from buildbot.steps import python from buildbot.steps import python_twisted from buildbot.steps import subunit from buildbot.steps import trigger from buildbot.steps import vstudio from buildbot.steps.package.rpm import rpmbuild from buildbot.steps.package.rpm import rpmlint from buildbot.util import eventual modules = [] # for the benefit of pyflakes modules.extend([worker]) modules.extend([p4poller, svnpoller]) modules.extend([sendchange, tryclient]) modules.extend([subunitlogobserver]) modules.extend([checkconfig, logwatcher, reconfig, runner]) modules.extend([master, maxq, python, python_twisted, subunit]) modules.extend([trigger, vstudio]) modules.extend([rpmbuild, rpmlint]) modules.extend([eventual])
2,061
Python
.py
47
42.765957
79
0.827363
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,305
test_clients_sendchange.py
buildbot_buildbot/master/buildbot/test/unit/test_clients_sendchange.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 unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.spread import pb from twisted.trial import unittest from buildbot.clients import sendchange class Sender(unittest.TestCase): def setUp(self): # patch out some PB components and make up some mocks self.patch(pb, 'PBClientFactory', self._fake_PBClientFactory) self.patch(reactor, 'connectTCP', self._fake_connectTCP) self.factory = mock.Mock(name='PBClientFactory') self.factory.login = self._fake_login self.factory.login_d = defer.Deferred() self.remote = mock.Mock(name='PB Remote') self.remote.callRemote = self._fake_callRemote self.remote.broker.transport.loseConnection = self._fake_loseConnection # results self.creds = None self.conn_host = self.conn_port = None self.lostConnection = False self.added_changes = [] self.vc_used = None def _fake_PBClientFactory(self): return self.factory def _fake_login(self, creds): self.creds = creds return self.factory.login_d def _fake_connectTCP(self, host, port, factory): self.conn_host = host self.conn_port = port self.assertIdentical(factory, self.factory) self.factory.login_d.callback(self.remote) def _fake_callRemote(self, method, change): self.assertEqual(method, 'addChange') self.added_changes.append(change) return defer.succeed(None) def _fake_loseConnection(self): self.lostConnection = True def assertProcess(self, host, port, username, password, changes): self.assertEqual( [host, port, username, password, changes], [ self.conn_host, self.conn_port, self.creds.username, self.creds.password, self.added_changes, ], ) @defer.inlineCallbacks def test_send_minimal(self): s = sendchange.Sender('localhost:1234') yield s.send('branch', 'rev', 'comm', ['a']) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '', "repository": '', "who": None, "files": ['a'], "comments": 'comm', "branch": 'branch', "revision": 'rev', "category": None, "when": None, "properties": {}, "revlink": '', "src": None, } ], ) @defer.inlineCallbacks def test_send_auth(self): s = sendchange.Sender('localhost:1234', auth=('me', 'sekrit')) yield s.send('branch', 'rev', 'comm', ['a']) self.assertProcess( 'localhost', 1234, b'me', b'sekrit', [ { "project": '', "repository": '', "who": None, "files": ['a'], "comments": 'comm', "branch": 'branch', "revision": 'rev', "category": None, "when": None, "properties": {}, "revlink": '', "src": None, } ], ) @defer.inlineCallbacks def test_send_full(self): s = sendchange.Sender('localhost:1234') yield s.send( 'branch', 'rev', 'comm', ['a'], who='me', category='cats', when=1234, properties={'a': 'b'}, repository='r', vc='git', project='p', revlink='rl', ) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": 'p', "repository": 'r', "who": 'me', "files": ['a'], "comments": 'comm', "branch": 'branch', "revision": 'rev', "category": 'cats', "when": 1234, "properties": {'a': 'b'}, "revlink": 'rl', "src": 'git', } ], ) @defer.inlineCallbacks def test_send_files_tuple(self): # 'buildbot sendchange' sends files as a tuple, rather than a list.. s = sendchange.Sender('localhost:1234') yield s.send('branch', 'rev', 'comm', ('a', 'b')) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '', "repository": '', "who": None, "files": ['a', 'b'], "comments": 'comm', "branch": 'branch', "revision": 'rev', "category": None, "when": None, "properties": {}, "revlink": '', "src": None, } ], ) @defer.inlineCallbacks def test_send_codebase(self): s = sendchange.Sender('localhost:1234') yield s.send('branch', 'rev', 'comm', ['a'], codebase='mycb') self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '', "repository": '', "who": None, "files": ['a'], "comments": 'comm', "branch": 'branch', "revision": 'rev', "category": None, "when": None, "properties": {}, "revlink": '', "src": None, "codebase": 'mycb', } ], ) @defer.inlineCallbacks def test_send_unicode(self): s = sendchange.Sender('localhost:1234') yield s.send( '\N{DEGREE SIGN}', '\U0001f49e', '\N{POSTAL MARK FACE}', ['\U0001f4c1'], project='\N{SKULL AND CROSSBONES}', repository='\N{SNOWMAN}', who='\N{THAI CHARACTER KHOMUT}', category='\U0001f640', when=1234, properties={'\N{LATIN SMALL LETTER A WITH MACRON}': 'b'}, revlink='\U0001f517', ) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '\N{SKULL AND CROSSBONES}', "repository": '\N{SNOWMAN}', "who": '\N{THAI CHARACTER KHOMUT}', "files": ['\U0001f4c1'], # FILE FOLDER "comments": '\N{POSTAL MARK FACE}', "branch": '\N{DEGREE SIGN}', "revision": '\U0001f49e', # REVOLVING HEARTS "category": '\U0001f640', # WEARY CAT FACE "when": 1234, "properties": {'\N{LATIN SMALL LETTER A WITH MACRON}': 'b'}, "revlink": '\U0001f517', # LINK SYMBOL "src": None, } ], ) @defer.inlineCallbacks def test_send_unicode_utf8(self): s = sendchange.Sender('localhost:1234') yield s.send( '\N{DEGREE SIGN}'.encode(), '\U0001f49e'.encode(), '\N{POSTAL MARK FACE}'.encode(), ['\U0001f4c1'.encode()], project='\N{SKULL AND CROSSBONES}'.encode(), repository='\N{SNOWMAN}'.encode(), who='\N{THAI CHARACTER KHOMUT}'.encode(), category='\U0001f640'.encode(), when=1234, properties={'\N{LATIN SMALL LETTER A WITH MACRON}'.encode(): 'b'}, revlink='\U0001f517'.encode(), ) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '\N{SKULL AND CROSSBONES}', "repository": '\N{SNOWMAN}', "who": '\N{THAI CHARACTER KHOMUT}', "files": ['\U0001f4c1'], # FILE FOLDER "comments": '\N{POSTAL MARK FACE}', "branch": '\N{DEGREE SIGN}', "revision": '\U0001f49e', # REVOLVING HEARTS "category": '\U0001f640', # WEARY CAT FACE "when": 1234, # NOTE: not decoded! "properties": {b'\xc4\x81': 'b'}, "revlink": '\U0001f517', # LINK SYMBOL "src": None, } ], ) @defer.inlineCallbacks def test_send_unicode_latin1(self): # hand send() a bunch of latin1 strings, and expect them recoded # to unicode s = sendchange.Sender('localhost:1234', encoding='latin1') yield s.send( '\N{YEN SIGN}'.encode('latin1'), '\N{POUND SIGN}'.encode('latin1'), '\N{BROKEN BAR}'.encode('latin1'), ['\N{NOT SIGN}'.encode('latin1')], project='\N{DEGREE SIGN}'.encode('latin1'), repository='\N{SECTION SIGN}'.encode('latin1'), who='\N{MACRON}'.encode('latin1'), category='\N{PILCROW SIGN}'.encode('latin1'), when=1234, properties={'\N{SUPERSCRIPT ONE}'.encode('latin1'): 'b'}, revlink='\N{INVERTED QUESTION MARK}'.encode('latin1'), ) self.assertProcess( 'localhost', 1234, b'change', b'changepw', [ { "project": '\N{DEGREE SIGN}', "repository": '\N{SECTION SIGN}', "who": '\N{MACRON}', "files": ['\N{NOT SIGN}'], "comments": '\N{BROKEN BAR}', "branch": '\N{YEN SIGN}', "revision": '\N{POUND SIGN}', "category": '\N{PILCROW SIGN}', "when": 1234, # NOTE: not decoded! "properties": {b'\xb9': 'b'}, "revlink": '\N{INVERTED QUESTION MARK}', "src": None, } ], )
11,681
Python
.py
327
22.097859
80
0.453895
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,306
test_download_secret_to_worker.py
buildbot_buildbot/master/buildbot/test/unit/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 import stat from twisted.internet import defer from twisted.python.filepath import FilePath from twisted.trial import unittest from buildbot.process import remotetransfer from buildbot.process.results import SUCCESS from buildbot.steps.download_secret_to_worker import DownloadSecretsToWorker from buildbot.steps.download_secret_to_worker import RemoveWorkerFileSecret from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectDownloadFile from buildbot.test.steps import ExpectRemoteRef from buildbot.test.steps import ExpectRmdir from buildbot.test.steps import ExpectRmfile from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util import config as configmixin class TestDownloadFileSecretToWorkerCommand( TestBuildStepMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) tempdir = FilePath(self.mktemp()) tempdir.createDirectory() self.temp_path = tempdir.path return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() def testBasic(self): self.setup_step( DownloadSecretsToWorker([ (os.path.join(self.temp_path, "pathA"), "something"), (os.path.join(self.temp_path, "pathB"), "something more"), ]) ) self.expect_commands( ExpectDownloadFile( maxsize=None, mode=stat.S_IRUSR | stat.S_IWUSR, reader=ExpectRemoteRef(remotetransfer.StringFileReader), blocksize=32 * 1024, workerdest=os.path.join(self.temp_path, "pathA"), workdir="wkdir", ).exit(0), ExpectDownloadFile( maxsize=None, mode=stat.S_IRUSR | stat.S_IWUSR, reader=ExpectRemoteRef(remotetransfer.StringFileReader), blocksize=32 * 1024, workerdest=os.path.join(self.temp_path, "pathB"), workdir="wkdir", ).exit(0), ) self.expect_outcome(result=SUCCESS, state_string="finished") d = self.run_step() return d class TestRemoveWorkerFileSecretCommand30(TestBuildStepMixin, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) tempdir = FilePath(self.mktemp()) tempdir.createDirectory() self.temp_path = tempdir.path return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() def testBasic(self): self.setup_build(worker_version={'*': '3.0'}) self.setup_step( RemoveWorkerFileSecret([ (os.path.join(self.temp_path, "pathA"), "something"), (os.path.join(self.temp_path, "pathB"), "somethingmore"), ]), ) self.expect_commands( ExpectRmdir( path=os.path.join(self.temp_path, "pathA"), dir=os.path.abspath(os.path.join(self.temp_path, "pathA")), log_environ=False, ).exit(0), ExpectRmdir( path=os.path.join(self.temp_path, "pathB"), dir=os.path.abspath(os.path.join(self.temp_path, "pathB")), log_environ=False, ).exit(0), ) self.expect_outcome(result=SUCCESS, state_string="finished") d = self.run_step() return d class TestRemoveFileSecretToWorkerCommand( TestBuildStepMixin, configmixin.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) tempdir = FilePath(self.mktemp()) tempdir.createDirectory() self.temp_path = tempdir.path return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() def testBasic(self): self.setup_step( RemoveWorkerFileSecret([ (os.path.join(self.temp_path, "pathA"), "something"), (os.path.join(self.temp_path, "pathB"), "somethingmore"), ]) ) self.expect_commands( ExpectRmfile(path=os.path.join(self.temp_path, "pathA"), log_environ=False).exit(0), ExpectRmfile(path=os.path.join(self.temp_path, "pathB"), log_environ=False).exit(0), ) self.expect_outcome(result=SUCCESS, state_string="finished") d = self.run_step() return d
5,524
Python
.py
132
33.30303
99
0.659903
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,307
test_secret_in_hvac.py
buildbot_buildbot/master/buildbot/test/unit/test_secret_in_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 from unittest.mock import patch from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.secrets.providers.vault_hvac import HashiCorpVaultKvSecretProvider from buildbot.secrets.providers.vault_hvac import VaultAuthenticatorApprole from buildbot.secrets.providers.vault_hvac import VaultAuthenticatorToken from buildbot.test.util import interfaces from buildbot.test.util.config import ConfigErrorsMixin try: import hvac assert hvac except ImportError: hvac = None class FakeHvacApprole: def login(self, role_id, secret_id): self.role_id = role_id self.secret_id = secret_id class FakeHvacAuth: approle = FakeHvacApprole() class FakeHvacKvV1: token = None def read_secret(self, path, mount_point): if self.token is None: raise hvac.exceptions.Unauthorized if path == "wrong/path": raise hvac.exceptions.InvalidPath(message="Fake InvalidPath exception") return {'data': {'key': "value"}} class FakeHvacKvV2: token = None def read_secret_version(self, path, mount_point, raise_on_deleted_version=True): if self.token is None: raise hvac.exceptions.Unauthorized(message="Fake Unauthorized exception") if path == "wrong/path": raise hvac.exceptions.InvalidPath(message="Fake InvalidPath exception") return {'data': {'data': {'key': "value"}}} class FakeHvacKv: default_kv_version = 2 v1 = FakeHvacKvV1() v2 = FakeHvacKvV2() class FakeHvacSecrets: kv = FakeHvacKv() class FakeHvacClient: auth = FakeHvacAuth() secrets = FakeHvacSecrets() _token = None @property def token(self): return self._token @token.setter def token(self, new_token): self._token = new_token self.secrets.kv.v1.token = new_token self.secrets.kv.v2.token = new_token def is_authenticated(self): return self._token def mock_vault(*args, **kwargs): client = FakeHvacClient() client.token = "mockToken" return client class TestSecretInVaultAuthenticator(interfaces.InterfaceTests): def test_authenticate(self): raise NotImplementedError class TestSecretInVaultAuthenticatorToken(unittest.TestCase, TestSecretInVaultAuthenticator): def setUp(self): if hvac is None: raise unittest.SkipTest("Need to install hvac to test VaultAuthenticatorToken") def test_authenticate(self): token = "mockToken" authenticator = VaultAuthenticatorToken(token) client = hvac.Client() authenticator.authenticate(client) self.assertEqual(client.token, token) class TestSecretInVaultAuthenticatorApprole(unittest.TestCase, TestSecretInVaultAuthenticator): def test_authenticate(self): authenticator = VaultAuthenticatorApprole("testRole", "testSecret") client = FakeHvacClient() authenticator.authenticate(client) self.assertEqual(client.auth.approle.secret_id, "testSecret") class TestSecretInHashiCorpVaultKvSecretProvider(ConfigErrorsMixin, unittest.TestCase): def setUp(self): if hvac is None: raise unittest.SkipTest("Need to install hvac to test HashiCorpVaultKvSecretProvider") param = { "vault_server": "", "authenticator": VaultAuthenticatorToken("mockToken"), "path_delimiter": '|', "path_escape": '\\', "api_version": 2, } self.provider = HashiCorpVaultKvSecretProvider(**param) self.provider.reconfigService(**param) self.provider.client = FakeHvacClient() self.provider.client.secrets.kv.default_kv_version = param['api_version'] self.provider.client.token = "mockToken" @parameterized.expand([ ('vault_server_not_string', {'vault_server': {}}, 'vault_server must be a string'), ( 'path_delimiter_not_char', {'vault_server': 'abc', 'path_delimiter': {}}, 'path_delimiter must be a single character', ), ( 'path_delimiter_too_long', {'vault_server': 'abc', 'path_delimiter': 'ab'}, 'path_delimiter must be a single character', ), ( 'path_escape_not_char', {'vault_server': 'abc', 'path_escape': {}}, 'path_escape must be a single character', ), ( 'path_escape_too_long', {'vault_server': 'abc', 'path_escape': 'ab'}, 'path_escape must be a single character', ), ( 'api_version_unsupported', {'vault_server': 'abc', 'api_version': 3}, 'api_version 3 is not supported', ), ]) def test_check_config(self, name, params, error): with self.assertRaisesConfigError(error): HashiCorpVaultKvSecretProvider( authenticator=VaultAuthenticatorToken("mockToken"), **params ) def test_check_config_authenticator(self): with self.assertRaisesConfigError('authenticator must be instance of VaultAuthenticator'): HashiCorpVaultKvSecretProvider(vault_server='abc') def test_escaped_split(self): parts = self.provider.escaped_split("a/b\\|c/d|e/f\\|g/h") self.assertEqual(parts, ["a/b|c/d", "e/f|g/h"]) def test_escaped_split_ends_with_escape(self): parts = self.provider.escaped_split("a|b\\") self.assertEqual(parts, ["a", "b"]) def test_thd_hvac_wrap_read_v1(self): self.provider.api_version = 1 self.provider.client.token = "mockToken" value = self.provider.thd_hvac_wrap_read("some/path") self.assertEqual(value['data']['key'], "value") def test_thd_hvac_wrap_read_v2(self): self.provider.client.token = "mockToken" value = self.provider.thd_hvac_wrap_read("some/path") self.assertEqual(value['data']['data']['key'], "value") # for some reason, errors regarding generator function were thrown @patch("hvac.Client", side_effect=mock_vault) def test_thd_hvac_wrap_read_unauthorized(self, mock_vault): self.provider.client.token = None yield self.assertFailure( self.provider.thd_hvac_wrap_read("some/path"), hvac.exceptions.Unauthorized ) def test_thd_hvac_get_reauthorize(self): """ When token is None, provider gets unauthorized exception and is forced to re-authenticate """ self.provider.client.token = None value = self.provider.thd_hvac_get("some/path") self.assertEqual(value['data']['data']['key'], "value") @defer.inlineCallbacks def test_get_v1(self): self.provider.api_version = 1 self.provider.client.token = "mockToken" value = yield self.provider.get("some/path|key") self.assertEqual(value, "value") @defer.inlineCallbacks def test_get_v2(self): self.provider.client.token = "mockToken" value = yield self.provider.get("some/path|key") self.assertEqual(value, "value") @defer.inlineCallbacks def test_get_fail_no_key(self): self.provider.client.token = "mockToken" with self.assertRaises(KeyError): yield self.provider.get("some/path") @defer.inlineCallbacks def test_get_fail_wrong_key(self): self.provider.client.token = "mockToken" with self.assertRaises(KeyError): yield self.provider.get("some/path|wrong_key") @defer.inlineCallbacks def test_get_fail_multiple_separators(self): self.provider.client.token = "mockToken" with self.assertRaises(KeyError): yield self.provider.get("some/path|unescaped|key")
8,521
Python
.py
200
35.16
98
0.675048
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,308
test_clients_usersclient.py
buildbot_buildbot/master/buildbot/test/unit/test_clients_usersclient.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 unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.spread import pb from twisted.trial import unittest from buildbot.clients import usersclient class TestUsersClient(unittest.TestCase): def setUp(self): # patch out some PB components and make up some mocks self.patch(pb, 'PBClientFactory', self._fake_PBClientFactory) self.patch(reactor, 'connectTCP', self._fake_connectTCP) self.factory = mock.Mock(name='PBClientFactory') self.factory.login = self._fake_login self.factory.login_d = defer.Deferred() self.remote = mock.Mock(name='PB Remote') self.remote.callRemote = self._fake_callRemote self.remote.broker.transport.loseConnection = self._fake_loseConnection # results self.conn_host = self.conn_port = None self.lostConnection = False def _fake_PBClientFactory(self): return self.factory def _fake_login(self, creds): return self.factory.login_d def _fake_connectTCP(self, host, port, factory): self.conn_host = host self.conn_port = port self.assertIdentical(factory, self.factory) self.factory.login_d.callback(self.remote) def _fake_callRemote(self, method, op, bb_username, bb_password, ids, info): self.assertEqual(method, 'commandline') self.called_with = { "op": op, "bb_username": bb_username, "bb_password": bb_password, "ids": ids, "info": info, } return defer.succeed(None) def _fake_loseConnection(self): self.lostConnection = True def assertProcess(self, host, port, called_with): self.assertEqual( [host, port, called_with], [self.conn_host, self.conn_port, self.called_with] ) @defer.inlineCallbacks def test_usersclient_info(self): uc = usersclient.UsersClient('localhost', "user", "userpw", 1234) yield uc.send( 'update', 'bb_user', 'hashed_bb_pass', None, [{'identifier': 'x', 'svn': 'x'}] ) self.assertProcess( 'localhost', 1234, { "op": 'update', "bb_username": 'bb_user', "bb_password": 'hashed_bb_pass', "ids": None, "info": [{"identifier": 'x', "svn": 'x'}], }, ) @defer.inlineCallbacks def test_usersclient_ids(self): uc = usersclient.UsersClient('localhost', "user", "userpw", 1234) yield uc.send('remove', None, None, ['x'], None) self.assertProcess( 'localhost', 1234, {"op": 'remove', "bb_username": None, "bb_password": None, "ids": ['x'], "info": None}, )
3,539
Python
.py
85
33.788235
99
0.64057
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,309
test_locks.py
buildbot_buildbot/master/buildbot/test/unit/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 unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.locks import BaseLock from buildbot.locks import LockAccess from buildbot.locks import MasterLock from buildbot.locks import RealMasterLock from buildbot.locks import RealWorkerLock from buildbot.locks import WorkerLock from buildbot.util.eventual import flushEventualQueue class Requester: pass class BaseLockTests(unittest.TestCase): @parameterized.expand([ ('counting', 0, 0), ('counting', 0, 1), ('counting', 1, 1), ('counting', 0, 2), ('counting', 1, 2), ('counting', 2, 2), ('counting', 0, 3), ('counting', 1, 3), ('counting', 2, 3), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_is_available_empty(self, mode, count, maxCount): req = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count self.assertTrue(lock.isAvailable(req, access)) @parameterized.expand([ ('counting', 0, 0), ('counting', 0, 1), ('counting', 1, 1), ('counting', 0, 2), ('counting', 1, 2), ('counting', 2, 2), ('counting', 0, 3), ('counting', 1, 3), ('counting', 2, 3), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_is_available_without_waiter(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) lock.release(req, access) self.assertTrue(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter, access)) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_is_available_with_waiter(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) lock.waitUntilMaybeAvailable(req_waiter, access) lock.release(req, access) self.assertFalse(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter, access)) lock.claim(req_waiter, access) lock.release(req_waiter, access) self.assertTrue(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter, access)) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_is_available_with_multiple_waiters(self, mode, count, maxCount): req = Requester() req_waiter1 = Requester() req_waiter2 = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) lock.waitUntilMaybeAvailable(req_waiter1, access) lock.waitUntilMaybeAvailable(req_waiter2, access) lock.release(req, access) self.assertFalse(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertFalse(lock.isAvailable(req_waiter2, access)) lock.claim(req_waiter1, access) lock.release(req_waiter1, access) self.assertFalse(lock.isAvailable(req, access)) self.assertFalse(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) lock.claim(req_waiter2, access) lock.release(req_waiter2, access) self.assertTrue(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) def test_is_available_with_multiple_waiters_multiple_counting(self): req1 = Requester() req2 = Requester() req_waiter1 = Requester() req_waiter2 = Requester() req_waiter3 = Requester() lock = BaseLock('test', maxCount=2) access = mock.Mock(spec=LockAccess) access.mode = 'counting' access.count = 1 lock.claim(req1, access) lock.claim(req2, access) lock.waitUntilMaybeAvailable(req_waiter1, access) lock.waitUntilMaybeAvailable(req_waiter2, access) lock.waitUntilMaybeAvailable(req_waiter3, access) lock.release(req1, access) lock.release(req2, access) self.assertFalse(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertFalse(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter1, access) lock.release(req_waiter1, access) self.assertFalse(lock.isAvailable(req1, access)) self.assertFalse(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter2, access) lock.release(req_waiter2, access) self.assertTrue(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter3, access) lock.release(req_waiter3, access) self.assertTrue(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) def test_is_available_with_mult_waiters_mult_counting_set_maxCount(self): req1 = Requester() req2 = Requester() req_waiter1 = Requester() req_waiter2 = Requester() req_waiter3 = Requester() lock = BaseLock('test', maxCount=2) access = mock.Mock(spec=LockAccess) access.mode = 'counting' access.count = 1 lock.claim(req1, access) lock.claim(req2, access) lock.waitUntilMaybeAvailable(req_waiter1, access) lock.waitUntilMaybeAvailable(req_waiter2, access) lock.waitUntilMaybeAvailable(req_waiter3, access) lock.release(req1, access) lock.release(req2, access) self.assertFalse(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertFalse(lock.isAvailable(req_waiter3, access)) lock.setMaxCount(4) self.assertTrue(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter1, access) lock.release(req_waiter1, access) self.assertTrue(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.setMaxCount(2) lock.waitUntilMaybeAvailable(req_waiter1, access) lock.claim(req_waiter2, access) lock.release(req_waiter2, access) self.assertFalse(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertFalse(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter3, access) lock.release(req_waiter3, access) self.assertTrue(lock.isAvailable(req1, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) self.assertTrue(lock.isAvailable(req_waiter3, access)) lock.claim(req_waiter1, access) lock.release(req_waiter1, access) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_duplicate_wait_until_maybe_available_throws(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) lock.waitUntilMaybeAvailable(req_waiter, access) with self.assertRaises(AssertionError): lock.waitUntilMaybeAvailable(req_waiter, access) lock.release(req, access) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_stop_waiting_ensures_deferred_was_previous_result_of_wait(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) lock.waitUntilMaybeAvailable(req_waiter, access) with self.assertRaises(AssertionError): wrong_d = defer.Deferred() lock.stopWaitingUntilAvailable(req_waiter, access, wrong_d) lock.release(req, access) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_stop_waiting_fires_deferred_if_not_woken(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) d = lock.waitUntilMaybeAvailable(req_waiter, access) lock.stopWaitingUntilAvailable(req_waiter, access, d) self.assertTrue(d.called) lock.release(req, access) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) @defer.inlineCallbacks def test_stop_waiting_does_not_fire_deferred_if_already_woken(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) d = lock.waitUntilMaybeAvailable(req_waiter, access) lock.release(req, access) yield flushEventualQueue() self.assertTrue(d.called) # note that if the function calls the deferred again, an exception would be thrown from # inside Twisted. lock.stopWaitingUntilAvailable(req_waiter, access, d) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_stop_waiting_does_not_raise_after_release(self, mode, count, maxCount): req = Requester() req_waiter = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) d = lock.waitUntilMaybeAvailable(req_waiter, access) lock.release(req, access) self.assertFalse(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter, access)) lock.stopWaitingUntilAvailable(req_waiter, access, d) lock.claim(req_waiter, access) lock.release(req_waiter, access) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_stop_waiting_removes_non_called_waiter(self, mode, count, maxCount): req = Requester() req_waiter1 = Requester() req_waiter2 = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) d1 = lock.waitUntilMaybeAvailable(req_waiter1, access) d2 = lock.waitUntilMaybeAvailable(req_waiter2, access) lock.release(req, access) yield flushEventualQueue() self.assertFalse(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertFalse(lock.isAvailable(req_waiter2, access)) self.assertTrue(d1.called) lock.stopWaitingUntilAvailable(req_waiter2, access, d2) self.assertFalse(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertFalse(lock.isAvailable(req_waiter2, access)) lock.claim(req_waiter1, access) lock.release(req_waiter1, access) self.assertTrue(lock.isAvailable(req, access)) self.assertTrue(lock.isAvailable(req_waiter1, access)) self.assertTrue(lock.isAvailable(req_waiter2, access)) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) @defer.inlineCallbacks def test_stop_waiting_wakes_up_next_deferred_if_already_woken(self, mode, count, maxCount): req = Requester() req_waiter1 = Requester() req_waiter2 = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.claim(req, access) d1 = lock.waitUntilMaybeAvailable(req_waiter1, access) d2 = lock.waitUntilMaybeAvailable(req_waiter2, access) lock.release(req, access) yield flushEventualQueue() self.assertTrue(d1.called) self.assertFalse(d2.called) lock.stopWaitingUntilAvailable(req_waiter1, access, d1) yield flushEventualQueue() self.assertTrue(d2.called) @parameterized.expand([ ('counting', 1, 1), ('counting', 2, 2), ('counting', 3, 3), ('exclusive', 1, 1), ]) def test_can_release_non_waited_lock(self, mode, count, maxCount): req = Requester() req_not_waited = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = mode access.count = count lock.release(req_not_waited, access) lock.claim(req, access) lock.release(req, access) yield flushEventualQueue() lock.release(req_not_waited, access) @parameterized.expand([ ('counting', 'counting', 1, 1, 1), ('counting', 'exclusive', 1, 1, 1), ('exclusive', 'counting', 1, 1, 1), ('exclusive', 'exclusive', 1, 1, 1), ]) @defer.inlineCallbacks def test_release_calls_waiters_in_fifo_order(self, mode1, mode2, count1, count2, maxCount): req = Requester() req_waiters = [Requester() for _ in range(5)] lock = BaseLock('test', maxCount=maxCount) access1 = mock.Mock(spec=LockAccess) access1.mode = mode1 access1.count = count1 access2 = mock.Mock(spec=LockAccess) access2.mode = mode2 access2.count = count2 accesses = [access1, access2, access1, access2, access1] expected_called = [False] * 5 lock.claim(req, access1) deferreds = [ lock.waitUntilMaybeAvailable(req_waiter, access) for req_waiter, access in zip(req_waiters, accesses) ] self.assertEqual([d.called for d in deferreds], expected_called) lock.release(req, access1) yield flushEventualQueue() expected_called[0] = True self.assertEqual([d.called for d in deferreds], expected_called) for i in range(4): self.assertTrue(lock.isAvailable(req_waiters[i], accesses[i])) lock.claim(req_waiters[i], accesses[i]) self.assertEqual([d.called for d in deferreds], expected_called) lock.release(req_waiters[i], accesses[i]) yield flushEventualQueue() expected_called[i + 1] = True self.assertEqual([d.called for d in deferreds], expected_called) lock.claim(req_waiters[4], accesses[4]) lock.release(req_waiters[4], accesses[4]) @parameterized.expand([ (1,), ]) @defer.inlineCallbacks def test_release_calls_multiple_waiters_on_release(self, count): req = Requester() req_waiters = [Requester() for _ in range(5)] lock = BaseLock('test', maxCount=5) access_counting = mock.Mock(spec=LockAccess) access_counting.mode = 'counting' access_counting.count = count access_excl = mock.Mock(spec=LockAccess) access_excl.mode = 'exclusive' access_excl.count = 1 lock.claim(req, access_excl) deferreds = [ lock.waitUntilMaybeAvailable(req_waiter, access_counting) for req_waiter in req_waiters ] self.assertEqual([d.called for d in deferreds], [False] * 5) lock.release(req, access_excl) yield flushEventualQueue() self.assertEqual([d.called for d in deferreds], [True] * 5) @parameterized.expand([ (1, 1), ]) @defer.inlineCallbacks def test_release_calls_multiple_waiters_on_setMaxCount(self, count, maxCount): req = Requester() req_waiters = [Requester() for _ in range(5)] lock = BaseLock('test', maxCount=maxCount) access_counting = mock.Mock(spec=LockAccess) access_counting.mode = 'counting' access_counting.count = count lock.claim(req, access_counting) deferreds = [ lock.waitUntilMaybeAvailable(req_waiter, access_counting) for req_waiter in req_waiters ] self.assertEqual([d.called for d in deferreds], [False] * 5) lock.release(req, access_counting) yield flushEventualQueue() self.assertEqual([d.called for d in deferreds], [True] + [False] * 4) lock.setMaxCount(5) yield flushEventualQueue() self.assertEqual([d.called for d in deferreds], [True] * 5) @parameterized.expand([ (2, 2), (3, 3), (4, 4), (5, 5), ]) def test_exclusive_must_have_count_one(self, count, maxCount): req = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = 'exclusive' access.count = count with self.assertRaises(AssertionError): lock.claim(req, access) @parameterized.expand([ (0, 1), (1, 1), (0, 2), (1, 2), (2, 2), (0, 3), (1, 3), (2, 3), (3, 3), ]) def test_counting_count_zero_always_succeeds(self, count, maxCount): reqs = [Requester() for _ in range(10)] req_waiters = [Requester() for _ in range(10)] req_nonzero = Requester() lock = BaseLock('test', maxCount=maxCount) access_zero = mock.Mock(spec=LockAccess) access_zero.mode = 'counting' access_zero.count = 0 access_nonzero = mock.Mock(spec=LockAccess) access_nonzero.mode = 'counting' access_nonzero.count = count lock.claim(req_nonzero, access_nonzero) for req in reqs: self.assertTrue(lock.isAvailable(req, access_zero)) lock.claim(req, access_zero) for req_waiter in req_waiters: self.assertTrue(lock.isAvailable(req_waiter, access_zero)) for req in reqs: self.assertTrue(lock.isAvailable(req, access_zero)) lock.release(req, access_zero) lock.release(req_nonzero, access_nonzero) @parameterized.expand([ (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), ]) def test_count_cannot_be_larger_than_maxcount(self, count, maxCount): req = Requester() lock = BaseLock('test', maxCount=maxCount) access = mock.Mock(spec=LockAccess) access.mode = 'counting' access.count = count self.assertFalse(lock.isAvailable(req, access)) @parameterized.expand([ (0, 1, 1), (0, 1, 2), (1, 2, 3), (1, 2, 4), (1, 3, 4), (1, 3, 5), (2, 3, 5), (2, 3, 6), ]) def test_different_counts_below_limit(self, count1, count2, maxCount): req1 = Requester() req2 = Requester() lock = BaseLock('test', maxCount=maxCount) access1 = mock.Mock(spec=LockAccess) access1.mode = 'counting' access1.count = count1 access2 = mock.Mock(spec=LockAccess) access2.mode = 'counting' access2.count = count2 self.assertTrue(lock.isAvailable(req1, access1)) lock.claim(req1, access1) self.assertTrue(lock.isAvailable(req2, access2)) lock.release(req1, access1) @parameterized.expand([ (0, 2, 1), (0, 3, 1), (0, 3, 2), (1, 2, 2), (1, 3, 3), (1, 4, 3), (2, 3, 2), (2, 3, 3), (2, 3, 4), (2, 4, 4), ]) def test_different_counts_over_limit(self, count1, count2, maxCount): req1 = Requester() req2 = Requester() lock = BaseLock('test', maxCount=maxCount) access1 = mock.Mock(spec=LockAccess) access1.mode = 'counting' access1.count = count1 access2 = mock.Mock(spec=LockAccess) access2.mode = 'counting' access2.count = count2 self.assertTrue(lock.isAvailable(req1, access1)) lock.claim(req1, access1) self.assertFalse(lock.isAvailable(req2, access2)) lock.release(req1, access1) class RealLockTests(unittest.TestCase): def test_master_lock_init_from_lockid(self): lock = RealMasterLock('lock1') lock.updateFromLockId(MasterLock('lock1', maxCount=3), 0) self.assertEqual(lock.lockName, 'lock1') self.assertEqual(lock.maxCount, 3) self.assertEqual(lock.description, '<MasterLock(lock1, 3)>') def test_master_lock_update_from_lockid(self): lock = RealMasterLock('lock1') lock.updateFromLockId(MasterLock('lock1', maxCount=3), 0) lock.updateFromLockId(MasterLock('lock1', maxCount=4), 0) self.assertEqual(lock.lockName, 'lock1') self.assertEqual(lock.maxCount, 4) self.assertEqual(lock.description, '<MasterLock(lock1, 4)>') with self.assertRaises(AssertionError): lock.updateFromLockId(MasterLock('lock2', maxCount=4), 0) def test_worker_lock_init_from_lockid(self): lock = RealWorkerLock('lock1') lock.updateFromLockId(WorkerLock('lock1', maxCount=3), 0) self.assertEqual(lock.lockName, 'lock1') self.assertEqual(lock.maxCount, 3) self.assertEqual(lock.description, '<WorkerLock(lock1, 3, {})>') worker_lock = lock.getLockForWorker('worker1') self.assertEqual(worker_lock.lockName, 'lock1') self.assertEqual(worker_lock.maxCount, 3) self.assertTrue(worker_lock.description.startswith('<WorkerLock(lock1, 3)[worker1]')) def test_worker_lock_init_from_lockid_count_for_worker(self): lock = RealWorkerLock('lock1') lock.updateFromLockId(WorkerLock('lock1', maxCount=3, maxCountForWorker={'worker2': 5}), 0) self.assertEqual(lock.lockName, 'lock1') self.assertEqual(lock.maxCount, 3) worker_lock = lock.getLockForWorker('worker1') self.assertEqual(worker_lock.maxCount, 3) worker_lock = lock.getLockForWorker('worker2') self.assertEqual(worker_lock.maxCount, 5) def test_worker_lock_update_from_lockid(self): lock = RealWorkerLock('lock1') lock.updateFromLockId(WorkerLock('lock1', maxCount=3), 0) worker_lock = lock.getLockForWorker('worker1') self.assertEqual(worker_lock.maxCount, 3) lock.updateFromLockId(WorkerLock('lock1', maxCount=5), 0) self.assertEqual(lock.lockName, 'lock1') self.assertEqual(lock.maxCount, 5) self.assertEqual(lock.description, '<WorkerLock(lock1, 5, {})>') self.assertEqual(worker_lock.lockName, 'lock1') self.assertEqual(worker_lock.maxCount, 5) self.assertTrue(worker_lock.description.startswith('<WorkerLock(lock1, 5)[worker1]')) with self.assertRaises(AssertionError): lock.updateFromLockId(WorkerLock('lock2', maxCount=4), 0) @parameterized.expand([ (True, True, True), (True, True, False), (True, False, True), (True, False, False), (False, True, True), (False, True, False), (False, False, True), (False, False, False), ]) def test_worker_lock_update_from_lockid_count_for_worker( self, acquire_before, worker_count_before, worker_count_after ): max_count_before = {} if worker_count_before: max_count_before = {'worker1': 5} max_count_after = {} if worker_count_after: max_count_after = {'worker1': 7} lock = RealWorkerLock('lock1') lock.updateFromLockId( WorkerLock('lock1', maxCount=3, maxCountForWorker=max_count_before), 0 ) if acquire_before: worker_lock = lock.getLockForWorker('worker1') self.assertEqual(worker_lock.maxCount, 5 if worker_count_before else 3) lockid = WorkerLock('lock1', maxCount=4, maxCountForWorker=max_count_after) lock.updateFromLockId(lockid, 0) if not acquire_before: worker_lock = lock.getLockForWorker('worker1') self.assertEqual(worker_lock.maxCount, 7 if worker_count_after else 4)
27,285
Python
.py
659
32.831563
100
0.635307
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,310
test_buildbot_net_usage_data.py
buildbot_buildbot/master/buildbot/test/unit/test_buildbot_net_usage_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 import os import platform from unittest.case import SkipTest from urllib import request as urllib_request from twisted.internet import reactor from twisted.python.filepath import FilePath from twisted.trial import unittest import buildbot.buildbot_net_usage_data from buildbot import config from buildbot.buildbot_net_usage_data import _sendBuildbotNetUsageData from buildbot.buildbot_net_usage_data import computeUsageData from buildbot.buildbot_net_usage_data import linux_distribution from buildbot.config import BuilderConfig from buildbot.master import BuildMaster from buildbot.plugins import steps from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.test.util.integration import DictLoader from buildbot.test.util.warnings import assertProducesWarning from buildbot.warnings import ConfigWarning from buildbot.worker.base import Worker class Tests(unittest.TestCase): def getMaster(self, config_dict): """ Create a started ``BuildMaster`` with the given configuration. """ basedir = FilePath(self.mktemp()) basedir.createDirectory() master = BuildMaster(basedir.path, reactor=reactor, config_loader=DictLoader(config_dict)) master.config = master.config_loader.loadConfig() return master def getBaseConfig(self): return { 'builders': [ BuilderConfig( name="testy", workernames=["local1", "local2"], factory=BuildFactory([steps.ShellCommand(command='echo hello')]), ), ], 'workers': [Worker('local' + str(i), 'pass') for i in range(3)], 'schedulers': [ForceScheduler(name="force", builderNames=["testy"])], 'protocols': {'null': {}}, 'multiMaster': True, } def test_basic(self): self.patch(config.master, "get_is_in_unit_tests", lambda: False) with assertProducesWarning( ConfigWarning, message_pattern=r"`buildbotNetUsageData` is not configured and defaults to basic.", ): master = self.getMaster(self.getBaseConfig()) data = computeUsageData(master) self.assertEqual( sorted(data.keys()), sorted(['versions', 'db', 'platform', 'installid', 'mq', 'plugins', 'www_plugins']), ) self.assertEqual(data['plugins']['buildbot/worker/base/Worker'], 3) self.assertEqual( sorted(data['plugins'].keys()), sorted([ 'buildbot/schedulers/forcesched/ForceScheduler', 'buildbot/worker/base/Worker', 'buildbot/steps/shell/ShellCommand', 'buildbot/config/builder/BuilderConfig', ]), ) def test_full(self): c = self.getBaseConfig() c['buildbotNetUsageData'] = 'full' master = self.getMaster(c) data = computeUsageData(master) self.assertEqual( sorted(data.keys()), sorted([ 'versions', 'db', 'installid', 'platform', 'mq', 'plugins', 'builders', 'www_plugins', ]), ) def test_custom(self): c = self.getBaseConfig() def myCompute(data): return {"db": data['db']} c['buildbotNetUsageData'] = myCompute master = self.getMaster(c) data = computeUsageData(master) self.assertEqual(sorted(data.keys()), sorted(['db'])) def test_urllib(self): self.patch(buildbot.buildbot_net_usage_data, '_sendWithRequests', lambda _, __: None) class FakeRequest: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs open_url = [] class urlopen: def __init__(self, r): self.request = r open_url.append(self) def read(self): return "ok" def close(self): pass self.patch(urllib_request, "Request", FakeRequest) self.patch(urllib_request, "urlopen", urlopen) _sendBuildbotNetUsageData({'foo': 'bar'}) self.assertEqual(len(open_url), 1) self.assertEqual( open_url[0].request.args, ( 'https://events.buildbot.net/events/phone_home', b'{"foo": "bar"}', {'Content-Length': 14, 'Content-Type': 'application/json'}, ), ) def test_real(self): if "TEST_BUILDBOTNET_USAGEDATA" not in os.environ: raise SkipTest( "_sendBuildbotNetUsageData real test only run when environment variable" " TEST_BUILDBOTNET_USAGEDATA is set" ) _sendBuildbotNetUsageData({'foo': 'bar'}) def test_linux_distro(self): system = platform.system() if system != "Linux": raise SkipTest("test is only for linux") distro = linux_distribution() self.assertEqual(len(distro), 2) self.assertNotIn("unknown", distro[0]) # Rolling distributions like Arch Linux (arch) does not have VERSION_ID if distro[0] not in ["arch", "gentoo", "antergos"]: self.assertNotIn("unknown", distro[1])
6,162
Python
.py
151
31.456954
98
0.622371
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,311
test_revlinks.py
buildbot_buildbot/master/buildbot/test/unit/test_revlinks.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.revlinks import BitbucketRevlink from buildbot.revlinks import GithubRevlink from buildbot.revlinks import GitwebMatch from buildbot.revlinks import RevlinkMatch from buildbot.revlinks import SourceforgeGitRevlink from buildbot.revlinks import SourceforgeGitRevlink_AlluraPlatform from buildbot.revlinks import default_revlink_matcher class TestGithubRevlink(unittest.TestCase): revision = 'b6874701b54e0043a78882b020afc86033133f91' url = 'https://github.com/buildbot/buildbot/commit/b6874701b54e0043a78882b020afc86033133f91' def testHTTPS(self): self.assertEqual( GithubRevlink(self.revision, 'https://github.com/buildbot/buildbot.git'), self.url ) def testGIT(self): self.assertEqual( GithubRevlink(self.revision, 'git://github.com/buildbot/buildbot.git'), self.url ) def testSSH(self): self.assertEqual( GithubRevlink(self.revision, '[email protected]:buildbot/buildbot.git'), self.url ) def testSSHuri(self): self.assertEqual( GithubRevlink(self.revision, 'ssh://[email protected]/buildbot/buildbot.git'), self.url ) class TestSourceforgeGitRevlink(unittest.TestCase): revision = 'b99c89a2842d386accea8072ae5bb6e24aa7cf29' url = 'http://gemrb.git.sourceforge.net/git/gitweb.cgi?p=gemrb/gemrb;a=commit;h=b99c89a2842d386accea8072ae5bb6e24aa7cf29' def testGIT(self): url = SourceforgeGitRevlink( self.revision, 'git://gemrb.git.sourceforge.net/gitroot/gemrb/gemrb' ) self.assertEqual(url, self.url) def testSSH(self): url = SourceforgeGitRevlink( self.revision, '[email protected]:gitroot/gemrb/gemrb' ) self.assertEqual(url, self.url) def testSSHuri(self): url = SourceforgeGitRevlink( self.revision, 'ssh://[email protected]/gitroot/gemrb/gemrb' ) self.assertEqual(url, self.url) class TestSourceforgeGitRevlink_AlluraPlatform(unittest.TestCase): revision = '6f9b1470bae497c6ce47e4cf8c9195d864d2ba2f' url = 'https://sourceforge.net/p/klusters/klusters/ci/6f9b1470bae497c6ce47e4cf8c9195d864d2ba2f/' def testGIT(self): url = SourceforgeGitRevlink_AlluraPlatform( self.revision, 'git://git.code.sf.net/p/klusters/klusters' ) self.assertEqual(url, self.url) def testSSHuri(self): url = SourceforgeGitRevlink_AlluraPlatform( self.revision, 'ssh://[email protected]/p/klusters/klusters' ) self.assertEqual(url, self.url) class TestRevlinkMatch(unittest.TestCase): def testNotmuch(self): revision = 'f717d2ece1836c863f9cc02abd1ff2539307cd1d' matcher = RevlinkMatch( ['git://notmuchmail.org/git/(.*)'], r'http://git.notmuchmail.org/git/\1/commit/%s' ) self.assertEqual( matcher(revision, 'git://notmuchmail.org/git/notmuch'), 'http://git.notmuchmail.org/git/notmuch/commit/f717d2ece1836c863f9cc02abd1ff2539307cd1d', ) def testSingleString(self): revision = 'rev' matcher = RevlinkMatch('test', 'out%s') self.assertEqual(matcher(revision, 'test'), 'outrev') def testSingleUnicode(self): revision = 'rev' matcher = RevlinkMatch('test', 'out%s') self.assertEqual(matcher(revision, 'test'), 'outrev') def testTwoCaptureGroups(self): revision = 'rev' matcher = RevlinkMatch('([A-Z]*)Z([0-9]*)', r'\2-\1-%s') self.assertEqual(matcher(revision, 'ABCZ43'), '43-ABC-rev') class TestGitwebMatch(unittest.TestCase): def testOrgmode(self): revision = '490d6ace10e0cfe74bab21c59e4b7bd6aa3c59b8' matcher = GitwebMatch('git://orgmode.org/(?P<repo>.*)', 'http://orgmode.org/w/') self.assertEqual( matcher(revision, 'git://orgmode.org/org-mode.git'), 'http://orgmode.org/w/?p=org-mode.git;a=commit;h=490d6ace10e0cfe74bab21c59e4b7bd6aa3c59b8', ) class TestBitbucketRevlink(unittest.TestCase): revision = '4d4284cf4fb49ce82fefb6cbac8e462073c5f106' url = 'https://bitbucket.org/fakeproj/fakerepo/commits/4d4284cf4fb49ce82fefb6cbac8e462073c5f106' def testHTTPS(self): self.assertEqual( BitbucketRevlink(self.revision, 'https://[email protected]/fakeproj/fakerepo.git'), self.url, ) def testSSH(self): self.assertEqual( BitbucketRevlink(self.revision, '[email protected]:fakeproj/fakerepo.git'), self.url ) class TestDefaultRevlinkMultiPlexer(unittest.TestCase): revision = "0" def testAllRevlinkMatchers(self): # GithubRevlink self.assertTrue( default_revlink_matcher(self.revision, 'https://github.com/buildbot/buildbot.git') ) # BitbucketRevlink self.assertTrue( default_revlink_matcher(self.revision, '[email protected]:fakeproj/fakerepo.git') ) # SourceforgeGitRevlink self.assertTrue( default_revlink_matcher( self.revision, 'git://gemrb.git.sourceforge.net/gitroot/gemrb/gemrb' ) ) # SourceforgeGitRevlink_AlluraPlatform self.assertTrue( default_revlink_matcher(self.revision, 'git://git.code.sf.net/p/klusters/klusters') )
6,169
Python
.py
135
38.244444
125
0.702316
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,312
test_mq_connector.py
buildbot_buildbot/master/buildbot/test/unit/test_mq_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 from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.mq import base from buildbot.mq import connector from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util import service class FakeMQ(service.ReconfigurableServiceMixin, base.MQBase): new_config = "not_called" def reconfigServiceWithBuildbotConfig(self, new_config): self.new_config = new_config return defer.succeed(None) def produce(self, routingKey, data): pass def startConsuming(self, callback, filter, persistent_name=None): return defer.succeed(None) class MQConnector(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.mqconfig = self.master.config.mq = {} self.conn = connector.MQConnector() yield self.conn.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def patchFakeMQ(self, name='fake'): self.patch( connector.MQConnector, 'classes', { name: {'class': 'buildbot.test.unit.test_mq_connector.FakeMQ'}, }, ) @defer.inlineCallbacks def test_setup_unknown_type(self): self.mqconfig['type'] = 'unknown' with self.assertRaises(AssertionError): yield self.conn.setup() @defer.inlineCallbacks def test_setup_simple_type(self): self.patchFakeMQ(name='simple') self.mqconfig['type'] = 'simple' yield self.conn.setup() self.assertIsInstance(self.conn.impl, FakeMQ) self.assertEqual(self.conn.impl.produce, self.conn.produce) self.assertEqual(self.conn.impl.startConsuming, self.conn.startConsuming) @defer.inlineCallbacks def test_reconfigServiceWithBuildbotConfig(self): self.patchFakeMQ() self.mqconfig['type'] = 'fake' self.conn.setup() new_config = mock.Mock() new_config.mq = {"type": 'fake'} yield self.conn.reconfigServiceWithBuildbotConfig(new_config) self.assertIdentical(self.conn.impl.new_config, new_config) @defer.inlineCallbacks def test_reconfigService_change_type(self): self.patchFakeMQ() self.mqconfig['type'] = 'fake' yield self.conn.setup() new_config = mock.Mock() new_config.mq = {"type": 'other'} try: yield self.conn.reconfigServiceWithBuildbotConfig(new_config) except AssertionError: pass # expected else: self.fail("should have failed")
3,501
Python
.py
85
34.576471
81
0.701677
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,313
test_contrib_buildbot_cvs_mail.py
buildbot_buildbot/master/buildbot/test/unit/test_contrib_buildbot_cvs_mail.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 re import sys from twisted.internet import defer from twisted.internet import protocol from twisted.internet import reactor from twisted.internet import utils from twisted.python import log from twisted.trial import unittest from buildbot.test.util.misc import encodeExecutableAndArgs test = """ Update of /cvsroot/test In directory example:/tmp/cvs-serv21085 Modified Files: README hello.c Log Message: two files checkin """ golden_1_11_regex = [ '^From:', '^To: [email protected]$', '^Reply-To: [email protected]$', '^Subject: cvs update for project test$', '^Date:', '^X-Mailer: Python buildbot-cvs-mail', '^$', '^Cvsmode: 1.11$', '^Category: None', '^CVSROOT: "ext:example:/cvsroot"', '^Files: test README 1.1,1.2 hello.c 2.2,2.3$', '^Project: test$', '^$', '^Update of /cvsroot/test$', '^In directory example:/tmp/cvs-serv21085$', '^$', '^Modified Files:$', 'README hello.c$', 'Log Message:$', '^two files checkin', '^$', '^$', ] golden_1_12_regex = [ '^From: ', '^To: [email protected]$', '^Reply-To: [email protected]$', '^Subject: cvs update for project test$', '^Date: ', '^X-Mailer: Python buildbot-cvs-mail', '^$', '^Cvsmode: 1.12$', '^Category: None$', '^CVSROOT: "ext:example.com:/cvsroot"$', '^Files: README 1.1 1.2 hello.c 2.2 2.3$', '^Path: test$', '^Project: test$', '^$', '^Update of /cvsroot/test$', '^In directory example:/tmp/cvs-serv21085$', '^$', '^Modified Files:$', 'README hello.c$', '^Log Message:$', 'two files checkin', '^$', '^$', ] class _SubprocessProtocol(protocol.ProcessProtocol): def __init__(self, input, deferred): if isinstance(input, str): input = input.encode('utf-8') self.input = input self.deferred = deferred self.output = b'' def outReceived(self, data): self.output += data errReceived = outReceived def connectionMade(self): # push the input and send EOF self.transport.write(self.input) self.transport.closeStdin() def processEnded(self, reason): self.deferred.callback((self.output, reason.value.exitCode)) def getProcessOutputAndValueWithInput(executable, args, input): "similar to getProcessOutputAndValue, but also allows injection of input on stdin" d = defer.Deferred() p = _SubprocessProtocol(input, d) (executable, args) = encodeExecutableAndArgs(executable, args) reactor.spawnProcess(p, executable, (executable, *tuple(args))) return d class TestBuildbotCvsMail(unittest.TestCase): buildbot_cvs_mail_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../contrib/buildbot_cvs_mail.py') ) if not os.path.exists(buildbot_cvs_mail_path): skip = f"'{buildbot_cvs_mail_path}' does not exist (normal unless run from git)" def assertOutputOk(self, result, regexList): "assert that the output from getProcessOutputAndValueWithInput matches expectations" (output, code) = result if isinstance(output, bytes): output = output.decode("utf-8") try: self.assertEqual(code, 0, "subprocess exited uncleanly") lines = output.splitlines() self.assertEqual(len(lines), len(regexList), "got wrong number of lines of output") misses = [] for line, regex in zip(lines, regexList): m = re.search(regex, line) if not m: misses.append((regex, line)) self.assertEqual(misses, [], "got non-matching lines") except Exception: log.msg("got output:\n" + output) raise def test_buildbot_cvs_mail_from_cvs1_11(self): # Simulate CVS 1.11 executable = sys.executable args = [ self.buildbot_cvs_mail_path, '--cvsroot="ext:example:/cvsroot"', '[email protected]', '-P', 'test', '-R', '[email protected]', '-t', 'test', 'README', '1.1,1.2', 'hello.c', '2.2,2.3', ] (executable, args) = encodeExecutableAndArgs(executable, args) d = getProcessOutputAndValueWithInput(executable, args, input=test) d.addCallback(self.assertOutputOk, golden_1_11_regex) return d def test_buildbot_cvs_mail_from_cvs1_12(self): # Simulate CVS 1.12, with --path option executable = sys.executable args = [ self.buildbot_cvs_mail_path, '--cvsroot="ext:example.com:/cvsroot"', '[email protected]', '-P', 'test', '--path', 'test', '-R', '[email protected]', '-t', 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3', ] (executable, args) = encodeExecutableAndArgs(executable, args) d = getProcessOutputAndValueWithInput(executable, args, input=test) d.addCallback(self.assertOutputOk, golden_1_12_regex) return d def test_buildbot_cvs_mail_no_args_exits_with_error(self): executable = sys.executable args = [self.buildbot_cvs_mail_path] (executable, args) = encodeExecutableAndArgs(executable, args) d = utils.getProcessOutputAndValue(executable, args) def check(result): _, __, code = result self.assertEqual(code, 2) d.addCallback(check) return d def test_buildbot_cvs_mail_without_email_opt_exits_with_error(self): executable = sys.executable args = [ self.buildbot_cvs_mail_path, '--cvsroot="ext:example.com:/cvsroot"', '-P', 'test', '--path', 'test', '-R', '[email protected]', '-t', 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3', ] (executable, args) = encodeExecutableAndArgs(executable, args) d = utils.getProcessOutputAndValue(executable, args) def check(result): _, __, code = result self.assertEqual(code, 2) d.addCallback(check) return d def test_buildbot_cvs_mail_without_cvsroot_opt_exits_with_error(self): executable = sys.executable args = [ self.buildbot_cvs_mail_path, '--complete-garbage-opt=gomi', '--cvsroot="ext:example.com:/cvsroot"', '[email protected]', '-P', 'test', '--path', 'test', '-R', '[email protected]', '-t', 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3', ] (executable, args) = encodeExecutableAndArgs(executable, args) d = utils.getProcessOutputAndValue(executable, args) def check(result): _, __, code = result self.assertEqual(code, 2) d.addCallback(check) return d def test_buildbot_cvs_mail_with_unknown_opt_exits_with_error(self): executable = sys.executable args = [ self.buildbot_cvs_mail_path, '[email protected]', '-P', 'test', '--path', 'test', '-R', '[email protected]', '-t', 'README', '1.1', '1.2', 'hello.c', '2.2', '2.3', ] (executable, args) = encodeExecutableAndArgs(executable, args) d = utils.getProcessOutputAndValue(executable, args) def check(result): _, __, code = result self.assertEqual(code, 2) d.addCallback(check) return d
8,880
Python
.py
265
25
95
0.576623
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,314
test_clients_tryclient.py
buildbot_buildbot/master/buildbot/test/unit/test_clients_tryclient.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 json import sys from twisted.trial import unittest from buildbot.clients import tryclient from buildbot.util import bytes2unicode class createJobfile(unittest.TestCase): def makeNetstring(self, *strings): return ''.join([f'{len(s)}:{s},' for s in strings]) # versions 1-4 are deprecated and not produced by the try client def test_createJobfile_v5(self): jobid = '123-456' branch = 'branch' baserev = 'baserev' patch_level = 0 patch_body = b'diff...' repository = 'repo' project = 'proj' who = 'someuser' comment = 'insightful comment' builderNames = ['runtests'] properties = {'foo': 'bar'} job = tryclient.createJobfile( jobid, branch, baserev, patch_level, patch_body, repository, project, who, comment, builderNames, properties, ) jobstr = self.makeNetstring( '5', json.dumps({ 'jobid': jobid, 'branch': branch, 'baserev': baserev, 'patch_level': patch_level, 'repository': repository, 'project': project, 'who': who, 'comment': comment, 'builderNames': builderNames, 'properties': properties, 'patch_body': bytes2unicode(patch_body), }), ) self.assertEqual(job, jobstr) def test_createJobfile_v6(self): jobid = '123-456' branch = 'branch' baserev = 'baserev' patch_level = 0 patch_body = b'diff...\xff' repository = 'repo' project = 'proj' who = 'someuser' comment = 'insightful comment' builderNames = ['runtests'] properties = {'foo': 'bar'} job = tryclient.createJobfile( jobid, branch, baserev, patch_level, patch_body, repository, project, who, comment, builderNames, properties, ) jobstr = self.makeNetstring( '6', json.dumps({ 'jobid': jobid, 'branch': branch, 'baserev': baserev, 'patch_level': patch_level, 'repository': repository, 'project': project, 'who': who, 'comment': comment, 'builderNames': builderNames, 'properties': properties, 'patch_body_base64': bytes2unicode(base64.b64encode(patch_body)), }), ) self.assertEqual(job, jobstr) def test_SourceStampExtractor_readPatch(self): sse = tryclient.GitExtractor(None, None, None) for patchlevel, diff in enumerate((None, "", b"")): sse.readPatch(diff, patchlevel) self.assertEqual(sse.patch, (patchlevel, None)) sse.readPatch(b"diff schmiff blah blah blah", 23) self.assertEqual(sse.patch, (23, b"diff schmiff blah blah blah")) def test_GitExtractor_fixBranch(self): sse = tryclient.GitExtractor(None, "origin/master", None) self.assertEqual(sse.branch, "origin/master") sse.fixBranch(b'origi\n') self.assertEqual(sse.branch, "origin/master") sse.fixBranch(b'origin\n') self.assertEqual(sse.branch, "master") def test_GitExtractor_override_baserev(self): sse = tryclient.GitExtractor(None, None, None) sse.override_baserev(b"23ae367063327b79234e081f396ecbc\n") self.assertEqual(sse.baserev, "23ae367063327b79234e081f396ecbc") class RemoteTryPP_TestStream: def __init__(self): self.writes = [] self.is_open = True def write(self, data): assert self.is_open self.writes.append(data) def closeStdin(self): assert self.is_open self.is_open = False def test_RemoteTryPP_encoding(self): rmt = tryclient.RemoteTryPP("job") self.assertTrue(isinstance(rmt.job, str)) rmt.transport = self.RemoteTryPP_TestStream() rmt.connectionMade() self.assertFalse(rmt.transport.is_open) self.assertEqual(len(rmt.transport.writes), 1) self.assertFalse(isinstance(rmt.transport.writes[0], str)) for streamname in "out", "err": sys_streamattr = "std" + streamname rmt_methodattr = streamname + "Received" teststream = self.RemoteTryPP_TestStream() saved_stream = getattr(sys, sys_streamattr) try: setattr(sys, sys_streamattr, teststream) getattr(rmt, rmt_methodattr)(b"data") finally: setattr(sys, sys_streamattr, saved_stream) self.assertEqual(len(teststream.writes), 1) self.assertTrue(isinstance(teststream.writes[0], str))
5,835
Python
.py
156
27.198718
81
0.586791
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,315
test_master.py
buildbot_buildbot/master/buildbot/test/unit/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 import os import signal from unittest import mock from twisted.internet import defer from twisted.internet import reactor from twisted.python import log from twisted.trial import unittest from zope.interface import implementer from buildbot import config from buildbot import master from buildbot import monkeypatches from buildbot.config.master import FileLoader from buildbot.config.master import MasterConfig from buildbot.db import exceptions from buildbot.interfaces import IConfigLoader from buildbot.process.properties import Interpolate from buildbot.secrets.manager import SecretManager from buildbot.test import fakedb from buildbot.test.fake import fakedata from buildbot.test.fake import fakemaster from buildbot.test.fake import fakemq from buildbot.test.fake.botmaster import FakeBotMaster from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import dirs from buildbot.test.util import logging @implementer(IConfigLoader) class FailingLoader: def loadConfig(self): config.error('oh noes') @implementer(IConfigLoader) class DefaultLoader: def loadConfig(self): master_cfg = MasterConfig() master_cfg.db['db_url'] = Interpolate('sqlite:///path-to-%(secret:db_pwd)s-db-file') master_cfg.secretsProviders = [FakeSecretStorage(secretdict={'db_pwd': 's3cr3t'})] return master_cfg class InitTests(unittest.SynchronousTestCase): def test_configfile_configloader_conflict(self): """ If both configfile and config_loader are specified, a configuration error is raised. """ with self.assertRaises(config.ConfigErrors): master.BuildMaster(".", "master.cfg", reactor=reactor, config_loader=DefaultLoader()) def test_configfile_default(self): """ If neither configfile nor config_loader are specified, The default config_loader is a `FileLoader` pointing at `"master.cfg"`. """ m = master.BuildMaster(".", reactor=reactor) self.assertEqual(m.config_loader, FileLoader(".", "master.cfg")) class StartupAndReconfig(dirs.DirsMixin, logging.LoggingMixin, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpLogging() self.basedir = os.path.abspath('basedir') yield self.setUpDirs(self.basedir) # don't create child services self.patch(master.BuildMaster, 'create_child_services', lambda self: None) # patch out a few other annoying things the master likes to do self.patch(monkeypatches, 'patch_all', lambda: None) self.patch(signal, 'signal', lambda sig, hdlr: None) master.BuildMaster.masterHeartbeatService = mock.Mock() self.master = master.BuildMaster( self.basedir, reactor=self.reactor, config_loader=DefaultLoader() ) self.master.sendBuildbotNetUsageData = mock.Mock() self.master.botmaster = FakeBotMaster() self.master.caches = fakemaster.FakeCaches() self.secrets_manager = self.master.secrets_manager = SecretManager() yield self.secrets_manager.setServiceParent(self.master) self.db = self.master.db = fakedb.FakeDBConnector(self.basedir, self, auto_upgrade=True) yield self.db.setServiceParent(self.master) self.mq = self.master.mq = fakemq.FakeMQConnector(self) yield self.mq.setServiceParent(self.master) self.data = self.master.data = fakedata.FakeDataConnector(self.master, self) yield self.data.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tearDownDirs() yield self.tear_down_test_reactor() # tests @defer.inlineCallbacks def test_startup_bad_config(self): self.master.config_loader = FailingLoader() yield self.master.startService() self.assertTrue(self.reactor.stop_called) self.assertLogged("oh noes") self.assertLogged("BuildMaster startup failed") @defer.inlineCallbacks def test_startup_db_not_ready(self): def db_setup(): log.msg("GOT HERE") raise exceptions.DatabaseNotReadyError() self.db.setup = db_setup yield self.master.startService() self.assertTrue(self.reactor.stop_called) self.assertLogged("GOT HERE") self.assertLogged("BuildMaster startup failed") @defer.inlineCallbacks def test_startup_error(self): def db_setup(): raise RuntimeError("oh noes") self.db.setup = db_setup yield self.master.startService() self.assertTrue(self.reactor.stop_called) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) self.assertLogged("BuildMaster startup failed") @defer.inlineCallbacks def test_startup_ok(self): yield self.master.startService() self.assertEqual( self.master.db.configured_url, 'sqlite:///path-to-s3cr3t-db-file', ) self.assertTrue(self.master.data.updates.thisMasterActive) d = self.master.stopService() self.assertTrue(d.called) self.assertFalse(self.reactor.stop_called) self.assertLogged("BuildMaster is running") # check started/stopped messages self.assertFalse(self.master.data.updates.thisMasterActive) @defer.inlineCallbacks def test_startup_ok_waitforshutdown(self): yield self.master.startService() self.assertTrue(self.master.data.updates.thisMasterActive) # use fakebotmaster shutdown delaying self.master.botmaster.delayShutdown = True d = self.master.stopService() self.assertFalse(d.called) # master must only send shutdown once builds are completed self.assertTrue(self.master.data.updates.thisMasterActive) self.master.botmaster.shutdownDeferred.callback(None) self.assertTrue(d.called) self.assertFalse(self.reactor.stop_called) self.assertLogged("BuildMaster is running") # check started/stopped messages self.assertFalse(self.master.data.updates.thisMasterActive) @defer.inlineCallbacks def test_reconfig(self): self.master.reconfigServiceWithBuildbotConfig = mock.Mock( side_effect=lambda n: defer.succeed(None) ) self.master.masterHeartbeatService = mock.Mock() yield self.master.startService() yield self.master.reconfig() yield self.master.stopService() self.master.reconfigServiceWithBuildbotConfig.assert_called_with(mock.ANY) @defer.inlineCallbacks def test_reconfig_bad_config(self): self.master.reconfigService = mock.Mock(side_effect=lambda n: defer.succeed(None)) self.master.masterHeartbeatService = mock.Mock() yield self.master.startService() # reset, since startService called reconfigService self.master.reconfigService.reset_mock() # reconfig, with a failure self.master.config_loader = FailingLoader() yield self.master.reconfig() self.master.stopService() self.assertLogged("configuration update aborted without") self.assertFalse(self.master.reconfigService.called) @defer.inlineCallbacks def test_reconfigService_db_url_changed(self): old = self.master.config = MasterConfig() old.db['db_url'] = Interpolate('sqlite:///%(secret:db_pwd)s') old.secretsProviders = [FakeSecretStorage(secretdict={'db_pwd': 's3cr3t'})] yield self.master.secrets_manager.setup() yield self.master.db.setup() yield self.master.reconfigServiceWithBuildbotConfig(old) self.assertEqual(self.master.db.configured_url, 'sqlite:///s3cr3t') new = MasterConfig() new.db['db_url'] = old.db['db_url'] new.secretsProviders = [FakeSecretStorage(secretdict={'db_pwd': 'other-s3cr3t'})] with self.assertRaises(config.ConfigErrors): yield self.master.reconfigServiceWithBuildbotConfig(new)
8,889
Python
.py
191
39.554974
100
0.721188
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,316
test_fake_secrets_manager.py
buildbot_buildbot/master/buildbot/test/unit/test_fake_secrets_manager.py
from twisted.internet import defer from twisted.trial import unittest from buildbot.secrets.manager import SecretManager from buildbot.secrets.secret import SecretDetails from buildbot.test.fake import fakemaster from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin class TestSecretsManager(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.master.config.secretsProviders = [ FakeSecretStorage(secretdict={"foo": "bar", "other": "value"}) ] @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def testGetManagerService(self): secret_service_manager = SecretManager() fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": "value"}) secret_service_manager.services = [fakeStorageService] expectedClassName = FakeSecretStorage.__name__ expectedSecretDetail = SecretDetails(expectedClassName, "foo", "bar") secret_result = yield secret_service_manager.get("foo") strExpectedSecretDetail = str(secret_result) self.assertEqual(secret_result, expectedSecretDetail) self.assertEqual(secret_result.key, "foo") self.assertEqual(secret_result.value, "bar") self.assertEqual(secret_result.source, expectedClassName) self.assertEqual(strExpectedSecretDetail, "FakeSecretStorage foo: 'bar'") @defer.inlineCallbacks def testGetNoDataManagerService(self): secret_service_manager = SecretManager() fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": "value"}) secret_service_manager.services = [fakeStorageService] secret_result = yield secret_service_manager.get("foo2") self.assertEqual(secret_result, None) @defer.inlineCallbacks def testGetDataMultipleManagerService(self): secret_service_manager = SecretManager() fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": "value"}) otherFakeStorageService = FakeSecretStorage() otherFakeStorageService.reconfigService(secretdict={"foo2": "bar", "other2": "value"}) secret_service_manager.services = [fakeStorageService, otherFakeStorageService] expectedSecretDetail = SecretDetails(FakeSecretStorage.__name__, "foo2", "bar") secret_result = yield secret_service_manager.get("foo2") self.assertEqual(secret_result, expectedSecretDetail) @defer.inlineCallbacks def testGetDataMultipleManagerValues(self): secret_service_manager = SecretManager() fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": ""}) otherFakeStorageService = FakeSecretStorage() otherFakeStorageService.reconfigService(secretdict={"foo2": "bar2", "other": ""}) secret_service_manager.services = [fakeStorageService, otherFakeStorageService] expectedSecretDetail = SecretDetails(FakeSecretStorage.__name__, "other", "") secret_result = yield secret_service_manager.get("other") self.assertEqual(secret_result, expectedSecretDetail) @defer.inlineCallbacks def testGetDataMultipleManagerServiceNoDatas(self): secret_service_manager = SecretManager() fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": "value"}) otherFakeStorageService = FakeSecretStorage() otherFakeStorageService.reconfigService(secretdict={"foo2": "bar", "other2": "value"}) secret_service_manager.services = [fakeStorageService, otherFakeStorageService] secret_result = yield secret_service_manager.get("foo3") self.assertEqual(secret_result, None)
4,122
Python
.py
73
48.90411
94
0.734274
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,317
test_interpolate_secrets.py
buildbot_buildbot/master/buildbot/test/unit/test_interpolate_secrets.py
import gc from twisted.internet import defer from twisted.trial import unittest from buildbot.process.properties import Interpolate from buildbot.secrets.manager import SecretManager from buildbot.test.fake import fakemaster from buildbot.test.fake.fakebuild import FakeBuild from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.config import ConfigErrorsMixin class FakeBuildWithMaster(FakeBuild): def __init__(self, master): super().__init__() self.master = master class TestInterpolateSecrets(TestReactorMixin, unittest.TestCase, ConfigErrorsMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"foo": "bar", "other": "value"}) self.secretsrv = SecretManager() self.secretsrv.services = [fakeStorageService] yield self.secretsrv.setServiceParent(self.master) self.build = FakeBuildWithMaster(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_secret(self): command = Interpolate("echo %(secret:foo)s") rendered = yield self.build.render(command) self.assertEqual(rendered, "echo bar") @defer.inlineCallbacks def test_secret_not_found(self): command = Interpolate("echo %(secret:fuo)s") yield self.assertFailure(self.build.render(command), defer.FirstError) gc.collect() self.flushLoggedErrors(defer.FirstError) self.flushLoggedErrors(KeyError) class TestInterpolateSecretsNoService(TestReactorMixin, unittest.TestCase, ConfigErrorsMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.build = FakeBuildWithMaster(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_secret(self): command = Interpolate("echo %(secret:fuo)s") yield self.assertFailure(self.build.render(command), defer.FirstError) gc.collect() self.flushLoggedErrors(defer.FirstError) self.flushLoggedErrors(KeyError) class TestInterpolateSecretsHiddenSecrets(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) fakeStorageService = FakeSecretStorage() password = "bar" fakeStorageService.reconfigService( secretdict={"foo": password, "other": password + "random", "empty": ""} ) self.secretsrv = SecretManager() self.secretsrv.services = [fakeStorageService] yield self.secretsrv.setServiceParent(self.master) self.build = FakeBuildWithMaster(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_secret(self): command = Interpolate("echo %(secret:foo)s") rendered = yield self.build.render(command) cleantext = self.build.properties.cleanupTextFromSecrets(rendered) self.assertEqual(cleantext, "echo <foo>") @defer.inlineCallbacks def test_secret_replace(self): command = Interpolate("echo %(secret:foo)s %(secret:other)s") rendered = yield self.build.render(command) cleantext = self.build.properties.cleanupTextFromSecrets(rendered) self.assertEqual(cleantext, "echo <foo> <other>") @defer.inlineCallbacks def test_secret_replace_with_empty_secret(self): command = Interpolate("echo %(secret:empty)s %(secret:other)s") rendered = yield self.build.render(command) cleantext = self.build.properties.cleanupTextFromSecrets(rendered) self.assertEqual(cleantext, "echo <other>")
4,172
Python
.py
91
38.923077
94
0.724028
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,318
test_mq_wamp.py
buildbot_buildbot/master/buildbot/test/unit/test_mq_wamp.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 import os import textwrap from unittest import mock from autobahn.wamp.exception import TransportLost from autobahn.wamp.types import SubscribeOptions from twisted.internet import defer from twisted.trial import unittest from buildbot.mq import wamp from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.wamp import connector class FakeEventDetails: def __init__(self, topic): self.topic = topic class ComparableSubscribeOptions(SubscribeOptions): def __eq__(self, other): if not isinstance(other, SubscribeOptions): return False return self.match == other.match __repr__ = SubscribeOptions.__str__ class FakeSubscription: def __init__(self): self.exception_on_unsubscribe = None def unsubscribe(self): if self.exception_on_unsubscribe is not None: raise self.exception_on_unsubscribe() class TestException(Exception): pass class FakeWampConnector: # a fake wamp connector with only one queue def __init__(self): self.subscriptions = [] def topic_match(self, topic): topic = topic.split(".") owntopic = self.topic.split(".") if len(topic) != len(owntopic): return False for i, itopic in enumerate(topic): if owntopic[i] != "" and itopic != owntopic[i]: return False return True def subscribe(self, callback, topic=None, options=None): # record the topic, and to make sure subsequent publish # are correct self.topic = topic # we record the qref_cb self.qref_cb = callback subs = FakeSubscription() self.subscriptions.append(subs) return subs def publish(self, topic, data, options=None): # make sure the topic is compatible with what was subscribed assert self.topic_match(topic) self.last_data = data details = FakeEventDetails(topic=topic) self.qref_cb(json.loads(json.dumps(data)), details=details) class TopicMatch(unittest.TestCase): # test unit tests def test_topic_match(self): matches = [ ("a.b.c", "a.b.c"), ("a..c", "a.c.c"), ("a.b.", "a.b.c"), (".b.", "a.b.c"), ] for i, j in matches: w = FakeWampConnector() w.topic = i self.assertTrue(w.topic_match(j)) def test_topic_not_match(self): matches = [ ("a.b.c", "a.b.d"), ("a..c", "a.b.d"), ("a.b.", "a.c.c"), (".b.", "a.a.c"), ] for i, j in matches: w = FakeWampConnector() w.topic = i self.assertFalse(w.topic_match(j)) class WampMQ(TestReactorMixin, unittest.TestCase): """ Stimulate the code with a fake wamp router: A router which only accepts one subscriber on one topic """ @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.master.wamp = FakeWampConnector() self.mq = wamp.WampMQ() yield self.mq.setServiceParent(self.master) yield self.mq.startService() @defer.inlineCallbacks def tearDown(self): if self.mq.running: yield self.mq.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_startConsuming_basic(self): self.master.wamp.subscribe = mock.Mock() yield self.mq.startConsuming(None, ('a', 'b')) options = ComparableSubscribeOptions(details_arg='details') self.master.wamp.subscribe.assert_called_with( mock.ANY, 'org.buildbot.mq.a.b', options=options ) @defer.inlineCallbacks def test_startConsuming_wildcard(self): self.master.wamp.subscribe = mock.Mock() yield self.mq.startConsuming(None, ('a', None)) options = ComparableSubscribeOptions(match="wildcard", details_arg='details') self.master.wamp.subscribe.assert_called_with( mock.ANY, 'org.buildbot.mq.a.', options=options ) @defer.inlineCallbacks def test_forward_data(self): callback = mock.Mock() yield self.mq.startConsuming(callback, ('a', 'b')) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic callback.assert_called_with(('a', 'b'), 'foo') self.assertEqual(self.master.wamp.last_data, 'foo') @defer.inlineCallbacks def test_unsubscribe_ignores_transport_lost(self): callback = mock.Mock() consumer = yield self.mq.startConsuming(callback, ('a', 'b')) self.assertEqual(len(self.master.wamp.subscriptions), 1) self.master.wamp.subscriptions[0].exception_on_unsubscribe = TransportLost yield consumer.stopConsuming() @defer.inlineCallbacks def test_unsubscribe_logs_exceptions(self): callback = mock.Mock() consumer = yield self.mq.startConsuming(callback, ('a', 'b')) self.assertEqual(len(self.master.wamp.subscriptions), 1) self.master.wamp.subscriptions[0].exception_on_unsubscribe = TestException yield consumer.stopConsuming() self.assertEqual(len(self.flushLoggedErrors(TestException)), 1) @defer.inlineCallbacks def test_forward_data_wildcard(self): callback = mock.Mock() yield self.mq.startConsuming(callback, ('a', None)) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic callback.assert_called_with(('a', 'b'), 'foo') self.assertEqual(self.master.wamp.last_data, 'foo') @defer.inlineCallbacks def test_waits_for_called_callback(self): def callback(_, __): return defer.succeed(None) yield self.mq.startConsuming(callback, ('a', None)) yield self.mq._produce(('a', 'b'), 'foo') self.assertEqual(self.master.wamp.last_data, 'foo') d = self.mq.stopService() self.assertTrue(d.called) @defer.inlineCallbacks def test_waits_for_non_called_callback(self): d1 = defer.Deferred() def callback(_, __): return d1 yield self.mq.startConsuming(callback, ('a', None)) yield self.mq._produce(('a', 'b'), 'foo') self.assertEqual(self.master.wamp.last_data, 'foo') d = self.mq.stopService() self.assertFalse(d.called) d1.callback(None) self.assertTrue(d.called) class FakeConfig: mq = {"type": 'wamp', "router_url": 'wss://foo', "realm": 'realm1'} class WampMQReal(TestReactorMixin, unittest.TestCase): """ Tests a little bit more painful to run, but which involve real communication with a wamp router """ HOW_TO_RUN = textwrap.dedent("""\ define WAMP_ROUTER_URL to a wamp router to run this test > crossbar init > crossbar start & > export WAMP_ROUTER_URL=ws://localhost:8080/ws > trial buildbot.unit.test_mq_wamp""") @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) if "WAMP_ROUTER_URL" not in os.environ: raise unittest.SkipTest(self.HOW_TO_RUN) self.master = yield fakemaster.make_master(self) self.mq = wamp.WampMQ() yield self.mq.setServiceParent(self.master) self.connector = self.master.wamp = connector.WampConnector() yield self.connector.setServiceParent(self.master) yield self.master.startService() config = FakeConfig() config.mq['router_url'] = os.environ["WAMP_ROUTER_URL"] yield self.connector.reconfigServiceWithBuildbotConfig(config) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_forward_data(self): d = defer.Deferred() callback = mock.Mock(side_effect=lambda *a, **kw: d.callback(None)) yield self.mq.startConsuming(callback, ('a', 'b')) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic yield d callback.assert_called_with(('a', 'b'), 'foo') @defer.inlineCallbacks def test_forward_data_wildcard(self): d = defer.Deferred() callback = mock.Mock(side_effect=lambda *a, **kw: d.callback(None)) yield self.mq.startConsuming(callback, ('a', None)) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic yield d callback.assert_called_with(('a', 'b'), 'foo')
9,799
Python
.py
238
33.558824
85
0.651204
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,319
test_fake_httpclientservice.py
buildbot_buildbot/master/buildbot/test/unit/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 from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.reactor import TestReactorMixin from buildbot.util import httpclientservice from buildbot.util import service class myTestedService(service.BuildbotService): name = 'myTestedService' def reconfigService(self, baseurl): self._http = httpclientservice.HTTPSession(self.master.httpservice, baseurl) @defer.inlineCallbacks def doGetRoot(self): res = yield self._http.get("/") # note that at this point, only the http response headers are received if res.code != 200: raise RuntimeError(f"{res.code}: server did not succeed") res_json = yield res.json() # res.json() returns a deferred to represent the time needed to fetch the entire body return res_json class Test(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): yield self.setup_test_reactor(auto_tear_down=False) baseurl = 'http://127.0.0.1:8080' master = yield fakemaster.make_master(self) self._http = yield fakehttpclientservice.HTTPClientService.getService(master, self, baseurl) self.tested = myTestedService(baseurl) yield self.tested.setServiceParent(master) yield master.startService() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_root(self): self._http.expect("get", "/", content_json={'foo': 'bar'}) response = yield self.tested.doGetRoot() self.assertEqual(response, {'foo': 'bar'}) @defer.inlineCallbacks def test_root_error(self): self._http.expect("get", "/", content_json={'foo': 'bar'}, code=404) try: yield self.tested.doGetRoot() except Exception as e: self.assertEqual(str(e), '404: server did not succeed')
2,750
Python
.py
59
41.067797
100
0.725607
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,320
test_steps_git_diffinfo.py
buildbot_buildbot/master/buildbot/test/unit/test_steps_git_diffinfo.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.process import results from buildbot.steps import gitdiffinfo from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectShell from buildbot.test.steps import TestBuildStepMixin try: import unidiff except ImportError: unidiff = None class TestDiffInfo(TestBuildStepMixin, TestReactorMixin, unittest.TestCase): if not unidiff: skip = 'unidiff is required for GitDiffInfo tests' def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() def test_merge_base_failure(self): self.setup_step(gitdiffinfo.GitDiffInfo()) self.expect_commands( ExpectShell(workdir='wkdir', command=['git', 'merge-base', 'HEAD', 'master']) .log('stdio-merge-base', stderr='fatal: Not a valid object name') .exit(128) ) self.expect_log_file_stderr('stdio-merge-base', 'fatal: Not a valid object name\n') self.expect_outcome(result=results.FAILURE, state_string="GitDiffInfo (failure)") return self.run_step() def test_diff_failure(self): self.setup_step(gitdiffinfo.GitDiffInfo()) self.expect_commands( ExpectShell(workdir='wkdir', command=['git', 'merge-base', 'HEAD', 'master']) .log('stdio-merge-base', stdout='1234123412341234') .exit(0), ExpectShell( workdir='wkdir', command=['git', 'diff', '--no-prefix', '-U0', '1234123412341234', 'HEAD'], ) .log('stdio-diff', stderr='fatal: ambiguous argument') .exit(1), ) self.expect_log_file('stdio-merge-base', '1234123412341234') self.expect_log_file_stderr('stdio-diff', 'fatal: ambiguous argument\n') self.expect_outcome(result=results.FAILURE, state_string="GitDiffInfo (failure)") return self.run_step() def test_empty_diff(self): self.setup_step(gitdiffinfo.GitDiffInfo()) self.expect_commands( ExpectShell(workdir='wkdir', command=['git', 'merge-base', 'HEAD', 'master']) .log('stdio-merge-base', stdout='1234123412341234') .exit(0), ExpectShell( workdir='wkdir', command=['git', 'diff', '--no-prefix', '-U0', '1234123412341234', 'HEAD'], ) .log('stdio-diff', stdout='') .exit(0), ) self.expect_log_file('stdio-merge-base', '1234123412341234') self.expect_log_file_stderr('stdio-diff', '') self.expect_outcome(result=results.SUCCESS, state_string="GitDiffInfo") self.expect_build_data('diffinfo-master', b'[]', 'GitDiffInfo') return self.run_step() def test_complex_diff(self): self.setup_step(gitdiffinfo.GitDiffInfo()) self.expect_commands( ExpectShell(workdir='wkdir', command=['git', 'merge-base', 'HEAD', 'master']) .log('stdio-merge-base', stdout='1234123412341234') .exit(0), ExpectShell( workdir='wkdir', command=['git', 'diff', '--no-prefix', '-U0', '1234123412341234', 'HEAD'], ) .log( 'stdio-diff', stdout="""\ diff --git file1 file1 deleted file mode 100644 index 42f90fd..0000000 --- file1 +++ /dev/null @@ -1,3 +0,0 @@ -line11 -line12 -line13 diff --git file2 file2 index c337bf1..1cb02b9 100644 --- file2 +++ file2 @@ -4,0 +5,3 @@ line24 +line24n +line24n2 +line24n3 @@ -15,0 +19,3 @@ line215 +line215n +line215n2 +line215n3 diff --git file3 file3 new file mode 100644 index 0000000..632e269 --- /dev/null +++ file3 @@ -0,0 +1,3 @@ +line31 +line32 +line33 """, ) .exit(0), ) self.expect_log_file('stdio-merge-base', '1234123412341234') self.expect_outcome(result=results.SUCCESS, state_string="GitDiffInfo") diff_info = ( b'[{"source_file": "file1", "target_file": "/dev/null", ' + b'"is_binary": false, "is_rename": false, ' + b'"hunks": [{"ss": 1, "sl": 3, "ts": 0, "tl": 0}]}, ' + b'{"source_file": "file2", "target_file": "file2", ' + b'"is_binary": false, "is_rename": false, ' + b'"hunks": [{"ss": 4, "sl": 0, "ts": 5, "tl": 3}, ' + b'{"ss": 15, "sl": 0, "ts": 19, "tl": 3}]}, ' + b'{"source_file": "/dev/null", "target_file": "file3", ' + b'"is_binary": false, "is_rename": false, ' + b'"hunks": [{"ss": 0, "sl": 0, "ts": 1, "tl": 3}]}]' ) self.expect_build_data('diffinfo-master', diff_info, 'GitDiffInfo') return self.run_step()
5,637
Python
.py
143
32.265734
91
0.617111
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,321
test_configurator_base.py
buildbot_buildbot/master/buildbot/test/unit/test_configurator_base.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.configurators import ConfiguratorBase from buildbot.test.util import configurators class ConfiguratorBaseTests(configurators.ConfiguratorMixin, unittest.SynchronousTestCase): ConfiguratorClass = ConfiguratorBase def test_basic(self): self.setupConfigurator() self.assertEqual( self.config_dict, { 'schedulers': [], 'protocols': {}, 'builders': [], 'workers': [], 'projects': [], 'secretsProviders': [], 'www': {}, }, ) self.assertEqual(self.configurator.workers, [])
1,414
Python
.py
34
34.911765
91
0.685091
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,322
test_mq.py
buildbot_buildbot/master/buildbot/test/unit/test_mq.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.mq import simple from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import interfaces from buildbot.test.util import tuplematching class Tests(interfaces.InterfaceTests): def setUp(self): raise NotImplementedError def test_empty_produce(self): self.mq.produce(('a', 'b', 'c'), {"x": 1}) # ..nothing happens def test_signature_produce(self): @self.assertArgSpecMatches(self.mq.produce) def produce(self, routingKey, data): pass def test_signature_startConsuming(self): @self.assertArgSpecMatches(self.mq.startConsuming) def startConsuming(self, callback, filter, persistent_name=None): pass @defer.inlineCallbacks def test_signature_stopConsuming(self): cons = yield self.mq.startConsuming(lambda: None, ('a',)) @self.assertArgSpecMatches(cons.stopConsuming) def stopConsuming(self): pass def test_signature_waitUntilEvent(self): @self.assertArgSpecMatches(self.mq.waitUntilEvent) def waitUntilEvent(self, filter, check_callback): pass class RealTests(tuplematching.TupleMatchingMixin, Tests): # tests that only "real" implementations will pass # called by the TupleMatchingMixin methods @defer.inlineCallbacks def do_test_match(self, routingKey, shouldMatch, filter): cb = mock.Mock() yield self.mq.startConsuming(cb, filter) self.mq.produce(routingKey, 'x') self.assertEqual(shouldMatch, cb.call_count == 1) if shouldMatch: cb.assert_called_once_with(routingKey, 'x') @defer.inlineCallbacks def test_stopConsuming(self): cb = mock.Mock() qref = yield self.mq.startConsuming(cb, ('abc',)) self.mq.produce(('abc',), {"x": 1}) qref.stopConsuming() self.mq.produce(('abc',), {"x": 1}) cb.assert_called_once_with(('abc',), {"x": 1}) @defer.inlineCallbacks def test_stopConsuming_twice(self): cb = mock.Mock() qref = yield self.mq.startConsuming(cb, ('abc',)) qref.stopConsuming() qref.stopConsuming() # ..nothing bad happens @defer.inlineCallbacks def test_non_persistent(self): cb = mock.Mock() qref = yield self.mq.startConsuming(cb, ('abc',)) cb2 = mock.Mock() qref2 = yield self.mq.startConsuming(cb2, ('abc',)) qref.stopConsuming() self.mq.produce(('abc',), '{}') qref = yield self.mq.startConsuming(cb, ('abc',)) qref.stopConsuming() qref2.stopConsuming() self.assertTrue(cb2.called) self.assertFalse(cb.called) @defer.inlineCallbacks def test_persistent(self): cb = mock.Mock() qref = yield self.mq.startConsuming(cb, ('abc',), persistent_name='ABC') qref.stopConsuming() self.mq.produce(('abc',), '{}') qref = yield self.mq.startConsuming(cb, ('abc',), persistent_name='ABC') qref.stopConsuming() self.assertTrue(cb.called) @defer.inlineCallbacks def test_waitUntilEvent_check_false(self): d = self.mq.waitUntilEvent(('abc',), lambda: False) self.assertEqual(d.called, False) self.mq.produce(('abc',), {"x": 1}) self.assertEqual(d.called, True) res = yield d self.assertEqual(res, (('abc',), {"x": 1})) class TestFakeMQ(TestReactorMixin, unittest.TestCase, Tests): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True) self.mq = self.master.mq self.mq.verifyMessages = False @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class TestSimpleMQ(TestReactorMixin, unittest.TestCase, RealTests): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.mq = simple.SimpleMQ() yield self.mq.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor()
5,093
Python
.py
122
34.959016
80
0.68098
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,323
test_janitor_configurator.py
buildbot_buildbot/master/buildbot/test/unit/test_janitor_configurator.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 datetime from datetime import timedelta from unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.configurators import janitor from buildbot.configurators.janitor import JANITOR_NAME from buildbot.configurators.janitor import BuildDataJanitor from buildbot.configurators.janitor import JanitorConfigurator from buildbot.configurators.janitor import LogChunksJanitor from buildbot.process.results import SUCCESS from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.timed import Nightly from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util import config as configmixin from buildbot.test.util import configurators from buildbot.util import datetime2epoch from buildbot.worker.local import LocalWorker class JanitorConfiguratorTests(configurators.ConfiguratorMixin, unittest.SynchronousTestCase): ConfiguratorClass = JanitorConfigurator def test_nothing(self): self.setupConfigurator() self.assertEqual(self.config_dict, {}) @parameterized.expand([ ('logs', {'logHorizon': timedelta(weeks=1)}, [LogChunksJanitor]), ('build_data', {'build_data_horizon': timedelta(weeks=1)}, [BuildDataJanitor]), ( 'logs_build_data', {'build_data_horizon': timedelta(weeks=1), 'logHorizon': timedelta(weeks=1)}, [LogChunksJanitor, BuildDataJanitor], ), ]) def test_steps(self, name, configuration, exp_steps): self.setupConfigurator(**configuration) self.expectWorker(JANITOR_NAME, LocalWorker) self.expectScheduler(JANITOR_NAME, Nightly) self.expectScheduler(JANITOR_NAME + "_force", ForceScheduler) self.expectBuilderHasSteps(JANITOR_NAME, exp_steps) self.expectNoConfigError() class LogChunksJanitorTests( TestBuildStepMixin, configmixin.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setup_test_build_step() self.patch(janitor, "now", lambda: datetime.datetime(year=2017, month=1, day=1)) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_basic(self): self.setup_step(LogChunksJanitor(logHorizon=timedelta(weeks=1))) self.master.db.logs.deleteOldLogChunks = mock.Mock(return_value=3) self.expect_outcome(result=SUCCESS, state_string="deleted 3 logchunks") yield self.run_step() expected_timestamp = datetime2epoch(datetime.datetime(year=2016, month=12, day=25)) self.master.db.logs.deleteOldLogChunks.assert_called_with(expected_timestamp) @defer.inlineCallbacks def test_build_data(self): self.setup_step(BuildDataJanitor(build_data_horizon=timedelta(weeks=1))) self.master.db.build_data.deleteOldBuildData = mock.Mock(return_value=4) self.expect_outcome(result=SUCCESS, state_string="deleted 4 build data key-value pairs") yield self.run_step() expected_timestamp = datetime2epoch(datetime.datetime(year=2016, month=12, day=25)) self.master.db.build_data.deleteOldBuildData.assert_called_with(expected_timestamp)
4,150
Python
.py
83
44.939759
96
0.765417
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,324
test_mq_simple.py
buildbot_buildbot/master/buildbot/test/unit/test_mq_simple.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.mq import simple from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin class SimpleMQ(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.mq = simple.SimpleMQ() self.mq.setServiceParent(self.master) yield self.mq.startService() @defer.inlineCallbacks def tearDown(self): if self.mq.running: yield self.mq.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_forward_data(self): callback = mock.Mock() yield self.mq.startConsuming(callback, ('a', 'b')) # _produce returns a deferred yield self.mq.produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic callback.assert_called_with(('a', 'b'), 'foo') @defer.inlineCallbacks def test_forward_data_wildcard(self): callback = mock.Mock() yield self.mq.startConsuming(callback, ('a', None)) # _produce returns a deferred yield self.mq.produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic callback.assert_called_with(('a', 'b'), 'foo') @defer.inlineCallbacks def test_waits_for_called_callback(self): def callback(_, __): return defer.succeed(None) yield self.mq.startConsuming(callback, ('a', None)) yield self.mq.produce(('a', 'b'), 'foo') d = self.mq.stopService() self.assertTrue(d.called) @defer.inlineCallbacks def test_waits_for_non_called_callback(self): d1 = defer.Deferred() def callback(_, __): return d1 yield self.mq.startConsuming(callback, ('a', None)) yield self.mq.produce(('a', 'b'), 'foo') d = self.mq.stopService() self.assertFalse(d.called) d1.callback(None) self.assertTrue(d.called)
2,932
Python
.py
70
35.585714
79
0.68458
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,325
test_stats_service.py
buildbot_buildbot/master/buildbot/test/unit/test_stats_service.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.errors import CaptureCallbackError from buildbot.statistics import capture from buildbot.statistics import stats_service from buildbot.statistics import storage_backends from buildbot.statistics.storage_backends.base import StatsStorageBase from buildbot.statistics.storage_backends.influxdb_client import InfluxStorageService from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.fake import fakestats from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util import logging if TYPE_CHECKING: from buildbot.db.builds import BuildModel class TestStatsServicesBase(TestReactorMixin, unittest.TestCase): BUILDER_NAMES = ['builder1', 'builder2'] BUILDER_IDS = [1, 2] @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) yield self.master.db.insert_test_data([ fakedb.Builder(id=builderid, name=name) for builderid, name in zip(self.BUILDER_IDS, self.BUILDER_NAMES) ]) self.stats_service = stats_service.StatsService( storage_backends=[fakestats.FakeStatsStorageService()], name="FakeStatsService" ) yield self.stats_service.setServiceParent(self.master) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() class TestStatsServicesConfiguration(TestStatsServicesBase): @defer.inlineCallbacks def test_reconfig_with_no_storage_backends(self): new_storage_backends = [] yield self.stats_service.reconfigService(new_storage_backends) self.checkEqual(new_storage_backends) @defer.inlineCallbacks def test_reconfig_with_fake_storage_backend(self): new_storage_backends = [ fakestats.FakeStatsStorageService(name='One'), fakestats.FakeStatsStorageService(name='Two'), ] yield self.stats_service.reconfigService(new_storage_backends) self.checkEqual(new_storage_backends) @defer.inlineCallbacks def test_reconfig_with_consumers(self): backend = fakestats.FakeStatsStorageService(name='One') backend.captures = [capture.CaptureProperty('test_builder', 'test')] new_storage_backends = [backend] yield self.stats_service.reconfigService(new_storage_backends) yield self.stats_service.reconfigService(new_storage_backends) self.assertEqual(len(self.master.mq.qrefs), 1) @defer.inlineCallbacks def test_bad_configuration(self): # Reconfigure with a bad configuration. new_storage_backends = [mock.Mock()] with self.assertRaises(TypeError): yield self.stats_service.reconfigService(new_storage_backends) def checkEqual(self, new_storage_backends): # Check whether the new_storage_backends was set in reconfigService registeredStorageServices = [ s for s in self.stats_service.registeredStorageServices if isinstance(s, StatsStorageBase) ] for s in new_storage_backends: if s not in registeredStorageServices: raise AssertionError("reconfigService failed. Not all storage services registered.") class TestInfluxDB(TestStatsServicesBase, logging.LoggingMixin): # Smooth test of influx db service. We don't want to force people to install influxdb, so we # just disable this unit test if the influxdb module is not installed, # using SkipTest @defer.inlineCallbacks def test_influxdb_not_installed(self): captures = [capture.CaptureProperty('test_builder', 'test')] try: # Try to import import influxdb # pylint: disable=import-outside-toplevel # consume it somehow to please pylint _ = influxdb except ImportError: with self.assertRaises(config.ConfigErrors): InfluxStorageService( "fake_url", 12345, "fake_user", "fake_password", "fake_db", captures ) # if instead influxdb is installed, then initialize it - no errors # should be realized else: new_storage_backends = [ InfluxStorageService( "fake_url", 12345, "fake_user", "fake_password", "fake_db", captures ) ] yield self.stats_service.reconfigService(new_storage_backends) @defer.inlineCallbacks def test_influx_storage_service_fake_install(self): # use a fake InfluxDBClient to test InfluxStorageService in systems which # don't have influxdb installed. Primarily useful for test coverage. self.patch(storage_backends.influxdb_client, 'InfluxDBClient', fakestats.FakeInfluxDBClient) captures = [capture.CaptureProperty('test_builder', 'test')] new_storage_backends = [ InfluxStorageService( "fake_url", "fake_port", "fake_user", "fake_password", "fake_db", captures ) ] yield self.stats_service.reconfigService(new_storage_backends) def test_influx_storage_service_post_value(self): # test the thd_postStatsValue method of InfluxStorageService self.patch(storage_backends.influxdb_client, 'InfluxDBClient', fakestats.FakeInfluxDBClient) svc = InfluxStorageService( "fake_url", "fake_port", "fake_user", "fake_password", "fake_db", "fake_stats" ) post_data = {'name': 'test', 'value': 'test'} context = {'x': 'y'} svc.thd_postStatsValue(post_data, "test_series_name", context) data = { 'measurement': "test_series_name", 'fields': {"name": "test", "value": "test"}, 'tags': {'x': 'y'}, } points = [data] self.assertEqual(svc.client.points, points) def test_influx_service_not_inited(self): self.setUpLogging() self.patch(storage_backends.influxdb_client, 'InfluxDBClient', fakestats.FakeInfluxDBClient) svc = InfluxStorageService( "fake_url", "fake_port", "fake_user", "fake_password", "fake_db", "fake_stats" ) svc._inited = False svc.thd_postStatsValue("test", "test", "test") self.assertLogged("Service.*not initialized") class TestStatsServicesConsumers(TestBuildStepMixin, TestStatsServicesBase): """ Test the stats service from a fake step """ @defer.inlineCallbacks def setUp(self): yield super().setUp() self.routingKey = ("builders", self.BUILDER_IDS[0], "builds", 1, "finished") self.master.mq.verifyMessages = False @defer.inlineCallbacks def setupBuild(self): yield self.master.db.insert_test_data([ fakedb.Build( id=1, masterid=1, workerid=1, builderid=self.BUILDER_IDS[0], buildrequestid=1, number=1, ), ]) @defer.inlineCallbacks def setupFakeStorage(self, captures): self.fake_storage_service = fakestats.FakeStatsStorageService() self.fake_storage_service.captures = captures yield self.stats_service.reconfigService([self.fake_storage_service]) def get_dict(self, build: BuildModel): return { "buildid": 1, "number": build.number, "builderid": build.builderid, "buildrequestid": build.buildrequestid, "workerid": build.workerid, "masterid": build.masterid, "started_at": build.started_at, "complete": True, "complete_at": build.complete_at, "state_string": '', "results": 0, } @defer.inlineCallbacks def end_build_call_consumers(self): self.master.db.builds.finishBuild(buildid=1, results=0) build = yield self.master.db.builds.getBuild(buildid=1) self.master.mq.callConsumer(self.routingKey, self.get_dict(build)) @defer.inlineCallbacks def test_property_capturing(self): self.setupFakeStorage([capture.CaptureProperty('builder1', 'test_name')]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') yield self.end_build_call_consumers() self.assertEqual( [ ( {'name': 'test_name', 'value': 'test_value'}, 'builder1-test_name', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_property_capturing_all_builders(self): self.setupFakeStorage([capture.CapturePropertyAllBuilders('test_name')]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') yield self.end_build_call_consumers() self.assertEqual( [ ( {'name': 'test_name', 'value': 'test_value'}, 'builder1-test_name', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_property_capturing_regex(self): self.setupFakeStorage([capture.CaptureProperty('builder1', 'test_n.*', regex=True)]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') yield self.end_build_call_consumers() self.assertEqual( [ ( {'name': 'test_name', 'value': 'test_value'}, 'builder1-test_name', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_property_capturing_error(self): self.setupFakeStorage([capture.CaptureProperty('builder1', 'test')]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') self.master.db.builds.finishBuild(buildid=1, results=0) build = yield self.master.db.builds.getBuild(buildid=1) cap = self.fake_storage_service.captures[0] yield self.assertFailure( cap.consume(self.routingKey, self.get_dict(build)), CaptureCallbackError ) @defer.inlineCallbacks def test_property_capturing_alt_callback(self): def cb(*args, **kwargs): return 'test_value' self.setupFakeStorage([capture.CaptureProperty('builder1', 'test_name', cb)]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') yield self.end_build_call_consumers() self.assertEqual( [ ( {'name': 'test_name', 'value': 'test_value'}, 'builder1-test_name', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_build_start_time_capturing(self): self.setupFakeStorage([capture.CaptureBuildStartTime('builder1')]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual( 'start-time', next(iter(self.fake_storage_service.stored_data[0][0].keys())) ) @defer.inlineCallbacks def test_build_start_time_capturing_all_builders(self): self.setupFakeStorage([capture.CaptureBuildStartTimeAllBuilders()]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual( 'start-time', next(iter(self.fake_storage_service.stored_data[0][0].keys())) ) @defer.inlineCallbacks def test_build_start_time_capturing_alt_callback(self): def cb(*args, **kwargs): return '2015-07-08T01:45:17.391018' self.setupFakeStorage([capture.CaptureBuildStartTime('builder1', cb)]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual( 'start-time', next(iter(self.fake_storage_service.stored_data[0][0].keys())) ) @defer.inlineCallbacks def test_build_end_time_capturing(self): self.setupFakeStorage([capture.CaptureBuildEndTime('builder1')]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual('end-time', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_end_time_capturing_all_builders(self): self.setupFakeStorage([capture.CaptureBuildEndTimeAllBuilders()]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual('end-time', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_end_time_capturing_alt_callback(self): def cb(*args, **kwargs): return '2015-07-08T01:45:17.391018' self.setupFakeStorage([capture.CaptureBuildEndTime('builder1', cb)]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual('end-time', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def build_time_capture_helper(self, time_type, cb=None): self.setupFakeStorage([ capture.CaptureBuildDuration('builder1', report_in=time_type, callback=cb) ]) yield self.setupBuild() yield self.end_build_call_consumers() @defer.inlineCallbacks def test_build_duration_capturing_seconds(self): yield self.build_time_capture_helper('seconds') self.assertEqual('duration', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_duration_capturing_minutes(self): yield self.build_time_capture_helper('minutes') self.assertEqual('duration', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_duration_capturing_hours(self): yield self.build_time_capture_helper('hours') self.assertEqual('duration', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) def test_build_duration_report_in_error(self): with self.assertRaises(config.ConfigErrors): capture.CaptureBuildDuration('builder1', report_in='foobar') @defer.inlineCallbacks def test_build_duration_capturing_alt_callback(self): def cb(*args, **kwargs): return 10 yield self.build_time_capture_helper('seconds', cb) self.assertEqual('duration', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_duration_capturing_all_builders(self): self.setupFakeStorage([capture.CaptureBuildDurationAllBuilders()]) yield self.setupBuild() yield self.end_build_call_consumers() self.assertEqual('duration', next(iter(self.fake_storage_service.stored_data[0][0].keys()))) @defer.inlineCallbacks def test_build_times_capturing_error(self): def cb(*args, **kwargs): raise TypeError self.setupFakeStorage([capture.CaptureBuildStartTime('builder1', cb)]) yield self.setupBuild() self.master.db.builds.setBuildProperty(1, 'test_name', 'test_value', 'test_source') self.master.db.builds.finishBuild(buildid=1, results=0) build = yield self.master.db.builds.getBuild(buildid=1) cap = self.fake_storage_service.captures[0] yield self.assertFailure( cap.consume(self.routingKey, self.get_dict(build)), CaptureCallbackError ) self.setupFakeStorage([capture.CaptureBuildEndTime('builder1', cb)]) cap = self.fake_storage_service.captures[0] yield self.assertFailure( cap.consume(self.routingKey, self.get_dict(build)), CaptureCallbackError ) self.setupFakeStorage([capture.CaptureBuildDuration('builder1', callback=cb)]) cap = self.fake_storage_service.captures[0] yield self.assertFailure( cap.consume(self.routingKey, self.get_dict(build)), CaptureCallbackError ) @defer.inlineCallbacks def test_yield_metrics_value(self): self.setupFakeStorage([capture.CaptureBuildStartTime('builder1')]) yield self.setupBuild() yield self.end_build_call_consumers() yield self.stats_service.yieldMetricsValue('test', {'test': 'test'}, 1) build_data = yield self.stats_service.master.data.get(('builds', 1)) routingKey = ("stats-yieldMetricsValue", "stats-yield-data") msg = {'data_name': 'test', 'post_data': {'test': 'test'}, 'build_data': build_data} exp = [(routingKey, msg)] self.stats_service.master.mq.assertProductions(exp) @defer.inlineCallbacks def test_capture_data(self): self.setupFakeStorage([capture.CaptureData('test', 'builder1')]) yield self.setupBuild() self.master.db.builds.finishBuild(buildid=1, results=0) build_data = yield self.stats_service.master.data.get(('builds', 1)) msg = {'data_name': 'test', 'post_data': {'test': 'test'}, 'build_data': build_data} routingKey = ("stats-yieldMetricsValue", "stats-yield-data") self.master.mq.callConsumer(routingKey, msg) self.assertEqual( [ ( {'test': 'test'}, 'builder1-test', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_capture_data_all_builders(self): self.setupFakeStorage([capture.CaptureDataAllBuilders('test')]) yield self.setupBuild() self.master.db.builds.finishBuild(buildid=1, results=0) build_data = yield self.stats_service.master.data.get(('builds', 1)) msg = {'data_name': 'test', 'post_data': {'test': 'test'}, 'build_data': build_data} routingKey = ("stats-yieldMetricsValue", "stats-yield-data") self.master.mq.callConsumer(routingKey, msg) self.assertEqual( [ ( {'test': 'test'}, 'builder1-test', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_capture_data_alt_callback(self): def cb(*args, **kwargs): return {'test': 'test'} self.setupFakeStorage([capture.CaptureData('test', 'builder1', cb)]) yield self.setupBuild() self.master.db.builds.finishBuild(buildid=1, results=0) build_data = yield self.stats_service.master.data.get(('builds', 1)) msg = {'data_name': 'test', 'post_data': {'test': 'test'}, 'build_data': build_data} routingKey = ("stats-yieldMetricsValue", "stats-yield-data") self.master.mq.callConsumer(routingKey, msg) self.assertEqual( [ ( {'test': 'test'}, 'builder1-test', {'build_number': '1', 'builder_name': 'builder1'}, ) ], self.fake_storage_service.stored_data, ) @defer.inlineCallbacks def test_capture_data_error(self): def cb(*args, **kwargs): raise TypeError self.setupFakeStorage([capture.CaptureData('test', 'builder1', cb)]) yield self.setupBuild() self.master.db.builds.finishBuild(buildid=1, results=0) build_data = yield self.stats_service.master.data.get(('builds', 1)) msg = {'data_name': 'test', 'post_data': {'test': 'test'}, 'build_data': build_data} routingKey = ("stats-yieldMetricsValue", "stats-yield-data") cap = self.fake_storage_service.captures[0] yield self.assertFailure(cap.consume(routingKey, msg), CaptureCallbackError)
21,619
Python
.py
462
37.274892
100
0.646732
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,326
test_test_util_validation.py
buildbot_buildbot/master/buildbot/test/unit/test_test_util_validation.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 datetime import locale from twisted.python import log from twisted.trial import unittest from buildbot.test.util import validation from buildbot.util import UTC class VerifyDict(unittest.TestCase): def doValidationTest(self, validator, good, bad): for g in good: log.msg(f'expect {g!r} to be good') msgs = list(validator.validate('g', g)) self.assertEqual(msgs, [], f'messages for {g!r}') for b in bad: log.msg(f'expect {b!r} to be bad') msgs = list(validator.validate('b', b)) self.assertNotEqual(msgs, [], f'no messages for {b!r}') log.msg('..got messages:') for msg in msgs: log.msg(" " + msg) def test_IntValidator(self): self.doValidationTest( validation.IntValidator(), good=[1, 10**100], bad=[1.0, "one", "1", None] ) def test_BooleanValidator(self): self.doValidationTest( validation.BooleanValidator(), good=[True, False], bad=["yes", "no", 1, 0, None] ) def test_StringValidator(self): self.doValidationTest( validation.StringValidator(), good=["unicode only"], bad=[None, b"bytestring"] ) def test_BinaryValidator(self): self.doValidationTest( validation.BinaryValidator(), good=[b"bytestring"], bad=[None, "no unicode"] ) def test_DateTimeValidator(self): self.doValidationTest( validation.DateTimeValidator(), good=[ datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC), ], bad=[ None, 198847493, # no timezone datetime.datetime(1980, 6, 15, 12, 31, 15), ], ) def test_IdentifierValidator(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 self.doValidationTest( validation.IdentifierValidator(50), good=["linux", "Linux", "abc123", "a" * 50, '\N{SNOWMAN}'], bad=[ None, '', b'linux', 'a/b', "a.b.c.d", "a-b_c.d9", 'spaces not allowed', "a" * 51, "123 no initial digits", ], ) def test_NoneOk(self): self.doValidationTest( validation.NoneOk(validation.BooleanValidator()), good=[True, False, None], bad=[1, "yes"], ) def test_DictValidator(self): self.doValidationTest( validation.DictValidator( a=validation.BooleanValidator(), b=validation.StringValidator(), optionalNames=['b'] ), good=[ {'a': True}, {'a': True, 'b': 'xyz'}, ], bad=[ None, 1, "hi", {}, {'a': 1}, {'a': 1, 'b': 'xyz'}, {'a': True, 'b': 999}, {'a': True, 'b': 'xyz', 'c': 'extra'}, ], ) def test_DictValidator_names(self): v = validation.DictValidator(a=validation.BooleanValidator()) self.assertEqual(list(v.validate('v', {'a': 1})), ["v['a'] (1) is not a boolean"]) def test_ListValidator(self): self.doValidationTest( validation.ListValidator(validation.BooleanValidator()), good=[ [], [True], [False, True], ], bad=[None, ['a'], [True, 'a'], 1, "hi"], ) def test_ListValidator_names(self): v = validation.ListValidator(validation.BooleanValidator()) self.assertEqual(list(v.validate('v', ['a'])), ["v[0] ('a') is not a boolean"]) def test_SourcedPropertiesValidator(self): self.doValidationTest( validation.SourcedPropertiesValidator(), good=[ {'pname': ('{"a":"b"}', 'test')}, ], bad=[ None, 1, b"hi", {'pname': {b'a': b'b'}}, # no source # name not unicode {'pname': ({b'a': b'b'}, 'test')}, # source not unicode {'pname': ({b'a': b'b'}, 'test')}, # self is not json-able {'pname': (self, 'test')}, ], ) def test_MessageValidator(self): self.doValidationTest( validation.MessageValidator( events=[b'started', b'stopped'], messageValidator=validation.DictValidator( a=validation.BooleanValidator(), xid=validation.IntValidator(), yid=validation.IntValidator(), ), ), good=[ (('thing', '1', '2', 'started'), {'xid': 1, 'yid': 2, 'a': True}), ], bad=[ # routingKey is not a tuple ('thing', {}), # routingKey has wrong event (('thing', '1', '2', 'exploded'), {'xid': 1, 'yid': 2, 'a': True}), # routingKey element has wrong type (('thing', 1, 2, 'started'), {'xid': 1, 'yid': 2, 'a': True}), # routingKey element isn't in message (('thing', '1', '2', 'started'), {'xid': 1, 'a': True}), # message doesn't validate (('thing', '1', '2', 'started'), {'xid': 1, 'yid': 2, 'a': 'x'}), ], ) def test_Selector(self): sel = validation.Selector() sel.add(lambda x: x == 'int', validation.IntValidator()) sel.add(lambda x: x == 'str', validation.StringValidator()) self.doValidationTest( sel, good=[ ('int', 1), ('str', 'hi'), ], bad=[ ('int', 'hi'), ('str', 1), ('float', 1.0), ], )
7,182
Python
.py
190
26.021053
100
0.503155
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,327
test_steps_mixin.py
buildbot_buildbot/master/buildbot/test/unit/test_steps_mixin.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.process import buildstep from buildbot.process.results import SUCCESS from buildbot.test.reactor import TestReactorMixin from buildbot.test.steps import ExpectShell from buildbot.test.steps import TestBuildStepMixin from buildbot.test.util.warnings import assertProducesWarning from buildbot.test.util.warnings import assertProducesWarnings from buildbot.warnings import DeprecatedApiWarning class TestStep(buildstep.ShellMixin, buildstep.BuildStep): def __init__(self, text): self.setupShellMixin({}) super().__init__() self.text = text @defer.inlineCallbacks def run(self): for file in self.build.allFiles(): cmd = yield self.makeRemoteShellCommand(command=["echo", "build_file", file]) yield self.runCommand(cmd) version = self.build.getWorkerCommandVersion("shell", None) if version != "99.99": cmd = yield self.makeRemoteShellCommand(command=["echo", "version", version]) yield self.runCommand(cmd) cmd = yield self.makeRemoteShellCommand(command=["echo", "done", self.text]) yield self.runCommand(cmd) return SUCCESS class TestTestBuildStepMixin(TestBuildStepMixin, TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) return self.setup_test_build_step() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_build_step() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_setup_build(self): self.setup_build( worker_version={"*": "2.9"}, worker_env={"key": "value"}, build_files=["build.txt"] ) self.setup_step(TestStep("step1")) self.expect_commands( ExpectShell( workdir="wkdir", command=["echo", "build_file", "build.txt"], env={"key": "value"} ).exit(0), ExpectShell( workdir="wkdir", command=["echo", "version", "2.9"], env={"key": "value"} ).exit(0), ExpectShell( workdir="wkdir", command=["echo", "done", "step1"], env={"key": "value"} ).exit(0), ) self.expect_outcome(SUCCESS) yield self.run_step() @defer.inlineCallbacks def test_old_setup_step_args(self): with assertProducesWarnings( DeprecatedApiWarning, num_warnings=3, message_pattern=".*has been deprecated, use setup_build\\(\\) to pass this information", ): self.setup_step( TestStep("step1"), worker_version={"*": "2.9"}, worker_env={"key": "value"}, build_files=["build.txt"], ) self.expect_commands( ExpectShell( workdir="wkdir", command=["echo", "build_file", "build.txt"], env={"key": "value"} ).exit(0), ExpectShell( workdir="wkdir", command=["echo", "version", "2.9"], env={"key": "value"} ).exit(0), ExpectShell( workdir="wkdir", command=["echo", "done", "step1"], env={"key": "value"} ).exit(0), ) self.expect_outcome(SUCCESS) yield self.run_step() def test_get_nth_step(self): self.setup_step(TestStep("step1")) self.assertTrue(isinstance(self.get_nth_step(0), TestStep)) with assertProducesWarning(DeprecatedApiWarning, "step attribute has been deprecated"): self.assertTrue(isinstance(self.step, TestStep)) @defer.inlineCallbacks def test_multiple_steps(self): self.setup_step(TestStep("step1")) self.setup_step(TestStep("step2")) self.expect_commands( ExpectShell(workdir="wkdir", command=["echo", "done", "step1"]).stdout("out1").exit(0), ExpectShell(workdir="wkdir", command=["echo", "done", "step2"]).stdout("out2").exit(0), ) self.expect_log_file("stdio", "out1\n", step_index=0) self.expect_log_file("stdio", "out2\n", step_index=1) self.expect_outcome(SUCCESS) self.expect_outcome(SUCCESS) yield self.run_step()
5,004
Python
.py
112
36.267857
100
0.640631
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,328
test_plugins.py
buildbot_buildbot/master/buildbot/test/unit/test_plugins.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 """ Unit tests for the plugin framework """ import warnings from unittest import mock from twisted.trial import unittest from zope.interface import implementer import buildbot.plugins.db from buildbot.errors import PluginDBError from buildbot.interfaces import IPlugin from buildbot.test.util.warnings import assertProducesWarning # buildbot.plugins.db needs to be imported for patching, however just 'db' is # much shorter for using in tests db = buildbot.plugins.db class FakeEntry: """ An entry suitable for unit tests """ def __init__(self, name, group, fail_require, value, warnings=None): self._name = name self._group = group self._fail_require = fail_require self._value = value self._warnings = [] if warnings is None else warnings @property def name(self): return self._name @property def group(self): return self._group def require(self): """ handle external dependencies """ if self._fail_require: raise RuntimeError('Fail require as requested') def load(self): """ handle loading """ for w in self._warnings: warnings.warn(w, DeprecationWarning, stacklevel=2) return self._value class FakeDistribution: def __init__(self, name, version, fake_entries_distribution): self.entry_points = fake_entries_distribution self.version = version self.metadata = {} self.metadata['Name'] = name self.metadata['Version'] = version class FakeDistributionNoMetadata: def __init__(self, name, version, fake_entries_distribution): self.entry_points = fake_entries_distribution self.metadata = {} class ITestInterface(IPlugin): """ test interface """ def hello(): pass @implementer(ITestInterface) class ClassWithInterface: """ a class to implement a simple interface """ def __init__(self, name=None): self._name = name def hello(self, name=None): "implement the required method" return name or self._name class ClassWithNoInterface: """ just a class """ # NOTE: buildbot.plugins.db prepends the group with common namespace -- # 'buildbot.' _FAKE_ENTRIES = { 'buildbot.interface': [ FakeEntry('good', 'buildbot.interface', False, ClassWithInterface), FakeEntry('deep.path', 'buildbot.interface', False, ClassWithInterface), ], 'buildbot.interface_warnings': [ FakeEntry( 'good', 'buildbot.interface_warnings', False, ClassWithInterface, warnings=['test warning'], ), FakeEntry( 'deep.path', 'buildbot.interface_warnings', False, ClassWithInterface, warnings=['test warning'], ), ], 'buildbot.interface_failed': [ FakeEntry('good', 'buildbot.interface_failed', True, ClassWithInterface) ], 'buildbot.no_interface': [ FakeEntry('good', 'buildbot.no_interface', False, ClassWithNoInterface) ], 'buildbot.no_interface_again': [ FakeEntry('good', 'buildbot.no_interface_again', False, ClassWithNoInterface) ], 'buildbot.no_interface_failed': [ FakeEntry('good', 'buildbot.no_interface_failed', True, ClassWithNoInterface) ], 'buildbot.duplicates': [ FakeEntry('good', 'buildbot.duplicates', False, ClassWithNoInterface), FakeEntry('good', 'buildbot.duplicates', False, ClassWithNoInterface), ], } def fake_find_distribution_info(entry_name, entry_group): return ('non-existent', 'irrelevant') class TestFindDistributionInfo(unittest.TestCase): def test_exists_in_1st_ep(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep1', 'group_ep1') self.assertEqual(('name_1', 'version_1'), result) def test_exists_in_last_ep(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), FakeEntry('ep2', 'group_ep2', False, ClassWithNoInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep2', 'group_ep2') self.assertEqual(('name_1', 'version_1'), result) def test_no_group(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('ep1', 'no_group') def test_no_name(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('no_name', 'group_ep1') def test_no_name_no_group(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('no_name', 'no_group') def test_no_metadata_error_in_1st_dist(self): distributions = [ FakeDistributionNoMetadata( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ) ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('ep1', 'group_ep1') def test_no_metadata_error_in_last_dist(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistributionNoMetadata( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep2', False, ClassWithInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('ep2', 'group_ep2') def test_exists_in_last_dist_1st_ep(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistribution( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep2', False, ClassWithInterface), FakeEntry('ep3', 'group_ep3', False, ClassWithNoInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep2', 'group_ep2') self.assertEqual(('name_2', 'version_2'), result) def test_exists_in_last_dist_last_ep(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistribution( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep2', False, ClassWithInterface), FakeEntry('ep3', 'group_ep3', False, ClassWithNoInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep3', 'group_ep3') self.assertEqual(('name_2', 'version_2'), result) def test_1st_dist_no_ep(self): distributions = [ FakeDistribution('name_1', 'version_1', []), FakeDistribution( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep2', False, ClassWithInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep2', 'group_ep2') self.assertEqual(('name_2', 'version_2'), result) def test_exists_in_2nd_dist_ep_no_metadada(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistributionNoMetadata( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep2', False, ClassWithInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): with self.assertRaises(PluginDBError): buildbot.plugins.db.find_distribution_info('ep2', 'group_ep2') def test_same_groups_different_ep(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistribution( 'name_2', 'version_2', [ FakeEntry('ep2', 'group_ep1', False, ClassWithInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep2', 'group_ep1') self.assertEqual(('name_2', 'version_2'), result) def test_same_ep_different_groups(self): distributions = [ FakeDistribution( 'name_1', 'version_1', [ FakeEntry('ep1', 'group_ep1', False, ClassWithInterface), ], ), FakeDistribution( 'name_2', 'version_2', [ FakeEntry('ep1', 'group_ep2', False, ClassWithInterface), ], ), ] with mock.patch('buildbot.plugins.db.distributions', return_value=distributions): result = buildbot.plugins.db.find_distribution_info('ep1', 'group_ep2') self.assertEqual(('name_2', 'version_2'), result) def provide_fake_entry_points(): return _FAKE_ENTRIES _fake_find_distribution_info_dups_counter = 0 def fake_find_distribution_info_dups(entry_name, entry_group): # entry_name is always 'good' global _fake_find_distribution_info_dups_counter if _fake_find_distribution_info_dups_counter == 0: _fake_find_distribution_info_dups_counter += 1 return ('non-existent', 'module_first') else: # _fake_find_distribution_info_dups_counter == 1: _fake_find_distribution_info_dups_counter = 0 return ('non-existent', 'module_second') @mock.patch('buildbot.plugins.db.entry_points', provide_fake_entry_points) class TestBuildbotPlugins(unittest.TestCase): def setUp(self): buildbot.plugins.db._DB = buildbot.plugins.db._PluginDB() def test_check_group_registration(self): with mock.patch.object(buildbot.plugins.db, '_DB', db._PluginDB()): # The groups will be prepended with namespace, so info() will # return a dictionary with right keys, but no data groups = set(_FAKE_ENTRIES.keys()) for group in groups: db.get_plugins(group) registered = set(db.info().keys()) self.assertEqual(registered, groups) self.assertEqual(registered, set(db.namespaces())) @mock.patch('buildbot.plugins.db.find_distribution_info', fake_find_distribution_info) def test_interface_provided_simple(self): # Basic check before the actual test self.assertTrue(ITestInterface.implementedBy(ClassWithInterface)) plugins = db.get_plugins('interface', interface=ITestInterface) self.assertTrue('good' in plugins.names) result_get = plugins.get('good') result_getattr = plugins.good self.assertFalse(result_get is None) self.assertTrue(result_get is result_getattr) # Make sure we actually got our class greeter = result_get('yes') self.assertEqual('yes', greeter.hello()) self.assertEqual('no', greeter.hello('no')) def test_missing_plugin(self): plugins = db.get_plugins('interface', interface=ITestInterface) with self.assertRaises(AttributeError): _ = plugins.bad with self.assertRaises(PluginDBError): plugins.get('bad') with self.assertRaises(PluginDBError): plugins.get('good.extra') @mock.patch('buildbot.plugins.db.find_distribution_info', fake_find_distribution_info) def test_interface_provided_deep(self): # Basic check before the actual test self.assertTrue(ITestInterface.implementedBy(ClassWithInterface)) plugins = db.get_plugins('interface', interface=ITestInterface) self.assertTrue('deep.path' in plugins.names) self.assertTrue('deep.path' in plugins) self.assertFalse('even.deeper.path' in plugins) result_get = plugins.get('deep.path') result_getattr = plugins.deep.path self.assertFalse(result_get is None) self.assertTrue(result_get is result_getattr) # Make sure we actually got our class greeter = result_get('yes') self.assertEqual('yes', greeter.hello()) self.assertEqual('no', greeter.hello('no')) @mock.patch('buildbot.plugins.db.find_distribution_info', fake_find_distribution_info) def test_interface_warnings(self): # we should not get no warnings when not trying to access the plugin plugins = db.get_plugins('interface_warnings', interface=ITestInterface) self.assertTrue('good' in plugins.names) self.assertTrue('deep.path' in plugins.names) # we should get warning when trying to access the plugin with assertProducesWarning(DeprecationWarning, "test warning"): _ = plugins.get('good') with assertProducesWarning(DeprecationWarning, "test warning"): _ = plugins.good with assertProducesWarning(DeprecationWarning, "test warning"): _ = plugins.get('deep.path') with assertProducesWarning(DeprecationWarning, "test warning"): _ = plugins.deep.path def test_required_interface_not_provided(self): plugins = db.get_plugins('no_interface_again', interface=ITestInterface) self.assertTrue(plugins._interface is ITestInterface) with self.assertRaises(PluginDBError): plugins.get('good') def test_no_interface_provided(self): plugins = db.get_plugins('no_interface') self.assertFalse(plugins.get('good') is None) @mock.patch('buildbot.plugins.db.find_distribution_info', fake_find_distribution_info_dups) def test_failure_on_dups(self): with self.assertRaises(PluginDBError): db.get_plugins('duplicates', load_now=True) @mock.patch('buildbot.plugins.db.find_distribution_info', fake_find_distribution_info) def test_get_info_on_a_known_plugin(self): plugins = db.get_plugins('interface') self.assertEqual(('non-existent', 'irrelevant'), plugins.info('good')) def test_failure_on_unknown_plugin_info(self): plugins = db.get_plugins('interface') with self.assertRaises(PluginDBError): plugins.info('bad') def test_failure_on_unknown_plugin_get(self): plugins = db.get_plugins('interface') with self.assertRaises(PluginDBError): plugins.get('bad') class SimpleFakeEntry(FakeEntry): def __init__(self, name, value): super().__init__(name, 'group', False, value) _WORKER_FAKE_ENTRIES = { 'buildbot.worker': [ SimpleFakeEntry('Worker', ClassWithInterface), SimpleFakeEntry('EC2LatentWorker', ClassWithInterface), SimpleFakeEntry('LibVirtWorker', ClassWithInterface), SimpleFakeEntry('OpenStackLatentWorker', ClassWithInterface), SimpleFakeEntry('newthirdparty', ClassWithInterface), SimpleFakeEntry('deep.newthirdparty', ClassWithInterface), ], 'buildbot.util': [ SimpleFakeEntry('WorkerLock', ClassWithInterface), SimpleFakeEntry('enforceChosenWorker', ClassWithInterface), SimpleFakeEntry('WorkerChoiceParameter', ClassWithInterface), ], } def provide_worker_fake_entries(group): """ give a set of fake entries for known groups """ return _WORKER_FAKE_ENTRIES.get(group, [])
19,277
Python
.py
472
30.504237
95
0.601677
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,329
test_util_queue.py
buildbot_buildbot/master/buildbot/test/unit/test_util_queue.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 import threading from twisted.internet import defer from twisted.trial import unittest from buildbot.util.backoff import BackoffTimeoutExceededError from buildbot.util.queue import ConnectableThreadQueue class FakeConnection: pass class TestableConnectableThreadQueue(ConnectableThreadQueue): def __init__(self, case, *args, **kwargs): super().__init__(*args, **kwargs) self.case = case self.create_connection_called_count = 0 self.close_connection_called_count = 0 self._test_conn = None def create_connection(self): self.case.assertTrue(self.connecting) self.create_connection_called_count += 1 self.case.assertIsNone(self._test_conn) self._test_conn = FakeConnection() return self._test_conn def on_close_connection(self, conn): self.case.assertIs(conn, self._test_conn) self._test_conn = None self.close_connection() def close_connection(self): self.case.assertFalse(self.connecting) self._test_conn = None self.close_connection_called_count += 1 super().close_connection() class TestException(Exception): pass class TestConnectableThreadQueue(unittest.TestCase): timeout = 10 def setUp(self): self.queue = TestableConnectableThreadQueue( self, connect_backoff_start_seconds=0, connect_backoff_multiplier=0, connect_backoff_max_wait_seconds=0, ) def tearDown(self): self.join_queue() def join_queue(self, connection_called_count=None): self.queue.join(timeout=self.timeout) if self.queue.is_alive(): raise AssertionError('Thread is still alive') if connection_called_count is not None: self.assertEqual(self.queue.create_connection_called_count, connection_called_count) self.assertEqual(self.queue.close_connection_called_count, connection_called_count) def test_no_work(self): self.join_queue(0) @defer.inlineCallbacks def test_single_item_called(self): def work(conn, *args, **kwargs): self.assertIs(conn, self.queue.conn) self.assertEqual(args, ('arg',)) self.assertEqual(kwargs, {'kwarg': 'kwvalue'}) return 'work_result' result = yield self.queue.execute_in_thread(work, 'arg', kwarg='kwvalue') self.assertEqual(result, 'work_result') self.join_queue(1) @defer.inlineCallbacks def test_single_item_called_exception(self): def work(conn): raise TestException() with self.assertRaises(TestException): yield self.queue.execute_in_thread(work) self.join_queue(1) @defer.inlineCallbacks def test_exception_does_not_break_further_work(self): def work_exception(conn): raise TestException() def work_success(conn): return 'work_result' with self.assertRaises(TestException): yield self.queue.execute_in_thread(work_exception) result = yield self.queue.execute_in_thread(work_success) self.assertEqual(result, 'work_result') self.join_queue(1) @defer.inlineCallbacks def test_single_item_called_disconnect(self): def work(conn): pass yield self.queue.execute_in_thread(work) self.queue.close_connection() yield self.queue.execute_in_thread(work) self.join_queue(2) @defer.inlineCallbacks def test_many_items_called_in_order(self): self.expected_work_index = 0 def work(conn, work_index): self.assertEqual(self.expected_work_index, work_index) self.expected_work_index = work_index + 1 return work_index work_deferreds = [self.queue.execute_in_thread(work, i) for i in range(0, 100)] for i, d in enumerate(work_deferreds): self.assertEqual((yield d), i) self.join_queue(1) class FailingConnectableThreadQueue(ConnectableThreadQueue): def __init__(self, case, lock, *args, **kwargs): super().__init__(*args, **kwargs) self.case = case self.lock = lock self.create_connection_called_count = 0 def on_close_connection(self, conn): raise AssertionError("on_close_connection should not have been called") def close_connection(self): raise AssertionError("close_connection should not have been called") def _drain_queue_with_exception(self, e): with self.lock: return super()._drain_queue_with_exception(e) class ThrowingConnectableThreadQueue(FailingConnectableThreadQueue): def create_connection(self): with self.lock: self.create_connection_called_count += 1 self.case.assertTrue(self.connecting) raise TestException() class NoneReturningConnectableThreadQueue(FailingConnectableThreadQueue): def create_connection(self): with self.lock: self.create_connection_called_count += 1 self.case.assertTrue(self.connecting) return None class ConnectionErrorTests: timeout = 10 def setUp(self): self.lock = threading.Lock() self.queue = self.QueueClass( self, self.lock, connect_backoff_start_seconds=0.001, connect_backoff_multiplier=1, connect_backoff_max_wait_seconds=0.0039, ) def tearDown(self): self.queue.join(timeout=self.timeout) if self.queue.is_alive(): raise AssertionError('Thread is still alive') @defer.inlineCallbacks def test_resets_after_reject(self): def work(conn): raise AssertionError('work should not be executed') with self.lock: d = self.queue.execute_in_thread(work) with self.assertRaises(BackoffTimeoutExceededError): yield d self.assertEqual(self.queue.create_connection_called_count, 5) with self.lock: d = self.queue.execute_in_thread(work) with self.assertRaises(BackoffTimeoutExceededError): yield d self.assertEqual(self.queue.create_connection_called_count, 10) self.flushLoggedErrors(TestException) @defer.inlineCallbacks def test_multiple_work_rejected(self): def work(conn): raise AssertionError('work should not be executed') with self.lock: d1 = self.queue.execute_in_thread(work) d2 = self.queue.execute_in_thread(work) d3 = self.queue.execute_in_thread(work) with self.assertRaises(BackoffTimeoutExceededError): yield d1 with self.assertRaises(BackoffTimeoutExceededError): yield d2 with self.assertRaises(BackoffTimeoutExceededError): yield d3 self.assertEqual(self.queue.create_connection_called_count, 5) self.flushLoggedErrors(TestException) class TestConnectionErrorThrow(ConnectionErrorTests, unittest.TestCase): QueueClass = ThrowingConnectableThreadQueue class TestConnectionErrorReturnNone(ConnectionErrorTests, unittest.TestCase): QueueClass = NoneReturningConnectableThreadQueue
8,007
Python
.py
187
34.486631
96
0.681672
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,330
test_asyncio.py
buildbot_buildbot/master/buildbot/test/unit/test_asyncio.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 from twisted.internet import defer from twisted.trial import unittest from buildbot import util from buildbot.asyncio import as_deferred from buildbot.test.reactor import TestReactorMixin class TestAsyncioTestLoop(TestReactorMixin, unittest.TestCase): maxDiff = None def setUp(self): self.setup_test_reactor(use_asyncio=True) def test_coroutine_schedule(self): d1 = defer.Deferred() f1 = d1.asFuture(self.asyncio_loop) async def coro1(): await f1 f = asyncio.ensure_future(coro1()) d1.callback(None) return defer.Deferred.fromFuture(f) async def test_asyncio_gather(self): self.calls = 0 async def coro1(): await asyncio.sleep(1) self.calls += 1 async def coro2(): await asyncio.sleep(1) self.calls += 1 @defer.inlineCallbacks def inlineCallbacks1(): yield util.asyncSleep(1, self.reactor) self.calls += 1 @defer.inlineCallbacks def inlineCallbacks2(): yield util.asyncSleep(1, self.reactor) self.calls += 1 async def main_coro(): dl = [] dl.append(coro1()) dl.append(coro2()) # We support directly yielding a deferred inside a asyncio coroutine # this needs a patch of Deferred.__await__ implemented in asyncio.py dl.append(inlineCallbacks1()) dl.append(inlineCallbacks2().asFuture(self.asyncio_loop)) await asyncio.gather(*dl) self.calls += 1 f1 = main_coro() def advance(): self.reactor.advance(1) if self.calls < 3: self.reactor.callLater(0, advance) yield advance() yield as_deferred(f1) self.assertEqual(self.calls, 5) @defer.inlineCallbacks def test_asyncio_threadsafe(self): f1 = asyncio.Future() async def coro(): self.asyncio_loop.call_soon_threadsafe(f1.set_result, "ok") res = await f1 return res res = yield as_deferred(coro()) self.assertEqual(res, "ok") @defer.inlineCallbacks def test_asyncio_negative_call_at(self): res = yield as_deferred(defer.succeed("OK")) self.assertEqual(res, "OK") @defer.inlineCallbacks def test_asyncio_as_deferred_deferred(self): d = defer.Deferred() self.asyncio_loop.call_at(-1, d.callback, "OK") res = yield d self.assertEqual(res, "OK") @defer.inlineCallbacks def test_asyncio_as_deferred_default(self): res = yield as_deferred("OK") self.assertEqual(res, "OK")
3,451
Python
.py
89
30.797753
80
0.651184
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,331
test_wamp_connector.py
buildbot_buildbot/master/buildbot/test/unit/test_wamp_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 from __future__ import annotations from unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.util import service from buildbot.wamp import connector class FakeConfig: def __init__(self, mq_dict): self.mq = mq_dict class FakeService(service.AsyncMultiService): name: str | None = "fakeWampService" # type: ignore[assignment] # Fake wamp service # just call the maker on demand by the test def __init__( self, url, realm, make, extra=None, debug=False, debug_wamp=False, debug_app=False ): super().__init__() self.make = make self.extra = extra def gotConnection(self): self.make(None) r = self.make(self) r.publish = mock.Mock(spec=r.publish) r.register = mock.Mock(spec=r.register) r.subscribe = mock.Mock(spec=r.subscribe) r.onJoin(None) class TestedWampConnector(connector.WampConnector): serviceClass = FakeService class WampConnector(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield fakemaster.make_master(self) self.connector = TestedWampConnector() config = FakeConfig({'type': 'wamp', 'router_url': "wss://foo", 'realm': "bb"}) yield self.connector.setServiceParent(master) yield master.startService() yield self.connector.reconfigServiceWithBuildbotConfig(config) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_reconfig_same_config(self): config = FakeConfig({'type': 'wamp', 'router_url': "wss://foo", 'realm': "bb"}) yield self.connector.reconfigServiceWithBuildbotConfig(config) @parameterized.expand([ ('type', 'simple'), ('router_url', 'wss://other-foo'), ('realm', 'bb-other'), ('wamp_debug_level', 'info'), ]) @defer.inlineCallbacks def test_reconfig_does_not_allow_config_change(self, attr_name, attr_value): mq_dict = {'type': 'wamp', 'router_url': "wss://foo", 'realm': "bb"} mq_dict[attr_name] = attr_value with self.assertRaises( ValueError, msg="Cannot use different wamp settings when reconfiguring" ): yield self.connector.reconfigServiceWithBuildbotConfig(FakeConfig(mq_dict)) @defer.inlineCallbacks def test_startup(self): d = self.connector.getService() self.connector.app.gotConnection() yield d # 824 is the hardcoded masterid of fakemaster self.connector.service.publish.assert_called_with("org.buildbot.824.connected") @defer.inlineCallbacks def test_subscribe(self): d = self.connector.subscribe('callback', 'topic', 'options') self.connector.app.gotConnection() yield d self.connector.service.subscribe.assert_called_with('callback', 'topic', 'options') @defer.inlineCallbacks def test_publish(self): d = self.connector.publish('topic', 'data', 'options') self.connector.app.gotConnection() yield d self.connector.service.publish.assert_called_with('topic', 'data', options='options') @defer.inlineCallbacks def test_OnLeave(self): d = self.connector.getService() self.connector.app.gotConnection() yield d self.assertTrue(self.connector.master.running) self.connector.service.onLeave(None) self.assertFalse(self.connector.master.running)
4,450
Python
.py
103
37.019417
93
0.700116
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,332
test_secret_in_file.py
buildbot_buildbot/master/buildbot/test/unit/test_secret_in_file.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 stat from twisted.internet import defer from twisted.python.filepath import FilePath from twisted.trial import unittest from buildbot.secrets.providers.file import SecretInAFile from buildbot.test.util.config import ConfigErrorsMixin from buildbot.util.misc import writeLocalFile class TestSecretInFile(ConfigErrorsMixin, unittest.TestCase): def createTempDir(self, dirname): tempdir = FilePath(self.mktemp()) tempdir.createDirectory() return tempdir.path def createFileTemp(self, tempdir, filename, text="", chmodRights=0o700): file_path = os.path.join(tempdir, filename) writeLocalFile(file_path, text, chmodRights) return file_path @defer.inlineCallbacks def setUp(self): self.tmp_dir = self.createTempDir("temp") self.filepath = self.createFileTemp(self.tmp_dir, "tempfile.txt", text="key value\n") self.srvfile = SecretInAFile(self.tmp_dir) yield self.srvfile.startService() @defer.inlineCallbacks def tearDown(self): yield self.srvfile.stopService() def testCheckConfigSecretInAFileService(self): self.assertEqual(self.srvfile.name, "SecretInAFile") self.assertEqual(self.srvfile._dirname, self.tmp_dir) def testCheckConfigErrorSecretInAFileService(self): if os.name != "posix": self.skipTest("Permission checks only works on posix systems") filepath = self.createFileTemp(self.tmp_dir, "tempfile2.txt", chmodRights=stat.S_IROTH) expctd_msg_error = ( " on file tempfile2.txt are too " "open. It is required that your secret files are" " NOT accessible by others!" ) with self.assertRaisesConfigError(expctd_msg_error): self.srvfile.checkConfig(self.tmp_dir) os.remove(filepath) @defer.inlineCallbacks def testCheckConfigfileExtension(self): filepath = self.createFileTemp( self.tmp_dir, "tempfile2.ini", text="test suffix", chmodRights=stat.S_IRWXU ) filepath2 = self.createFileTemp( self.tmp_dir, "tempfile2.txt", text="some text", chmodRights=stat.S_IRWXU ) yield self.srvfile.reconfigService(self.tmp_dir, suffixes=[".ini"]) self.assertEqual(self.srvfile.get("tempfile2"), "test suffix") self.assertEqual(self.srvfile.get("tempfile3"), None) os.remove(filepath) os.remove(filepath2) @defer.inlineCallbacks def testReconfigSecretInAFileService(self): otherdir = self.createTempDir("temp2") yield self.srvfile.reconfigService(otherdir) self.assertEqual(self.srvfile.name, "SecretInAFile") self.assertEqual(self.srvfile._dirname, otherdir) def testGetSecretInFile(self): value = self.srvfile.get("tempfile.txt") self.assertEqual(value, "key value") @defer.inlineCallbacks def testGetSecretInFileSuffixes(self): yield self.srvfile.reconfigService(self.tmp_dir, suffixes=[".txt"]) value = self.srvfile.get("tempfile") self.assertEqual(value, "key value") def testGetSecretInFileNotFound(self): value = self.srvfile.get("tempfile2.txt") self.assertEqual(value, None) @defer.inlineCallbacks def testGetSecretInFileNoStrip(self): yield self.srvfile.reconfigService(self.tmp_dir, strip=False) value = self.srvfile.get("tempfile.txt") self.assertEqual(value, "key value\n")
4,203
Python
.py
90
40.055556
95
0.717598
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,333
test_util.py
buildbot_buildbot/master/buildbot/test/unit/test_util.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 datetime import locale import os import sys from unittest import mock from twisted.internet import reactor from twisted.internet import task from twisted.trial import unittest from buildbot import util class formatInterval(unittest.TestCase): def test_zero(self): self.assertEqual(util.formatInterval(0), "0 secs") def test_seconds_singular(self): self.assertEqual(util.formatInterval(1), "1 secs") def test_seconds(self): self.assertEqual(util.formatInterval(7), "7 secs") def test_minutes_one(self): self.assertEqual(util.formatInterval(60), "60 secs") def test_minutes_over_one(self): self.assertEqual(util.formatInterval(61), "1 mins, 1 secs") def test_minutes(self): self.assertEqual(util.formatInterval(300), "5 mins, 0 secs") def test_hours_one(self): self.assertEqual(util.formatInterval(3600), "60 mins, 0 secs") def test_hours_over_one_sec(self): self.assertEqual(util.formatInterval(3601), "1 hrs, 1 secs") def test_hours_over_one_min(self): self.assertEqual(util.formatInterval(3660), "1 hrs, 60 secs") def test_hours(self): self.assertEqual(util.formatInterval(7200), "2 hrs, 0 secs") def test_mixed(self): self.assertEqual(util.formatInterval(7392), "2 hrs, 3 mins, 12 secs") class TestHumanReadableDelta(unittest.TestCase): def test_timeDeltaToHumanReadable(self): """ It will return a human readable time difference. """ result = util.human_readable_delta(1, 1) self.assertEqual('super fast', result) result = util.human_readable_delta(1, 2) self.assertEqual('1 seconds', result) result = util.human_readable_delta(1, 61) self.assertEqual('1 minutes', result) result = util.human_readable_delta(1, 62) self.assertEqual('1 minutes, 1 seconds', result) result = util.human_readable_delta(1, 60 * 60 + 1) self.assertEqual('1 hours', result) result = util.human_readable_delta(1, 60 * 60 + 61) self.assertEqual('1 hours, 1 minutes', result) result = util.human_readable_delta(1, 60 * 60 + 62) self.assertEqual('1 hours, 1 minutes, 1 seconds', result) result = util.human_readable_delta(1, 24 * 60 * 60 + 1) self.assertEqual('1 days', result) result = util.human_readable_delta(1, 24 * 60 * 60 + 2) self.assertEqual('1 days, 1 seconds', result) class TestFuzzyInterval(unittest.TestCase): def test_moment(self): self.assertEqual(util.fuzzyInterval(1), "a moment") def test_seconds(self): self.assertEqual(util.fuzzyInterval(17), "17 seconds") def test_seconds_rounded(self): self.assertEqual(util.fuzzyInterval(48), "50 seconds") def test_minute(self): self.assertEqual(util.fuzzyInterval(58), "a minute") def test_minutes(self): self.assertEqual(util.fuzzyInterval(3 * 60 + 24), "3 minutes") def test_minutes_rounded(self): self.assertEqual(util.fuzzyInterval(32 * 60 + 24), "30 minutes") def test_hour(self): self.assertEqual(util.fuzzyInterval(3600 + 1200), "an hour") def test_hours(self): self.assertEqual(util.fuzzyInterval(9 * 3600 - 720), "9 hours") def test_day(self): self.assertEqual(util.fuzzyInterval(32 * 3600 + 124), "a day") def test_days(self): self.assertEqual(util.fuzzyInterval((19 + 24) * 3600 + 124), "2 days") def test_month(self): self.assertEqual(util.fuzzyInterval(36 * 24 * 3600 + 124), "a month") def test_months(self): self.assertEqual(util.fuzzyInterval(86 * 24 * 3600 + 124), "3 months") def test_year(self): self.assertEqual(util.fuzzyInterval(370 * 24 * 3600), "a year") def test_years(self): self.assertEqual(util.fuzzyInterval((2 * 365 + 96) * 24 * 3600), "2 years") class safeTranslate(unittest.TestCase): def test_str_good(self): self.assertEqual(util.safeTranslate("full"), b"full") def test_str_bad(self): self.assertEqual(util.safeTranslate("speed=slow;quality=high"), b"speed_slow_quality_high") def test_str_pathological(self): # if you needed proof this wasn't for use with sensitive data self.assertEqual( util.safeTranslate("p\ath\x01ogy"), b"p\ath\x01ogy" ) # bad chars still here! def test_unicode_good(self): self.assertEqual(util.safeTranslate("full"), b"full") def test_unicode_bad(self): self.assertEqual(util.safeTranslate("speed=slow;quality=high"), b"speed_slow_quality_high") def test_unicode_pathological(self): self.assertEqual(util.safeTranslate("\u0109"), b"\xc4\x89") # yuck! class naturalSort(unittest.TestCase): def test_alpha(self): self.assertEqual(util.naturalSort(['x', 'aa', 'ab']), ['aa', 'ab', 'x']) def test_numeric(self): self.assertEqual( util.naturalSort(['1', '10', '11', '2', '20']), ['1', '2', '10', '11', '20'] ) def test_alphanum(self): l1 = 'aa10ab aa1ab aa10aa f a aa3 aa30 aa3a aa30a'.split() l2 = 'a aa1ab aa3 aa3a aa10aa aa10ab aa30 aa30a f'.split() self.assertEqual(util.naturalSort(l1), l2) class none_or_str(unittest.TestCase): def test_none(self): self.assertEqual(util.none_or_str(None), None) def test_str(self): self.assertEqual(util.none_or_str("hi"), "hi") def test_int(self): self.assertEqual(util.none_or_str(199), "199") class TimeFunctions(unittest.TestCase): def test_UTC(self): self.assertEqual(util.UTC.utcoffset(datetime.datetime.now()), datetime.timedelta(0)) self.assertEqual(util.UTC.dst(datetime.datetime.now()), datetime.timedelta(0)) self.assertEqual(util.UTC.tzname(datetime.datetime.now(datetime.timezone.utc)), "UTC") def test_epoch2datetime(self): self.assertEqual( util.epoch2datetime(0), datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=util.UTC) ) self.assertEqual( util.epoch2datetime(1300000000), datetime.datetime(2011, 3, 13, 7, 6, 40, tzinfo=util.UTC), ) def test_datetime2epoch(self): dt = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=util.UTC) self.assertEqual(util.datetime2epoch(dt), 0) dt = datetime.datetime(2011, 3, 13, 7, 6, 40, tzinfo=util.UTC) self.assertEqual(util.datetime2epoch(dt), 1300000000) class DiffSets(unittest.TestCase): def test_empty(self): removed, added = util.diffSets(set([]), set([])) self.assertEqual((removed, added), (set([]), set([]))) def test_no_lists(self): removed, added = util.diffSets([1, 2], [2, 3]) self.assertEqual((removed, added), (set([1]), set([3]))) def test_no_overlap(self): removed, added = util.diffSets(set([1, 2]), set([3, 4])) self.assertEqual((removed, added), (set([1, 2]), set([3, 4]))) def test_no_change(self): removed, added = util.diffSets(set([1, 2]), set([1, 2])) self.assertEqual((removed, added), (set([]), set([]))) def test_added(self): removed, added = util.diffSets(set([1, 2]), set([1, 2, 3])) self.assertEqual((removed, added), (set([]), set([3]))) def test_removed(self): removed, added = util.diffSets(set([1, 2]), set([1])) self.assertEqual((removed, added), (set([2]), set([]))) class MakeList(unittest.TestCase): def test_empty_string(self): self.assertEqual(util.makeList(''), ['']) def test_None(self): self.assertEqual(util.makeList(None), []) def test_string(self): self.assertEqual(util.makeList('hello'), ['hello']) def test_unicode(self): self.assertEqual(util.makeList('\N{SNOWMAN}'), ['\N{SNOWMAN}']) def test_list(self): self.assertEqual(util.makeList(['a', 'b']), ['a', 'b']) def test_tuple(self): self.assertEqual(util.makeList(('a', 'b')), ['a', 'b']) def test_copy(self): input = ['a', 'b'] output = util.makeList(input) input.append('c') self.assertEqual(output, ['a', 'b']) class Flatten(unittest.TestCase): def test_simple(self): self.assertEqual(util.flatten([1, 2, 3]), [1, 2, 3]) def test_deep(self): self.assertEqual(util.flatten([[1, 2], 3, [[4]]]), [1, 2, 3, 4]) # def test_deeply_nested(self): # self.assertEqual(util.flatten([5, [6, (7, 8)]]), # [5, 6, 7, 8]) # def test_tuples(self): # self.assertEqual(util.flatten([(1, 2), 3]), [1, 2, 3]) def test_dict(self): d = {'a': [5, 6, 7], 'b': [7, 8, 9]} self.assertEqual(util.flatten(d), d) def test_string(self): self.assertEqual(util.flatten("abc"), "abc") class Ascii2Unicode(unittest.TestCase): def test_unicode(self): rv = util.bytes2unicode('\N{SNOWMAN}', encoding='ascii') self.assertEqual((rv, type(rv)), ('\N{SNOWMAN}', str)) def test_ascii(self): rv = util.bytes2unicode('abcd', encoding='ascii') self.assertEqual((rv, type(rv)), ('abcd', str)) def test_nonascii(self): with self.assertRaises(UnicodeDecodeError): util.bytes2unicode(b'a\x85', encoding='ascii') def test_None(self): self.assertEqual(util.bytes2unicode(None, encoding='ascii'), None) def test_bytes2unicode(self): rv1 = util.bytes2unicode(b'abcd') rv2 = util.bytes2unicode('efgh') self.assertEqual(type(rv1), str) self.assertEqual(type(rv2), str) class StringToBoolean(unittest.TestCase): def test_it(self): stringValues = [ (b'on', True), (b'true', True), (b'yes', True), (b'1', True), (b'off', False), (b'false', False), (b'no', False), (b'0', False), (b'ON', True), (b'TRUE', True), (b'YES', True), (b'OFF', False), (b'FALSE', False), (b'NO', False), ] for s, b in stringValues: self.assertEqual(util.string2boolean(s), b, repr(s)) def test_ascii(self): rv = util.bytes2unicode(b'abcd', encoding='ascii') self.assertEqual((rv, type(rv)), ('abcd', str)) def test_nonascii(self): with self.assertRaises(UnicodeDecodeError): util.bytes2unicode(b'a\x85', encoding='ascii') def test_None(self): self.assertEqual(util.bytes2unicode(None, encoding='ascii'), None) class AsyncSleep(unittest.TestCase): def test_sleep(self): clock = task.Clock() self.patch(reactor, 'callLater', clock.callLater) d = util.asyncSleep(2) self.assertFalse(d.called) clock.advance(1) self.assertFalse(d.called) clock.advance(1) self.assertTrue(d.called) class FunctionalEnvironment(unittest.TestCase): def test_working_locale(self): environ = {'LANG': 'en_GB.UTF-8'} self.patch(os, 'environ', environ) config = mock.Mock() util.check_functional_environment(config) self.assertEqual(config.error.called, False) def test_broken_locale(self): def err(): raise KeyError if sys.version_info >= (3, 11, 0): self.patch(locale, 'getencoding', err) else: self.patch(locale, 'getdefaultlocale', err) config = mock.Mock() util.check_functional_environment(config) config.error.assert_called_with(mock.ANY) class StripUrlPassword(unittest.TestCase): def test_simple_url(self): self.assertEqual(util.stripUrlPassword('http://foo.com/bar'), 'http://foo.com/bar') def test_username(self): self.assertEqual(util.stripUrlPassword('http://[email protected]/bar'), 'http://[email protected]/bar') def test_username_with_at(self): self.assertEqual( util.stripUrlPassword('http://[email protected]@foo.com/bar'), 'http://[email protected]@foo.com/bar' ) def test_username_pass(self): self.assertEqual( util.stripUrlPassword('http://d:[email protected]/bar'), 'http://d:[email protected]/bar' ) def test_username_pass_with_at(self): self.assertEqual( util.stripUrlPassword('http://[email protected]:[email protected]/bar'), 'http://[email protected]:[email protected]/bar', ) class JoinList(unittest.TestCase): def test_list(self): self.assertEqual(util.join_list(['aa', 'bb']), 'aa bb') def test_tuple(self): self.assertEqual(util.join_list(('aa', 'bb')), 'aa bb') def test_string(self): self.assertEqual(util.join_list('abc'), 'abc') def test_unicode(self): self.assertEqual(util.join_list('abc'), 'abc') def test_nonascii(self): with self.assertRaises(UnicodeDecodeError): util.join_list([b'\xff']) class CommandToString(unittest.TestCase): def test_short_string(self): self.assertEqual(util.command_to_string("ab cd"), "'ab cd'") def test_long_string(self): self.assertEqual(util.command_to_string("ab cd ef"), "'ab cd ...'") def test_list(self): self.assertEqual(util.command_to_string(['ab', 'cd', 'ef']), "'ab cd ...'") def test_nested_list(self): self.assertEqual(util.command_to_string(['ab', ['cd', ['ef']]]), "'ab cd ...'") def test_object(self): # this looks like a renderable self.assertEqual(util.command_to_string(object()), None) def test_list_with_objects(self): self.assertRegex(util.command_to_string(['ab', object(), 'cd']), r"'ab <object .*> \.\.\.'") def test_invalid_ascii(self): self.assertEqual(util.command_to_string(b'a\xffc'), "'a\ufffdc'") class TestRewrap(unittest.TestCase): def test_main(self): tests = [ ("", "", None), ("\n", "\n", None), ("\n ", "\n", None), (" \n", "\n", None), (" \n ", "\n", None), ( """ multiline with indent """, "\nmultiline with indent", None, ), ( """\ multiline with indent """, "multiline with indent\n", None, ), ( """\ multiline with indent """, "multiline with indent\n", None, ), ( """\ multiline with indent and formatting """, "multiline with indent\n and\n formatting\n", None, ), ( """\ multiline with indent and wrapping and formatting """, "multiline with\nindent and\nwrapping\n and\n formatting\n", 15, ), ] for text, expected, width in tests: self.assertEqual(util.rewrap(text, width=width), expected) class TestMerge(unittest.TestCase): def test_merge(self): self.assertEqual( util.dictionary_merge({'a': {'b': 1}}, {'a': {'c': 2}}), {'a': {'b': 1, 'c': 2}} ) def test_overwrite(self): self.assertEqual(util.dictionary_merge({'a': {'b': 1}}, {'a': 1}), {'a': 1}) def test_overwrite2(self): self.assertEqual( util.dictionary_merge({'a': {'b': 1, 'c': 2}}, {'a': {'b': [1, 2, 3]}}), {'a': {'b': [1, 2, 3], 'c': 2}}, )
16,660
Python
.py
393
33.544529
100
0.595526
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,334
test_machine_generic.py
buildbot_buildbot/master/buildbot/test/unit/test_machine_generic.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 parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.machine.generic import HttpAction from buildbot.machine.generic import LocalWakeAction from buildbot.machine.generic import LocalWOLAction from buildbot.machine.generic import RemoteSshSuspendAction from buildbot.machine.generic import RemoteSshWakeAction from buildbot.machine.generic import RemoteSshWOLAction from buildbot.test.fake import fakemaster from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.private_tempdir import MockPrivateTemporaryDirectory from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import config class FakeManager: def __init__(self, master): self.master = master def renderSecrets(self, args): return defer.succeed(args) def create_simple_mock_master(reactor, basedir=None): master = mock.Mock() master.basedir = basedir master.reactor = reactor return master class TestActions( MasterRunProcessMixin, config.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_local_wake_action(self): self.expect_commands( ExpectMasterShell(['cmd', 'arg1', 'arg2']).exit(1), ExpectMasterShell(['cmd', 'arg1', 'arg2']).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor)) action = LocalWakeAction(['cmd', 'arg1', 'arg2']) self.assertFalse((yield action.perform(manager))) self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() def test_local_wake_action_command_not_list(self): with self.assertRaisesConfigError('command parameter must be a list'): LocalWakeAction('not-list') @defer.inlineCallbacks def test_local_wol_action(self): self.expect_commands( ExpectMasterShell(['wol', '00:11:22:33:44:55']).exit(1), ExpectMasterShell(['wakeonlan', '00:11:22:33:44:55']).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor)) action = LocalWOLAction('00:11:22:33:44:55', wolBin='wol') self.assertFalse((yield action.perform(manager))) action = LocalWOLAction('00:11:22:33:44:55') self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.misc.writeLocalFile') @defer.inlineCallbacks def test_remote_ssh_wake_action_no_keys(self, write_local_file_mock, temp_dir_mock): self.expect_commands( ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'remotebin', 'arg1', ]).exit(1), ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'remotebin', 'arg1', ]).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor)) action = RemoteSshWakeAction('remote_host', ['remotebin', 'arg1']) self.assertFalse((yield action.perform(manager))) self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() self.assertEqual(temp_dir_mock.dirs, []) write_local_file_mock.assert_not_called() @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.misc.writeLocalFile') @defer.inlineCallbacks def test_remote_ssh_wake_action_with_keys(self, write_local_file_mock, temp_dir_mock): temp_dir_path = os.path.join('path-to-master', 'ssh-@@@') ssh_key_path = os.path.join(temp_dir_path, 'ssh-key') ssh_known_hosts_path = os.path.join(temp_dir_path, 'ssh-known-hosts') self.expect_commands( ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', '-i', ssh_key_path, '-o', f'UserKnownHostsFile={ssh_known_hosts_path}', 'remote_host', 'remotebin', 'arg1', ]).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor, 'path-to-master')) action = RemoteSshWakeAction( 'remote_host', ['remotebin', 'arg1'], sshKey='ssh_key', sshHostKey='ssh_host_key' ) self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) self.assertSequenceEqual( write_local_file_mock.call_args_list, [ mock.call(ssh_key_path, 'ssh_key', mode=0o400), mock.call(ssh_known_hosts_path, '* ssh_host_key'), ], ) def test_remote_ssh_wake_action_sshBin_not_str(self): with self.assertRaisesConfigError('sshBin parameter must be a string'): RemoteSshWakeAction('host', ['cmd'], sshBin=123) def test_remote_ssh_wake_action_host_not_str(self): with self.assertRaisesConfigError('host parameter must be a string'): RemoteSshWakeAction(123, ['cmd']) def test_remote_ssh_wake_action_command_not_list(self): with self.assertRaisesConfigError('remoteCommand parameter must be a list'): RemoteSshWakeAction('host', 'cmd') @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.misc.writeLocalFile') @defer.inlineCallbacks def test_remote_ssh_wol_action_no_keys(self, write_local_file_mock, temp_dir_mock): self.expect_commands( ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'wakeonlan', '00:11:22:33:44:55', ]).exit(0), ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'wolbin', '00:11:22:33:44:55', ]).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor)) action = RemoteSshWOLAction('remote_host', '00:11:22:33:44:55') self.assertTrue((yield action.perform(manager))) action = RemoteSshWOLAction('remote_host', '00:11:22:33:44:55', wolBin='wolbin') self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() self.assertEqual(temp_dir_mock.dirs, []) write_local_file_mock.assert_not_called() @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.misc.writeLocalFile') @defer.inlineCallbacks def test_remote_ssh_suspend_action_no_keys(self, write_local_file_mock, temp_dir_mock): self.expect_commands( ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'systemctl', 'suspend', ]).exit(0), ExpectMasterShell([ 'ssh', '-o', 'BatchMode=yes', 'remote_host', 'dosuspend', 'arg1', ]).exit(0), ) manager = FakeManager(create_simple_mock_master(self.reactor)) action = RemoteSshSuspendAction('remote_host') self.assertTrue((yield action.perform(manager))) action = RemoteSshSuspendAction('remote_host', remoteCommand=['dosuspend', 'arg1']) self.assertTrue((yield action.perform(manager))) self.assert_all_commands_ran() self.assertEqual(temp_dir_mock.dirs, []) write_local_file_mock.assert_not_called() class TestHttpAction(config.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) self.http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, "http://localhost/request" ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_http_wrong_method(self): manager = FakeManager(self.master) action = HttpAction('http://localhost/request', method='non-existing-method') with self.assertRaisesConfigError('Invalid method non-existing-method'): yield action.perform(manager) @parameterized.expand([ 'get', 'post', 'delete', 'put', ]) @defer.inlineCallbacks def test_http(self, method): self.http.expect(method, '') manager = FakeManager(self.master) action = HttpAction('http://localhost/request', method=method) yield action.perform(manager)
10,556
Python
.py
251
32.840637
93
0.639536
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,335
test_secret_rendered_service.py
buildbot_buildbot/master/buildbot/test/unit/test_secret_rendered_service.py
from twisted.internet import defer from twisted.trial import unittest from buildbot.process.properties import Secret from buildbot.secrets.manager import SecretManager from buildbot.test.fake import fakemaster from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.util.service import BuildbotService class FakeServiceUsingSecrets(BuildbotService): name = "FakeServiceUsingSecrets" secrets = ["foo", "bar", "secret"] def reconfigService(self, foo=None, bar=None, secret=None, other=None): self.foo = foo self.bar = bar self.secret = secret def returnRenderedSecrets(self, secretKey): return getattr(self, secretKey) class TestRenderSecrets(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) fakeStorageService = FakeSecretStorage(secretdict={"foo": "bar", "other": "value"}) self.secretsrv = SecretManager() self.secretsrv.services = [fakeStorageService] yield self.secretsrv.setServiceParent(self.master) self.srvtest = FakeServiceUsingSecrets() yield self.srvtest.setServiceParent(self.master) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_secret_rendered(self): yield self.srvtest.configureService() new = FakeServiceUsingSecrets(foo=Secret("foo"), other=Secret("other")) yield self.srvtest.reconfigServiceWithSibling(new) self.assertEqual("bar", self.srvtest.returnRenderedSecrets("foo")) @defer.inlineCallbacks def test_secret_rendered_not_found(self): new = FakeServiceUsingSecrets(foo=Secret("foo")) yield self.srvtest.reconfigServiceWithSibling(new) with self.assertRaises(AttributeError): self.srvtest.returnRenderedSecrets("more")
2,106
Python
.py
45
40.333333
91
0.742565
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,336
test_secret_in_passwordstore.py
buildbot_buildbot/master/buildbot/test/unit/test_secret_in_passwordstore.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 pathlib import Path from unittest import mock from twisted.internet import defer from twisted.python.filepath import FilePath from twisted.trial import unittest from buildbot.secrets.providers.passwordstore import SecretInPass from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util.config import ConfigErrorsMixin class TestSecretInPass( MasterRunProcessMixin, TestReactorMixin, ConfigErrorsMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() self.master = yield fakemaster.make_master(self) with mock.patch.object(Path, "is_file", return_value=True): self.tmp_dir = self.create_temp_dir("temp") self.srvpass = SecretInPass("password", self.tmp_dir) yield self.srvpass.setServiceParent(self.master) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.srvpass.stopService() yield self.tear_down_test_reactor() def create_temp_dir(self, dirname): tempdir = FilePath(self.mktemp()) tempdir.createDirectory() return tempdir.path def test_check_config_secret_in_pass_service(self): self.assertEqual(self.srvpass.name, "SecretInPass") env = self.srvpass._env self.assertEqual(env["PASSWORD_STORE_GPG_OPTS"], "--passphrase password") self.assertEqual(env["PASSWORD_STORE_DIR"], self.tmp_dir) def test_check_config_binary_error_secret_in_pass_service(self): expected_error_msg = "pass does not exist in PATH" with mock.patch.object(Path, "is_file", return_value=False): with self.assertRaisesConfigError(expected_error_msg): self.srvpass.checkConfig("password", "temp") def test_check_config_directory_error_secret_in_pass_service(self): expected_error_msg = "directory temp2 does not exist" with mock.patch.object(Path, "is_file", return_value=True): with self.assertRaisesConfigError(expected_error_msg): self.srvpass.checkConfig("password", "temp2") @defer.inlineCallbacks def test_reconfig_secret_in_a_file_service(self): with mock.patch.object(Path, "is_file", return_value=True): otherdir = self.create_temp_dir("temp2") yield self.srvpass.reconfigService("password2", otherdir) self.assertEqual(self.srvpass.name, "SecretInPass") env = self.srvpass._env self.assertEqual(env["PASSWORD_STORE_GPG_OPTS"], "--passphrase password2") self.assertEqual(env["PASSWORD_STORE_DIR"], otherdir) @defer.inlineCallbacks def test_get_secret_in_pass(self): self.expect_commands(ExpectMasterShell(['pass', 'secret']).stdout(b'value')) value = yield self.srvpass.get("secret") self.assertEqual(value, "value") self.assert_all_commands_ran() @defer.inlineCallbacks def test_get_secret_in_pass_multiple_lines_unix(self): self.expect_commands( ExpectMasterShell(['pass', 'secret']).stdout(b"value1\nvalue2\nvalue3") ) value = yield self.srvpass.get("secret") self.assertEqual(value, "value1") self.assert_all_commands_ran() @defer.inlineCallbacks def test_get_secret_in_pass_multiple_lines_darwin(self): self.expect_commands( ExpectMasterShell(['pass', 'secret']).stdout(b"value1\rvalue2\rvalue3") ) value = yield self.srvpass.get("secret") self.assertEqual(value, "value1") self.assert_all_commands_ran() @defer.inlineCallbacks def test_get_secret_in_pass_multiple_lines_windows(self): self.expect_commands( ExpectMasterShell(['pass', 'secret']).stdout(b"value1\r\nvalue2\r\nvalue3") ) value = yield self.srvpass.get("secret") self.assertEqual(value, "value1") self.assert_all_commands_ran() @defer.inlineCallbacks def test_get_secret_in_pass_not_found(self): self.expect_commands(ExpectMasterShell(['pass', 'secret']).stderr(b"Not found")) value = yield self.srvpass.get("secret") self.assertEqual(value, None)
5,131
Python
.py
105
41.914286
88
0.709458
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,337
test_test_util_warnings.py
buildbot_buildbot/master/buildbot/test/unit/test_test_util_warnings.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 warnings from twisted.trial import unittest from buildbot.test.util.warnings import assertNotProducesWarnings from buildbot.test.util.warnings import assertProducesWarning from buildbot.test.util.warnings import assertProducesWarnings from buildbot.test.util.warnings import ignoreWarning class SomeWarning(Warning): pass class OtherWarning(Warning): pass class TestWarningsFilter(unittest.TestCase): def test_warnigs_caught(self): # Assertion is correct. with assertProducesWarning(SomeWarning): warnings.warn("test", SomeWarning, stacklevel=1) def test_warnigs_caught_num_check(self): # Assertion is correct. with assertProducesWarnings(SomeWarning, num_warnings=3): warnings.warn("1", SomeWarning, stacklevel=1) warnings.warn("2", SomeWarning, stacklevel=1) warnings.warn("3", SomeWarning, stacklevel=1) def test_warnigs_caught_num_check_fail(self): def f1(): with assertProducesWarnings(SomeWarning, num_warnings=2): pass with self.assertRaises(AssertionError): f1() def f2(): with assertProducesWarnings(SomeWarning, num_warnings=2): warnings.warn("1", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f2() def f3(): with assertProducesWarnings(SomeWarning, num_warnings=2): warnings.warn("1", SomeWarning, stacklevel=1) warnings.warn("2", SomeWarning, stacklevel=1) warnings.warn("3", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f3() def test_warnigs_caught_pattern_check(self): # Assertion is correct. with assertProducesWarning(SomeWarning, message_pattern=r"t.st"): warnings.warn("The test", SomeWarning, stacklevel=1) def test_warnigs_caught_pattern_check_fail(self): def f(): # Assertion fails. with assertProducesWarning(SomeWarning, message_pattern=r"other"): warnings.warn("The test", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f() def test_warnigs_caught_patterns_check(self): # Assertion is correct. with assertProducesWarnings(SomeWarning, messages_patterns=["1", "2", "3"]): warnings.warn("log 1 message", SomeWarning, stacklevel=1) warnings.warn("log 2 message", SomeWarning, stacklevel=1) warnings.warn("log 3 message", SomeWarning, stacklevel=1) def test_warnigs_caught_patterns_check_fails(self): def f1(): # Assertion fails. with assertProducesWarnings(SomeWarning, messages_patterns=["1", "2"]): warnings.warn("msg 1", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f1() def f2(): # Assertion fails. with assertProducesWarnings(SomeWarning, messages_patterns=["1", "2"]): warnings.warn("msg 2", SomeWarning, stacklevel=1) warnings.warn("msg 1", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f2() def f3(): # Assertion fails. with assertProducesWarnings(SomeWarning, messages_patterns=["1", "2"]): warnings.warn("msg 1", SomeWarning, stacklevel=1) warnings.warn("msg 2", SomeWarning, stacklevel=1) warnings.warn("msg 3", SomeWarning, stacklevel=1) with self.assertRaises(AssertionError): f3() def test_no_warnigs_check(self): with assertNotProducesWarnings(SomeWarning): pass with ignoreWarning(OtherWarning): with assertNotProducesWarnings(SomeWarning): warnings.warn("msg 3", OtherWarning, stacklevel=1) def test_warnigs_filter(self): with ignoreWarning(OtherWarning): with assertProducesWarnings(SomeWarning, messages_patterns=["1", "2", "3"]): warnings.warn("other", OtherWarning, stacklevel=1) warnings.warn("log 1 message", SomeWarning, stacklevel=1) warnings.warn("other", OtherWarning, stacklevel=1) warnings.warn("log 2 message", SomeWarning, stacklevel=1) warnings.warn("other", OtherWarning, stacklevel=1) warnings.warn("log 3 message", SomeWarning, stacklevel=1) warnings.warn("other", OtherWarning, stacklevel=1) def test_nested_filters(self): with assertProducesWarnings(SomeWarning, messages_patterns=["some 1"]): with assertProducesWarnings(OtherWarning, messages_patterns=["other 1"]): warnings.warn("other 1", OtherWarning, stacklevel=1) warnings.warn("some 1", SomeWarning, stacklevel=1) def test_ignore_warnings(self): with assertNotProducesWarnings(SomeWarning): with ignoreWarning(SomeWarning): warnings.warn("some 1", SomeWarning, stacklevel=1)
5,849
Python
.py
117
40.102564
88
0.664912
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,338
test_version.py
buildbot_buildbot/master/buildbot/test/unit/test_version.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 class VersioningUtilsTests(unittest.SynchronousTestCase): # Version utils are copied in three packages. # this unit test is made to be able to test the three versions # with the same test module_under_test = "buildbot" def setUp(self): try: self.m = __import__(self.module_under_test) except ImportError as e: raise unittest.SkipTest(self.module_under_test + " package is not installed") from e def test_gitDescribeToPep440devVersion(self): self.assertEqual(self.m.gitDescribeToPep440("v0.9.8-20-gf0f45ca"), "0.9.9.dev20") def test_gitDescribeToPep440tag(self): self.assertEqual(self.m.gitDescribeToPep440("v0.9.8"), "0.9.8") def test_gitDescribeToPep440p1tag(self): self.assertEqual(self.m.gitDescribeToPep440("v0.9.9.post1"), "0.9.9.post1") def test_gitDescribeToPep440p1dev(self): self.assertEqual(self.m.gitDescribeToPep440("v0.9.9.post1-20-gf0f45ca"), "0.9.10.dev20") def test_getVersionFromArchiveIdNoTag(self): version = self.m.getVersionFromArchiveId("1514651968 v0.9.9.post1-20-gf0f45ca") self.assertEqual(version, "0.9.10.dev20") def test_getVersionFromArchiveIdtag(self): version = self.m.getVersionFromArchiveId('1514808197 v1.0.0') self.assertEqual(version, "1.0.0") class VersioningUtilsTests_PKG(VersioningUtilsTests): module_under_test = "buildbot_pkg" class VersioningUtilsTests_WORKER(VersioningUtilsTests): module_under_test = "buildbot_worker"
2,274
Python
.py
43
47.930233
96
0.745151
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,339
test_mq_base.py
buildbot_buildbot/master/buildbot/test/unit/test_mq_base.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 unittest import mock from twisted.internet import defer from twisted.python import failure from twisted.trial import unittest from buildbot.mq import base class QueueRef(unittest.TestCase): def test_success(self): cb = mock.Mock(name='cb') qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') def test_success_deferred(self): cb = mock.Mock(name='cb') cb.return_value = defer.succeed(None) qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') def test_exception(self): cb = mock.Mock(name='cb') cb.side_effect = RuntimeError('oh noes!') qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) def test_failure(self): cb = mock.Mock(name='cb') cb.return_value = defer.fail(failure.Failure(RuntimeError('oh noes!'))) qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
1,914
Python
.py
45
37.066667
79
0.691685
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,340
test_auth.py
buildbot_buildbot/master/buildbot/test/unit/www/test_auth.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 unittest import mock from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.cred.credentials import UsernamePassword from twisted.cred.error import UnauthorizedLogin from twisted.internet import defer from twisted.trial import unittest from twisted.web.error import Error from twisted.web.guard import BasicCredentialFactory from twisted.web.guard import HTTPAuthSessionWrapper from twisted.web.resource import IResource from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.www import auth class AuthResourceMixin: @defer.inlineCallbacks def setUpAuthResource(self): self.master = yield self.make_master(url='h:/a/b/') self.auth = self.master.config.www['auth'] self.master.www.auth = self.auth self.auth.master = self.master class AuthRootResource(TestReactorMixin, www.WwwTestMixin, AuthResourceMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpAuthResource() self.rsrc = auth.AuthRootResource(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_getChild_login(self): glr = mock.Mock(name='glr') self.master.www.auth.getLoginResource = glr child = self.rsrc.getChild(b'login', mock.Mock(name='req')) self.assertIdentical(child, glr()) def test_getChild_logout(self): glr = mock.Mock(name='glr') self.master.www.auth.getLogoutResource = glr child = self.rsrc.getChild(b'logout', mock.Mock(name='req')) self.assertIdentical(child, glr()) class AuthBase(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.auth = auth.AuthBase() self.master = yield self.make_master(url='h:/a/b/') self.auth.master = self.master self.req = self.make_request(b'/') @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_maybeAutoLogin(self): self.assertEqual((yield self.auth.maybeAutoLogin(self.req)), None) def test_getLoginResource(self): with self.assertRaises(Error): self.auth.getLoginResource() @defer.inlineCallbacks def test_updateUserInfo(self): self.auth.userInfoProvider = auth.UserInfoProviderBase() self.auth.userInfoProvider.getUserInfo = lambda un: {'info': un} self.req.session.user_info = {'username': 'elvira'} yield self.auth.updateUserInfo(self.req) self.assertEqual(self.req.session.user_info, {'info': 'elvira', 'username': 'elvira'}) def getConfigDict(self): self.assertEqual(auth.getConfigDict(), {'name': 'AuthBase'}) class UseAuthInfoProviderBase(unittest.TestCase): @defer.inlineCallbacks def test_getUserInfo(self): uip = auth.UserInfoProviderBase() self.assertEqual((yield uip.getUserInfo('jess')), {'email': 'jess'}) class NoAuth(unittest.TestCase): def test_exists(self): assert auth.NoAuth # type: ignore[truthy-function] class RemoteUserAuth(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.auth = auth.RemoteUserAuth(header=b'HDR') yield self.make_master() self.request = self.make_request(b'/') @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_maybeAutoLogin(self): self.request.input_headers[b'HDR'] = b'[email protected]' yield self.auth.maybeAutoLogin(self.request) self.assertEqual( self.request.session.user_info, {'username': 'rachel', 'realm': 'foo.com', 'email': 'rachel'}, ) @defer.inlineCallbacks def test_maybeAutoLogin_no_header(self): try: yield self.auth.maybeAutoLogin(self.request) except Error as e: self.assertEqual(int(e.status), 403) else: self.fail("403 expected") @defer.inlineCallbacks def test_maybeAutoLogin_mismatched_value(self): self.request.input_headers[b'HDR'] = b'rachel' try: yield self.auth.maybeAutoLogin(self.request) except Error as e: self.assertEqual(int(e.status), 403) else: self.fail("403 expected") def test_get_login_resource_does_not_throw(self): self.auth.getLoginResource() class AuthRealm(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.auth = auth.RemoteUserAuth(header=b'HDR') self.auth = auth.NoAuth() yield self.make_master() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_requestAvatar(self): realm = auth.AuthRealm(self.master, self.auth) itfc, rsrc, _ = realm.requestAvatar("me", None, IResource) self.assertIdentical(itfc, IResource) self.assertIsInstance(rsrc, auth.PreAuthenticatedLoginResource) class TwistedICredAuthBase(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) # twisted.web makes it difficult to simulate the authentication process, so # this only tests the mechanics of the getLoginResource method. @defer.inlineCallbacks def test_getLoginResource(self): self.auth = auth.TwistedICredAuthBase( credentialFactories=[BasicCredentialFactory("buildbot")], checkers=[InMemoryUsernamePasswordDatabaseDontUse(good=b'guy')], ) self.auth.master = yield self.make_master(url='h:/a/b/') rsrc = self.auth.getLoginResource() self.assertIsInstance(rsrc, HTTPAuthSessionWrapper) class UserPasswordAuth(www.WwwTestMixin, unittest.TestCase): def test_passwordStringToBytes(self): login = {"user_string": "password", "user_bytes": b"password"} correct_login = {b"user_string": b"password", b"user_bytes": b"password"} self.auth = auth.UserPasswordAuth(login) self.assertEqual(self.auth.checkers[0].users, correct_login) login = [("user_string", "password"), ("user_bytes", b"password")] correct_login = {b"user_string": b"password", b"user_bytes": b"password"} self.auth = auth.UserPasswordAuth(login) self.assertEqual(self.auth.checkers[0].users, correct_login) class CustomAuth(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): class MockCustomAuth(auth.CustomAuth): def check_credentials(self, us, ps): return us == 'fellow' and ps == 'correct' def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_callable(self): self.auth = self.MockCustomAuth() cred_good = UsernamePassword('fellow', 'correct') result_good = yield self.auth.checkers[0].requestAvatarId(cred_good) self.assertEqual(result_good, 'fellow') cred_bad = UsernamePassword('bandid', 'incorrect') defer_bad = self.auth.checkers[0].requestAvatarId(cred_bad) yield self.assertFailure(defer_bad, UnauthorizedLogin) class LoginResource(TestReactorMixin, www.WwwTestMixin, AuthResourceMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpAuthResource() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_render(self): self.rsrc = auth.LoginResource(self.master) self.rsrc.renderLogin = mock.Mock( spec=self.rsrc.renderLogin, return_value=defer.succeed(b'hi') ) yield self.render_resource(self.rsrc, b'/auth/login') self.rsrc.renderLogin.assert_called_with(mock.ANY) class PreAuthenticatedLoginResource( TestReactorMixin, www.WwwTestMixin, AuthResourceMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpAuthResource() self.rsrc = auth.PreAuthenticatedLoginResource(self.master, 'him') @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_render(self): self.auth.maybeAutoLogin = mock.Mock() def updateUserInfo(request): session = request.getSession() session.user_info['email'] = session.user_info['username'] + "@org" session.updateSession(request) self.auth.updateUserInfo = mock.Mock(side_effect=updateUserInfo) res = yield self.render_resource(self.rsrc, b'/auth/login') self.assertEqual(res, {'redirected': b'h:/a/b/#/'}) self.assertFalse(self.auth.maybeAutoLogin.called) self.auth.updateUserInfo.assert_called_with(mock.ANY) self.assertEqual(self.master.session.user_info, {'email': 'him@org', 'username': 'him'}) class LogoutResource(TestReactorMixin, www.WwwTestMixin, AuthResourceMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpAuthResource() self.rsrc = auth.LogoutResource(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_render(self): self.master.session.expire = mock.Mock() res = yield self.render_resource(self.rsrc, b'/auth/logout') self.assertEqual(res, {'redirected': b'h:/a/b/#/'}) self.master.session.expire.assert_called_with() @defer.inlineCallbacks def test_render_with_crlf(self): self.master.session.expire = mock.Mock() res = yield self.render_resource(self.rsrc, b'/auth/logout?redirect=%0d%0abla') # everything after a %0d shall be stripped self.assertEqual(res, {'redirected': b'h:/a/b/#'}) self.master.session.expire.assert_called_with()
11,249
Python
.py
243
39.279835
97
0.703974
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,341
test_hooks_bitbucketcloud.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_bitbucketcloud.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 # Copyright Mamba Team from io import BytesIO from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.util import unicode2bytes from buildbot.www import change_hook from buildbot.www.hooks.bitbucketcloud import _HEADER_EVENT _CT_JSON = b'application/json' bitbucketPRproperties = { 'pullrequesturl': 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21', 'bitbucket.id': '21', 'bitbucket.link': 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21', 'bitbucket.title': 'dot 1496311906', 'bitbucket.authorLogin': 'Buildbot', 'bitbucket.fromRef.branch.name': 'branch_1496411680', 'bitbucket.fromRef.branch.rawNode': 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba', 'bitbucket.fromRef.commit.authorTimestamp': 0, 'bitbucket.fromRef.commit.date': None, 'bitbucket.fromRef.commit.hash': 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba', 'bitbucket.fromRef.commit.message': None, 'bitbucket.fromRef.repository.fullName': 'CI/py-repo', 'bitbucket.fromRef.repository.links.self.href': 'http://localhost:7990/projects/CI/repos/py-repo', 'bitbucket.fromRef.repository.owner.display_name': 'CI', 'bitbucket.fromRef.repository.owner.nickname': 'CI', 'bitbucket.fromRef.repository.ownerName': 'CI', 'bitbucket.fromRef.repository.project.key': 'CI', 'bitbucket.fromRef.repository.project.name': 'Continuous Integration', 'bitbucket.fromRef.repository.public': False, 'bitbucket.fromRef.repository.scm': 'git', 'bitbucket.fromRef.repository.slug': 'py-repo', 'bitbucket.toRef.branch.name': 'master', 'bitbucket.toRef.branch.rawNode': '7aebbb0089c40fce138a6d0b36d2281ea34f37f5', 'bitbucket.toRef.commit.authorTimestamp': 0, 'bitbucket.toRef.commit.date': None, 'bitbucket.toRef.commit.hash': '7aebbb0089c40fce138a6d0b36d2281ea34f37f5', 'bitbucket.toRef.commit.message': None, 'bitbucket.toRef.repository.fullName': 'CI/py-repo', 'bitbucket.toRef.repository.links.self.href': 'http://localhost:7990/projects/CI/repos/py-repo', 'bitbucket.toRef.repository.owner.display_name': 'CI', 'bitbucket.toRef.repository.owner.nickname': 'CI', 'bitbucket.toRef.repository.ownerName': 'CI', 'bitbucket.toRef.repository.project.key': 'CI', 'bitbucket.toRef.repository.project.name': 'Continuous Integration', 'bitbucket.toRef.repository.public': False, 'bitbucket.toRef.repository.scm': 'git', 'bitbucket.toRef.repository.slug': 'py-repo', } pushJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" }, "html": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": false, "new": { "type": "branch", "name": "branch_1496411680", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "old": { "type": "branch", "name": "branch_1496411680", "target": { "type": "commit", "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba" } } } ] } } """ pullRequestCreatedJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestUpdatedJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestRejectedJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestFulfilledJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" } } """ deleteTagJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" }, "html": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "ownerName": "BUIL", "public": false, "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": true, "old": { "type": "tag", "name": "1.0.0", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "new": null } ] } } """ deleteBranchJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" }, "html": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "ownerName": "CI", "public": false, "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": true, "old": { "type": "branch", "name": "branch_1496758965", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "new": null } ] } } """ newTagJsonPayload = """ { "actor": { "nickname": "John", "display_name": "John Smith" }, "repository": { "scm": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": { "href": "http://localhost:7990/projects/CI/repos/py-repo" }, "html": { "href": "http://localhost:7990/projects/CI/repos/py-repo" } }, "public": false, "ownerName": "CI", "owner": { "nickname": "CI", "display_name": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": true, "closed": false, "old": null, "new": { "type": "tag", "name": "1.0.0", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } } } ] } } """ def _prepare_request(payload, headers=None, change_dict=None): headers = headers or {} request = FakeRequest(change_dict) request.uri = b"/change_hook/bitbucketcloud" request.method = b"POST" if isinstance(payload, str): payload = unicode2bytes(payload) request.content = BytesIO(payload) request.received_headers[b'Content-Type'] = _CT_JSON request.received_headers.update(headers) return request class TestChangeHookConfiguredWithGitChange(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield fakeMasterForHooks(self) self.change_hook = change_hook.ChangeHookResource( dialects={ 'bitbucketcloud': { 'bitbucket_property_whitelist': ["bitbucket.*"], } }, master=master, ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertDictSubset(self, expected_dict, response_dict): expected = {} for key in expected_dict.keys(): self.assertIn(key, set(response_dict.keys())) expected[key] = response_dict[key] self.assertDictEqual(expected_dict, expected) def _checkPush(self, change): self.assertEqual(change['repository'], 'http://localhost:7990/projects/CI/repos/py-repo') self.assertEqual(change['author'], 'John Smith <John>') self.assertEqual(change['project'], 'Continuous Integration') self.assertEqual(change['revision'], '793d4754230023d85532f9a38dba3290f959beb4') self.assertEqual( change['comments'], 'Bitbucket Cloud commit 793d4754230023d85532f9a38dba3290f959beb4' ) self.assertEqual( change['revlink'], 'http://localhost:7990/projects/CI/repos/py-repo/commits/' '793d4754230023d85532f9a38dba3290f959beb4', ) @defer.inlineCallbacks def testHookWithChangeOnPushEvent(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: 'repo:push'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496411680') self.assertEqual(change['category'], 'push') @defer.inlineCallbacks def testHookWithNonDictOption(self): self.change_hook.dialects = {'bitbucketcloud': True} yield self.testHookWithChangeOnPushEvent() def _checkPullRequest(self, change): self.assertEqual(change['repository'], 'http://localhost:7990/projects/CI/repos/py-repo') self.assertEqual(change['author'], 'John Smith <John>') self.assertEqual(change['project'], 'Continuous Integration') self.assertEqual(change['comments'], 'Bitbucket Cloud Pull Request #21') self.assertEqual( change['revlink'], 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21' ) self.assertEqual(change['revision'], 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba') self.assertDictSubset(bitbucketPRproperties, change["properties"]) @defer.inlineCallbacks def testHookWithChangeOnPullRequestCreated(self): request = _prepare_request( pullRequestCreatedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:created'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/pull-requests/21/merge') self.assertEqual(change['category'], 'pull-created') @defer.inlineCallbacks def testHookWithChangeOnPullRequestUpdated(self): request = _prepare_request( pullRequestUpdatedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:updated'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/pull-requests/21/merge') self.assertEqual(change['category'], 'pull-updated') @defer.inlineCallbacks def testHookWithChangeOnPullRequestRejected(self): request = _prepare_request( pullRequestRejectedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:rejected'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496411680') self.assertEqual(change['category'], 'pull-rejected') @defer.inlineCallbacks def testHookWithChangeOnPullRequestFulfilled(self): request = _prepare_request( pullRequestFulfilledJsonPayload, headers={_HEADER_EVENT: 'pullrequest:fulfilled'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/heads/master') self.assertEqual(change['category'], 'pull-fulfilled') @defer.inlineCallbacks def _checkCodebase(self, event_type, expected_codebase): payloads = { 'repo:push': pushJsonPayload, 'pullrequest:updated': pullRequestUpdatedJsonPayload, } request = _prepare_request(payloads[event_type], headers={_HEADER_EVENT: event_type}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self.assertEqual(change['codebase'], expected_codebase) @defer.inlineCallbacks def testHookWithCodebaseValueOnPushEvent(self): self.change_hook.dialects = {'bitbucketcloud': {'codebase': 'super-codebase'}} yield self._checkCodebase('repo:push', 'super-codebase') @defer.inlineCallbacks def testHookWithCodebaseFunctionOnPushEvent(self): self.change_hook.dialects = { 'bitbucketcloud': {'codebase': lambda payload: payload['repository']['project']['key']} } yield self._checkCodebase('repo:push', 'CI') @defer.inlineCallbacks def testHookWithCodebaseValueOnPullEvent(self): self.change_hook.dialects = {'bitbucketcloud': {'codebase': 'super-codebase'}} yield self._checkCodebase('pullrequest:updated', 'super-codebase') @defer.inlineCallbacks def testHookWithCodebaseFunctionOnPullEvent(self): self.change_hook.dialects = { 'bitbucketcloud': {'codebase': lambda payload: payload['repository']['project']['key']} } yield self._checkCodebase('pullrequest:updated', 'CI') @defer.inlineCallbacks def testHookWithUnhandledEvent(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: 'invented:event'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b"Unknown event: invented_event") @defer.inlineCallbacks def testHookWithChangeOnCreateTag(self): request = _prepare_request(newTagJsonPayload, headers={_HEADER_EVENT: 'repo:push'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/tags/1.0.0') self.assertEqual(change['category'], 'push') @defer.inlineCallbacks def testHookWithChangeOnDeleteTag(self): request = _prepare_request(deleteTagJsonPayload, headers={_HEADER_EVENT: 'repo:push'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/tags/1.0.0') self.assertEqual(change['category'], 'ref-deleted') @defer.inlineCallbacks def testHookWithChangeOnDeleteBranch(self): request = _prepare_request(deleteBranchJsonPayload, headers={_HEADER_EVENT: 'repo:push'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496758965') self.assertEqual(change['category'], 'ref-deleted') @defer.inlineCallbacks def testHookWithInvalidContentType(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: b'repo:push'}) request.received_headers[b'Content-Type'] = b'invalid/content' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b"Unknown content type: invalid/content")
29,911
Python
.py
839
24.230036
102
0.520517
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,342
test_endpointmatchers.py
buildbot_buildbot/master/buildbot/test/unit/www/test_endpointmatchers.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.schedulers.forcesched import ForceScheduler from buildbot.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.www.authz import endpointmatchers class EndpointBase(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='h:/a/b/') self.db = self.master.db self.matcher = self.makeMatcher() self.matcher.setAuthz(self.master.authz) yield self.insertData() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeMatcher(self): raise NotImplementedError() def assertMatch(self, match): self.assertTrue(match is not None) def assertNotMatch(self, match): self.assertTrue(match is None) @defer.inlineCallbacks def insertData(self): yield self.db.insert_test_data([ fakedb.Builder(id=21, name="builder"), fakedb.SourceStamp(id=13, branch='secret'), fakedb.Master(id=1), fakedb.Worker(id=2, name='worker'), fakedb.Build(id=15, buildrequestid=16, masterid=1, workerid=2, builderid=21), fakedb.BuildRequest(id=16, buildsetid=17, builderid=21), fakedb.Buildset(id=17), fakedb.BuildsetSourceStamp(id=20, buildsetid=17, sourcestampid=13), ]) class ValidEndpointMixin: @defer.inlineCallbacks def test_invalidPath(self): ret = yield self.matcher.match(("foo", "bar")) self.assertNotMatch(ret) class AnyEndpointMatcher(EndpointBase): def makeMatcher(self): return endpointmatchers.AnyEndpointMatcher(role="foo") @defer.inlineCallbacks def test_nominal(self): ret = yield self.matcher.match(("foo", "bar")) self.assertMatch(ret) class AnyControlEndpointMatcher(EndpointBase): def makeMatcher(self): return endpointmatchers.AnyControlEndpointMatcher(role="foo") @defer.inlineCallbacks def test_default_action(self): ret = yield self.matcher.match(("foo", "bar")) self.assertMatch(ret) @defer.inlineCallbacks def test_get(self): ret = yield self.matcher.match(("foo", "bar"), action="GET") self.assertNotMatch(ret) @defer.inlineCallbacks def test_other_action(self): ret = yield self.matcher.match(("foo", "bar"), action="foo") self.assertMatch(ret) class ViewBuildsEndpointMatcherBranch(EndpointBase, ValidEndpointMixin): def makeMatcher(self): return endpointmatchers.ViewBuildsEndpointMatcher(branch="secret", role="agent") @defer.inlineCallbacks def test_build(self): ret = yield self.matcher.match(("builds", "15")) self.assertMatch(ret) test_build.skip = "ViewBuildsEndpointMatcher is not implemented yet" # type: ignore[attr-defined] class StopBuildEndpointMatcherBranch(EndpointBase, ValidEndpointMixin): def makeMatcher(self): return endpointmatchers.StopBuildEndpointMatcher(builder="builder", role="owner") @defer.inlineCallbacks def test_build(self): ret = yield self.matcher.match(("builds", "15"), "stop") self.assertMatch(ret) @defer.inlineCallbacks def test_build_no_match(self): self.matcher.builder = "foo" ret = yield self.matcher.match(("builds", "15"), "stop") self.assertNotMatch(ret) @defer.inlineCallbacks def test_build_no_builder(self): self.matcher.builder = None ret = yield self.matcher.match(("builds", "15"), "stop") self.assertMatch(ret) class ForceBuildEndpointMatcherBranch(EndpointBase, ValidEndpointMixin): def makeMatcher(self): return endpointmatchers.ForceBuildEndpointMatcher(builder="builder", role="owner") @defer.inlineCallbacks def insertData(self): yield super().insertData() self.master.allSchedulers = lambda: [ ForceScheduler(name="sched1", builderNames=["builder"]) ] @defer.inlineCallbacks def test_build(self): ret = yield self.matcher.match(("builds", "15"), "stop") self.assertNotMatch(ret) @defer.inlineCallbacks def test_forcesched(self): ret = yield self.matcher.match(("forceschedulers", "sched1"), "force") self.assertMatch(ret) @defer.inlineCallbacks def test_noforcesched(self): ret = yield self.matcher.match(("forceschedulers", "sched2"), "force") self.assertNotMatch(ret) @defer.inlineCallbacks def test_forcesched_builder_no_match(self): self.matcher.builder = "foo" ret = yield self.matcher.match(("forceschedulers", "sched1"), "force") self.assertNotMatch(ret) @defer.inlineCallbacks def test_forcesched_nobuilder(self): self.matcher.builder = None ret = yield self.matcher.match(("forceschedulers", "sched1"), "force") self.assertMatch(ret) class EnableSchedulerEndpointMatcher(EndpointBase, ValidEndpointMixin): def makeMatcher(self): return endpointmatchers.EnableSchedulerEndpointMatcher(role="agent") @defer.inlineCallbacks def test_build(self): ret = yield self.matcher.match(("builds", "15"), "stop") self.assertNotMatch(ret) @defer.inlineCallbacks def test_scheduler_enable(self): ret = yield self.matcher.match(("schedulers", "15"), "enable") self.assertMatch(ret)
6,342
Python
.py
145
37.186207
102
0.705815
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,343
test_resource.py
buildbot_buildbot/master/buildbot/test/unit/www/test_resource.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.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.www import resource class ResourceSubclass(resource.Resource): needsReconfig = True class Resource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_base_url(self): master = yield self.make_master(url=b'h:/a/b/') rsrc = resource.Resource(master) self.assertEqual(rsrc.base_url, b'h:/a/b/') @defer.inlineCallbacks def test_reconfigResource_registration(self): master = yield self.make_master(url=b'h:/a/b/') rsrc = ResourceSubclass(master) master.www.resourceNeedsReconfigs.assert_called_with(rsrc) class RedirectResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_redirect(self): master = yield self.make_master(url=b'h:/a/b/') rsrc = resource.RedirectResource(master, b'foo') self.render_resource(rsrc, b'/') self.assertEqual(self.request.redirected_to, b'h:/a/b/foo') @defer.inlineCallbacks def test_redirect_cr_lf(self): master = yield self.make_master(url=b'h:/a/b/') rsrc = resource.RedirectResource(master, b'foo\r\nbar') self.render_resource(rsrc, b'/') self.assertEqual(self.request.redirected_to, b'h:/a/b/foo')
2,482
Python
.py
55
40.145455
79
0.734245
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,344
test_hooks_poller.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_poller.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 import util from buildbot.changes import base from buildbot.changes.manager import ChangeManager from buildbot.test.fake import fakemaster from buildbot.test.fake.web import FakeRequest from buildbot.test.reactor import TestReactorMixin from buildbot.www import change_hook class TestPollingChangeHook(TestReactorMixin, unittest.TestCase): class Subclass(base.ReconfigurablePollingChangeSource): pollInterval = None called = False def poll(self): self.called = True def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def setUpRequest(self, args, options=True, activate=True): self.request = FakeRequest(args=args) self.request.uri = b"/change_hook/poller" self.request.method = b"GET" www = self.request.site.master.www self.master = master = self.request.site.master = yield fakemaster.make_master( self, wantData=True ) master.www = www yield self.master.startService() self.changeHook = change_hook.ChangeHookResource( dialects={'poller': options}, master=master ) master.change_svc = ChangeManager() yield master.change_svc.setServiceParent(master) self.changesrc = self.Subclass(21, name=b'example') yield self.changesrc.setServiceParent(master.change_svc) self.otherpoller = self.Subclass(22, name=b"otherpoller") yield self.otherpoller.setServiceParent(master.change_svc) anotherchangesrc = base.ChangeSource(name=b'notapoller') anotherchangesrc.setName("notapoller") yield anotherchangesrc.setServiceParent(master.change_svc) yield self.request.test_render(self.changeHook) yield util.asyncSleep(0.1) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_no_args(self): yield self.setUpRequest({}) self.assertEqual(self.request.written, b"no change found") self.assertEqual(self.changesrc.called, True) self.assertEqual(self.otherpoller.called, True) @defer.inlineCallbacks def test_no_poller(self): yield self.setUpRequest({b"poller": [b"nosuchpoller"]}) expected = b"Could not find pollers: nosuchpoller" self.assertEqual(self.request.written, expected) self.request.setResponseCode.assert_called_with(400, expected) self.assertEqual(self.changesrc.called, False) self.assertEqual(self.otherpoller.called, False) @defer.inlineCallbacks def test_invalid_poller(self): yield self.setUpRequest({b"poller": [b"notapoller"]}) expected = b"Could not find pollers: notapoller" self.assertEqual(self.request.written, expected) self.request.setResponseCode.assert_called_with(400, expected) self.assertEqual(self.changesrc.called, False) self.assertEqual(self.otherpoller.called, False) @defer.inlineCallbacks def test_trigger_poll(self): yield self.setUpRequest({b"poller": [b"example"]}) self.assertEqual(self.request.written, b"no change found") self.assertEqual(self.changesrc.called, True) self.assertEqual(self.otherpoller.called, False) @defer.inlineCallbacks def test_allowlist_deny(self): yield self.setUpRequest({b"poller": [b"otherpoller"]}, options={b"allowed": [b"example"]}) expected = b"Could not find pollers: otherpoller" self.assertEqual(self.request.written, expected) self.request.setResponseCode.assert_called_with(400, expected) self.assertEqual(self.changesrc.called, False) self.assertEqual(self.otherpoller.called, False) @defer.inlineCallbacks def test_allowlist_allow(self): yield self.setUpRequest({b"poller": [b"example"]}, options={b"allowed": [b"example"]}) self.assertEqual(self.request.written, b"no change found") self.assertEqual(self.changesrc.called, True) self.assertEqual(self.otherpoller.called, False) @defer.inlineCallbacks def test_allowlist_all(self): yield self.setUpRequest({}, options={b"allowed": [b"example"]}) self.assertEqual(self.request.written, b"no change found") self.assertEqual(self.changesrc.called, True) self.assertEqual(self.otherpoller.called, False)
5,251
Python
.py
108
41.851852
98
0.722873
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,345
test_graphql.py
buildbot_buildbot/master/buildbot/test/unit/www/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 from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import connector from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.util import unicode2bytes from buildbot.www import graphql try: import graphql as graphql_core except ImportError: graphql_core = None # type: ignore[assignment] class V3RootResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): if not graphql_core: skip = "graphql is required for V3RootResource tests" @defer.inlineCallbacks def setUp(self): self.patch(connector.DataConnector, 'submodules', []) self.setup_test_reactor(use_asyncio=True) self.master = yield self.make_master(url="http://server/path/", wantGraphql=True) self.master.config.www["graphql"] = {"debug": True} self.rsrc = graphql.V3RootResource(self.master) self.rsrc.reconfigResource(self.master.config) def assertSimpleError(self, message_or_error, responseCode): if isinstance(message_or_error, list): errors = message_or_error else: errors = [{"message": message_or_error}] content = json.dumps({"data": None, "errors": errors}) self.assertRequest(content=unicode2bytes(content), responseCode=responseCode) def assertResult(self, result): content = json.dumps({"data": result, "errors": None}) self.assertRequest(content=unicode2bytes(content), responseCode=200) @defer.inlineCallbacks def test_failure(self): self.master.graphql.query = mock.Mock(return_value=defer.fail(RuntimeError("oh noes"))) yield self.render_resource( self.rsrc, b"/?query={builders{name}}", ) self.assertSimpleError("internal error - see logs", 500) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) @defer.inlineCallbacks def test_invalid_http_method(self): yield self.render_resource(self.rsrc, b"/", method=b"PATCH") self.assertSimpleError("invalid HTTP method", 400) # https://graphql.org/learn/serving-over-http/#get-request @defer.inlineCallbacks def test_get_query(self): yield self.render_resource( self.rsrc, b"/?query={tests{testid}}", ) self.assertResult({ "tests": [ {"testid": 13}, {"testid": 14}, {"testid": 15}, {"testid": 16}, {"testid": 17}, {"testid": 18}, {"testid": 19}, {"testid": 20}, ] }) @defer.inlineCallbacks def test_get_query_item(self): yield self.render_resource( self.rsrc, b"/?query={test(testid:13){testid, info}}", ) self.assertResult({"test": {"testid": 13, "info": "ok"}}) @defer.inlineCallbacks def test_get_query_subresource(self): yield self.render_resource( self.rsrc, b"/?query={test(testid:13){testid, info, steps { info }}}", ) self.assertResult({ "test": { "testid": 13, "info": "ok", "steps": [{"info": "ok"}, {"info": "failed"}], } }) @defer.inlineCallbacks def test_get_query_items_result_spec(self): yield self.render_resource( self.rsrc, b"/?query={tests(testid__gt:18){testid, info}}", ) self.assertResult({ "tests": [{"testid": 19, "info": "todo"}, {"testid": 20, "info": "error"}] }) @defer.inlineCallbacks def test_get_noquery(self): yield self.render_resource( self.rsrc, b"/", ) self.assertSimpleError("GET request must contain a 'query' parameter", 400) # https://graphql.org/learn/serving-over-http/#post-request @defer.inlineCallbacks def test_post_query_graphql_content(self): yield self.render_resource( self.rsrc, method=b"POST", content=b"{tests{testid}}", content_type=b"application/graphql", ) self.assertResult({ "tests": [ {"testid": 13}, {"testid": 14}, {"testid": 15}, {"testid": 16}, {"testid": 17}, {"testid": 18}, {"testid": 19}, {"testid": 20}, ] }) @defer.inlineCallbacks def test_post_query_json_content(self): query = {"query": "{tests{testid}}"} yield self.render_resource( self.rsrc, method=b"POST", content=json.dumps(query).encode(), content_type=b"application/json", ) self.assertResult({ "tests": [ {"testid": 13}, {"testid": 14}, {"testid": 15}, {"testid": 16}, {"testid": 17}, {"testid": 18}, {"testid": 19}, {"testid": 20}, ] }) @defer.inlineCallbacks def test_post_query_json_content_operationName(self): query = { "query": "query foo {tests{testid}} query bar {tests{name}}", "operationName": "fsoo", } yield self.render_resource( self.rsrc, method=b"POST", content=json.dumps(query).encode(), content_type=b"application/json", ) self.assertSimpleError("json request unsupported fields: operationName", 400) @defer.inlineCallbacks def test_post_query_json_badcontent_type(self): yield self.render_resource( self.rsrc, method=b"POST", content=b"foo", content_type=b"application/foo" ) self.assertSimpleError("unsupported content-type: application/foo", 400) @defer.inlineCallbacks def test_post_query_json_nocontent_type(self): yield self.render_resource(self.rsrc, method=b"POST") self.assertSimpleError("no content-type", 400) @defer.inlineCallbacks def test_get_bad_query(self): yield self.render_resource( self.rsrc, b"/?query={notexistant{id}}", ) self.assertSimpleError( [ { "message": "Cannot query field 'notexistant' on type 'Query'.", "locations": [{"line": 1, "column": 2}], } ], 200, ) class DisabledV3RootResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): if not graphql_core: skip = "graphql is required for V3RootResource tests" @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url="http://server/path/") self.rsrc = graphql.V3RootResource(self.master) self.rsrc.reconfigResource(self.master.config) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_basic_disabled(self): yield self.render_resource(self.rsrc, b"/") self.assertRequest( content=unicode2bytes( json.dumps({"data": None, "errors": [{"message": "graphql not enabled"}]}) ), responseCode=501, )
8,284
Python
.py
218
28.619266
95
0.595223
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,346
test_roles.py
buildbot_buildbot/master/buildbot/test/unit/www/test_roles.py
# redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.trial import unittest from buildbot.test.util.config import ConfigErrorsMixin from buildbot.www.authz import roles class RolesFromGroups(unittest.TestCase): def setUp(self): self.roles = roles.RolesFromGroups("buildbot-") def test_noGroups(self): ret = self.roles.getRolesFromUser({"username": 'homer'}) self.assertEqual(ret, []) def test_noBuildbotGroups(self): ret = self.roles.getRolesFromUser({"username": "homer", "groups": ["employee"]}) self.assertEqual(ret, []) def test_someBuildbotGroups(self): ret = self.roles.getRolesFromUser({ "username": "homer", "groups": ["employee", "buildbot-maintainer", "buildbot-admin"], }) self.assertEqual(ret, ["maintainer", "admin"]) class RolesFromEmails(unittest.TestCase): def setUp(self): self.roles = roles.RolesFromEmails( employee=["[email protected]", "[email protected]"], boss=["[email protected]"] ) def test_noUser(self): ret = self.roles.getRolesFromUser({"username": 'lisa', "email": '[email protected]'}) self.assertEqual(ret, []) def test_User1(self): ret = self.roles.getRolesFromUser({"username": 'homer', "email": '[email protected]'}) self.assertEqual(ret, ["employee"]) def test_User2(self): ret = self.roles.getRolesFromUser({"username": 'burns', "email": '[email protected]'}) self.assertEqual(sorted(ret), ["boss", "employee"]) class RolesFromOwner(unittest.TestCase): def setUp(self): self.roles = roles.RolesFromOwner("ownerofbuild") def test_noOwner(self): ret = self.roles.getRolesFromUser({"username": 'lisa', "email": '[email protected]'}, None) self.assertEqual(ret, []) def test_notOwner(self): ret = self.roles.getRolesFromUser( {"username": 'lisa', "email": '[email protected]'}, "[email protected]" ) self.assertEqual(ret, []) def test_owner(self): ret = self.roles.getRolesFromUser( {"username": 'homer', "email": '[email protected]'}, "[email protected]" ) self.assertEqual(ret, ["ownerofbuild"]) class RolesFromUsername(unittest.TestCase, ConfigErrorsMixin): def setUp(self): self.roles = roles.RolesFromUsername(roles=["admins"], usernames=["Admin"]) self.roles2 = roles.RolesFromUsername( roles=["developers", "integrators"], usernames=["Alice", "Bob"] ) def test_anonymous(self): ret = self.roles.getRolesFromUser({"anonymous": True}) self.assertEqual(ret, []) def test_normalUser(self): ret = self.roles.getRolesFromUser({"username": 'Alice'}) self.assertEqual(ret, []) def test_admin(self): ret = self.roles.getRolesFromUser({"username": 'Admin'}) self.assertEqual(ret, ["admins"]) def test_multipleGroups(self): ret = self.roles2.getRolesFromUser({"username": 'Bob'}) self.assertEqual(ret, ["developers", "integrators"]) def test_badUsernames(self): with self.assertRaisesConfigError('Usernames cannot be None'): roles.RolesFromUsername(roles=[], usernames=[None])
3,855
Python
.py
82
40.207317
97
0.670846
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,347
test_hooks_gitlab.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_gitlab.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.plugins import util from buildbot.secrets.manager import SecretManager from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.www import change_hook from buildbot.www.hooks.gitlab import _HEADER_EVENT from buildbot.www.hooks.gitlab import _HEADER_GITLAB_TOKEN # Sample GITLAB commit payload from https://docs.gitlab.com/ce/user/project/integrations/webhooks.html # Added "modified" and "removed", and change email gitJsonPayload = b""" { "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "ref": "refs/heads/master", "user_id": 4, "user_name": "John Smith", "repository": { "name": "Diaspora", "url": "git@localhost:diaspora.git", "description": "", "homepage": "http://localhost/diaspora" }, "commits": [ { "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", "message": "Update Catalan translation to e38cb41.", "timestamp": "2011-12-12T14:27:31+02:00", "url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", "author": { "name": "Jordi Mallach", "email": "[email protected]" } }, { "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "message": "fixed readme", "timestamp": "2012-01-03T23:36:29+02:00", "url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "author": { "name": "GitLab dev user", "email": "gitlabdev@dv6700.(none)" } } ], "total_commits_count": 2 } """ gitJsonPayloadTag = b""" { "object_kind": "tag_push", "before": "0000000000000000000000000000000000000000", "after": "82b3d5ae55f7080f1e6022629cdb57bfae7cccc7", "ref": "refs/tags/v1.0.0", "checkout_sha": "82b3d5ae55f7080f1e6022629cdb57bfae7cccc7", "user_id": 1, "user_name": "John Smith", "repository":{ "name": "Example", "url": "git@localhost:diaspora.git", "description": "", "homepage": "http://example.com/jsmith/example", "git_http_url":"http://example.com/jsmith/example.git", "git_ssh_url":"[email protected]:jsmith/example.git", "visibility_level":0 }, "commits": [ { "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", "message": "Update Catalan translation to e38cb41.", "timestamp": "2011-12-12T14:27:31+02:00", "url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", "author": { "name": "Jordi Mallach", "email": "[email protected]" } }, { "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "message": "fixed readme", "timestamp": "2012-01-03T23:36:29+02:00", "url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", "author": { "name": "GitLab dev user", "email": "gitlabdev@dv6700.(none)" } } ], "total_commits_count": 2 } """ # == Merge requests from a different branch of the same project # GITLAB commit payload from an actual version 10.7.1-ee gitlab instance # chronicling the lives and times of a trivial MR through the operations # open, edit description, add commit, close, and reopen, in that order. # (Tidied with json_pp --json_opt=canonical,pretty and an editor.) # FIXME: only show diffs here to keep file smaller and increase clarity gitJsonPayloadMR_open = b""" { "event_type" : "merge_request", "object_attributes" : { "action" : "open", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-15 07:45:37 -0700", "description" : "This to both gitlab gateways!", "head_pipeline_id" : 29931, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10850, "iid" : 6, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "92268bc781b24f0a61b907da062950e9e5252a69", "message" : "Remove the dummy line again", "timestamp" : "2018-05-14T07:54:04-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/92268bc781b24f0a61b907da062950e9e5252a69" }, "last_edited_at" : null, "last_edited_by_id" : null, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : 0 }, "merge_status" : "unchecked", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 239, "state" : "opened", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Remove the dummy line again", "total_time_spent" : 0, "updated_at" : "2018-05-15 07:45:37 -0700", "updated_by_id" : null, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/6", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ gitJsonPayloadMR_editdesc = b""" { "event_type" : "merge_request", "object_attributes" : { "action" : "update", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-15 07:45:37 -0700", "description" : "Edited description.", "head_pipeline_id" : 29931, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10850, "iid" : 6, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "92268bc781b24f0a61b907da062950e9e5252a69", "message" : "Remove the dummy line again", "timestamp" : "2018-05-14T07:54:04-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/92268bc781b24f0a61b907da062950e9e5252a69" }, "last_edited_at" : "2018-05-15 07:49:55 -0700", "last_edited_by_id" : 15, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : 0 }, "merge_status" : "can_be_merged", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 239, "state" : "opened", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Remove the dummy line again", "total_time_spent" : 0, "updated_at" : "2018-05-15 07:49:55 -0700", "updated_by_id" : 15, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/6", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ gitJsonPayloadMR_addcommit = b""" { "event_type" : "merge_request", "object_attributes" : { "action" : "update", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-15 07:45:37 -0700", "description" : "Edited description.", "head_pipeline_id" : 29931, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10850, "iid" : 6, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "cee8b01dcbaeed89563c2822f7c59a93c813eb6b", "message" : "debian/compat: update to 9", "timestamp" : "2018-05-15T07:51:11-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/cee8b01dcbaeed89563c2822f7c59a93c813eb6b" }, "last_edited_at" : "2018-05-15 14:49:55 UTC", "last_edited_by_id" : 15, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : 0 }, "merge_status" : "unchecked", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "oldrev" : "92268bc781b24f0a61b907da062950e9e5252a69", "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 239, "state" : "opened", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Remove the dummy line again", "total_time_spent" : 0, "updated_at" : "2018-05-15 14:51:27 UTC", "updated_by_id" : 15, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/6", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ gitJsonPayloadMR_close = b""" { "event_type" : "merge_request", "object_attributes" : { "action" : "close", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-15 07:45:37 -0700", "description" : "Edited description.", "head_pipeline_id" : 29958, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10850, "iid" : 6, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "cee8b01dcbaeed89563c2822f7c59a93c813eb6b", "message" : "debian/compat: update to 9", "timestamp" : "2018-05-15T07:51:11-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/cee8b01dcbaeed89563c2822f7c59a93c813eb6b" }, "last_edited_at" : "2018-05-15 07:49:55 -0700", "last_edited_by_id" : 15, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : 0 }, "merge_status" : "can_be_merged", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 239, "state" : "closed", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Remove the dummy line again", "total_time_spent" : 0, "updated_at" : "2018-05-15 07:52:01 -0700", "updated_by_id" : 15, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/6", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ gitJsonPayloadMR_reopen = b""" { "event_type" : "merge_request", "object_attributes" : { "action" : "reopen", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-15 07:45:37 -0700", "description" : "Edited description.", "head_pipeline_id" : 29958, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10850, "iid" : 6, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "cee8b01dcbaeed89563c2822f7c59a93c813eb6b", "message" : "debian/compat: update to 9", "timestamp" : "2018-05-15T07:51:11-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/cee8b01dcbaeed89563c2822f7c59a93c813eb6b" }, "last_edited_at" : "2018-05-15 07:49:55 -0700", "last_edited_by_id" : 15, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : 0 }, "merge_status" : "can_be_merged", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 239, "state" : "opened", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Remove the dummy line again", "total_time_spent" : 0, "updated_at" : "2018-05-15 07:53:27 -0700", "updated_by_id" : 15, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/6", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ # == Merge requests from a fork of the project # (Captured more accurately than above test data) gitJsonPayloadMR_open_forked = b""" { "changes" : { "total_time_spent" : { "current" : 0, "previous" : null } }, "event_type" : "merge_request", "labels" : [], "object_attributes" : { "action" : "open", "assignee_id" : null, "author_id" : 15, "created_at" : "2018-05-19 06:57:12 -0700", "description" : "This is a merge request from a fork of the project.", "head_pipeline_id" : null, "human_time_estimate" : null, "human_total_time_spent" : null, "id" : 10914, "iid" : 7, "last_commit" : { "author" : { "email" : "[email protected]", "name" : "Max Mustermann" }, "id" : "e46ee239f3d6d41ade4d1e610669dd71ed86ec80", "message" : "Add note to README", "timestamp" : "2018-05-19T06:35:26-07:00", "url" : "https://gitlab.example.com/mmusterman/awesome_project/commit/e46ee239f3d6d41ade4d1e610669dd71ed86ec80" }, "last_edited_at" : null, "last_edited_by_id" : null, "merge_commit_sha" : null, "merge_error" : null, "merge_params" : { "force_remove_source_branch" : "0" }, "merge_status" : "unchecked", "merge_user_id" : null, "merge_when_pipeline_succeeds" : false, "milestone_id" : null, "source" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/build/awesome_project.git", "git_ssh_url" : "[email protected]:build/awesome_project.git", "homepage" : "https://gitlab.example.com/build/awesome_project", "http_url" : "https://gitlab.example.com/build/awesome_project.git", "id" : 2337, "name" : "awesome_project", "namespace" : "build", "path_with_namespace" : "build/awesome_project", "ssh_url" : "[email protected]:build/awesome_project.git", "url" : "[email protected]:build/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/build/awesome_project" }, "source_branch" : "ms-viewport", "source_project_id" : 2337, "state" : "opened", "target" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "target_branch" : "master", "target_project_id" : 239, "time_estimate" : 0, "title" : "Add note to README", "total_time_spent" : 0, "updated_at" : "2018-05-19 06:57:12 -0700", "updated_by_id" : null, "url" : "https://gitlab.example.com/mmusterman/awesome_project/merge_requests/7", "work_in_progress" : false }, "object_kind" : "merge_request", "project" : { "avatar_url" : null, "ci_config_path" : null, "default_branch" : "master", "description" : "Trivial project for testing build machinery quickly", "git_http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "git_ssh_url" : "[email protected]:mmusterman/awesome_project.git", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "http_url" : "https://gitlab.example.com/mmusterman/awesome_project.git", "id" : 239, "name" : "awesome_project", "namespace" : "mmusterman", "path_with_namespace" : "mmusterman/awesome_project", "ssh_url" : "[email protected]:mmusterman/awesome_project.git", "url" : "[email protected]:mmusterman/awesome_project.git", "visibility_level" : 0, "web_url" : "https://gitlab.example.com/mmusterman/awesome_project" }, "repository" : { "description" : "Trivial project for testing build machinery quickly", "homepage" : "https://gitlab.example.com/mmusterman/awesome_project", "name" : "awesome_project", "url" : "[email protected]:mmusterman/awesome_project.git" }, "user" : { "avatar_url" : "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=40&d=identicon", "name" : "Max Mustermann", "username" : "mmusterman" } } """ # == Merge requests from a fork of the project # (Captured more accurately than above test data) captured from gitlab/v4 rest api gitJsonPayloadMR_commented = b""" { "object_kind": "note", "event_type": "note", "user": { "id": 343, "name": "Name Surname", "username": "rollo", "avatar_url": "null", "email": "[REDACTED]" }, "project_id": 926, "project": { "id": 926, "name": "awesome_project", "description": "", "web_url": "https://gitlab.example.com/mmusterman/awesome_project", "avatar_url": null, "git_ssh_url": "[email protected]:mmusterman/awesome_project.git", "git_http_url": "https://gitlab.example.com/mmusterman/awesome_project.git", "namespace" : "mmusterman", "visibility_level": 0, "path_with_namespace": "awesome_project", "default_branch": "master", "ci_config_path": null, "homepage": "https://gitlab.example.com/mmusterman/awesome_project", "url": "[email protected]:mmusterman/awesome_project.git", "ssh_url": "[email protected]:mmusterman/awesome_project.git", "http_url": "https://gitlab.example.com/mmusterman/awesome_project.git" }, "object_attributes": { "attachment": null, "author_id": 343, "change_position": { "base_sha": null, "start_sha": null, "head_sha": null, "old_path": null, "new_path": null, "position_type": "text", "old_line": null, "new_line": null, "line_range": null }, "commit_id": null, "created_at": "2022-02-04 09:13:56 UTC", "discussion_id": "0a307b85835ac7c3e2c1b4e6283d7baf42df0f8e", "id": 83474, "line_code": "762ab21851f67780cfb68832884fa1f859ccd00e_761_762", "note": "036 #BB", "noteable_id": 4085, "noteable_type": "MergeRequest", "original_position": { "base_sha": "7e2c01527d87c36cf4f9e78dd9fc6aa4f602c365", "start_sha": "7e2c01527d87c36cf4f9e78dd9fc6aa4f602c365", "head_sha": "b91a85e84404932476f76ccbf0f42c963005501b", "old_path": "run/exp.fun_R2B4", "new_path": "run/exp.fun_R2B4", "position_type": "text", "old_line": null, "new_line": 762, "line_range": { "start": { "line_code": "762abg1851f67780cfb68832884fa1f859ccd00e_761_762", "type": "new", "old_line": null, "new_line": 762 }, "end": { "line_code": "762abg1851f67780cfb68832884fa1f859ccd00e_761_762", "type": "new", "old_line": null, "new_line": 762 } } }, "position": { "base_sha": "7e2c01527d87c36cf4f9e78dd9fc6aa4f602c365", "start_sha": "7e2c01527d87c36cf4f9e78dd9fc6aa4f602c365", "head_sha": "d1ce5517d3745dbd68e1eeb45f42380d76d0c490", "old_path": "run/exp.esm_R2B4", "new_path": "run/exp.esm_R2B4", "position_type": "text", "old_line": null, "new_line": 762, "line_range": { "start": { "line_code": "762ab21851f67780cfb68832884fa1f859ccd00e_761_762", "type": "new", "old_line": null, "new_line": 762 }, "end": { "line_code": "762ab21851f67780cfb68832884fa1f859ccd00e_761_762", "type": "new", "old_line": null, "new_line": 762 } } }, "project_id": 926, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "st_diff": null, "system": false, "type": "DiffNote", "updated_at": "2022-02-04 09:13:56 UTC", "updated_by_id": null, "description": "036 #BB", "url": "https://gitlab.example.com/mmusterman/awesome_project_id/-/merge_requests/7#note_83474" }, "repository": { "name": "awesome_project", "url": "[email protected]:mmusterman/awesome_project.git", "description": "", "homepage": "https://gitlab.example.com/mmusterman/awesome_project" }, "merge_request": { "assignee_id": 343, "author_id": 343, "created_at": "2022-01-28 09:17:41 UTC", "description": "Some tests got disabled in the last merge. I will try to re-activate all infrastructure-related tests", "head_pipeline_id": 14675, "id": 4085, "iid": 7, "last_edited_at": "2022-02-01 15:10:38 UTC", "last_edited_by_id": 343, "merge_commit_sha": null, "merge_error": null, "merge_params": { "force_remove_source_branch": "1" }, "merge_status": "can_be_merged", "merge_user_id": null, "merge_when_pipeline_succeeds": false, "milestone_id": null, "source_branch": "fix-missing-tests", "source_project_id": 926, "state_id": 1, "target_branch": "master", "target_project_id": 926, "time_estimate": 0, "title": "Draft: Fix missing tests: pio", "updated_at": "2022-02-04 09:13:17 UTC", "updated_by_id": 343, "url": "https://gitlab.example.com/mmusterman/awesome_project/-/merge_requests/7", "source": { "id": 926, "name": "awesome_project", "description": "", "web_url": "https://gitlab.example.com/mmusterman/awesome_project", "avatar_url": null, "git_ssh_url": "[email protected]:mmusterman/awesome_project.git", "git_http_url": "https://gitlab.example.com/mmusterman/awesome_project.git", "namespace": "mmusterman", "visibility_level": 0, "path_with_namespace": "awesome_project", "default_branch": "master", "ci_config_path": null, "homepage": "https://gitlab.example.com/mmusterman/awesome_project", "url": "[email protected]:mmusterman/awesome_project.git", "ssh_url": "[email protected]:mmusterman/awesome_project.git", "http_url": "https://gitlab.example.com/mmusterman/awesome_project.git" }, "target": { "id": 926, "name": "awesome_project", "description": "", "web_url": "https://gitlab.example.com/mmusterman/awesome_project", "avatar_url": null, "git_ssh_url": "[email protected]:mmusterman/awesome_project.git", "git_http_url": "https://gitlab.example.com/mmusterman/awesome_project.git", "namespace": "mmusterman", "visibility_level": 0, "path_with_namespace": "awesome_project", "default_branch": "master", "ci_config_path": null, "homepage": "https://gitlab.example.com/mmusterman/awesome_project", "url": "[email protected]:mmusterman/awesome_project.git", "ssh_url": "[email protected]:mmusterman/awesome_project.git", "http_url": "https://gitlab.example.com/mmusterman/awesome_project.git" }, "last_commit": { "id": "d1ce5517d3745dbd68e1eeb45f42380d76d0c490", "message": "adopt radiation changes for ruby0 runs in bb", "title": "adopt radiation changes for ruby0 runs in bb", "timestamp": "2022-01-28T10:13:12+01:00", "url": "https://gitlab.example.com/mmusterman/awesome_project/-/commit/d1ce5517d3745dbd68e1eeb45f42380d76d0c490", "author": { "name": "Name Surname", "email": "[email protected]" } }, "work_in_progress": true, "total_time_spent": 0, "time_change": 0, "human_total_time_spent": null, "human_time_change": null, "human_time_estimate": null, "assignee_ids": [ 343 ], "state": "opened" } } """ def FakeRequestMR(content): request = FakeRequest(content=content) request.uri = b"/change_hook/gitlab" request.args = {b'codebase': [b'MyCodebase']} request.received_headers[_HEADER_EVENT] = b"Merge Request Hook" request.method = b"POST" return request class TestChangeHookConfiguredWithGitChange(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield fakeMasterForHooks(self) self.changeHook = change_hook.ChangeHookResource(dialects={'gitlab': True}, master=master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def check_changes_tag_event(self, r, project='', codebase=None): self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["repository"], "git@localhost:diaspora.git") self.assertEqual(change["when_timestamp"], 1323692851) self.assertEqual(change["branch"], "v1.0.0") def check_changes_mr_event( self, r, project='awesome_project', codebase=None, timestamp=1526309644, source_repo=None ): self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual( change["repository"], "https://gitlab.example.com/mmusterman/awesome_project.git" ) if source_repo is None: source_repo = "https://gitlab.example.com/mmusterman/awesome_project.git" self.assertEqual(change['properties']["source_repository"], source_repo) self.assertEqual( change['properties']["target_repository"], "https://gitlab.example.com/mmusterman/awesome_project.git", ) self.assertEqual(change["when_timestamp"], timestamp) self.assertEqual(change["branch"], "master") self.assertEqual(change['properties']["source_branch"], 'ms-viewport') self.assertEqual(change['properties']["target_branch"], 'master') self.assertEqual(change["category"], "merge_request") self.assertEqual(change.get("project"), project) def check_changes_mr_event_by_comment( self, r, project='awesome_project', codebase=None, timestamp=1526309644, source_repo=None, repo='https://gitlab.example.com/mmusterman/awesome_project.git', source_branch='ms-viewport', target_branch='master', ): self.maxDiff = None self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["repository"], repo) if source_repo is None: source_repo = repo self.assertEqual(change['properties']["source_repository"], source_repo) self.assertEqual(change['properties']["target_repository"], repo) self.assertEqual(change["when_timestamp"], timestamp) self.assertEqual(change["branch"], target_branch) self.assertEqual(change['properties']["source_branch"], source_branch) self.assertEqual(change['properties']["target_branch"], target_branch) self.assertEqual(change["category"], "note") self.assertEqual(change.get("project"), project) def check_changes_push_event(self, r, project='diaspora', codebase=None): self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["repository"], "git@localhost:diaspora.git") self.assertEqual(change["when_timestamp"], 1323692851) self.assertEqual(change["author"], "Jordi Mallach <[email protected]>") self.assertEqual(change["revision"], 'b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327') self.assertEqual(change["comments"], "Update Catalan translation to e38cb41.") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", ) change = self.changeHook.master.data.updates.changesAdded[1] self.assertEqual(change["repository"], "git@localhost:diaspora.git") self.assertEqual(change["when_timestamp"], 1325626589) self.assertEqual(change["author"], "GitLab dev user <gitlabdev@dv6700.(none)>") self.assertEqual(change["src"], "git") self.assertEqual(change["revision"], 'da1560886d4f094c3e6c9ef40349f7d38b5d27d7') self.assertEqual(change["comments"], "fixed readme") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", ) # FIXME: should we convert project name to canonical case? # Or should change filter be case insensitive? self.assertEqual(change.get("project").lower(), project.lower()) self.assertEqual(change.get("codebase"), codebase) # Test 'base' hook with attributes. We should get a json string representing # a Change object as a dictionary. All values show be set. @defer.inlineCallbacks def testGitWithChange(self): self.request = FakeRequest(content=gitJsonPayload) self.request.uri = b"/change_hook/gitlab" self.request.method = b"POST" self.request.received_headers[_HEADER_EVENT] = b"Push Hook" res = yield self.request.test_render(self.changeHook) self.check_changes_push_event(res) @defer.inlineCallbacks def testGitWithChange_WithProjectToo(self): self.request = FakeRequest(content=gitJsonPayload) self.request.uri = b"/change_hook/gitlab" self.request.args = {b'project': [b'Diaspora']} self.request.received_headers[_HEADER_EVENT] = b"Push Hook" self.request.method = b"POST" res = yield self.request.test_render(self.changeHook) self.check_changes_push_event(res, project="Diaspora") @defer.inlineCallbacks def testGitWithChange_WithCodebaseToo(self): self.request = FakeRequest(content=gitJsonPayload) self.request.uri = b"/change_hook/gitlab" self.request.args = {b'codebase': [b'MyCodebase']} self.request.received_headers[_HEADER_EVENT] = b"Push Hook" self.request.method = b"POST" res = yield self.request.test_render(self.changeHook) self.check_changes_push_event(res, codebase="MyCodebase") @defer.inlineCallbacks def testGitWithChange_WithPushTag(self): self.request = FakeRequest(content=gitJsonPayloadTag) self.request.uri = b"/change_hook/gitlab" self.request.args = {b'codebase': [b'MyCodebase']} self.request.received_headers[_HEADER_EVENT] = b"Push Hook" self.request.method = b"POST" res = yield self.request.test_render(self.changeHook) self.check_changes_tag_event(res, codebase="MyCodebase") @defer.inlineCallbacks def testGitWithNoJson(self): self.request = FakeRequest() self.request.uri = b"/change_hook/gitlab" self.request.method = b"POST" self.request.received_headers[_HEADER_EVENT] = b"Push Hook" yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertIn(b"Error loading JSON:", self.request.written) self.request.setResponseCode.assert_called_with(400, mock.ANY) @defer.inlineCallbacks def test_event_property(self): self.request = FakeRequest(content=gitJsonPayload) self.request.received_headers[_HEADER_EVENT] = b"Push Hook" self.request.uri = b"/change_hook/gitlab" self.request.method = b"POST" yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["properties"]["event"], "Push Hook") self.assertEqual(change["category"], "Push Hook") @defer.inlineCallbacks def testGitWithChange_WithMR_open(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_open) res = yield self.request.test_render(self.changeHook) self.check_changes_mr_event(res, codebase="MyCodebase") change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["category"], "merge_request") @defer.inlineCallbacks def testGitWithChange_WithMR_editdesc(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_editdesc) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def testGitWithChange_WithMR_addcommit(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_addcommit) res = yield self.request.test_render(self.changeHook) self.check_changes_mr_event(res, codebase="MyCodebase", timestamp=1526395871) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["category"], "merge_request") @defer.inlineCallbacks def testGitWithChange_WithMR_close(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_close) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def testGitWithChange_WithMR_reopen(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_reopen) res = yield self.request.test_render(self.changeHook) self.check_changes_mr_event(res, codebase="MyCodebase", timestamp=1526395871) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["category"], "merge_request") @defer.inlineCallbacks def testGitWithChange_WithMR_open_forked(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_open_forked) res = yield self.request.test_render(self.changeHook) self.check_changes_mr_event( res, codebase="MyCodebase", timestamp=1526736926, source_repo="https://gitlab.example.com/build/awesome_project.git", ) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["category"], "merge_request") @defer.inlineCallbacks def testGitWithChange_WithMR_commented(self): self.request = FakeRequestMR(content=gitJsonPayloadMR_commented) res = yield self.request.test_render(self.changeHook) self.check_changes_mr_event_by_comment( res, codebase="MyCodebase", timestamp=1643361192, project="awesome_project", source_repo="https://gitlab.example.com/mmusterman/awesome_project.git", source_branch="fix-missing-tests", ) class TestChangeHookConfiguredWithSecret(unittest.TestCase, TestReactorMixin): _SECRET = 'thesecret' @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakeMasterForHooks(self) fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"secret_key": self._SECRET}) self.secretService = SecretManager() self.secretService.services = [fakeStorageService] self.master.addService(self.secretService) self.changeHook = change_hook.ChangeHookResource( dialects={'gitlab': {'secret': util.Secret("secret_key")}}, master=self.master ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_missing_secret(self): self.request = FakeRequest(content=gitJsonPayloadTag) self.request.uri = b"/change_hook/gitlab" self.request.args = {b'codebase': [b'MyCodebase']} self.request.method = b"POST" self.request.received_headers[_HEADER_EVENT] = b"Push Hook" yield self.request.test_render(self.changeHook) expected = b'Invalid secret' self.assertEqual(self.request.written, expected) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_valid_secret(self): self.request = FakeRequest(content=gitJsonPayload) self.request.received_headers[_HEADER_GITLAB_TOKEN] = self._SECRET self.request.received_headers[_HEADER_EVENT] = b"Push Hook" self.request.uri = b"/change_hook/gitlab" self.request.method = b"POST" yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2)
53,859
Python
.py
1,247
35.935846
123
0.639292
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,348
test_authz.py
buildbot_buildbot/master/buildbot/test/unit/www/test_authz.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.test import fakedb from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.www import authz from buildbot.www.authz.endpointmatchers import AnyControlEndpointMatcher from buildbot.www.authz.endpointmatchers import AnyEndpointMatcher from buildbot.www.authz.endpointmatchers import BranchEndpointMatcher from buildbot.www.authz.endpointmatchers import ForceBuildEndpointMatcher from buildbot.www.authz.endpointmatchers import RebuildBuildEndpointMatcher from buildbot.www.authz.endpointmatchers import StopBuildEndpointMatcher from buildbot.www.authz.endpointmatchers import ViewBuildsEndpointMatcher from buildbot.www.authz.roles import RolesFromDomain from buildbot.www.authz.roles import RolesFromEmails from buildbot.www.authz.roles import RolesFromGroups from buildbot.www.authz.roles import RolesFromOwner class Authz(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) authzcfg = authz.Authz( # simple matcher with '*' glob character stringsMatcher=authz.fnmatchStrMatcher, # stringsMatcher = authz.Authz.reStrMatcher, # if you prefer # regular expressions allowRules=[ # admins can do anything, # defaultDeny=False: if user does not have the admin role, we # continue parsing rules AnyEndpointMatcher(role="admins", defaultDeny=False), # rules for viewing builds, builders, step logs # depending on the sourcestamp or buildername ViewBuildsEndpointMatcher(branch="secretbranch", role="agents"), ViewBuildsEndpointMatcher(project="secretproject", role="agents"), ViewBuildsEndpointMatcher(branch="*", role="*"), ViewBuildsEndpointMatcher(project="*", role="*"), StopBuildEndpointMatcher(role="owner"), RebuildBuildEndpointMatcher(role="owner"), # nine-* groups can do stuff on the nine branch BranchEndpointMatcher(branch="nine", role="nine-*"), # eight-* groups can do stuff on the eight branch BranchEndpointMatcher(branch="eight", role="eight-*"), # *-try groups can start "try" builds ForceBuildEndpointMatcher(builder="try", role="*-developers"), # *-mergers groups can start "merge" builds ForceBuildEndpointMatcher(builder="merge", role="*-mergers"), # *-releasers groups can start "release" builds ForceBuildEndpointMatcher(builder="release", role="*-releasers"), # finally deny any control endpoint for non-admin users AnyControlEndpointMatcher(role="admins"), ], roleMatchers=[ RolesFromGroups(groupPrefix="buildbot-"), RolesFromEmails(admins=["[email protected]"], agents=["[email protected]"]), RolesFromOwner(role="owner"), RolesFromDomain(admins=["mi7.uk"]), ], ) self.users = { "homer": {"email": "[email protected]"}, "bond": {"email": "[email protected]"}, "moneypenny": {"email": "[email protected]"}, "nineuser": { "email": "[email protected]", "groups": ["buildbot-nine-mergers", "buildbot-nine-developers"], }, "eightuser": {"email": "[email protected]", "groups": ["buildbot-eight-deverlopers"]}, } self.master = yield self.make_master(url='h:/a/b/', authz=authzcfg) self.authz = self.master.authz yield self.master.db.insert_test_data([ fakedb.Builder(id=77, name="mybuilder"), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildsetProperty( buildsetid=8822, property_name='owner', property_value='["[email protected]", "force"]' ), fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Build( id=14, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=4 ), fakedb.Build( id=15, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=5 ), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def setAllowRules(self, allow_rules): # we should add links to authz and master instances in each new rule for r in allow_rules: r.setAuthz(self.authz) self.authz.allowRules = allow_rules def assertUserAllowed(self, ep, action, options, user): return self.authz.assertUserAllowed(tuple(ep.split("/")), action, options, self.users[user]) @defer.inlineCallbacks def assertUserForbidden(self, ep, action, options, user): try: yield self.authz.assertUserAllowed( tuple(ep.split("/")), action, options, self.users[user] ) except authz.Forbidden as err: self.assertIn('need to have role', repr(err)) else: self.fail('authz.Forbidden with error "need to have role" was expected!') @defer.inlineCallbacks def test_anyEndpoint(self): # admin users can do anything yield self.assertUserAllowed("foo/bar", "get", {}, "homer") yield self.assertUserAllowed("foo/bar", "stop", {}, "moneypenny") # non-admin user can only do "get" action yield self.assertUserAllowed("foo/bar", "get", {}, "bond") # non-admin user cannot do control actions yield self.assertUserForbidden("foo/bar", "stop", {}, "bond") # non-admin user cannot do any actions allow_rules = [ AnyEndpointMatcher(role="admins"), ] self.setAllowRules(allow_rules) yield self.assertUserForbidden("foo/bar", "get", {}, "bond") yield self.assertUserForbidden("foo/bar", "stop", {}, "bond") @defer.inlineCallbacks def test_stopBuild(self): # admin can always stop yield self.assertUserAllowed("builds/13", "stop", {}, "homer") # owner can always stop yield self.assertUserAllowed("builds/13", "stop", {}, "nineuser") yield self.assertUserAllowed("buildrequests/82", "stop", {}, "nineuser") # not owner cannot stop yield self.assertUserForbidden("builds/13", "stop", {}, "eightuser") yield self.assertUserForbidden("buildrequests/82", "stop", {}, "eightuser") # can stop build/buildrequest with matching builder allow_rules = [ StopBuildEndpointMatcher(role="eight-*", builder="mybuilder"), AnyEndpointMatcher(role="admins"), ] self.setAllowRules(allow_rules) yield self.assertUserAllowed("builds/13", "stop", {}, "eightuser") yield self.assertUserAllowed("buildrequests/82", "stop", {}, "eightuser") yield self.assertUserForbidden("builds/999", "stop", {}, "eightuser") yield self.assertUserForbidden("buildrequests/999", "stop", {}, "eightuser") # cannot stop build/buildrequest with non-matching builder allow_rules = [ StopBuildEndpointMatcher(role="eight-*", builder="foo"), AnyEndpointMatcher(role="admins"), ] self.setAllowRules(allow_rules) yield self.assertUserForbidden("builds/13", "stop", {}, "eightuser") yield self.assertUserForbidden("buildrequests/82", "stop", {}, "eightuser") @defer.inlineCallbacks def test_rebuildBuild(self): # admin can rebuild yield self.assertUserAllowed("builds/13", "rebuild", {}, "homer") # owner can always rebuild yield self.assertUserAllowed("builds/13", "rebuild", {}, "nineuser") # not owner cannot rebuild yield self.assertUserForbidden("builds/13", "rebuild", {}, "eightuser") # can rebuild build with matching builder allow_rules = [ RebuildBuildEndpointMatcher(role="eight-*", builder="mybuilder"), AnyEndpointMatcher(role="admins"), ] self.setAllowRules(allow_rules) yield self.assertUserAllowed("builds/13", "rebuild", {}, "eightuser") yield self.assertUserForbidden("builds/999", "rebuild", {}, "eightuser") # cannot rebuild build with non-matching builder allow_rules = [ RebuildBuildEndpointMatcher(role="eight-*", builder="foo"), AnyEndpointMatcher(role="admins"), ] self.setAllowRules(allow_rules) yield self.assertUserForbidden("builds/13", "rebuild", {}, "eightuser") @defer.inlineCallbacks def test_fnmatchPatternRoleCheck(self): # defaultDeny is True by default so action is denied if no match allow_rules = [AnyEndpointMatcher(role="[a,b]dmin?")] self.setAllowRules(allow_rules) yield self.assertUserAllowed("builds/13", "rebuild", {}, "homer") # check if action is denied with self.assertRaisesRegex(authz.Forbidden, '403 you need to have role .+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "nineuser") with self.assertRaisesRegex(authz.Forbidden, '403 you need to have role .+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "eightuser") @defer.inlineCallbacks def test_regexPatternRoleCheck(self): # change matcher self.authz.match = authz.reStrMatcher # defaultDeny is True by default so action is denied if no match allow_rules = [ AnyEndpointMatcher(role="(admin|agent)s"), ] self.setAllowRules(allow_rules) yield self.assertUserAllowed("builds/13", "rebuild", {}, "homer") yield self.assertUserAllowed("builds/13", "rebuild", {}, "bond") # check if action is denied with self.assertRaisesRegex(authz.Forbidden, '403 you need to have role .+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "nineuser") with self.assertRaisesRegex(authz.Forbidden, '403 you need to have role .+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "eightuser") @defer.inlineCallbacks def test_DefaultDenyFalseContinuesCheck(self): # defaultDeny is True in the last rule so action is denied in the last check allow_rules = [ AnyEndpointMatcher(role="not-exists1", defaultDeny=False), AnyEndpointMatcher(role="not-exists2", defaultDeny=False), AnyEndpointMatcher(role="not-exists3", defaultDeny=True), ] self.setAllowRules(allow_rules) # check if action is denied and last check was exact against not-exist3 with self.assertRaisesRegex(authz.Forbidden, '.+not-exists3.+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "nineuser") @defer.inlineCallbacks def test_DefaultDenyTrueStopsCheckIfFailed(self): # defaultDeny is True in the first rule so action is denied in the first check allow_rules = [ AnyEndpointMatcher(role="not-exists1", defaultDeny=True), AnyEndpointMatcher(role="not-exists2", defaultDeny=False), AnyEndpointMatcher(role="not-exists3", defaultDeny=False), ] self.setAllowRules(allow_rules) # check if action is denied and last check was exact against not-exist1 with self.assertRaisesRegex(authz.Forbidden, '.+not-exists1.+'): yield self.assertUserAllowed("builds/13", "rebuild", {}, "nineuser")
12,725
Python
.py
242
42.818182
100
0.652851
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,349
test_sse.py
buildbot_buildbot/master/buildbot/test/unit/www/test_sse.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 datetime import json from twisted.internet import defer from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.test.unit.data import test_changes from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.util import datetime2epoch from buildbot.util import unicode2bytes from buildbot.www import sse class EventResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = master = yield self.make_master(url=b'h:/a/b/') self.sse = sse.EventResource(master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_simpleapi(self): self.render_resource(self.sse, b'/changes/*/*') self.readUUID(self.request) self.assertReceivesChangeNewMessage(self.request) self.assertEqual(self.request.finished, False) def test_listen(self): self.render_resource(self.sse, b'/listen/changes/*/*') self.readUUID(self.request) self.assertReceivesChangeNewMessage(self.request) self.assertEqual(self.request.finished, False) def test_listen_add_then_close(self): self.render_resource(self.sse, b'/listen') request = self.request self.request = None uuid = self.readUUID(request) self.render_resource(self.sse, b'/add/' + unicode2bytes(uuid) + b"/changes/*/*") self.assertReceivesChangeNewMessage(request) self.assertEqual(self.request.finished, True) self.assertEqual(request.finished, False) request.finish() # fake close connection on client side with self.assertRaises(AssertionError): self.assertReceivesChangeNewMessage(request) def test_listen_add_then_remove(self): self.render_resource(self.sse, b'/listen') request = self.request uuid = self.readUUID(request) self.render_resource(self.sse, b'/add/' + unicode2bytes(uuid) + b"/changes/*/*") self.assertReceivesChangeNewMessage(request) self.assertEqual(request.finished, False) self.render_resource(self.sse, b'/remove/' + unicode2bytes(uuid) + b"/changes/*/*") with self.assertRaises(AssertionError): self.assertReceivesChangeNewMessage(request) def test_listen_add_nouuid(self): self.render_resource(self.sse, b'/listen') request = self.request self.readUUID(request) self.render_resource(self.sse, b'/add/') self.assertEqual(self.request.finished, True) self.assertEqual(self.request.responseCode, 400) self.assertIn(b"need uuid", self.request.written) def test_listen_add_baduuid(self): self.render_resource(self.sse, b'/listen') request = self.request self.readUUID(request) self.render_resource(self.sse, b'/add/foo') self.assertEqual(self.request.finished, True) self.assertEqual(self.request.responseCode, 400) self.assertIn(b"unknown uuid", self.request.written) def readEvent(self, request): kw = {} hasEmptyLine = False for line in request.written.splitlines(): if line.find(b":") > 0: k, v = line.split(b": ", 1) self.assertTrue(k not in kw, k + b" in " + unicode2bytes(str(kw))) kw[k] = v else: self.assertEqual(line, b"") hasEmptyLine = True request.written = b"" self.assertTrue(hasEmptyLine) return kw def readUUID(self, request): kw = self.readEvent(request) self.assertEqual(kw[b"event"], b"handshake") return kw[b"data"] def assertReceivesChangeNewMessage(self, request): self.master.mq.callConsumer(("changes", "500", "new"), test_changes.Change.changeEvent) kw = self.readEvent(request) self.assertEqual(kw[b"event"], b"event") msg = json.loads(bytes2unicode(kw[b"data"])) self.assertEqual(msg["key"], ['changes', '500', 'new']) self.assertEqual( msg["message"], json.loads(json.dumps(test_changes.Change.changeEvent, default=self._toJson)), ) def _toJson(self, obj): if isinstance(obj, datetime.datetime): return datetime2epoch(obj) return None
5,165
Python
.py
114
37.877193
95
0.684545
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,350
test_oauth.py
buildbot_buildbot/master/buildbot/test/unit/www/test_oauth.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 import os import webbrowser from unittest import mock import twisted from twisted.internet import defer from twisted.internet import reactor from twisted.internet import threads from twisted.python import failure from twisted.trial import unittest from twisted.web.resource import Resource import buildbot from buildbot.process.properties import Secret from buildbot.secrets.manager import SecretManager from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.test.util.config import ConfigErrorsMixin from buildbot.test.util.site import SiteWithClose from buildbot.util import bytes2unicode try: import requests except ImportError: requests = None # type: ignore[assignment] if requests: from buildbot.www import oauth2 # pylint: disable=ungrouped-imports else: oauth2 = None # type: ignore[assignment] class FakeResponse: def __init__(self, _json): self.json = lambda: _json self.content = json.dumps(_json) def raise_for_status(self): pass class OAuth2Auth(TestReactorMixin, www.WwwTestMixin, ConfigErrorsMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) if requests is None: raise unittest.SkipTest("Need to install requests to test oauth2") self.patch(requests, 'request', mock.Mock(spec=requests.request)) self.patch(requests, 'post', mock.Mock(spec=requests.post)) self.patch(requests, 'get', mock.Mock(spec=requests.get)) self.googleAuth = oauth2.GoogleAuth("ggclientID", "clientSECRET") self.githubAuth = oauth2.GitHubAuth("ghclientID", "clientSECRET") self.githubAuth_v4 = oauth2.GitHubAuth("ghclientID", "clientSECRET", apiVersion=4) self.githubAuth_v4_teams = oauth2.GitHubAuth( "ghclientID", "clientSECRET", apiVersion=4, getTeamsMembership=True ) self.githubAuthEnt = oauth2.GitHubAuth( "ghclientID", "clientSECRET", serverURL="https://git.corp.fakecorp.com" ) self.githubAuthEnt_v4 = oauth2.GitHubAuth( "ghclientID", "clientSECRET", apiVersion=4, getTeamsMembership=True, serverURL="https://git.corp.fakecorp.com", ) self.gitlabAuth = oauth2.GitLabAuth("https://gitlab.test/", "glclientID", "clientSECRET") self.bitbucketAuth = oauth2.BitbucketAuth("bbclientID", "clientSECRET") for auth in [ self.googleAuth, self.githubAuth, self.githubAuth_v4, self.githubAuth_v4_teams, self.githubAuthEnt, self.gitlabAuth, self.bitbucketAuth, self.githubAuthEnt_v4, ]: self._master = master = yield self.make_master(url='h:/a/b/', auth=auth) auth.reconfigAuth(master, master.config) self.githubAuth_secret = oauth2.GitHubAuth( Secret("client-id"), Secret("client-secret"), apiVersion=4 ) self._master = master = yield self.make_master(url='h:/a/b/', auth=auth) fake_storage_service = FakeSecretStorage() fake_storage_service.reconfigService( secretdict={"client-id": "secretClientId", "client-secret": "secretClientSecret"} ) secret_service = SecretManager() secret_service.services = [fake_storage_service] yield secret_service.setServiceParent(self._master) self.githubAuth_secret.reconfigAuth(master, master.config) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_getGoogleLoginURL(self): res = yield self.googleAuth.getLoginURL('http://redir') exp = ( "https://accounts.google.com/o/oauth2/auth?client_id=ggclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+" "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.googleAuth.getLoginURL(None) exp = ( "https://accounts.google.com/o/oauth2/auth?client_id=ggclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+" "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getGithubLoginURL(self): res = yield self.githubAuth.getLoginURL('http://redir') exp = ( "https://github.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.githubAuth.getLoginURL(None) exp = ( "https://github.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getGithubLoginURL_with_secret(self): res = yield self.githubAuth_secret.getLoginURL('http://redir') exp = ( "https://github.com/login/oauth/authorize?client_id=secretClientId&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.githubAuth_secret.getLoginURL(None) exp = ( "https://github.com/login/oauth/authorize?client_id=secretClientId&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getGithubELoginURL(self): res = yield self.githubAuthEnt.getLoginURL('http://redir') exp = ( "https://git.corp.fakecorp.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.githubAuthEnt.getLoginURL(None) exp = ( "https://git.corp.fakecorp.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getGithubLoginURL_v4(self): res = yield self.githubAuthEnt_v4.getLoginURL('http://redir') exp = ( "https://git.corp.fakecorp.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.githubAuthEnt_v4.getLoginURL(None) exp = ( "https://git.corp.fakecorp.com/login/oauth/authorize?client_id=ghclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&response_type=code&" "scope=user%3Aemail+read%3Aorg" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getGitLabLoginURL(self): res = yield self.gitlabAuth.getLoginURL('http://redir') exp = ( "https://gitlab.test/oauth/authorize" "?client_id=glclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&" "response_type=code&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.gitlabAuth.getLoginURL(None) exp = ( "https://gitlab.test/oauth/authorize" "?client_id=glclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&" "response_type=code" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_getBitbucketLoginURL(self): res = yield self.bitbucketAuth.getLoginURL('http://redir') exp = ( "https://bitbucket.org/site/oauth2/authorize?" "client_id=bbclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&" "response_type=code&" "state=redirect%3Dhttp%253A%252F%252Fredir" ) self.assertEqual(res, exp) res = yield self.bitbucketAuth.getLoginURL(None) exp = ( "https://bitbucket.org/site/oauth2/authorize?" "client_id=bbclientID&" "redirect_uri=h%3A%2Fa%2Fb%2Fauth%2Flogin&" "response_type=code" ) self.assertEqual(res, exp) @defer.inlineCallbacks def test_GoogleVerifyCode(self): requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] self.googleAuth.get = mock.Mock( side_effect=[{"name": 'foo bar', "email": 'bar@foo', "picture": 'http://pic'}] ) res = yield self.googleAuth.verifyCode("code!") self.assertEqual( { 'avatar_url': 'http://pic', 'email': 'bar@foo', 'full_name': 'foo bar', 'username': 'bar', }, res, ) @defer.inlineCallbacks def test_GithubVerifyCode(self): test = self requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] def fake_get(self, ep, **kwargs): test.assertEqual( self.headers, { 'Authorization': 'token TOK3N', 'User-Agent': f'buildbot/{buildbot.version}', }, ) if ep == '/user': return {"login": 'bar', "name": 'foo bar', "email": 'buzz@bar'} if ep == '/user/emails': return [ {'email': 'buzz@bar', 'verified': True, 'primary': False}, {'email': 'bar@foo', 'verified': True, 'primary': True}, ] if ep == '/user/orgs': return [ {"login": 'hello'}, {"login": 'grp'}, ] return None self.githubAuth.get = fake_get res = yield self.githubAuth.verifyCode("code!") self.assertEqual( { 'email': 'bar@foo', 'username': 'bar', 'groups': ["hello", "grp"], 'full_name': 'foo bar', }, res, ) @defer.inlineCallbacks def test_GithubVerifyCode_v4(self): requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] self.githubAuth_v4.post = mock.Mock( side_effect=[ { 'data': { 'viewer': { 'organizations': { 'edges': [{'node': {'login': 'hello'}}, {'node': {'login': 'grp'}}] }, 'login': 'bar', 'email': 'bar@foo', 'name': 'foo bar', } } } ] ) res = yield self.githubAuth_v4.verifyCode("code!") self.assertEqual( { 'email': 'bar@foo', 'username': 'bar', 'groups': ["hello", "grp"], 'full_name': 'foo bar', }, res, ) @defer.inlineCallbacks def test_GithubVerifyCode_v4_teams(self): requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] self.githubAuth_v4_teams.post = mock.Mock( side_effect=[ { 'data': { 'viewer': { 'organizations': { 'edges': [{'node': {'login': 'hello'}}, {'node': {'login': 'grp'}}] }, 'login': 'bar', 'email': 'bar@foo', 'name': 'foo bar', } } }, { 'data': { 'hello': { 'teams': { 'edges': [ {'node': {'name': 'developers', 'slug': 'develpers'}}, {'node': {'name': 'contributors', 'slug': 'contributors'}}, ] } }, 'grp': { 'teams': { 'edges': [ {'node': {'name': 'developers', 'slug': 'develpers'}}, {'node': {'name': 'contributors', 'slug': 'contributors'}}, {'node': {'name': 'committers', 'slug': 'committers'}}, { 'node': { 'name': 'Team with spaces and caps', 'slug': 'team-with-spaces-and-caps', } }, ] } }, } }, ] ) res = yield self.githubAuth_v4_teams.verifyCode("code!") self.assertEqual( { 'email': 'bar@foo', 'username': 'bar', 'groups': [ 'hello', 'grp', 'grp/Team with spaces and caps', 'grp/committers', 'grp/contributors', 'grp/developers', 'grp/develpers', 'grp/team-with-spaces-and-caps', 'hello/contributors', 'hello/developers', 'hello/develpers', ], 'full_name': 'foo bar', }, res, ) def test_GitHubAuthBadApiVersion(self): for bad_api_version in (2, 5, 'a'): with self.assertRaisesConfigError('GitHubAuth apiVersion must be 3 or 4 not '): oauth2.GitHubAuth("ghclientID", "clientSECRET", apiVersion=bad_api_version) def test_GitHubAuthRaiseErrorWithApiV3AndGetTeamMembership(self): with self.assertRaisesConfigError( 'Retrieving team membership information using ' 'GitHubAuth is only possible using GitHub api v4.' ): oauth2.GitHubAuth("ghclientID", "clientSECRET", apiVersion=3, getTeamsMembership=True) @defer.inlineCallbacks def test_GitlabVerifyCode(self): requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] self.gitlabAuth.get = mock.Mock( side_effect=[ { # /user "name": "Foo Bar", "username": "fbar", "id": 5, "avatar_url": "https://avatar/fbar.png", "email": "foo@bar", "twitter": "fb", }, [ # /groups {"id": 10, "name": "Hello", "path": "hello"}, {"id": 20, "name": "Group", "path": "grp"}, ], ] ) res = yield self.gitlabAuth.verifyCode("code!") self.assertEqual( { "full_name": "Foo Bar", "username": "fbar", "email": "foo@bar", "avatar_url": "https://avatar/fbar.png", "groups": ["hello", "grp"], }, res, ) @defer.inlineCallbacks def test_BitbucketVerifyCode(self): requests.get.side_effect = [] requests.post.side_effect = [FakeResponse({"access_token": 'TOK3N'})] self.bitbucketAuth.get = mock.Mock( side_effect=[ {"username": 'bar', "display_name": 'foo bar'}, # /user { "values": [ {'email': 'buzz@bar', 'is_primary': False}, {'email': 'bar@foo', 'is_primary': True}, ] }, # /user/emails {"values": [{'slug': 'hello'}, {'slug': 'grp'}]}, # /workspaces?role=member ] ) res = yield self.bitbucketAuth.verifyCode("code!") self.assertEqual( { 'email': 'bar@foo', 'username': 'bar', "groups": ["hello", "grp"], 'full_name': 'foo bar', }, res, ) @defer.inlineCallbacks def test_loginResource(self): class fakeAuth: homeUri = "://me" getLoginURL = mock.Mock(side_effect=lambda x: defer.succeed("://")) verifyCode = mock.Mock(side_effect=lambda code: defer.succeed({"username": "bar"})) acceptToken = mock.Mock(side_effect=lambda token: defer.succeed({"username": "bar"})) userInfoProvider = None rsrc = self.githubAuth.getLoginResource() rsrc.auth = fakeAuth() res = yield self.render_resource(rsrc, b'/') rsrc.auth.getLoginURL.assert_called_once_with(None) rsrc.auth.verifyCode.assert_not_called() self.assertEqual(res, {'redirected': b'://'}) rsrc.auth.getLoginURL.reset_mock() rsrc.auth.verifyCode.reset_mock() res = yield self.render_resource(rsrc, b'/?code=code!') rsrc.auth.getLoginURL.assert_not_called() rsrc.auth.verifyCode.assert_called_once_with(b"code!") self.assertEqual(self.master.session.user_info, {'username': 'bar'}) self.assertEqual(res, {'redirected': b'://me'}) # token not supported anymore res = yield self.render_resource(rsrc, b'/?token=token!') rsrc.auth.getLoginURL.assert_called_once() def test_getConfig(self): self.assertEqual( self.githubAuth.getConfigDict(), {'fa_icon': 'fa-github', 'autologin': False, 'name': 'GitHub', 'oauth2': True}, ) self.assertEqual( self.googleAuth.getConfigDict(), {'fa_icon': 'fa-google-plus', 'autologin': False, 'name': 'Google', 'oauth2': True}, ) self.assertEqual( self.gitlabAuth.getConfigDict(), {'fa_icon': 'fa-git', 'autologin': False, 'name': 'GitLab', 'oauth2': True}, ) self.assertEqual( self.bitbucketAuth.getConfigDict(), {'fa_icon': 'fa-bitbucket', 'autologin': False, 'name': 'Bitbucket', 'oauth2': True}, ) # unit tests are not very useful to write new oauth support # so following is an e2e test, which opens a browser, and do the oauth # negotiation. The browser window close in the end of the test # in order to use this tests, you need to create Github/Google ClientID (see doc on how to do it) # point OAUTHCONF environment variable to a file with following params: # { # "GitHubAuth": { # "CLIENTID": "XX # "CLIENTSECRET": "XX" # }, # "GoogleAuth": { # "CLIENTID": "XX", # "CLIENTSECRET": "XX" # } # "GitLabAuth": { # "INSTANCEURI": "XX", # "CLIENTID": "XX", # "CLIENTSECRET": "XX" # } # } class OAuth2AuthGitHubE2E(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): authClass = "GitHubAuth" def _instantiateAuth(self, cls, config): return cls(config["CLIENTID"], config["CLIENTSECRET"]) @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) if requests is None: raise unittest.SkipTest("Need to install requests to test oauth2") if "OAUTHCONF" not in os.environ: raise unittest.SkipTest( "Need to pass OAUTHCONF path to json file via environ to run this e2e test" ) with open(os.environ['OAUTHCONF'], encoding='utf-8') as f: jsonData = f.read() config = json.loads(jsonData)[self.authClass] from buildbot.www import oauth2 self.auth = self._instantiateAuth(getattr(oauth2, self.authClass), config) # 5000 has to be hardcoded, has oauth clientids are bound to a fully # classified web site master = yield self.make_master(url='http://localhost:5000/', auth=self.auth) self.auth.reconfigAuth(master, master.config) def tearDown(self): from twisted.internet.tcp import Server # browsers has the bad habit on not closing the persistent # connections, so we need to hack them away to make trial happy f = failure.Failure(Exception("test end")) for reader in reactor.getReaders(): if isinstance(reader, Server): reader.connectionLost(f) yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_E2E(self): d = defer.Deferred() twisted.web.http._logDateTimeUsers = 1 class HomePage(Resource): isLeaf = True def render_GET(self, request): info = request.getSession().user_info reactor.callLater(0, d.callback, info) return ( b"<html><script>setTimeout(close,1000)</script><body>WORKED: " + info + b"</body></html>" ) class MySite(SiteWithClose): def makeSession(self): uid = self._mkuid() session = self.sessions[uid] = self.sessionFactory(self, uid) return session root = Resource() root.putChild(b"", HomePage()) auth = Resource() root.putChild(b'auth', auth) auth.putChild(b'login', self.auth.getLoginResource()) site = MySite(root) listener = reactor.listenTCP(5000, site) def thd(): res = requests.get('http://localhost:5000/auth/login', timeout=30) content = bytes2unicode(res.content) webbrowser.open(content) threads.deferToThread(thd) res = yield d yield listener.stopListening() yield site.stopFactory() yield site.close_connections() self.assertIn("full_name", res) self.assertIn("email", res) self.assertIn("username", res) class OAuth2AuthGoogleE2E(OAuth2AuthGitHubE2E): authClass = "GoogleAuth" class OAuth2AuthGitLabE2E(OAuth2AuthGitHubE2E): authClass = "GitLabAuth" def _instantiateAuth(self, cls, config): return cls(config["INSTANCEURI"], config["CLIENTID"], config["CLIENTSECRET"])
24,467
Python
.py
583
30.02916
99
0.556195
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,351
test_ws.py
buildbot_buildbot/master/buildbot/test/unit/www/test_ws.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 import re from unittest.case import SkipTest from unittest.mock import Mock from twisted.internet import defer from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.www import ws class WsResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(use_asyncio=True) self.master = master = yield self.make_master(url="h:/a/b/", wantMq=True, wantGraphql=True) self.skip_graphql = False if not self.master.graphql.enabled: self.skip_graphql = True self.ws = ws.WsResource(master) self.proto = self.ws._factory.buildProtocol("me") self.proto.sendMessage = Mock(spec=self.proto.sendMessage) def assert_called_with_json(self, obj, expected_json): jsonArg = obj.call_args[0][0] jsonArg = bytes2unicode(jsonArg) actual_json = json.loads(jsonArg) keys_to_pop = [] for key in expected_json: if hasattr(expected_json[key], 'match'): keys_to_pop.append(key) regex = expected_json[key] value = actual_json[key] self.assertRegex(value, regex) for key in keys_to_pop: expected_json.pop(key) actual_json.pop(key) self.assertEqual(actual_json, expected_json) def do_onConnect(self, protocols): self.proto.is_graphql = None class FakeRequest: pass r = FakeRequest() r.protocols = protocols return self.proto.onConnect(r) def test_onConnect(self): self.assertEqual(self.do_onConnect([]), None) self.assertEqual(self.do_onConnect(["foo", "graphql-websocket"]), None) self.assertEqual(self.proto.is_graphql, None) # undecided yet self.assertEqual(self.do_onConnect(["graphql-ws"]), "graphql-ws") self.assertEqual(self.proto.is_graphql, True) self.assertEqual(self.do_onConnect(["foo", "graphql-ws"]), "graphql-ws") self.assertEqual(self.proto.is_graphql, True) def test_ping(self): self.proto.onMessage(json.dumps({"cmd": 'ping', "_id": 1}), False) self.assert_called_with_json(self.proto.sendMessage, {"msg": "pong", "code": 200, "_id": 1}) def test_bad_cmd(self): self.proto.onMessage(json.dumps({"cmd": 'poing', "_id": 1}), False) self.assert_called_with_json( self.proto.sendMessage, {"_id": 1, "code": 404, "error": "no such command type 'poing'"}, ) def test_no_cmd(self): self.proto.onMessage(json.dumps({"_id": 1}), False) self.assert_called_with_json( self.proto.sendMessage, {"_id": None, "code": 400, "error": "no 'cmd' in websocket frame"}, ) def test_too_many_arguments(self): self.proto.onMessage(json.dumps({"_id": 1, "cmd": 'ping', "foo": 'bar'}), False) self.assert_called_with_json( self.proto.sendMessage, { "_id": 1, "code": 400, "error": re.compile(".*Invalid method argument.*"), }, ) def test_too_many_arguments_graphql(self): self.proto.is_graphql = True self.proto.onMessage(json.dumps({"id": 1, "type": 'connection_init', "foo": 'bar'}), False) self.assert_called_with_json( self.proto.sendMessage, { "id": None, "message": re.compile('.*Invalid method argument.*'), "type": "error", }, ) def test_no_type_while_graphql(self): self.proto.is_graphql = True self.proto.onMessage(json.dumps({"_id": 1, "cmd": 'ping'}), False) self.assert_called_with_json( self.proto.sendMessage, { "id": None, "message": "missing 'type' in websocket frame when already started using " "graphql", "type": "error", }, ) def test_type_while_not_graphql(self): self.proto.is_graphql = False self.proto.onMessage(json.dumps({"_id": 1, "type": 'ping'}), False) self.assert_called_with_json( self.proto.sendMessage, { "_id": None, "error": "using 'type' in websocket frame when " "already started using buildbot protocol", "code": 400, }, ) def test_no_id(self): self.proto.onMessage(json.dumps({"cmd": 'ping'}), False) self.assert_called_with_json( self.proto.sendMessage, { "_id": None, "code": 400, "error": "no '_id' or 'type' in websocket frame", }, ) def test_startConsuming(self): self.proto.onMessage( json.dumps({"cmd": 'startConsuming', "path": 'builds/*/*', "_id": 1}), False ) self.assert_called_with_json(self.proto.sendMessage, {"msg": "OK", "code": 200, "_id": 1}) self.master.mq.verifyMessages = False self.master.mq.callConsumer(("builds", "1", "new"), {"buildid": 1}) self.assert_called_with_json( self.proto.sendMessage, {"k": "builds/1/new", "m": {"buildid": 1}} ) def test_startConsumingBadPath(self): self.proto.onMessage(json.dumps({"cmd": 'startConsuming', "path": {}, "_id": 1}), False) self.assert_called_with_json( self.proto.sendMessage, {"_id": 1, "code": 400, "error": "invalid path format '{}'"}, ) def test_stopConsumingNotRegistered(self): self.proto.onMessage( json.dumps({"cmd": 'stopConsuming', "path": 'builds/*/*', "_id": 1}), False ) self.assert_called_with_json( self.proto.sendMessage, {"_id": 1, "code": 400, "error": "path was not consumed 'builds/*/*'"}, ) def test_stopConsuming(self): self.proto.onMessage( json.dumps({"cmd": 'startConsuming', "path": 'builds/*/*', "_id": 1}), False ) self.assert_called_with_json(self.proto.sendMessage, {"msg": "OK", "code": 200, "_id": 1}) self.proto.onMessage( json.dumps({"cmd": 'stopConsuming', "path": 'builds/*/*', "_id": 2}), False ) self.assert_called_with_json(self.proto.sendMessage, {"msg": "OK", "code": 200, "_id": 2}) # graphql def test_connection_init(self): self.proto.onMessage(json.dumps({"type": 'connection_init'}), False) self.assert_called_with_json(self.proto.sendMessage, {"type": "connection_ack"}) @defer.inlineCallbacks def test_start_stop_graphql(self): if self.skip_graphql: raise SkipTest("graphql-core not installed") yield self.proto.onMessage( json.dumps({"type": "start", "payload": {"query": "{builders{name}}"}, "id": 1}), False, ) self.assertEqual(len(self.proto.graphql_subs), 1) self.assert_called_with_json( self.proto.sendMessage, { "payload": { "data": {"builders": []}, "errors": None, }, "type": "data", "id": 1, }, ) self.proto.sendMessage.reset_mock() yield self.proto.graphql_dispatch_events.function() self.proto.sendMessage.assert_not_called() # auto create a builder in the db yield self.master.db.builders.findBuilderId("builder1") self.master.mq.callConsumer( ("builders", "1", "started"), {"name": "builder1", "masterid": 1, "builderid": 1}, ) self.assertNotEqual(self.proto.graphql_dispatch_events.phase, 0) # then force the call anyway to speed up the test yield self.proto.graphql_dispatch_events.function() self.assert_called_with_json( self.proto.sendMessage, { "payload": { "data": {"builders": [{"name": "builder1"}]}, "errors": None, }, "type": "data", "id": 1, }, ) yield self.proto.onMessage(json.dumps({"type": 'stop', "id": 1}), False) self.assertEqual(len(self.proto.graphql_subs), 0) @defer.inlineCallbacks def test_start_graphql_bad_query(self): if self.skip_graphql: raise SkipTest("graphql-core not installed") yield self.proto.onMessage( json.dumps({ "type": "start", "payload": {"query": "{builders{not_existing}}"}, "id": 1, }), False, ) self.assert_called_with_json( self.proto.sendMessage, { "payload": { "data": None, "errors": [ { "locations": [{"column": 11, "line": 1}], "message": "Cannot query field 'not_existing' on type 'Builder'.", } ], }, "id": 1, "type": "data", }, ) self.assertEqual(len(self.proto.graphql_subs), 0)
10,228
Python
.py
246
31.004065
100
0.562054
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,352
test_hooks_bitbucketserver.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_bitbucketserver.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 # Copyright Mamba Team from io import BytesIO from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.util import unicode2bytes from buildbot.www import change_hook from buildbot.www.hooks.bitbucketserver import _HEADER_EVENT _CT_JSON = b'application/json' bitbucketPRproperties = { 'pullrequesturl': 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21', 'bitbucket.id': '21', 'bitbucket.link': 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21', 'bitbucket.title': 'dot 1496311906', 'bitbucket.authorLogin': 'Buildbot', 'bitbucket.fromRef.branch.name': 'branch_1496411680', 'bitbucket.fromRef.branch.rawNode': 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba', 'bitbucket.fromRef.commit.authorTimestamp': 0, 'bitbucket.fromRef.commit.date': None, 'bitbucket.fromRef.commit.hash': 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba', 'bitbucket.fromRef.commit.message': None, 'bitbucket.fromRef.repository.fullName': 'CI/py-repo', 'bitbucket.fromRef.repository.links.self': [ {'href': 'http://localhost:7990/projects/CI/repos/py-repo/browse'} ], 'bitbucket.fromRef.repository.owner.displayName': 'CI', 'bitbucket.fromRef.repository.owner.username': 'CI', 'bitbucket.fromRef.repository.ownerName': 'CI', 'bitbucket.fromRef.repository.project.key': 'CI', 'bitbucket.fromRef.repository.project.name': 'Continuous Integration', 'bitbucket.fromRef.repository.public': False, 'bitbucket.fromRef.repository.scmId': 'git', 'bitbucket.fromRef.repository.slug': 'py-repo', 'bitbucket.toRef.branch.name': 'master', 'bitbucket.toRef.branch.rawNode': '7aebbb0089c40fce138a6d0b36d2281ea34f37f5', 'bitbucket.toRef.commit.authorTimestamp': 0, 'bitbucket.toRef.commit.date': None, 'bitbucket.toRef.commit.hash': '7aebbb0089c40fce138a6d0b36d2281ea34f37f5', 'bitbucket.toRef.commit.message': None, 'bitbucket.toRef.repository.fullName': 'CI/py-repo', 'bitbucket.toRef.repository.links.self': [ {'href': 'http://localhost:7990/projects/CI/repos/py-repo/browse'} ], 'bitbucket.toRef.repository.owner.displayName': 'CI', 'bitbucket.toRef.repository.owner.username': 'CI', 'bitbucket.toRef.repository.ownerName': 'CI', 'bitbucket.toRef.repository.project.key': 'CI', 'bitbucket.toRef.repository.project.name': 'Continuous Integration', 'bitbucket.toRef.repository.public': False, 'bitbucket.toRef.repository.scmId': 'git', 'bitbucket.toRef.repository.slug': 'py-repo', } pushJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": false, "new": { "type": "branch", "name": "branch_1496411680", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "old": { "type": "branch", "name": "branch_1496411680", "target": { "type": "commit", "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba" } } } ] } } """ pullRequestCreatedJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestUpdatedJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestRejectedJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" } } """ pullRequestFulfilledJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "pullrequest": { "id": "21", "title": "dot 1496311906", "link": "http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21", "authorLogin": "Buildbot", "fromRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "authorTimestamp": 0 }, "branch": { "rawNode": "a87e21f7433d8c16ac7be7413483fbb76c72a8ba", "name": "branch_1496411680" } }, "toRef": { "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "commit": { "message": null, "date": null, "hash": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "authorTimestamp": 0 }, "branch": { "rawNode": "7aebbb0089c40fce138a6d0b36d2281ea34f37f5", "name": "master" } } }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" } } """ deleteTagJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "ownerName": "BUIL", "public": false, "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": true, "old": { "type": "tag", "name": "1.0.0", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "new": null } ] } } """ deleteBranchJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "ownerName": "CI", "public": false, "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": false, "closed": true, "old": { "type": "branch", "name": "branch_1496758965", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } }, "new": null } ] } } """ newTagJsonPayload = """ { "actor": { "username": "John", "displayName": "John Smith" }, "repository": { "scmId": "git", "project": { "key": "CI", "name": "Continuous Integration" }, "slug": "py-repo", "links": { "self": [ { "href": "http://localhost:7990/projects/CI/repos/py-repo/browse" } ] }, "public": false, "ownerName": "CI", "owner": { "username": "CI", "displayName": "CI" }, "fullName": "CI/py-repo" }, "push": { "changes": [ { "created": true, "closed": false, "old": null, "new": { "type": "tag", "name": "1.0.0", "target": { "type": "commit", "hash": "793d4754230023d85532f9a38dba3290f959beb4" } } } ] } } """ def _prepare_request(payload, headers=None, change_dict=None): headers = headers or {} request = FakeRequest(change_dict) request.uri = b"/change_hook/bitbucketserver" request.method = b"POST" if isinstance(payload, str): payload = unicode2bytes(payload) request.content = BytesIO(payload) request.received_headers[b'Content-Type'] = _CT_JSON request.received_headers.update(headers) return request class TestChangeHookConfiguredWithGitChange(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield fakeMasterForHooks(self) self.change_hook = change_hook.ChangeHookResource( dialects={ 'bitbucketserver': { 'bitbucket_property_whitelist': ["bitbucket.*"], } }, master=master, ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertDictSubset(self, expected_dict, response_dict): expected = {} for key in expected_dict.keys(): self.assertIn(key, set(response_dict.keys())) expected[key] = response_dict[key] self.assertDictEqual(expected_dict, expected) def _checkPush(self, change): self.assertEqual(change['repository'], 'http://localhost:7990/projects/CI/repos/py-repo/') self.assertEqual(change['author'], 'John Smith <John>') self.assertEqual(change['project'], 'Continuous Integration') self.assertEqual(change['revision'], '793d4754230023d85532f9a38dba3290f959beb4') self.assertEqual( change['comments'], 'Bitbucket Server commit 793d4754230023d85532f9a38dba3290f959beb4', ) self.assertEqual( change['revlink'], 'http://localhost:7990/projects/CI/repos/py-repo/commits/' '793d4754230023d85532f9a38dba3290f959beb4', ) @defer.inlineCallbacks def testHookWithChangeOnRefsChangedEvent(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: 'repo:refs_changed'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496411680') self.assertEqual(change['category'], 'push') @defer.inlineCallbacks def testHookWithChangeOnPushEvent(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: 'repo:push'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496411680') self.assertEqual(change['category'], 'push') @defer.inlineCallbacks def testHookWithNonDictOption(self): self.change_hook.dialects = {'bitbucketserver': True} yield self.testHookWithChangeOnPushEvent() def _checkPullRequest(self, change): self.assertEqual(change['repository'], 'http://localhost:7990/projects/CI/repos/py-repo/') self.assertEqual(change['author'], 'John Smith <John>') self.assertEqual(change['project'], 'Continuous Integration') self.assertEqual(change['comments'], 'Bitbucket Server Pull Request #21') self.assertEqual( change['revlink'], 'http://localhost:7990/projects/CI/repos/py-repo/pull-requests/21' ) self.assertEqual(change['revision'], 'a87e21f7433d8c16ac7be7413483fbb76c72a8ba') self.assertDictSubset(bitbucketPRproperties, change["properties"]) @defer.inlineCallbacks def testHookWithChangeOnPullRequestCreated(self): request = _prepare_request( pullRequestCreatedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:created'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/pull-requests/21/merge') self.assertEqual(change['category'], 'pull-created') @defer.inlineCallbacks def testHookWithChangeOnPullRequestUpdated(self): request = _prepare_request( pullRequestUpdatedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:updated'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/pull-requests/21/merge') self.assertEqual(change['category'], 'pull-updated') @defer.inlineCallbacks def testHookWithChangeOnPullRequestRejected(self): request = _prepare_request( pullRequestRejectedJsonPayload, headers={_HEADER_EVENT: 'pullrequest:rejected'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496411680') self.assertEqual(change['category'], 'pull-rejected') @defer.inlineCallbacks def testHookWithChangeOnPullRequestFulfilled(self): request = _prepare_request( pullRequestFulfilledJsonPayload, headers={_HEADER_EVENT: 'pullrequest:fulfilled'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPullRequest(change) self.assertEqual(change['branch'], 'refs/heads/master') self.assertEqual(change['category'], 'pull-fulfilled') @defer.inlineCallbacks def _checkCodebase(self, event_type, expected_codebase): payloads = { 'repo:refs_changed': pushJsonPayload, 'pullrequest:updated': pullRequestUpdatedJsonPayload, } request = _prepare_request(payloads[event_type], headers={_HEADER_EVENT: event_type}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self.assertEqual(change['codebase'], expected_codebase) @defer.inlineCallbacks def testHookWithCodebaseValueOnPushEvent(self): self.change_hook.dialects = {'bitbucketserver': {'codebase': 'super-codebase'}} yield self._checkCodebase('repo:refs_changed', 'super-codebase') @defer.inlineCallbacks def testHookWithCodebaseFunctionOnPushEvent(self): self.change_hook.dialects = { 'bitbucketserver': {'codebase': lambda payload: payload['repository']['project']['key']} } yield self._checkCodebase('repo:refs_changed', 'CI') @defer.inlineCallbacks def testHookWithCodebaseValueOnPullEvent(self): self.change_hook.dialects = {'bitbucketserver': {'codebase': 'super-codebase'}} yield self._checkCodebase('pullrequest:updated', 'super-codebase') @defer.inlineCallbacks def testHookWithCodebaseFunctionOnPullEvent(self): self.change_hook.dialects = { 'bitbucketserver': {'codebase': lambda payload: payload['repository']['project']['key']} } yield self._checkCodebase('pullrequest:updated', 'CI') @defer.inlineCallbacks def testHookWithUnhandledEvent(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: 'invented:event'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b"Unknown event: invented_event") @defer.inlineCallbacks def testHookWithChangeOnCreateTag(self): request = _prepare_request(newTagJsonPayload, headers={_HEADER_EVENT: 'repo:refs_changed'}) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/tags/1.0.0') self.assertEqual(change['category'], 'push') @defer.inlineCallbacks def testHookWithChangeOnDeleteTag(self): request = _prepare_request( deleteTagJsonPayload, headers={_HEADER_EVENT: 'repo:refs_changed'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/tags/1.0.0') self.assertEqual(change['category'], 'ref-deleted') @defer.inlineCallbacks def testHookWithChangeOnDeleteBranch(self): request = _prepare_request( deleteBranchJsonPayload, headers={_HEADER_EVENT: 'repo:refs_changed'} ) yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) change = self.change_hook.master.data.updates.changesAdded[0] self._checkPush(change) self.assertEqual(change['branch'], 'refs/heads/branch_1496758965') self.assertEqual(change['category'], 'ref-deleted') @defer.inlineCallbacks def testHookWithInvalidContentType(self): request = _prepare_request(pushJsonPayload, headers={_HEADER_EVENT: b'repo:refs_changed'}) request.received_headers[b'Content-Type'] = b'invalid/content' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b"Unknown content type: invalid/content")
31,085
Python
.py
877
23.690992
100
0.514342
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,353
test_avatar.py
buildbot_buildbot/master/buildbot/test/unit/www/test_avatar.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 import config from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.www import auth from buildbot.www import avatar class TestAvatar(avatar.AvatarBase): def getUserAvatar(self, email, username, size, defaultAvatarUrl): user_avatar = f'{email!r} {size!r} {defaultAvatarUrl!r}'.encode() return defer.succeed((b"image/png", user_avatar)) class AvatarResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_default(self): master = yield self.make_master(url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[]) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/') self.assertEqual(res, {"redirected": avatar.AvatarResource.defaultAvatarUrl}) @defer.inlineCallbacks def test_gravatar(self): master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[avatar.AvatarGravatar()] ) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/?email=foo') self.assertEqual( res, { "redirected": b'//www.gravatar.com/avatar/acbd18db4cc2f85ce' b'def654fccc4a4d8?d=retro&s=32' }, ) @defer.inlineCallbacks def test_avatar_call(self): master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[TestAvatar()] ) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/?email=foo') self.assertEqual(res, b"b'foo' 32 b'http://a/b/img/nobody.png'") @defer.inlineCallbacks def test_custom_size(self): master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[TestAvatar()] ) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/?email=foo&size=64') self.assertEqual(res, b"b'foo' 64 b'http://a/b/img/nobody.png'") @defer.inlineCallbacks def test_invalid_size(self): master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[TestAvatar()] ) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/?email=foo&size=abcd') self.assertEqual(res, b"b'foo' 32 b'http://a/b/img/nobody.png'") @defer.inlineCallbacks def test_custom_not_found(self): # use gravatar if the custom avatar fail to return a response class CustomAvatar(avatar.AvatarBase): def getUserAvatar(self, email, username, size, defaultAvatarUrl): return defer.succeed(None) master = yield self.make_master( url=b'http://a/b/', auth=auth.NoAuth(), avatar_methods=[CustomAvatar(), avatar.AvatarGravatar()], ) rsrc = avatar.AvatarResource(master) rsrc.reconfigResource(master.config) res = yield self.render_resource(rsrc, b'/?email=foo') self.assertEqual( res, { "redirected": b'//www.gravatar.com/avatar/acbd18db4cc2f85ce' b'def654fccc4a4d8?d=retro&s=32' }, ) github_username_search_reply = { "login": "defunkt", "id": 42424242, "node_id": "MDQ6VXNlcjQyNDI0MjQy", "avatar_url": "https://avatars3.githubusercontent.com/u/42424242?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt", "html_url": "https://github.com/defunkt", "followers_url": "https://api.github.com/users/defunkt/followers", "following_url": "https://api.github.com/users/defunkt/following{/other_user}", "gists_url": "https://api.github.com/users/defunkt/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt/subscriptions", "organizations_url": "https://api.github.com/users/defunkt/orgs", "repos_url": "https://api.github.com/users/defunkt/repos", "events_url": "https://api.github.com/users/defunkt/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt/received_events", "type": "User", "site_admin": False, "name": "Defunkt User", "company": None, "blog": "", "location": None, "email": None, "hireable": None, "bio": None, "twitter_username": None, "public_repos": 1, "public_gists": 1, "followers": 1, "following": 1, "created_at": "2000-01-01T00:00:00Z", "updated_at": "2021-01-01T00:00:00Z", } github_username_not_found_reply = { "message": "Not Found", "documentation_url": "https://docs.github.com/rest/reference/users#get-a-user", } github_email_search_reply = { "total_count": 1, "incomplete_results": False, "items": [ { "login": "defunkt", "id": 42424242, "node_id": "MDQ6VXNlcjQyNDI0MjQy", "avatar_url": "https://avatars3.githubusercontent.com/u/42424242?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt", "html_url": "https://github.com/defunkt", "followers_url": "https://api.github.com/users/defunkt/followers", "following_url": "https://api.github.com/users/defunkt/following{/other_user}", "gists_url": "https://api.github.com/users/defunkt/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt/subscriptions", "organizations_url": "https://api.github.com/users/defunkt/orgs", "repos_url": "https://api.github.com/users/defunkt/repos", "events_url": "https://api.github.com/users/defunkt/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt/received_events", "type": "User", "site_admin": False, "score": 1.0, } ], } github_email_search_not_found_reply = {"total_count": 0, "incomplete_results": False, "items": []} github_commit_search_reply = { "total_count": 1, "incomplete_results": False, "items": [ { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/1111111111111111111111111111111111111111", "sha": "1111111111111111111111111111111111111111", "node_id": "MDY6Q29tbWl0NDM0MzQzNDM6MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx", "html_url": "https://github.com/defunkt-org/defunkt-repo/" "commit/1111111111111111111111111111111111111111", "comments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/1111111111111111111111111111111111111111/comments", "commit": { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/commits/1111111111111111111111111111111111111111", "author": { "date": "2021-01-01T01:01:01.000-01:00", "name": "Defunkt User", "email": "[email protected]", }, "committer": { "date": "2021-01-01T01:01:01.000-01:00", "name": "Defunkt User", "email": "[email protected]", }, "message": "defunkt message", "tree": { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/trees/2222222222222222222222222222222222222222", "sha": "2222222222222222222222222222222222222222", }, "comment_count": 0, }, "author": { "login": "defunkt", "id": 42424242, "node_id": "MDQ6VXNlcjQyNDI0MjQy", "avatar_url": "https://avatars3.githubusercontent.com/u/42424242?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt", "html_url": "https://github.com/defunkt", "followers_url": "https://api.github.com/users/defunkt/followers", "following_url": "https://api.github.com/users/defunkt/following{/other_user}", "gists_url": "https://api.github.com/users/defunkt/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt/subscriptions", "organizations_url": "https://api.github.com/users/defunkt/orgs", "repos_url": "https://api.github.com/users/defunkt/repos", "events_url": "https://api.github.com/users/defunkt/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt/received_events", "type": "User", "site_admin": False, }, "committer": { "login": "defunkt", "id": 42424242, "node_id": "MDQ6VXNlcjQyNDI0MjQy", "avatar_url": "https://avatars3.githubusercontent.com/u/42424242?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt", "html_url": "https://github.com/defunkt", "followers_url": "https://api.github.com/users/defunkt/followers", "following_url": "https://api.github.com/users/defunkt/following{/other_user}", "gists_url": "https://api.github.com/users/defunkt/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt/subscriptions", "organizations_url": "https://api.github.com/users/defunkt/orgs", "repos_url": "https://api.github.com/users/defunkt/repos", "events_url": "https://api.github.com/users/defunkt/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt/received_events", "type": "User", "site_admin": False, }, "parents": [ { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/3333333333333333333333333333333333333333", "html_url": "https://github.com/defunkt-org/defunkt-repo/" "commit/3333333333333333333333333333333333333333", "sha": "3333333333333333333333333333333333333333", } ], "repository": { "id": 43434343, "node_id": "MDEwOlJlcG9zaXRvcnk0MzQzNDM0Mw==", "name": "defunkt-repo", "full_name": "defunkt-org/defunkt-repo", "private": False, "owner": { "login": "defunkt-org", "id": 44444444, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ0NDQ0NDQ0", "avatar_url": "https://avatars2.githubusercontent.com/u/44444444?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt-org", "html_url": "https://github.com/defunkt-org", "followers_url": "https://api.github.com/users/defunkt-org/followers", "following_url": "https://api.github.com/users/defunkt-org/" "following{/other_user}", "gists_url": "https://api.github.com/users/defunkt-org/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt-org/" "starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt-org/subscriptions", "organizations_url": "https://api.github.com/users/defunkt-org/orgs", "repos_url": "https://api.github.com/users/defunkt-org/repos", "events_url": "https://api.github.com/users/defunkt-org/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt-org/" "received_events", "type": "Organization", "site_admin": False, }, "html_url": "https://github.com/defunkt-org/defunkt-repo", "description": "defunkt project", "fork": False, "url": "https://api.github.com/repos/defunkt-org/defunkt-repo", "forks_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/forks", "keys_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/teams", "hooks_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/hooks", "issue_events_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues/events{/number}", "events_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/events", "assignees_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "assignees{/user}", "branches_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "branches{/branch}", "tags_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/tags", "blobs_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/refs{/sha}", "trees_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/trees{/sha}", "statuses_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "statuses/{sha}", "languages_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "languages", "stargazers_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "stargazers", "contributors_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "contributors", "subscribers_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "subscribers", "subscription_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "subscription", "commits_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits{/sha}", "git_commits_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/commits{/sha}", "comments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "comments{/number}", "issue_comment_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues/comments{/number}", "contents_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "contents/{+path}", "compare_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "compare/{base}...{head}", "merges_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/merges", "archive_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "downloads", "issues_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues{/number}", "pulls_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "pulls{/number}", "milestones_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "milestones{/number}", "notifications_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "labels{/name}", "releases_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "releases{/id}", "deployments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "deployments", }, "score": 1.0, } ], } github_commit_search_no_user_reply = { "total_count": 1, "incomplete_results": False, "items": [ { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/1111111111111111111111111111111111111111", "sha": "1111111111111111111111111111111111111111", "node_id": "MDY6Q29tbWl0NDM0MzQzNDM6MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx", "html_url": "https://github.com/defunkt-org/defunkt-repo/" "commit/1111111111111111111111111111111111111111", "comments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/1111111111111111111111111111111111111111/comments", "commit": { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/commits/1111111111111111111111111111111111111111", "author": { "date": "2021-01-01T01:01:01.000-01:00", "name": "Defunkt User", "email": "[email protected]", }, "committer": { "date": "2021-01-01T01:01:01.000-01:00", "name": "Defunkt User", "email": "[email protected]", }, "message": "defunkt message", "tree": { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/trees/2222222222222222222222222222222222222222", "sha": "2222222222222222222222222222222222222222", }, "comment_count": 0, }, "author": None, "committer": None, "parents": [ { "url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits/3333333333333333333333333333333333333333", "html_url": "https://github.com/defunkt-org/defunkt-repo/" "commit/3333333333333333333333333333333333333333", "sha": "3333333333333333333333333333333333333333", } ], "repository": { "id": 43434343, "node_id": "MDEwOlJlcG9zaXRvcnk0MzQzNDM0Mw==", "name": "defunkt-repo", "full_name": "defunkt-org/defunkt-repo", "private": False, "owner": { "login": "defunkt-org", "id": 44444444, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ0NDQ0NDQ0", "avatar_url": "https://avatars2.githubusercontent.com/u/44444444?v=4", "gravatar_id": "", "url": "https://api.github.com/users/defunkt-org", "html_url": "https://github.com/defunkt-org", "followers_url": "https://api.github.com/users/defunkt-org/followers", "following_url": "https://api.github.com/users/defunkt-org/" "following{/other_user}", "gists_url": "https://api.github.com/users/defunkt-org/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt-org/" "starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt-org/subscriptions", "organizations_url": "https://api.github.com/users/defunkt-org/orgs", "repos_url": "https://api.github.com/users/defunkt-org/repos", "events_url": "https://api.github.com/users/defunkt-org/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt-org/" "received_events", "type": "Organization", "site_admin": False, }, "html_url": "https://github.com/defunkt-org/defunkt-repo", "description": "defunkt project", "fork": False, "url": "https://api.github.com/repos/defunkt-org/defunkt-repo", "forks_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/forks", "keys_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/teams", "hooks_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/hooks", "issue_events_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues/events{/number}", "events_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/events", "assignees_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "assignees{/user}", "branches_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "branches{/branch}", "tags_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/tags", "blobs_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/refs{/sha}", "trees_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/trees{/sha}", "statuses_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "statuses/{sha}", "languages_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "languages", "stargazers_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "stargazers", "contributors_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "contributors", "subscribers_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "subscribers", "subscription_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "subscription", "commits_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "commits{/sha}", "git_commits_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "git/commits{/sha}", "comments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "comments{/number}", "issue_comment_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues/comments{/number}", "contents_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "contents/{+path}", "compare_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "compare/{base}...{head}", "merges_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/merges", "archive_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "downloads", "issues_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "issues{/number}", "pulls_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "pulls{/number}", "milestones_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "milestones{/number}", "notifications_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "labels{/name}", "releases_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "releases{/id}", "deployments_url": "https://api.github.com/repos/defunkt-org/defunkt-repo/" "deployments", }, "score": 1.0, } ], } github_commit_search_not_found_reply = {"total_count": 0, "incomplete_results": False, "items": []} class GitHubAvatar(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[avatar.AvatarGitHub(token="abcd")], ) self.rsrc = avatar.AvatarResource(master) self.rsrc.reconfigResource(master.config) headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token abcd', } self._http = yield fakehttpclientservice.HTTPClientService.getService( master, self, avatar.AvatarGitHub.DEFAULT_GITHUB_API_URL, headers=headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_username(self): username_search_endpoint = '/users/defunkt' self._http.expect( 'get', username_search_endpoint, content_json=github_username_search_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/?username=defunkt') self.assertEqual( res, {"redirected": b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} ) @defer.inlineCallbacks def test_username_not_found(self): username_search_endpoint = '/users/inexistent' self._http.expect( 'get', username_search_endpoint, code=404, content_json=github_username_not_found_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/?username=inexistent') self.assertEqual(res, {"redirected": b'img/nobody.png'}) @defer.inlineCallbacks def test_username_error(self): username_search_endpoint = '/users/error' self._http.expect( 'get', username_search_endpoint, code=500, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/?username=error') self.assertEqual(res, {"redirected": b'img/nobody.png'}) @defer.inlineCallbacks def test_username_cached(self): username_search_endpoint = '/users/defunkt' self._http.expect( 'get', username_search_endpoint, content_json=github_username_search_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/?username=defunkt') self.assertEqual( res, {"redirected": b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} ) # Second request will give same result but without an HTTP request res = yield self.render_resource(self.rsrc, b'/?username=defunkt') self.assertEqual( res, {"redirected": b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} ) @defer.inlineCallbacks def test_email(self): email_search_endpoint = '/search/users?q=defunkt%40defunkt.com+in%3Aemail' self._http.expect( 'get', email_search_endpoint, content_json=github_email_search_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/[email protected]') self.assertEqual( res, {"redirected": b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} ) @defer.inlineCallbacks def test_email_commit(self): email_search_endpoint = '/search/users?q=defunkt%40defunkt.com+in%3Aemail' self._http.expect( 'get', email_search_endpoint, content_json=github_email_search_not_found_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) commit_search_endpoint = ( '/search/commits?' 'per_page=1&q=author-email%3Adefunkt%40defunkt.com&sort=committer-date' ) self._http.expect( 'get', commit_search_endpoint, content_json=github_commit_search_reply, headers={ 'Accept': 'application/vnd.github.v3+json,application/vnd.github.cloak-preview' }, ) res = yield self.render_resource(self.rsrc, b'/[email protected]') self.assertEqual( res, {"redirected": b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} ) @defer.inlineCallbacks def test_email_commit_no_user(self): email_search_endpoint = '/search/users?q=defunkt%40defunkt.com+in%3Aemail' self._http.expect( 'get', email_search_endpoint, content_json=github_email_search_not_found_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) commit_search_endpoint = ( '/search/commits?' 'per_page=1&q=author-email%3Adefunkt%40defunkt.com&sort=committer-date' ) self._http.expect( 'get', commit_search_endpoint, content_json=github_commit_search_no_user_reply, headers={ 'Accept': 'application/vnd.github.v3+json,application/vnd.github.cloak-preview' }, ) res = yield self.render_resource(self.rsrc, b'/[email protected]') self.assertEqual(res, {"redirected": b'img/nobody.png'}) @defer.inlineCallbacks def test_email_not_found(self): email_search_endpoint = '/search/users?q=notfound%40defunkt.com+in%3Aemail' self._http.expect( 'get', email_search_endpoint, content_json=github_email_search_not_found_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) commit_search_endpoint = ( '/search/commits?' 'per_page=1&q=author-email%3Anotfound%40defunkt.com&sort=committer-date' ) self._http.expect( 'get', commit_search_endpoint, content_json=github_commit_search_not_found_reply, headers={ 'Accept': 'application/vnd.github.v3+json,application/vnd.github.cloak-preview' }, ) res = yield self.render_resource(self.rsrc, b'/[email protected]') self.assertEqual(res, {"redirected": b'img/nobody.png'}) @defer.inlineCallbacks def test_email_error(self): email_search_endpoint = '/search/users?q=error%40defunkt.com+in%3Aemail' self._http.expect( 'get', email_search_endpoint, code=500, headers={'Accept': 'application/vnd.github.v3+json'}, ) commit_search_endpoint = ( '/search/commits?per_page=1&q=author-email%3Aerror%40defunkt.com&sort=committer-date' ) self._http.expect( 'get', commit_search_endpoint, code=500, headers={ 'Accept': 'application/vnd.github.v3+json,application/vnd.github.cloak-preview' }, ) res = yield self.render_resource(self.rsrc, b'/[email protected]') self.assertEqual(res, {"redirected": b'img/nobody.png'}) class GitHubAvatarBasicAuth(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) avatar_method = avatar.AvatarGitHub(client_id="oauth_id", client_secret="oauth_secret") master = yield self.make_master( url='http://a/b/', auth=auth.NoAuth(), avatar_methods=[avatar_method] ) self.rsrc = avatar.AvatarResource(master) self.rsrc.reconfigResource(master.config) headers = { 'User-Agent': 'Buildbot', # oauth_id:oauth_secret in Base64 'Authorization': 'basic b2F1dGhfaWQ6b2F1dGhfc2VjcmV0', } self._http = yield fakehttpclientservice.HTTPClientService.getService( master, self, avatar.AvatarGitHub.DEFAULT_GITHUB_API_URL, headers=headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def test_incomplete_credentials(self): with self.assertRaises(config.ConfigErrors): avatar.AvatarGitHub(client_id="oauth_id") with self.assertRaises(config.ConfigErrors): avatar.AvatarGitHub(client_secret="oauth_secret") def test_token_and_client_credentials(self): with self.assertRaises(config.ConfigErrors): avatar.AvatarGitHub(client_id="oauth_id", client_secret="oauth_secret", token="token") @defer.inlineCallbacks def test_username(self): username_search_endpoint = '/users/defunkt' self._http.expect( 'get', username_search_endpoint, content_json=github_username_search_reply, headers={'Accept': 'application/vnd.github.v3+json'}, ) res = yield self.render_resource(self.rsrc, b'/?username=defunkt') self.assertEqual( res, {'redirected': b'https://avatars3.githubusercontent.com/u/42424242?v=4&s=32'} )
36,937
Python
.py
740
37.325676
102
0.580468
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,354
test_hooks_gitorious.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_gitorious.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.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.www import change_hook # Sample Gitorious commit payload # source: http://gitorious.org/gitorious/pages/WebHooks gitJsonPayload = b""" { "after": "df5744f7bc8663b39717f87742dc94f52ccbf4dd", "before": "b4ca2d38e756695133cbd0e03d078804e1dc6610", "commits": [ { "author": { "email": "[email protected]", "name": "jason" }, "committed_at": "2012-01-10T11:02:27-07:00", "id": "df5744f7bc8663b39717f87742dc94f52ccbf4dd", "message": "added a place to put the docstring for Book", "timestamp": "2012-01-10T11:02:27-07:00", "url": "http://gitorious.org/q/mainline/commit/df5744f7bc8663b39717f87742dc94f52ccbf4dd" } ], "project": { "description": "a webapp to organize your ebook collectsion.", "name": "q" }, "pushed_at": "2012-01-10T11:09:25-07:00", "pushed_by": "jason", "ref": "new_look", "repository": { "clones": 4, "description": "", "name": "mainline", "owner": { "name": "jason" }, "url": "http://gitorious.org/q/mainline" } } """ class TestChangeHookConfiguredWithGitChange(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) dialects = {'gitorious': True} master = yield fakeMasterForHooks(self) self.changeHook = change_hook.ChangeHookResource(dialects=dialects, master=master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() # Test 'base' hook with attributes. We should get a json string # representing a Change object as a dictionary. All values show be set. @defer.inlineCallbacks def testGitWithChange(self): changeDict = {b"payload": [gitJsonPayload]} self.request = FakeRequest(changeDict) self.request.uri = b"/change_hook/gitorious" self.request.method = b"POST" yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] # Gitorious doesn't send changed files self.assertEqual(change['files'], []) self.assertEqual(change["repository"], "http://gitorious.org/q/mainline") self.assertEqual(change["when_timestamp"], 1326218547) self.assertEqual(change["author"], "jason <[email protected]>") self.assertEqual(change["revision"], 'df5744f7bc8663b39717f87742dc94f52ccbf4dd') self.assertEqual(change["comments"], "added a place to put the docstring for Book") self.assertEqual(change["branch"], "new_look") revlink = "http://gitorious.org/q/mainline/commit/df5744f7bc8663b39717f87742dc94f52ccbf4dd" self.assertEqual(change["revlink"], revlink) @defer.inlineCallbacks def testGitWithNoJson(self): self.request = FakeRequest() self.request.uri = b"/change_hook/gitorious" self.request.method = b"GET" yield self.request.test_render(self.changeHook) expected = b"Error processing changes." self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) self.request.setResponseCode.assert_called_with(500, expected) self.assertEqual(len(self.flushLoggedErrors()), 1)
4,326
Python
.py
99
38.393939
99
0.71554
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,355
test_hooks_bitbucket.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_bitbucket.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 # Copyright Manba Team from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.www import change_hook from buildbot.www.hooks.bitbucket import _HEADER_EVENT gitJsonPayload = b"""{ "canon_url": "https://bitbucket.org", "commits": [ { "author": "marcus", "branch": "master", "files": [ { "file": "somefile.py", "type": "modified" } ], "message": "Added some more things to somefile.py", "node": "620ade18607a", "parents": [ "702c70160afc" ], "raw_author": "Marcus Bertrand <[email protected]>", "raw_node": "620ade18607ac42d872b568bb92acaa9a28620e9", "revision": null, "size": -1, "timestamp": "2012-05-30 05:58:56", "utctimestamp": "2012-05-30 03:58:56+00:00" } ], "repository": { "absolute_url": "/marcus/project-x/", "fork": false, "is_private": true, "name": "Project X", "owner": "marcus", "scm": "git", "slug": "project-x", "website": "https://atlassian.com/" }, "user": "marcus" }""" mercurialJsonPayload = b"""{ "canon_url": "https://bitbucket.org", "commits": [ { "author": "marcus", "branch": "master", "files": [ { "file": "somefile.py", "type": "modified" } ], "message": "Added some more things to somefile.py", "node": "620ade18607a", "parents": [ "702c70160afc" ], "raw_author": "Marcus Bertrand <[email protected]>", "raw_node": "620ade18607ac42d872b568bb92acaa9a28620e9", "revision": null, "size": -1, "timestamp": "2012-05-30 05:58:56", "utctimestamp": "2012-05-30 03:58:56+00:00" } ], "repository": { "absolute_url": "/marcus/project-x/", "fork": false, "is_private": true, "name": "Project X", "owner": "marcus", "scm": "hg", "slug": "project-x", "website": "https://atlassian.com/" }, "user": "marcus" }""" gitJsonNoCommitsPayload = b"""{ "canon_url": "https://bitbucket.org", "commits": [ ], "repository": { "absolute_url": "/marcus/project-x/", "fork": false, "is_private": true, "name": "Project X", "owner": "marcus", "scm": "git", "slug": "project-x", "website": "https://atlassian.com/" }, "user": "marcus" }""" mercurialJsonNoCommitsPayload = b"""{ "canon_url": "https://bitbucket.org", "commits": [ ], "repository": { "absolute_url": "/marcus/project-x/", "fork": false, "is_private": true, "name": "Project X", "owner": "marcus", "scm": "hg", "slug": "project-x", "website": "https://atlassian.com/" }, "user": "marcus" }""" class TestChangeHookConfiguredWithBitbucketChange(unittest.TestCase, TestReactorMixin): """Unit tests for BitBucket Change Hook""" @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) master = yield fakeMasterForHooks(self) self.change_hook = change_hook.ChangeHookResource( dialects={'bitbucket': True}, master=master ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def testGitWithChange(self): change_dict = {b'payload': [gitJsonPayload]} request = FakeRequest(change_dict) request.received_headers[_HEADER_EVENT] = b"repo:push" request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) commit = self.change_hook.master.data.updates.changesAdded[0] self.assertEqual(commit['files'], ['somefile.py']) self.assertEqual(commit['repository'], 'https://bitbucket.org/marcus/project-x/') self.assertEqual(commit['when_timestamp'], 1338350336) self.assertEqual(commit['author'], 'Marcus Bertrand <[email protected]>') self.assertEqual(commit['revision'], '620ade18607ac42d872b568bb92acaa9a28620e9') self.assertEqual(commit['comments'], 'Added some more things to somefile.py') self.assertEqual(commit['branch'], 'master') self.assertEqual( commit['revlink'], 'https://bitbucket.org/marcus/project-x/commits/' '620ade18607ac42d872b568bb92acaa9a28620e9', ) self.assertEqual(commit['properties']['event'], 'repo:push') @defer.inlineCallbacks def testGitWithNoCommitsPayload(self): change_dict = {b'payload': [gitJsonNoCommitsPayload]} request = FakeRequest(change_dict) request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b'no change found') @defer.inlineCallbacks def testMercurialWithChange(self): change_dict = {b'payload': [mercurialJsonPayload]} request = FakeRequest(change_dict) request.received_headers[_HEADER_EVENT] = b"repo:push" request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) commit = self.change_hook.master.data.updates.changesAdded[0] self.assertEqual(commit['files'], ['somefile.py']) self.assertEqual(commit['repository'], 'https://bitbucket.org/marcus/project-x/') self.assertEqual(commit['when_timestamp'], 1338350336) self.assertEqual(commit['author'], 'Marcus Bertrand <[email protected]>') self.assertEqual(commit['revision'], '620ade18607ac42d872b568bb92acaa9a28620e9') self.assertEqual(commit['comments'], 'Added some more things to somefile.py') self.assertEqual(commit['branch'], 'master') self.assertEqual( commit['revlink'], 'https://bitbucket.org/marcus/project-x/commits/' '620ade18607ac42d872b568bb92acaa9a28620e9', ) self.assertEqual(commit['properties']['event'], 'repo:push') @defer.inlineCallbacks def testMercurialWithNoCommitsPayload(self): change_dict = {b'payload': [mercurialJsonNoCommitsPayload]} request = FakeRequest(change_dict) request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b'no change found') @defer.inlineCallbacks def testWithNoJson(self): request = FakeRequest() request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 0) self.assertEqual(request.written, b'Error processing changes.') request.setResponseCode.assert_called_with(500, b'Error processing changes.') self.assertEqual(len(self.flushLoggedErrors()), 1) @defer.inlineCallbacks def testGitWithChangeAndProject(self): change_dict = {b'payload': [gitJsonPayload], b'project': [b'project-name']} request = FakeRequest(change_dict) request.uri = b'/change_hook/bitbucket' request.method = b'POST' yield request.test_render(self.change_hook) self.assertEqual(len(self.change_hook.master.data.updates.changesAdded), 1) commit = self.change_hook.master.data.updates.changesAdded[0] self.assertEqual(commit['project'], 'project-name')
9,153
Python
.py
224
32.491071
89
0.628626
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,356
test_rest.py
buildbot_buildbot/master/buildbot/test/unit/www/test_rest.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 import re from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data.base import EndpointKind from buildbot.data.exceptions import InvalidQueryParameter from buildbot.test.fake import endpoint from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.www import authz from buildbot.www import graphql from buildbot.www import rest from buildbot.www.rest import JSONRPC_CODES class RestRootResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): maxVersion = 3 def setUp(self): self.setup_test_reactor(auto_tear_down=False) _ = graphql # used for import side effect @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_render(self): master = yield self.make_master(url='h:/a/b/') rsrc = rest.RestRootResource(master) rv = yield self.render_resource(rsrc, b'/') self.assertIn(b'api_versions', rv) @defer.inlineCallbacks def test_versions(self): master = yield self.make_master(url='h:/a/b/') rsrc = rest.RestRootResource(master) versions = [unicode2bytes(f'v{v}') for v in range(2, self.maxVersion + 1)] versions = [unicode2bytes(v) for v in versions] versions.append(b'latest') self.assertEqual(sorted(rsrc.listNames()), sorted(versions)) @defer.inlineCallbacks def test_versions_limited(self): master = yield self.make_master(url='h:/a/b/') master.config.www['rest_minimum_version'] = 2 rsrc = rest.RestRootResource(master) versions = [unicode2bytes(f'v{v}') for v in range(2, self.maxVersion + 1)] versions.append(b'latest') self.assertEqual(sorted(rsrc.listNames()), sorted(versions)) class V2RootResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='http://server/path/') self.master.data._scanModule(endpoint) self.rsrc = rest.V2RootResource(self.master) self.rsrc.reconfigResource(self.master.config) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertSimpleError(self, message, responseCode): content = json.dumps({'error': message}) self.assertRequest(content=unicode2bytes(content), responseCode=responseCode) @defer.inlineCallbacks def test_failure(self): self.rsrc.renderRest = mock.Mock(return_value=defer.fail(RuntimeError('oh noes'))) yield self.render_resource(self.rsrc, b'/') self.assertSimpleError('internal error - see logs', 500) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) @defer.inlineCallbacks def test_invalid_http_method(self): yield self.render_resource(self.rsrc, b'/', method=b'PATCH') self.assertSimpleError('invalid HTTP method', 400) def do_check_origin_regexp(self, goods, bads): self.assertEqual(len(self.rsrc.origins), 1) regexp = self.rsrc.origins[0] for good in goods: self.assertTrue( regexp.match(good), f"{good} should match default origin({regexp.pattern}), but its not", ) for bad in bads: self.assertFalse( regexp.match(bad), f"{bad} should not match default origin({regexp.pattern}), but it is", ) def test_default_origin(self): self.master.config.buildbotURL = 'http://server/path/' self.rsrc.reconfigResource(self.master.config) self.do_check_origin_regexp( ["http://server"], ["http://otherserver", "http://otherserver:909"], ) self.master.config.buildbotURL = 'http://server/' self.rsrc.reconfigResource(self.master.config) self.do_check_origin_regexp( ["http://server"], ["http://otherserver", "http://otherserver:909"], ) self.master.config.buildbotURL = 'http://server:8080/' self.rsrc.reconfigResource(self.master.config) self.do_check_origin_regexp( ["http://server:8080"], ["http://otherserver", "http://server:909"], ) self.master.config.buildbotURL = 'https://server:8080/' self.rsrc.reconfigResource(self.master.config) self.do_check_origin_regexp( ["https://server:8080"], ["http://server:8080", "https://otherserver:8080"], ) class V2RootResource_CORS(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='h:/') self.master.data._scanModule(endpoint) self.rsrc = rest.V2RootResource(self.master) self.master.config.www['allowed_origins'] = [b'h://good'] self.rsrc.reconfigResource(self.master.config) def renderRest(request): request.write(b'ok') return defer.succeed(None) self.rsrc.renderRest = renderRest @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertOk(self, expectHeaders=True, content=b'ok', origin=b'h://good'): hdrs = ( { b'access-control-allow-origin': [origin], b'access-control-allow-headers': [b'Content-Type'], b'access-control-max-age': [b'3600'], } if expectHeaders else {} ) self.assertRequest(content=content, responseCode=200, headers=hdrs) def assertNotOk(self, message): content = json.dumps({'error': message}) content = unicode2bytes(content) self.assertRequest(content=content, responseCode=400) @defer.inlineCallbacks def test_cors_no_origin(self): # if the browser doesn't send Origin, there's nothing we can do to # protect the user yield self.render_resource(self.rsrc, b'/') self.assertOk(expectHeaders=False) @defer.inlineCallbacks def test_cors_origin_match(self): yield self.render_resource(self.rsrc, b'/', origin=b'h://good') self.assertOk() @defer.inlineCallbacks def test_cors_origin_match_star(self): self.master.config.www['allowed_origins'] = ['*'] self.rsrc.reconfigResource(self.master.config) yield self.render_resource(self.rsrc, b'/', origin=b'h://good') self.assertOk() @defer.inlineCallbacks def test_cors_origin_patterns(self): self.master.config.www['allowed_origins'] = ['h://*.good', 'hs://*.secure'] self.rsrc.reconfigResource(self.master.config) yield self.render_resource(self.rsrc, b'/', origin=b'h://foo.good') self.assertOk(origin=b'h://foo.good') yield self.render_resource(self.rsrc, b'/', origin=b'hs://x.secure') self.assertOk(origin=b'hs://x.secure') yield self.render_resource(self.rsrc, b'/', origin=b'h://x.secure') self.assertNotOk('invalid origin') @defer.inlineCallbacks def test_cors_origin_mismatch(self): yield self.render_resource(self.rsrc, b'/', origin=b'h://bad') self.assertNotOk('invalid origin') @defer.inlineCallbacks def test_cors_origin_mismatch_post(self): yield self.render_resource(self.rsrc, b'/', method=b'POST', origin=b'h://bad') content = json.dumps({'error': {'message': 'invalid origin'}}) content = unicode2bytes(content) self.assertRequest(content=content, responseCode=400) @defer.inlineCallbacks def test_cors_origin_preflight_match_GET(self): yield self.render_resource( self.rsrc, b'/', method=b'OPTIONS', origin=b'h://good', access_control_request_method=b'GET', ) self.assertOk(content=b'') @defer.inlineCallbacks def test_cors_origin_preflight_match_POST(self): yield self.render_resource( self.rsrc, b'/', method=b'OPTIONS', origin=b'h://good', access_control_request_method=b'POST', ) self.assertOk(content=b'') @defer.inlineCallbacks def test_cors_origin_preflight_bad_method(self): yield self.render_resource( self.rsrc, b'/', method=b'OPTIONS', origin=b'h://good', access_control_request_method=b'PATCH', ) self.assertNotOk(message='invalid method') @defer.inlineCallbacks def test_cors_origin_preflight_bad_origin(self): yield self.render_resource( self.rsrc, b'/', method=b'OPTIONS', origin=b'h://bad', access_control_request_method=b'GET', ) self.assertNotOk(message='invalid origin') class V2RootResource_REST(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='h:/') self.master.config.www['debug'] = True self.master.data._scanModule(endpoint) self.rsrc = rest.V2RootResource(self.master) self.rsrc.reconfigResource(self.master.config) def allow(*args, **kw): return self.master.www.assertUserAllowed = allow endpoint.TestEndpoint.rtype = mock.MagicMock() endpoint.TestsEndpoint.rtype = mock.MagicMock() endpoint.Test.kind = EndpointKind.COLLECTION endpoint.Test.rtype = endpoint.Test @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertRestCollection( self, typeName, items, total=None, contentType=None, orderSignificant=False ): self.assertFalse(isinstance(self.request.written, str)) got = {} got['content'] = json.loads(bytes2unicode(self.request.written)) got['contentType'] = self.request.headers[b'content-type'] got['responseCode'] = self.request.responseCode meta = {} if total is not None: meta['total'] = total exp = {} exp['content'] = {typeName: items, 'meta': meta} exp['contentType'] = [contentType or b'text/plain; charset=utf-8'] exp['responseCode'] = 200 # if order is not significant, sort so the comparison works if not orderSignificant: if 'content' in got and typeName in got['content']: got['content'][typeName].sort(key=lambda x: sorted(x.items())) exp['content'][typeName].sort(key=lambda x: sorted(x.items())) if 'meta' in got['content'] and 'links' in got['content']['meta']: got['content']['meta']['links'].sort(key=lambda l: (l['rel'], l['href'])) self.assertEqual(got, exp) def assertRestDetails(self, typeName, item, contentType=None): got = {} got['content'] = json.loads(bytes2unicode(self.request.written)) got['contentType'] = self.request.headers[b'content-type'] got['responseCode'] = self.request.responseCode exp = {} exp['content'] = { typeName: [item], 'meta': {}, } exp['contentType'] = [contentType or b'text/plain; charset=utf-8'] exp['responseCode'] = 200 self.assertEqual(got, exp) def assertRestError(self, responseCode, message): content = json.loads(bytes2unicode(self.request.written)) gotResponseCode = self.request.responseCode self.assertEqual(list(content.keys()), ['error']) self.assertRegex(content['error'], message) self.assertEqual(responseCode, gotResponseCode) @defer.inlineCallbacks def test_not_found(self): yield self.render_resource(self.rsrc, b'/not/found') self.assertRequest( contentJson={"error": 'Invalid path: not/found'}, contentType=b'text/plain; charset=utf-8', responseCode=404, ) @defer.inlineCallbacks def test_invalid_query(self): yield self.render_resource(self.rsrc, b'/test?huh=1') self.assertRequest( contentJson={"error": "unrecognized query parameter 'huh'"}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_raw(self): yield self.render_resource(self.rsrc, b'/rawtest') self.assertRequest( content=b"value", contentType=b'text/test; charset=utf-8', responseCode=200, headers={b"content-disposition": [b'attachment; filename=test.txt']}, ) @defer.inlineCallbacks def test_api_head(self): get = yield self.render_resource(self.rsrc, b'/test', method=b'GET') head = yield self.render_resource(self.rsrc, b'/test', method=b'HEAD') self.assertEqual(head, b'') self.assertEqual(int(self.request.headers[b'content-length'][0]), len(get)) @defer.inlineCallbacks def test_api_collection(self): yield self.render_resource(self.rsrc, b'/test') self.assertRestCollection(typeName='tests', items=list(endpoint.testData.values()), total=8) @defer.inlineCallbacks def do_test_api_collection_pagination(self, query, ids, links): yield self.render_resource(self.rsrc, b'/test' + query) self.assertRestCollection( typeName='tests', items=[v for k, v in endpoint.testData.items() if k in ids], total=8 ) def test_api_collection_limit(self): return self.do_test_api_collection_pagination( b'?limit=2', [13, 14], { 'self': '%(self)s?limit=2', 'next': '%(self)s?offset=2&limit=2', }, ) def test_api_collection_offset(self): return self.do_test_api_collection_pagination( b'?offset=2', [15, 16, 17, 18, 19, 20], { 'self': '%(self)s?offset=2', 'first': '%(self)s', }, ) def test_api_collection_offset_limit(self): return self.do_test_api_collection_pagination( b'?offset=5&limit=2', [18, 19], { 'first': '%(self)s?limit=2', 'prev': '%(self)s?offset=3&limit=2', 'next': '%(self)s?offset=7&limit=2', 'self': '%(self)s?offset=5&limit=2', }, ) def test_api_collection_limit_at_end(self): return self.do_test_api_collection_pagination( b'?offset=5&limit=3', [18, 19, 20], { 'first': '%(self)s?limit=3', 'prev': '%(self)s?offset=2&limit=3', 'self': '%(self)s?offset=5&limit=3', }, ) def test_api_collection_limit_past_end(self): return self.do_test_api_collection_pagination( b'?offset=5&limit=20', [18, 19, 20], { 'first': '%(self)s?limit=20', 'prev': '%(self)s?limit=5', 'self': '%(self)s?offset=5&limit=20', }, ) def test_api_collection_offset_past_end(self): return self.do_test_api_collection_pagination( b'?offset=50&limit=10', [], { 'first': '%(self)s?limit=10', 'prev': '%(self)s?offset=40&limit=10', 'self': '%(self)s?offset=50&limit=10', }, ) @defer.inlineCallbacks def test_api_collection_invalid_limit(self): yield self.render_resource(self.rsrc, b'/test?limit=foo!') self.assertRequest( contentJson={"error": 'invalid limit'}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_collection_invalid_offset(self): yield self.render_resource(self.rsrc, b'/test?offset=foo!') self.assertRequest( contentJson={"error": 'invalid offset'}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_collection_invalid_simple_filter_value(self): yield self.render_resource(self.rsrc, b'/test?success=sorta') self.assertRequest( contentJson={"error": 'invalid filter value for success'}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_collection_invalid_filter_value(self): yield self.render_resource(self.rsrc, b'/test?testid__lt=fifteen') self.assertRequest( contentJson={"error": 'invalid filter value for testid__lt'}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_collection_fields(self): yield self.render_resource(self.rsrc, b'/test?field=success&field=info') self.assertRestCollection( typeName='tests', items=[ {'success': v['success'], 'info': v['info']} for v in endpoint.testData.values() ], total=8, ) @defer.inlineCallbacks def test_api_collection_invalid_field(self): yield self.render_resource(self.rsrc, b'/test?field=success&field=WTF') self.assertRequest( contentJson={"error": "no such field 'WTF'"}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_collection_simple_filter(self): yield self.render_resource(self.rsrc, b'/test?success=yes') self.assertRestCollection( typeName='tests', items=[v for v in endpoint.testData.values() if v['success']], total=5 ) @defer.inlineCallbacks def test_api_collection_list_filter(self): yield self.render_resource(self.rsrc, b'/test?tags__contains=a') self.assertRestCollection( typeName='tests', items=[v for v in endpoint.testData.values() if 'a' in v['tags']], total=2, ) @defer.inlineCallbacks def test_api_collection_operator_filter(self): yield self.render_resource(self.rsrc, b'/test?info__lt=skipped') self.assertRestCollection( typeName='tests', items=[v for v in endpoint.testData.values() if v['info'] < 'skipped'], total=4, ) @defer.inlineCallbacks def test_api_collection_order(self): yield self.render_resource(self.rsrc, b'/test?order=info') self.assertRestCollection( typeName='tests', items=sorted(list(endpoint.testData.values()), key=lambda v: v['info']), total=8, orderSignificant=True, ) @defer.inlineCallbacks def test_api_collection_filter_and_order(self): yield self.render_resource(self.rsrc, b'/test?field=info&order=info') self.assertRestCollection( typeName='tests', items=sorted( [{'info': v['info']} for v in endpoint.testData.values()], key=lambda v: v['info'] ), total=8, orderSignificant=True, ) @defer.inlineCallbacks def test_api_collection_order_desc(self): yield self.render_resource(self.rsrc, b'/test?order=-info') self.assertRestCollection( typeName='tests', items=sorted(list(endpoint.testData.values()), key=lambda v: v['info'], reverse=True), total=8, orderSignificant=True, ) @defer.inlineCallbacks def test_api_collection_filter_and_order_desc(self): yield self.render_resource(self.rsrc, b'/test?field=info&order=-info') self.assertRestCollection( typeName='tests', items=sorted( [{'info': v['info']} for v in endpoint.testData.values()], key=lambda v: v['info'], reverse=True, ), total=8, orderSignificant=True, ) @defer.inlineCallbacks def test_api_collection_order_on_unselected(self): yield self.render_resource(self.rsrc, b'/test?field=testid&order=info') self.assertRestError(message="cannot order on un-selected fields", responseCode=400) @defer.inlineCallbacks def test_api_collection_filter_on_unselected(self): yield self.render_resource(self.rsrc, b'/test?field=testid&info__gt=xx') self.assertRestError(message="cannot filter on un-selected fields", responseCode=400) @defer.inlineCallbacks def test_api_collection_filter_pagination(self): yield self.render_resource(self.rsrc, b'/test?success=false&limit=2') # note that the limit/offset and total are *after* the filter self.assertRestCollection( typeName='tests', items=sorted( [v for v in endpoint.testData.values() if not v['success']], key=lambda v: v['testid'], )[:2], total=3, ) @defer.inlineCallbacks def test_api_details(self): yield self.render_resource(self.rsrc, b'/test/13') self.assertRestDetails(typeName='tests', item=endpoint.testData[13]) @defer.inlineCallbacks def test_api_details_none(self): self.maxDiff = None yield self.render_resource(self.rsrc, b'/test/0') self.assertRequest( contentJson={ 'error': "not found while getting from endpoint for " "/tests/n:testid,/test/n:testid with arguments" " ResultSpec(**{'filters': [], 'fields': None, " "'properties': [], " "'order': None, 'limit': None, 'offset': None}) " "and {'testid': 0}" }, contentType=b'text/plain; charset=utf-8', responseCode=404, ) @defer.inlineCallbacks def test_api_details_filter_fails(self): yield self.render_resource(self.rsrc, b'/test/13?success=false') self.assertRequest( contentJson={"error": 'this is not a collection'}, contentType=b'text/plain; charset=utf-8', responseCode=400, ) @defer.inlineCallbacks def test_api_details_fields(self): yield self.render_resource(self.rsrc, b'/test/13?field=info') self.assertRestDetails(typeName='tests', item={'info': endpoint.testData[13]['info']}) @defer.inlineCallbacks def test_api_with_accept(self): # when 'application/json' is accepted, the result has that type yield self.render_resource(self.rsrc, b'/test/13', accept=b'application/json') self.assertRestDetails( typeName='tests', item=endpoint.testData[13], contentType=b'application/json; charset=utf-8', ) @defer.inlineCallbacks def test_api_fails(self): yield self.render_resource(self.rsrc, b'/test/fail') self.assertRestError(message=r"RuntimeError\('oh noes',?\)", responseCode=500) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) def test_decode_result_spec_raise_bad_request_on_bad_property_value(self): expected_props = [None, 'test2'] self.make_request(b'/test') self.request.args = {b'property': expected_props} with self.assertRaises(InvalidQueryParameter): self.rsrc.decodeResultSpec(self.request, endpoint.TestsEndpoint) def test_decode_result_spec_limit(self): expected_limit = 5 self.make_request(b'/test') self.request.args = {b'limit': str(expected_limit)} spec = self.rsrc.decodeResultSpec(self.request, endpoint.TestsEndpoint) self.assertEqual(spec.limit, expected_limit) def test_decode_result_spec_order(self): expected_order = ('info',) self.make_request(b'/test') self.request.args = {b'order': expected_order} spec = self.rsrc.decodeResultSpec(self.request, endpoint.Test) self.assertEqual(spec.order, expected_order) def test_decode_result_spec_offset(self): expected_offset = 5 self.make_request(b'/test') self.request.args = {b'offset': str(expected_offset)} spec = self.rsrc.decodeResultSpec(self.request, endpoint.TestsEndpoint) self.assertEqual(spec.offset, expected_offset) def test_decode_result_spec_properties(self): expected_props = ['test1', 'test2'] self.make_request(b'/test') self.request.args = {b'property': expected_props} spec = self.rsrc.decodeResultSpec(self.request, endpoint.TestsEndpoint) self.assertEqual(spec.properties[0].values, expected_props) def test_decode_result_spec_not_a_collection_limit(self): def expectRaiseInvalidQueryParameter(): limit = 5 self.make_request(b'/test') self.request.args = {b'limit': limit} self.rsrc.decodeResultSpec(self.request, endpoint.TestEndpoint) with self.assertRaises(InvalidQueryParameter): expectRaiseInvalidQueryParameter() def test_decode_result_spec_not_a_collection_order(self): def expectRaiseInvalidQueryParameter(): order = ('info',) self.make_request(b'/test') self.request.args = {b'order': order} self.rsrc.decodeResultSpec(self.request, endpoint.TestEndpoint) with self.assertRaises(InvalidQueryParameter): expectRaiseInvalidQueryParameter() def test_decode_result_spec_not_a_collection_offset(self): def expectRaiseInvalidQueryParameter(): offset = 0 self.make_request(b'/test') self.request.args = {b'offset': offset} self.rsrc.decodeResultSpec(self.request, endpoint.TestEndpoint) with self.assertRaises(InvalidQueryParameter): expectRaiseInvalidQueryParameter() def test_decode_result_spec_not_a_collection_properties(self): expected_props = ['test1', 'test2'] self.make_request(b'/test') self.request.args = {b'property': expected_props} spec = self.rsrc.decodeResultSpec(self.request, endpoint.TestEndpoint) self.assertEqual(spec.properties[0].values, expected_props) @defer.inlineCallbacks def test_authz_forbidden(self): def deny(request, ep, action, options): if "test" in ep: raise authz.Forbidden("no no") return None self.master.www.assertUserAllowed = deny yield self.render_resource(self.rsrc, b'/test') self.assertRestAuthError(message=re.compile('no no'), responseCode=403) def assertRestAuthError(self, message, responseCode=400): got = {} got['contentType'] = self.request.headers[b'content-type'] got['responseCode'] = self.request.responseCode content = json.loads(bytes2unicode(self.request.written)) if 'error' not in content: self.fail(f"response does not have proper error form: {content!r}") got['error'] = content['error'] exp = {} exp['contentType'] = [b'text/plain; charset=utf-8'] exp['responseCode'] = responseCode exp['error'] = message # process a regular expression for message, if given if not isinstance(message, str): if message.match(got['error']): exp['error'] = got['error'] else: exp['error'] = f"MATCHING: {message.pattern}" self.assertEqual(got, exp) class V2RootResource_JSONRPC2(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='h:/') def allow(*args, **kw): return self.master.www.assertUserAllowed = allow self.master.data._scanModule(endpoint) self.rsrc = rest.V2RootResource(self.master) self.rsrc.reconfigResource(self.master.config) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def assertJsonRpcError(self, message, responseCode=400, jsonrpccode=None): got = {} got['contentType'] = self.request.headers[b'content-type'] got['responseCode'] = self.request.responseCode content = json.loads(bytes2unicode(self.request.written)) if 'error' not in content or sorted(content['error'].keys()) != ['code', 'message']: self.fail(f"response does not have proper error form: {content!r}") got['error'] = content['error'] exp = {} exp['contentType'] = [b'application/json'] exp['responseCode'] = responseCode exp['error'] = {'code': jsonrpccode, 'message': message} # process a regular expression for message, if given if not isinstance(message, str): if message.match(got['error']['message']): exp['error']['message'] = got['error']['message'] else: exp['error']['message'] = f"MATCHING: {message.pattern}" self.assertEqual(got, exp) @defer.inlineCallbacks def test_invalid_path(self): yield self.render_control_resource(self.rsrc, b'/not/found') self.assertJsonRpcError( message='Invalid path: not/found', jsonrpccode=JSONRPC_CODES['invalid_request'], responseCode=404, ) @defer.inlineCallbacks def test_invalid_action(self): yield self.render_control_resource(self.rsrc, b'/test', action='nosuch') self.assertJsonRpcError( message='action: nosuch is not supported', jsonrpccode=JSONRPC_CODES['method_not_found'], responseCode=501, ) @defer.inlineCallbacks def test_invalid_json(self): yield self.render_control_resource(self.rsrc, b'/test', requestJson="{abc") self.assertJsonRpcError( message=re.compile('^JSON parse error'), jsonrpccode=JSONRPC_CODES['parse_error'] ) @defer.inlineCallbacks def test_invalid_content_type(self): yield self.render_control_resource( self.rsrc, b'/test', requestJson='{"jsonrpc": "2.0", "method": "foo","id":"abcdef", "params": {}}', content_type='application/x-www-form-urlencoded', ) self.assertJsonRpcError( message=re.compile('Invalid content-type'), jsonrpccode=JSONRPC_CODES['invalid_request'] ) @defer.inlineCallbacks def test_list_request(self): yield self.render_control_resource(self.rsrc, b'/test', requestJson="[1,2]") self.assertJsonRpcError( message="JSONRPC batch requests are not supported", jsonrpccode=JSONRPC_CODES['invalid_request'], ) @defer.inlineCallbacks def test_bad_req_type(self): yield self.render_control_resource(self.rsrc, b'/test', requestJson='"a string?!"') self.assertJsonRpcError( message="JSONRPC root object must be an object", jsonrpccode=JSONRPC_CODES['invalid_request'], ) @defer.inlineCallbacks def do_test_invalid_req(self, requestJson, message): yield self.render_control_resource(self.rsrc, b'/test', requestJson=requestJson) self.assertJsonRpcError(message=message, jsonrpccode=JSONRPC_CODES['invalid_request']) def test_bad_req_jsonrpc_missing(self): return self.do_test_invalid_req( '{"method": "foo", "id":"abcdef", "params": {}}', "missing key 'jsonrpc'" ) def test_bad_req_jsonrpc_type(self): return self.do_test_invalid_req( '{"jsonrpc": 13, "method": "foo", "id":"abcdef", "params": {}}', "'jsonrpc' must be a string", ) def test_bad_req_jsonrpc_value(self): return self.do_test_invalid_req( '{"jsonrpc": "3.0", "method": "foo", "id":"abcdef", "params": {}}', "only JSONRPC 2.0 is supported", ) def test_bad_req_method_missing(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "id":"abcdef", "params": {}}', "missing key 'method'" ) def test_bad_req_method_type(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "method": 999, "id":"abcdef", "params": {}}', "'method' must be a string", ) def test_bad_req_id_missing(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "method": "foo", "params": {}}', "missing key 'id'" ) def test_bad_req_id_type(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "method": "foo", "id": {}, "params": {}}', "'id' must be a string, number, or null", ) def test_bad_req_params_missing(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "method": "foo", "id": "abc"}', "missing key 'params'" ) def test_bad_req_params_type(self): return self.do_test_invalid_req( '{"jsonrpc": "2.0", "method": "foo", "id": "abc", "params": 999}', "'params' must be an object", ) @defer.inlineCallbacks def test_valid(self): yield self.render_control_resource( self.rsrc, b'/test/13', action="testy", params={'foo': 3, 'bar': 5} ) self.assertRequest( contentJson={ 'id': self.UUID, 'jsonrpc': '2.0', 'result': { 'action': 'testy', 'args': {'foo': 3, 'bar': 5, 'owner': 'anonymous'}, 'kwargs': {'testid': 13}, }, }, contentType=b'application/json', responseCode=200, ) @defer.inlineCallbacks def test_valid_int_id(self): yield self.render_control_resource( self.rsrc, b'/test/13', action="testy", params={'foo': 3, 'bar': 5}, id=1823 ) self.assertRequest( contentJson={ 'id': 1823, 'jsonrpc': '2.0', 'result': { 'action': 'testy', 'args': { 'foo': 3, 'bar': 5, 'owner': 'anonymous', }, 'kwargs': {'testid': 13}, }, }, contentType=b'application/json', responseCode=200, ) @defer.inlineCallbacks def test_valid_fails(self): yield self.render_control_resource(self.rsrc, b'/test/13', action="fail") self.assertJsonRpcError( message=re.compile('^RuntimeError'), jsonrpccode=JSONRPC_CODES['internal_error'], responseCode=500, ) # the error gets logged, too: self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) @defer.inlineCallbacks def test_authz_forbidden(self): def deny(request, ep, action, options): if "13" in ep: raise authz.Forbidden("no no") return None self.master.www.assertUserAllowed = deny yield self.render_control_resource(self.rsrc, b'/test/13', action="fail") self.assertJsonRpcError( message=re.compile('no no'), jsonrpccode=JSONRPC_CODES['invalid_request'], responseCode=403, ) @defer.inlineCallbacks def test_owner_without_email(self): self.master.session.user_info = { "username": "defunkt", "full_name": "Defunkt user", } yield self.render_control_resource(self.rsrc, b'/test/13', action="testy") self.assertRequest( contentJson={ 'id': self.UUID, 'jsonrpc': '2.0', 'result': { 'action': 'testy', 'args': {'owner': 'defunkt'}, 'kwargs': {'testid': 13}, }, }, contentType=b'application/json', responseCode=200, ) @defer.inlineCallbacks def test_owner_with_only_full_name(self): self.master.session.user_info = { "full_name": "Defunkt user", } yield self.render_control_resource(self.rsrc, b'/test/13', action="testy") self.assertRequest( contentJson={ 'id': self.UUID, 'jsonrpc': '2.0', 'result': { 'action': 'testy', 'args': {'owner': 'Defunkt user'}, 'kwargs': {'testid': 13}, }, }, contentType=b'application/json', responseCode=200, ) @defer.inlineCallbacks def test_owner_with_email(self): self.master.session.user_info = { "email": "[email protected]", "username": "defunkt", "full_name": "Defunkt user", } yield self.render_control_resource(self.rsrc, b'/test/13', action="testy") self.assertRequest( contentJson={ 'id': self.UUID, 'jsonrpc': '2.0', 'result': { 'action': 'testy', 'args': {'owner': '[email protected]'}, 'kwargs': {'testid': 13}, }, }, contentType=b'application/json', responseCode=200, ) class ContentTypeParser(unittest.TestCase): def test_simple(self): self.assertEqual(rest.ContentTypeParser(b"application/json").gettype(), "application/json") def test_complex(self): self.assertEqual( rest.ContentTypeParser(b"application/json; Charset=UTF-8").gettype(), "application/json" ) def test_text(self): self.assertEqual( rest.ContentTypeParser(b"text/plain; Charset=UTF-8").gettype(), "text/plain" )
39,385
Python
.py
917
33.032715
100
0.608445
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,357
test_config.py
buildbot_buildbot/master/buildbot/test/unit/www/test_config.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 import os from unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import www from buildbot.util import bytes2unicode from buildbot.www import auth from buildbot.www import config class Utils(unittest.TestCase): def test_serialize_www_frontend_theme_to_css(self): self.maxDiff = None self.assertEqual( config.serialize_www_frontend_theme_to_css({}, indent=4), """\ --bb-sidebar-background-color: #30426a; --bb-sidebar-header-background-color: #273759; --bb-sidebar-header-text-color: #fff; --bb-sidebar-title-text-color: #627cb7; --bb-sidebar-footer-background-color: #273759; --bb-sidebar-button-text-color: #b2bfdc; --bb-sidebar-button-hover-background-color: #1b263d; --bb-sidebar-button-hover-text-color: #fff; --bb-sidebar-button-current-background-color: #273759; --bb-sidebar-button-current-text-color: #b2bfdc; --bb-sidebar-stripe-hover-color: #e99d1a; --bb-sidebar-stripe-current-color: #8c5e10;""", ) class TestConfigResource(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_render(self): _auth = auth.NoAuth() _auth.maybeAutoLogin = mock.Mock() custom_versions = [['test compoent', '0.1.2'], ['test component 2', '0.2.1']] master = yield self.make_master(url='h:/a/b/', auth=_auth, versions=custom_versions) rsrc = config.ConfigResource(master) rsrc.reconfigResource(master.config) vjson = [list(v) for v in config.get_environment_versions()] + custom_versions res = yield self.render_resource(rsrc, b'/config') res = json.loads(bytes2unicode(res)) exp = { "authz": {}, "titleURL": "http://buildbot.net/", "versions": vjson, "title": "Buildbot", "auth": {"name": "NoAuth"}, "user": {"anonymous": True}, "buildbotURL": "h:/a/b/", "multiMaster": False, "port": None, } self.assertEqual(res, exp) class IndexResourceTest(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def get_react_base_path(self): path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) for _ in range(0, 4): path = os.path.dirname(path) return os.path.join(path, 'www/base') def find_matching_line(self, lines, match, start_i): for i in range(start_i, len(lines)): if match in lines[i]: return i return None def extract_config_json(self, res): lines = res.split('\n') first_line = self.find_matching_line(lines, '<script id="bb-config">', 0) if first_line is None: raise RuntimeError("Could not find first config line") first_line += 1 last_line = self.find_matching_line(lines, '</script>', first_line) if last_line is None: raise RuntimeError("Could not find last config line") config_json = '\n'.join(lines[first_line:last_line]) config_json = config_json.replace('window.buildbotFrontendConfig = ', '').strip() config_json = config_json.strip(';').strip() return json.loads(config_json) @parameterized.expand([ ('anonymous_user', None, {'anonymous': True}), ( 'logged_in_user', {"name": 'me', "email": '[email protected]'}, {"email": "[email protected]", "name": "me"}, ), ]) @defer.inlineCallbacks def test_render(self, name, user_info, expected_user): _auth = auth.NoAuth() _auth.maybeAutoLogin = mock.Mock() custom_versions = [['test compoent', '0.1.2'], ['test component 2', '0.2.1']] master = yield self.make_master( url='h:/a/b/', auth=_auth, versions=custom_versions, plugins={} ) if user_info is not None: master.session.user_info = user_info # IndexResource only uses static path to get index.html. In the source checkout # index.html resides not in www/base/public but in www/base. Thus # base path is sent to IndexResource. rsrc = config.IndexResource(master, self.get_react_base_path()) rsrc.reconfigResource(master.config) vjson = [list(v) for v in config.get_environment_versions()] + custom_versions res = yield self.render_resource(rsrc, b'/') config_json = self.extract_config_json(bytes2unicode(res)) _auth.maybeAutoLogin.assert_called_with(mock.ANY) exp = { "authz": {}, "titleURL": "http://buildbot.net/", "versions": vjson, "title": "Buildbot", "auth": {"name": "NoAuth"}, "user": expected_user, "buildbotURL": "h:/a/b/", "multiMaster": False, "port": None, "plugins": {}, } self.assertEqual(config_json, exp)
6,163
Python
.py
142
35.690141
92
0.64002
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,358
test_ldapuserinfo.py
buildbot_buildbot/master/buildbot/test/unit/www/test_ldapuserinfo.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 types from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.test.reactor import TestReactorMixin from buildbot.test.util.www import WwwTestMixin from buildbot.www import avatar from buildbot.www import ldapuserinfo try: import ldap3 except ImportError: ldap3 = None def get_config_parameter(p): params = {'DEFAULT_SERVER_ENCODING': 'utf-8'} return params[p] fake_ldap = types.ModuleType('ldap3') fake_ldap.SEARCH_SCOPE_WHOLE_SUBTREE = 2 # type: ignore[attr-defined] fake_ldap.get_config_parameter = get_config_parameter # type: ignore[attr-defined] class FakeLdap: def __init__(self): def search(base, filterstr='f', scope=None, attributes=None): pass self.search = mock.Mock(spec=search) class CommonTestCase(unittest.TestCase): """Common fixture for all ldapuserinfo tests we completely fake the ldap3 module, so no need to require it to run the unit tests """ if not ldap3: skip = 'ldap3 is required for LdapUserInfo tests' def setUp(self): self.ldap = FakeLdap() self.makeUserInfoProvider() self.userInfoProvider.connectLdap = lambda: self.ldap def search(base, filterstr='f', attributes=None): pass self.userInfoProvider.search = mock.Mock(spec=search) def makeUserInfoProvider(self): """To be implemented by subclasses""" raise NotImplementedError def _makeSearchSideEffect(self, attribute_type, ret): ret = [[{'dn': i[0], attribute_type: i[1]} for i in r] for r in ret] self.userInfoProvider.search.side_effect = ret def makeSearchSideEffect(self, ret): return self._makeSearchSideEffect('attributes', ret) def makeRawSearchSideEffect(self, ret): return self._makeSearchSideEffect('raw_attributes', ret) def assertSearchCalledWith(self, exp): got = self.userInfoProvider.search.call_args_list self.assertEqual(len(exp), len(got)) for i, val in enumerate(exp): self.assertEqual(val[0][0], got[i][0][1]) self.assertEqual(val[0][1], got[i][0][2]) self.assertEqual(val[0][2], got[i][1]['attributes']) class LdapUserInfo(CommonTestCase): def makeUserInfoProvider(self): self.userInfoProvider = ldapuserinfo.LdapUserInfo( uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", groupBase="groupbase", accountPattern="accpattern", groupMemberPattern="groupMemberPattern", accountFullName="accountFullName", accountEmail="accountEmail", groupName="groupName", avatarPattern="avatar", avatarData="picture", accountExtraFields=["myfield"], ) @defer.inlineCallbacks def test_updateUserInfoNoResults(self): self.makeSearchSideEffect([[], [], []]) try: yield self.userInfoProvider.getUserInfo("me") except KeyError as e: self.assertRegex( repr(e), r"KeyError\('ldap search \"accpattern\" returned 0 results',?\)" ) else: self.fail("should have raised a key error") @defer.inlineCallbacks def test_updateUserInfoNoGroups(self): self.makeSearchSideEffect([ [("cn", {"accountFullName": "me too", "accountEmail": "mee@too"})], [], [], ]) res = yield self.userInfoProvider.getUserInfo("me") self.assertSearchCalledWith([ (('accbase', 'accpattern', ['accountEmail', 'accountFullName', 'myfield']), {}), (('groupbase', 'groupMemberPattern', ['groupName']), {}), ]) self.assertEqual( res, {'email': 'mee@too', 'full_name': 'me too', 'groups': [], 'username': 'me'} ) @defer.inlineCallbacks def test_updateUserInfoGroups(self): self.makeSearchSideEffect([ [("cn", {"accountFullName": "me too", "accountEmail": "mee@too"})], [("cn", {"groupName": ["group"]}), ("cn", {"groupName": ["group2"]})], [], ]) res = yield self.userInfoProvider.getUserInfo("me") self.assertEqual( res, { 'email': 'mee@too', 'full_name': 'me too', 'groups': ["group", "group2"], 'username': 'me', }, ) @defer.inlineCallbacks def test_updateUserInfoGroupsUnicodeDn(self): # In case of non Ascii DN, ldap3 lib returns an UTF-8 str dn = "cn=Sébastien,dc=example,dc=org" # If groupMemberPattern is an str, and dn is not decoded, # the resulting filter will be an str, leading to UnicodeDecodeError # in ldap3.protocol.convert.validate_assertion_value() # So we use an unicode pattern: self.userInfoProvider.groupMemberPattern = '(member=%(dn)s)' self.makeSearchSideEffect([ [(dn, {"accountFullName": "me too", "accountEmail": "mee@too"})], [("cn", {"groupName": ["group"]}), ("cn", {"groupName": ["group2"]})], [], ]) res = yield self.userInfoProvider.getUserInfo("me") self.assertEqual( res, { 'email': 'mee@too', 'full_name': 'me too', 'groups': ["group", "group2"], 'username': 'me', }, ) class LdapAvatar(CommonTestCase, TestReactorMixin, WwwTestMixin): @defer.inlineCallbacks def setUp(self): CommonTestCase.setUp(self) self.setup_test_reactor(auto_tear_down=False) master = yield self.make_master(url='http://a/b/', avatar_methods=[self.userInfoProvider]) self.rsrc = avatar.AvatarResource(master) self.rsrc.reconfigResource(master.config) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeUserInfoProvider(self): self.userInfoProvider = ldapuserinfo.LdapUserInfo( uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", groupBase="groupbase", accountPattern="accpattern=%(username)s", groupMemberPattern="groupMemberPattern", accountFullName="accountFullName", accountEmail="accountEmail", groupName="groupName", avatarPattern="avatar=%(email)s", avatarData="picture", accountExtraFields=["myfield"], ) @defer.inlineCallbacks def _getUserAvatar(self, mimeTypeAndData): _, data = mimeTypeAndData self.makeRawSearchSideEffect([[("cn", {"picture": [data]})]]) res = yield self.render_resource(self.rsrc, b'/?email=me') self.assertSearchCalledWith([ (('accbase', 'avatar=me', ['picture']), {}), ]) return res @defer.inlineCallbacks def test_getUserAvatarPNG(self): mimeTypeAndData = (b'image/png', b'\x89PNG lljklj') yield self._getUserAvatar(mimeTypeAndData) self.assertRequest(contentType=mimeTypeAndData[0], content=mimeTypeAndData[1]) @defer.inlineCallbacks def test_getUserAvatarJPEG(self): mimeTypeAndData = (b'image/jpeg', b'\xff\xd8\xff lljklj') yield self._getUserAvatar(mimeTypeAndData) self.assertRequest(contentType=mimeTypeAndData[0], content=mimeTypeAndData[1]) @defer.inlineCallbacks def test_getUserAvatarGIF(self): mimeTypeAndData = (b'image/gif', b'GIF8 lljklj') yield self._getUserAvatar(mimeTypeAndData) self.assertRequest(contentType=mimeTypeAndData[0], content=mimeTypeAndData[1]) @defer.inlineCallbacks def test_getUserAvatarUnknownType(self): mimeTypeAndData = (b'', b'unknown image format') res = yield self._getUserAvatar(mimeTypeAndData) # Unknown format means data won't be sent self.assertEqual(res, {"redirected": b'img/nobody.png'}) @defer.inlineCallbacks def test_getUsernameAvatar(self): mimeType = b'image/gif' data = b'GIF8 lljklj' self.makeRawSearchSideEffect([[("cn", {"picture": [data]})]]) yield self.render_resource(self.rsrc, b'/?username=me') self.assertSearchCalledWith([ (('accbase', 'accpattern=me', ['picture']), {}), ]) self.assertRequest(contentType=mimeType, content=data) @defer.inlineCallbacks def test_getUnknownUsernameAvatar(self): self.makeSearchSideEffect([[], [], []]) res = yield self.render_resource(self.rsrc, b'/?username=other') self.assertSearchCalledWith([ (('accbase', 'accpattern=other', ['picture']), {}), ]) self.assertEqual(res, {"redirected": b'img/nobody.png'}) class LdapUserInfoNotEscCharsDn(CommonTestCase): def makeUserInfoProvider(self): self.userInfoProvider = ldapuserinfo.LdapUserInfo( uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", groupBase="groupbase", accountPattern="accpattern", groupMemberPattern="(member=%(dn)s)", accountFullName="accountFullName", accountEmail="accountEmail", groupName="groupName", avatarPattern="avatar", avatarData="picture", ) @defer.inlineCallbacks def test_getUserInfoGroupsNotEscCharsDn(self): dn = "cn=Lastname, Firstname \28UIDxxx\29,dc=example,dc=org" pattern = self.userInfoProvider.groupMemberPattern % {"dn": dn} self.makeSearchSideEffect([ [(dn, {"accountFullName": "Lastname, Firstname (UIDxxx)", "accountEmail": "mee@too"})], [("cn", {"groupName": ["group"]}), ("cn", {"groupName": ["group2"]})], [], ]) res = yield self.userInfoProvider.getUserInfo("me") self.assertSearchCalledWith([ (('accbase', 'accpattern', ['accountEmail', 'accountFullName']), {}), (('groupbase', pattern, ['groupName']), {}), ]) self.assertEqual( res, { 'email': 'mee@too', 'full_name': 'Lastname, Firstname (UIDxxx)', 'groups': ["group", "group2"], 'username': 'me', }, ) class LdapUserInfoNoGroups(CommonTestCase): def makeUserInfoProvider(self): self.userInfoProvider = ldapuserinfo.LdapUserInfo( uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", accountPattern="accpattern", accountFullName="accountFullName", accountEmail="accountEmail", avatarPattern="avatar", avatarData="picture", accountExtraFields=["myfield"], ) @defer.inlineCallbacks def test_updateUserInfo(self): self.makeSearchSideEffect([ [("cn", {"accountFullName": "me too", "accountEmail": "mee@too"})], [], [], ]) res = yield self.userInfoProvider.getUserInfo("me") self.assertSearchCalledWith([ (('accbase', 'accpattern', ['accountEmail', 'accountFullName', 'myfield']), {}), ]) self.assertEqual( res, {'email': 'mee@too', 'full_name': 'me too', 'groups': [], 'username': 'me'} ) class Config(unittest.TestCase): if not ldap3: skip = 'ldap3 is required for LdapUserInfo tests' def test_missing_group_name(self): with self.assertRaises(ValueError): ldapuserinfo.LdapUserInfo( groupMemberPattern="member=%(dn)s", groupBase="grpbase", uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", accountPattern="accpattern", accountFullName="accountFullName", accountEmail="accountEmail", ) def test_missing_group_base(self): with self.assertRaises(ValueError): ldapuserinfo.LdapUserInfo( groupMemberPattern="member=%(dn)s", groupName="group", uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", accountPattern="accpattern", accountFullName="accountFullName", accountEmail="accountEmail", ) def test_missing_two_params(self): with self.assertRaises(ValueError): ldapuserinfo.LdapUserInfo( groupName="group", uri="ldap://uri", bindUser="user", bindPw="pass", accountBase="accbase", accountPattern="accpattern", accountFullName="accountFullName", accountEmail="accountEmail", )
13,903
Python
.py
336
31.607143
99
0.607756
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,359
test_hooks_github.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_github.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 hmac import platform from copy import deepcopy from hashlib import sha1 from io import BytesIO from twisted.internet import defer from twisted.trial import unittest from buildbot.plugins import util from buildbot.secrets.manager import SecretManager from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.util import unicode2bytes from buildbot.www.change_hook import ChangeHookResource from buildbot.www.hooks.github import _HEADER_EVENT from buildbot.www.hooks.github import _HEADER_SIGNATURE from buildbot.www.hooks.github import GitHubEventHandler # Sample GITHUB commit payload from http://help.github.com/post-receive-hooks/ # Added "modified" and "removed", and change email # Added "head_commit" # https://developer.github.com/v3/activity/events/types/#webhook-payload-example-26 gitJsonPayload = b""" { "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", "repository": { "url": "http://github.com/defunkt/github", "html_url": "http://github.com/defunkt/github", "name": "github", "full_name": "defunkt/github", "description": "You're lookin' at it.", "watchers": 5, "forks": 2, "private": 1, "owner": { "email": "[email protected]", "name": "defunkt" } }, "commits": [ { "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", "distinct": true, "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "okay i give in", "timestamp": "2008-02-15T14:57:17-08:00", "added": ["filepath.rb"] }, { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] } ], "head_commit": { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] }, "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", "ref": "refs/heads/master" } """ gitJsonPayloadCiSkipTemplate = """ { "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", "repository": { "url": "http://github.com/defunkt/github", "html_url": "http://github.com/defunkt/github", "name": "github", "full_name": "defunkt/github", "description": "You're lookin' at it.", "watchers": 5, "forks": 2, "private": 1, "owner": { "email": "[email protected]", "name": "defunkt" } }, "commits": [ { "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", "distinct": true, "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "okay i give in", "timestamp": "2008-02-15T14:57:17-08:00", "added": ["filepath.rb"] }, { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad %(skip)s", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] } ], "head_commit": { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad %(skip)s", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] }, "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", "ref": "refs/heads/master" } """ gitJsonPayloadTag = b""" { "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", "repository": { "url": "http://github.com/defunkt/github", "html_url": "http://github.com/defunkt/github", "name": "github", "full_name": "defunkt/github", "description": "You're lookin' at it.", "watchers": 5, "forks": 2, "private": 1, "owner": { "email": "[email protected]", "name": "defunkt" } }, "commits": [ { "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", "distinct": true, "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "okay i give in", "timestamp": "2008-02-15T14:57:17-08:00", "added": ["filepath.rb"] }, { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] } ], "head_commit": { "id": "de8251ff97ee194a289832576287d6f8ad74e3d0", "url": "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "update pricing a tad", "timestamp": "2008-02-15T14:36:34-08:00", "modified": ["modfile"], "removed": ["removedFile"] }, "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", "ref": "refs/tags/v1.0.0" } """ gitJsonPayloadNonBranch = b""" { "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", "repository": { "url": "http://github.com/defunkt/github", "html_url": "http://github.com/defunkt/github", "name": "github", "full_name": "defunkt/github", "description": "You're lookin' at it.", "watchers": 5, "forks": 2, "private": 1, "owner": { "email": "[email protected]", "name": "defunkt" } }, "commits": [ { "id": "41a212ee83ca127e3c8cf465891ab7216a705f59", "distinct": true, "url": "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", "author": { "email": "[email protected]", "name": "Fred Flinstone" }, "committer": { "email": "[email protected]", "name": "Freddy Flinstone" }, "message": "okay i give in", "timestamp": "2008-02-15T14:57:17-08:00", "added": ["filepath.rb"] } ], "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", "ref": "refs/garbage/master" } """ gitJsonPayloadPullRequest = b""" { "action": "opened", "number": 50, "pull_request": { "url": "https://api.github.com/repos/defunkt/github/pulls/50", "html_url": "https://github.com/defunkt/github/pull/50", "number": 50, "state": "open", "title": "Update the README with new information", "user": { "login": "defunkt", "id": 42, "type": "User" }, "body": "This is a pretty simple change that we need to pull into master.", "created_at": "2014-10-10T00:09:50Z", "updated_at": "2014-10-10T00:09:50Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "cd3ff078a350901f91f4c4036be74f91d0b0d5d6", "head": { "label": "defunkt:changes", "ref": "changes", "sha": "05c588ba8cd510ecbe112d020f215facb17817a7", "user": { "login": "defunkt", "id": 42, "type": "User" }, "repo": { "id": 43, "name": "github", "full_name": "defunkt/github", "owner": { "login": "defunkt", "id": 42, "type": "User" }, "html_url": "https://github.com/defunkt/github", "description": "", "url": "https://api.github.com/repos/defunkt/github", "created_at": "2014-05-20T22:39:43Z", "updated_at": "2014-07-25T16:37:51Z", "pushed_at": "2014-10-10T00:09:49Z", "git_url": "git://github.com/defunkt/github.git", "ssh_url": "[email protected]:defunkt/github.git", "clone_url": "https://github.com/defunkt/github.git", "default_branch": "master" } }, "base": { "label": "defunkt:master", "ref": "master", "sha": "69a8b72e2d3d955075d47f03d902929dcaf74034", "user": { "login": "defunkt", "id": 42, "type": "User" }, "repo": { "id": 43, "name": "github", "full_name": "defunkt/github", "owner": { "login": "defunkt", "id": 42, "type": "User" }, "html_url": "https://github.com/defunkt/github", "description": "", "url": "https://api.github.com/repos/defunkt/github", "created_at": "2014-05-20T22:39:43Z", "updated_at": "2014-07-25T16:37:51Z", "pushed_at": "2014-10-10T00:09:49Z", "git_url": "git://github.com/defunkt/github.git", "ssh_url": "[email protected]:defunkt/github.git", "clone_url": "https://github.com/defunkt/github.git", "default_branch": "master" } }, "_links": { "self": { "href": "https://api.github.com/repos/defunkt/github/pulls/50" }, "html": { "href": "https://github.com/defunkt/github/pull/50" }, "commits": { "href": "https://api.github.com/repos/defunkt/github/pulls/50/commits" } }, "commits": 1, "additions": 2, "deletions": 0, "changed_files": 1 }, "repository": { "id": 43, "name": "github", "full_name": "defunkt/github", "owner": { "login": "defunkt", "id": 42, "type": "User" }, "html_url": "https://github.com/defunkt/github", "description": "", "url": "https://api.github.com/repos/defunkt/github", "created_at": "2014-05-20T22:39:43Z", "updated_at": "2014-07-25T16:37:51Z", "pushed_at": "2014-10-10T00:09:49Z", "git_url": "git://github.com/defunkt/github.git", "ssh_url": "[email protected]:defunkt/github.git", "clone_url": "https://github.com/defunkt/github.git", "default_branch": "master" }, "sender": { "login": "defunkt", "id": 42, "type": "User" } } """ gitJsonPayloadCommit = { "sha": "de8251ff97ee194a289832576287d6f8ad74e3d0", "commit": { "author": { "name": "defunkt", "email": "[email protected]", "date": "2017-02-12T14:39:33Z", }, "committer": { "name": "defunkt", "email": "[email protected]", "date": "2017-02-12T14:51:05Z", }, "message": "black magic", "tree": {}, "url": "...", "comment_count": 0, }, "url": "...", "html_url": "...", "comments_url": "...", "author": {}, "committer": {}, "parents": [], "stats": {}, "files": [], } gitJsonPayloadFiles = [{"filename": "README.md", "previous_filename": "old_README.md"}] gitPRproperties = { 'pullrequesturl': 'https://github.com/defunkt/github/pull/50', 'github.head.sha': '05c588ba8cd510ecbe112d020f215facb17817a7', 'github.state': 'open', 'github.base.repo.full_name': 'defunkt/github', 'github.number': 50, 'github.base.ref': 'master', 'github.base.sha': '69a8b72e2d3d955075d47f03d902929dcaf74034', 'github.head.repo.full_name': 'defunkt/github', 'github.merged_at': None, 'github.head.ref': 'changes', 'github.closed_at': None, 'github.title': 'Update the README with new information', 'event': 'pull_request', } gitJsonPayloadEmpty = b""" { "before": "5aef35982fb2d34e9d9d4502f6ede1072793222d", "repository": { "url": "http://github.com/defunkt/github", "html_url": "http://github.com/defunkt/github", "name": "github", "full_name": "defunkt/github", "description": "You're lookin' at it.", "watchers": 5, "forks": 2, "private": 1, "owner": { "email": "[email protected]", "name": "defunkt" } }, "commits": [ ], "head_commit": { }, "after": "de8251ff97ee194a289832576287d6f8ad74e3d0", "ref": "refs/heads/master" } """ gitJsonPayloadCreateTag = b""" { "ref": "refs/tags/v0.9.15.post1", "before": "0000000000000000000000000000000000000000", "after": "ffe1e9affb2b5399369443194c02068032f9295e", "created": true, "deleted": false, "forced": false, "base_ref": null, "compare": "https://github.com/buildbot/buildbot/compare/v0.9.15.post1", "commits": [ ], "head_commit": { "id": "57df618a4a450410c1dee440c7827ee105f5a226", "tree_id": "f9768673dc968b5c8fcbb15f119ce237b50b3252", "distinct": true, "message": "...", "timestamp": "2018-01-07T16:30:52+01:00", "url": "https://github.com/buildbot/buildbot/commit/...", "author": { "name": "User", "email": "[email protected]", "username": "userid" }, "committer": { "name": "GitHub", "email": "[email protected]", "username": "web-flow" }, "added": [ ], "removed": [ "master/buildbot/newsfragments/bit_length.bugfix", "master/buildbot/newsfragments/localworker_umask.bugfix", "master/buildbot/newsfragments/svn-utf8.bugfix" ], "modified": [ ".bbtravis.yml", "circle.yml", "master/docs/relnotes/index.rst" ] }, "repository": { "html_url": "https://github.com/buildbot/buildbot", "name": "buildbot", "full_name": "buildbot" }, "pusher": { "name": "userid", "email": "[email protected]" }, "organization": { "login": "buildbot", "url": "https://api.github.com/orgs/buildbot", "description": "Continous integration and delivery framework" }, "sender": { "login": "userid", "gravatar_id": "", "type": "User", "site_admin": false }, "ref_name": "v0.9.15.post1", "distinct_commits": [ ] }""" gitJsonPayloadNotFound = b"""{"message":"Not Found"}""" _HEADER_CT = b'Content-Type' _CT_ENCODED = b'application/x-www-form-urlencoded' _CT_JSON = b'application/json' @defer.inlineCallbacks def _prepare_github_change_hook(testcase, **params): master = yield fakeMasterForHooks(testcase) return ChangeHookResource(dialects={'github': params}, master=master) def _prepare_request(event, payload, _secret=None, headers=None): if headers is None: headers = {} request = FakeRequest() request.uri = b"/change_hook/github" request.method = b"GET" request.received_headers = {_HEADER_EVENT: event} assert isinstance( payload, (bytes, list) ), f"payload can only be bytes or list, not {type(payload)}" if isinstance(payload, bytes): request.content = BytesIO(payload) request.received_headers[_HEADER_CT] = _CT_JSON if _secret is not None: signature = hmac.new(unicode2bytes(_secret), msg=unicode2bytes(payload), digestmod=sha1) request.received_headers[_HEADER_SIGNATURE] = f'sha1={signature.hexdigest()}' else: request.args[b'payload'] = payload request.received_headers[_HEADER_CT] = _CT_ENCODED request.received_headers.update(headers) # print request.received_headers return request class TestChangeHookConfiguredWithGitChange(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_property_whitelist=["github.*"] ) self.master = self.changeHook.master fake_headers = {'User-Agent': 'Buildbot'} self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def assertDictSubset(self, expected_dict, response_dict): expected = {} for key in expected_dict.keys(): self.assertIn(key, set(response_dict.keys())) expected[key] = response_dict[key] self.assertDictEqual(expected_dict, expected) @defer.inlineCallbacks def test_unknown_event(self): bad_event = b'whatever' self.request = _prepare_request(bad_event, gitJsonPayload) yield self.request.test_render(self.changeHook) expected = b'Unknown event: ' + bad_event self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) @defer.inlineCallbacks def test_unknown_content_type(self): bad_content_type = b'application/x-useful' self.request = _prepare_request( b'push', gitJsonPayload, headers={_HEADER_CT: bad_content_type} ) yield self.request.test_render(self.changeHook) expected = b'Unknown content type: ' self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertIn(expected, self.request.written) @defer.inlineCallbacks def _check_ping(self, payload): self.request = _prepare_request(b'ping', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) def test_ping_encoded(self): self._check_ping([b'{}']) def test_ping_json(self): self._check_ping(b'{}') @defer.inlineCallbacks def test_git_with_push_tag(self): self.request = _prepare_request(b'push', gitJsonPayloadTag) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["branch"], "v1.0.0") self.assertEqual(change["category"], "tag") @defer.inlineCallbacks def test_git_with_push_newtag(self): self.request = _prepare_request(b'push', gitJsonPayloadCreateTag) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["author"], "User <[email protected]>") self.assertEqual(change["branch"], "v0.9.15.post1") self.assertEqual(change["category"], "tag") # Test 'base' hook with attributes. We should get a json string # representing a Change object as a dictionary. All values show be set. @defer.inlineCallbacks def _check_git_with_change(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['files'], ['filepath.rb']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203116237) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["revision"], '41a212ee83ca127e3c8cf465891ab7216a705f59') self.assertEqual(change["comments"], "okay i give in") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", ) change = self.changeHook.master.data.updates.changesAdded[1] self.assertEqual(change['files'], ['modfile', 'removedFile']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203114994) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["src"], "git") self.assertEqual(change["revision"], 'de8251ff97ee194a289832576287d6f8ad74e3d0') self.assertEqual(change["comments"], "update pricing a tad") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", ) self.assertEqual(change["properties"]["event"], "push") def test_git_with_change_encoded(self): self._check_git_with_change([gitJsonPayload]) def test_git_with_change_json(self): self._check_git_with_change(gitJsonPayload) # Test that, even with commits not marked as distinct, the changes get # recorded each time we receive the payload. This is important because # without it, commits can get pushed to a non-scheduled branch, get # recorded and associated with that branch, and then later get pushed to a # scheduled branch and not trigger a build. # # For example, if a commit is pushed to a dev branch, it then gets recorded # as a change associated with that dev branch. If that change is later # pushed to master, we still need to trigger a build even though we've seen # the commit before. @defer.inlineCallbacks def testGitWithDistinctFalse(self): self.request = _prepare_request( b'push', [gitJsonPayload.replace(b'"distinct": true,', b'"distinct": false,')] ) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['files'], ['filepath.rb']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203116237) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["revision"], '41a212ee83ca127e3c8cf465891ab7216a705f59') self.assertEqual(change["comments"], "okay i give in") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", ) self.assertEqual(change["properties"]["github_distinct"], False) change = self.changeHook.master.data.updates.changesAdded[1] self.assertEqual(change['files'], ['modfile', 'removedFile']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203114994) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["src"], "git") self.assertEqual(change["revision"], 'de8251ff97ee194a289832576287d6f8ad74e3d0') self.assertEqual(change["comments"], "update pricing a tad") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", ) @defer.inlineCallbacks def testGitWithNoJson(self): self.request = _prepare_request(b'push', b'') yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) if platform.python_implementation() == 'PyPy': expected = b"Unexpected '\x00': line 1 column 1 (char 0)" else: expected = b"Expecting value: line 1 column 1 (char 0)" self.assertIn(self.request.written, expected) self.request.setResponseCode.assert_called_with(400, expected) @defer.inlineCallbacks def _check_git_with_no_changes(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) expected = b"no change found" self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) def test_git_with_no_changes_encoded(self): self._check_git_with_no_changes([gitJsonPayloadEmpty]) def test_git_with_no_changes_json(self): self._check_git_with_no_changes(gitJsonPayloadEmpty) @defer.inlineCallbacks def _check_git_with_non_branch_changes(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) expected = b"no change found" self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) def test_git_with_non_branch_changes_encoded(self): self._check_git_with_non_branch_changes([gitJsonPayloadNonBranch]) def test_git_with_non_branch_changes_json(self): self._check_git_with_non_branch_changes(gitJsonPayloadNonBranch) @defer.inlineCallbacks def _check_git_with_pull(self, payload): self.request = _prepare_request('pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["repository"], "https://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1412899790) self.assertEqual(change["author"], "defunkt") self.assertEqual(change["revision"], '05c588ba8cd510ecbe112d020f215facb17817a7') self.assertEqual( change["comments"], "GitHub Pull Request #50 (1 commit)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", ) self.assertEqual(change["branch"], "refs/pull/50/merge") self.assertEqual(change['files'], []) self.assertEqual(change["revlink"], "https://github.com/defunkt/github/pull/50") self.assertEqual(change['properties']['basename'], "master") self.assertDictSubset(gitPRproperties, change["properties"]) def test_git_with_pull_encoded(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._check_git_with_pull([gitJsonPayloadPullRequest]) def test_git_with_pull_json(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._check_git_with_pull(gitJsonPayloadPullRequest) @defer.inlineCallbacks def _check_git_push_with_skip_message(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) def test_git_push_with_skip_message(self): gitJsonPayloadCiSkips = [ unicode2bytes(gitJsonPayloadCiSkipTemplate % {'skip': '[ci skip]'}), unicode2bytes(gitJsonPayloadCiSkipTemplate % {'skip': '[skip ci]'}), unicode2bytes(gitJsonPayloadCiSkipTemplate % {'skip': '[ ci skip ]'}), ] for payload in gitJsonPayloadCiSkips: self._check_git_push_with_skip_message(payload) class TestChangeHookConfiguredWithGitChangeCustomPullrequestRef( unittest.TestCase, TestReactorMixin ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_property_whitelist=["github.*"], pullrequest_ref="head" ) self.master = self.changeHook.master fake_headers = {'User-Agent': 'Buildbot'} self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_git_pull_request_with_custom_ref(self): commit = deepcopy([gitJsonPayloadPullRequest]) commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self.request = _prepare_request('pull_request', commit) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["branch"], "refs/pull/50/head") class TestChangeHookConfiguredWithGitChangeCustomPullrequestRefWithAuth( unittest.TestCase, TestReactorMixin ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) _token = '7e076f41-b73a-4045-a817' self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_property_whitelist=["github.*"], pullrequest_ref="head", token=_token, ) self.master = self.changeHook.master fake_headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token ' + _token, } self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_git_pull_request_with_custom_ref(self): commit = deepcopy([gitJsonPayloadPullRequest]) commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self.request = _prepare_request('pull_request', commit) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["branch"], "refs/pull/50/head") class TestChangeHookRefWithAuth(unittest.TestCase, TestReactorMixin): secret_name = 'secretkey' secret_value = 'githubtoken' @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_property_whitelist=["github.*"], token=util.Secret(self.secret_name), ) self.master = self.changeHook.master fake_headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token ' + self.secret_value, } self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) fake_storage = FakeSecretStorage() secret_service = SecretManager() secret_service.services = [fake_storage] yield secret_service.setServiceParent(self.master) yield self.master.startService() fake_storage.reconfigService(secretdict={self.secret_name: self.secret_value}) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_git_pull_request(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self.request = _prepare_request('pull_request', gitJsonPayloadPullRequest) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["branch"], "refs/pull/50/merge") class TestChangeHookConfiguredWithAuthAndCustomSkips(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) _token = '7e076f41-b73a-4045-a817' self.changeHook = yield _prepare_github_change_hook( self, strict=False, skips=[r'\[ *bb *skip *\]'], token=_token ) self.master = self.changeHook.master fake_headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token ' + _token, } self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_push_with_skip_message(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) def test_push_with_skip_message(self): gitJsonPayloadCiSkips = [ unicode2bytes(gitJsonPayloadCiSkipTemplate % {'skip': '[bb skip]'}), unicode2bytes(gitJsonPayloadCiSkipTemplate % {'skip': '[ bb skip ]'}), ] for payload in gitJsonPayloadCiSkips: self._check_push_with_skip_message(payload) @defer.inlineCallbacks def _check_push_no_ci_skip(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) def test_push_no_ci_skip(self): # user overrode the skip pattern already, # so the default patterns should not work. payload = gitJsonPayloadCiSkipTemplate % {'skip': '[ci skip]'} payload = unicode2bytes(payload) self._check_push_no_ci_skip(payload) @defer.inlineCallbacks def _check_pull_request_with_skip_message(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) def test_pull_request_with_skip_message(self): api_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' commit = deepcopy(gitJsonPayloadCommit) msgs = ( 'black magic [bb skip]', 'black magic [ bb skip ]', ) for msg in msgs: commit['commit']['message'] = msg self._http.expect('get', api_endpoint, content_json=commit) self._check_pull_request_with_skip_message(gitJsonPayloadPullRequest) @defer.inlineCallbacks def _check_pull_request_no_skip(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) def test_pull_request_no_skip(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) commit = deepcopy(gitJsonPayloadCommit) commit['commit']['message'] = 'black magic [skip bb]' # pattern not matched self._check_pull_request_no_skip(gitJsonPayloadPullRequest) class TestChangeHookConfiguredWithAuth(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) _token = '7e076f41-b73a-4045-a817' self.changeHook = yield _prepare_github_change_hook( self, strict=False, token=_token, github_property_whitelist=["github.*"] ) self.master = self.changeHook.master fake_headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token ' + _token, } self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.github.com', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def assertDictSubset(self, expected_dict, response_dict): expected = {} for key in expected_dict.keys(): self.assertIn(key, set(response_dict.keys())) expected[key] = response_dict[key] self.assertDictEqual(expected_dict, expected) @defer.inlineCallbacks def _check_pull_request(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) def test_pull_request(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self._check_pull_request(gitJsonPayloadPullRequest) @defer.inlineCallbacks def _check_git_with_pull(self, payload, valid_token=True): self.request = _prepare_request('pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change["repository"], "https://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1412899790) self.assertEqual(change["author"], "defunkt") self.assertEqual(change["revision"], '05c588ba8cd510ecbe112d020f215facb17817a7') self.assertEqual( change["comments"], "GitHub Pull Request #50 (1 commit)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", ) self.assertEqual(change["branch"], "refs/pull/50/merge") if valid_token: self.assertEqual(change['files'], ['README.md', 'old_README.md']) else: self.assertEqual(change['files'], []) self.assertEqual(change["revlink"], "https://github.com/defunkt/github/pull/50") self.assertEqual(change['properties']['basename'], "master") self.assertDictSubset(gitPRproperties, change["properties"]) def test_git_with_pull_encoded(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self._check_git_with_pull([gitJsonPayloadPullRequest]) def test_git_with_pull_json(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self._check_git_with_pull(gitJsonPayloadPullRequest) def test_git_with_pull_encoded_and_bad_token(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._check_git_with_pull([gitJsonPayloadPullRequest], valid_token=False) def test_git_with_pull_json_and_bad_token(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._check_git_with_pull(gitJsonPayloadPullRequest, valid_token=False) @defer.inlineCallbacks def _check_git_pull_request_with_skip_message(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) def test_git_pull_request_with_skip_message(self): api_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' commit = deepcopy(gitJsonPayloadCommit) msgs = ( 'black magic [ci skip]', 'black magic [skip ci]', 'black magic [ ci skip ]', ) for msg in msgs: commit['commit']['message'] = msg self._http.expect('get', api_endpoint, content_json=commit) self._check_git_pull_request_with_skip_message(gitJsonPayloadPullRequest) class TestChangeHookConfiguredWithCustomApiRoot(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_api_endpoint='https://black.magic.io' ) self.master = self.changeHook.master fake_headers = {'User-Agent': 'Buildbot'} self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://black.magic.io', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_pull_request(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) def test_pull_request(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadNotFound, code=404) self._check_pull_request(gitJsonPayloadPullRequest) class TestChangeHookConfiguredWithCustomApiRootWithAuth(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) _token = '7e076f41-b73a-4045-a817' self.changeHook = yield _prepare_github_change_hook( self, strict=False, github_api_endpoint='https://black.magic.io', token=_token ) self.master = self.changeHook.master fake_headers = { 'User-Agent': 'Buildbot', 'Authorization': 'token ' + _token, } self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://black.magic.io', headers=fake_headers, debug=False, verify=False, ) yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_pull_request(self, payload): self.request = _prepare_request(b'pull_request', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) def test_pull_request(self): commit_endpoint = '/repos/defunkt/github/commits/05c588ba8cd510ecbe112d020f215facb17817a7' files_endpoint = '/repos/defunkt/github/pulls/50/files' self._http.expect('get', commit_endpoint, content_json=gitJsonPayloadCommit) self._http.expect('get', files_endpoint, content_json=gitJsonPayloadFiles) self._check_pull_request(gitJsonPayloadPullRequest) class TestChangeHookConfiguredWithStrict(unittest.TestCase, TestReactorMixin): _SECRET = 'somethingreallysecret' @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) fakeStorageService = FakeSecretStorage() fakeStorageService.reconfigService(secretdict={"secret_key": self._SECRET}) secretService = SecretManager() secretService.services = [fakeStorageService] self.changeHook = yield _prepare_github_change_hook( self, strict=True, secret=util.Secret("secret_key") ) self.changeHook.master.addService(secretService) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_signature_ok(self): self.request = _prepare_request(b'push', gitJsonPayload, _secret=self._SECRET) yield self.request.test_render(self.changeHook) # Can it somehow be merged w/ the same code above in a different class? self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['files'], ['filepath.rb']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203116237) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["revision"], '41a212ee83ca127e3c8cf465891ab7216a705f59') self.assertEqual(change["comments"], "okay i give in") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59", ) change = self.changeHook.master.data.updates.changesAdded[1] self.assertEqual(change['files'], ['modfile', 'removedFile']) self.assertEqual(change["repository"], "http://github.com/defunkt/github") self.assertEqual(change["when_timestamp"], 1203114994) self.assertEqual(change["author"], "Fred Flinstone <[email protected]>") self.assertEqual(change["committer"], "Freddy Flinstone <[email protected]>") self.assertEqual(change["src"], "git") self.assertEqual(change["revision"], 'de8251ff97ee194a289832576287d6f8ad74e3d0') self.assertEqual(change["comments"], "update pricing a tad") self.assertEqual(change["branch"], "master") self.assertEqual( change["revlink"], "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0", ) @defer.inlineCallbacks def test_unknown_hash(self): bad_hash_type = b'blah' self.request = _prepare_request( b'push', gitJsonPayload, headers={_HEADER_SIGNATURE: bad_hash_type + b'=doesnotmatter'} ) yield self.request.test_render(self.changeHook) expected = b'Unknown hash type: ' + bad_hash_type self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) @defer.inlineCallbacks def test_signature_nok(self): bad_signature = b'sha1=wrongstuff' self.request = _prepare_request( b'push', gitJsonPayload, headers={_HEADER_SIGNATURE: bad_signature} ) yield self.request.test_render(self.changeHook) expected = b'Hash mismatch' self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) @defer.inlineCallbacks def test_missing_secret(self): # override the value assigned in setUp self.changeHook = yield _prepare_github_change_hook(self, strict=True) self.request = _prepare_request(b'push', gitJsonPayload) yield self.request.test_render(self.changeHook) expected = b'Strict mode is requested while no secret is provided' self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) @defer.inlineCallbacks def test_wrong_signature_format(self): bad_signature = b'hash=value=something' self.request = _prepare_request( b'push', gitJsonPayload, headers={_HEADER_SIGNATURE: bad_signature} ) yield self.request.test_render(self.changeHook) expected = b'Wrong signature format: ' + bad_signature self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) @defer.inlineCallbacks def test_signature_missing(self): self.request = _prepare_request(b'push', gitJsonPayload) yield self.request.test_render(self.changeHook) expected = b'Request has no required signature' self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertEqual(self.request.written, expected) class TestChangeHookConfiguredWithCodebaseValue(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook(self, codebase='foobar') @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_git_with_change(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['codebase'], 'foobar') def test_git_with_change_encoded(self): return self._check_git_with_change([gitJsonPayload]) def test_git_with_change_json(self): return self._check_git_with_change(gitJsonPayload) def _codebase_function(payload): return 'foobar-' + payload['repository']['name'] class TestChangeHookConfiguredWithCodebaseFunction(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_github_change_hook(self, codebase=_codebase_function) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_git_with_change(self, payload): self.request = _prepare_request(b'push', payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 2) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['codebase'], 'foobar-github') def test_git_with_change_encoded(self): return self._check_git_with_change([gitJsonPayload]) def test_git_with_change_json(self): return self._check_git_with_change(gitJsonPayload) class TestChangeHookConfiguredWithCustomEventHandler(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) class CustomGitHubEventHandler(GitHubEventHandler): def handle_ping(self, _, __): self.master.hook_called = True return [], None self.changeHook = yield _prepare_github_change_hook( self, **{'class': CustomGitHubEventHandler} ) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_ping(self): self.request = _prepare_request(b'ping', b'{}') yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 0) self.assertTrue(self.changeHook.master.hook_called)
58,262
Python
.py
1,351
35.703183
100
0.665175
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,360
test_hooks_base.py
buildbot_buildbot/master/buildbot/test/unit/www/test_hooks_base.py
import json from twisted.internet import defer from twisted.trial import unittest from buildbot.test.fake.web import FakeRequest from buildbot.test.fake.web import fakeMasterForHooks from buildbot.test.reactor import TestReactorMixin from buildbot.util import bytes2unicode from buildbot.www.change_hook import ChangeHookResource from buildbot.www.hooks.base import BaseHookHandler @defer.inlineCallbacks def _prepare_base_change_hook(testcase, **options): master = yield fakeMasterForHooks(testcase) return ChangeHookResource(dialects={'base': options}, master=master) def _prepare_request(payload, headers=None): if headers is None: headers = {b"Content-type": b"application/x-www-form-urlencoded", b"Accept": b"text/plain"} else: headers = {} if b'comments' not in payload: payload[b'comments'] = b'test_www_hook_base submission' # Required field request = FakeRequest() request.uri = b"/change_hook/base" request.method = b"POST" request.args = payload request.received_headers.update(headers) return request class TestChangeHookConfiguredWithBase(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.changeHook = yield _prepare_base_change_hook(self) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_base_with_change(self, payload): self.request = _prepare_request(payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] def _first_or_nothing(val): if isinstance(val, type([])): val = val[0] return bytes2unicode(val) if payload.get(b'files'): files = json.loads(_first_or_nothing(payload.get(b'files'))) else: files = [] self.assertEqual(change['files'], files) if payload.get(b'properties'): props = json.loads(_first_or_nothing(payload.get(b'properties'))) else: props = {} self.assertEqual(change['properties'], props) self.assertEqual( change['author'], _first_or_nothing(payload.get(b'author', payload.get(b'who'))) ) for field in ('revision', 'committer', 'comments', 'branch', 'category', 'revlink'): self.assertEqual(change[field], _first_or_nothing(payload.get(field.encode()))) for field in ('repository', 'project'): self.assertEqual(change[field], _first_or_nothing(payload.get(field.encode())) or '') def test_base_with_no_change(self): return self._check_base_with_change({}) def test_base_with_changes(self): return self._check_base_with_change({ b'revision': [b'1234badcaca5678'], b'branch': [b'master'], b'comments': [b'Fix foo bar'], b'category': [b'bug'], b'revlink': [b'https://git.myproject.org/commit/1234badcaca5678'], b'repository': [b'myproject'], b'project': [b'myproject'], b'author': [b'me <[email protected]>'], b'committer': [b'me <[email protected]>'], b'files': [b'["src/main.c", "src/foo.c"]'], b'properties': [b'{"color": "blue", "important": true, "size": 2}'], }) class TestChangeHookConfiguredWithCustomBase(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) class CustomBase(BaseHookHandler): def getChanges(self, request): args = request.args chdict = { "revision": args.get(b'revision'), "repository": args.get(b'_repository') or '', "project": args.get(b'project') or '', "codebase": args.get(b'codebase'), } return ([chdict], None) self.changeHook = yield _prepare_base_change_hook(self, custom_class=CustomBase) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def _check_base_with_change(self, payload): self.request = _prepare_request(payload) yield self.request.test_render(self.changeHook) self.assertEqual(len(self.changeHook.master.data.updates.changesAdded), 1) change = self.changeHook.master.data.updates.changesAdded[0] self.assertEqual(change['repository'], payload.get(b'_repository') or '') def test_base_with_no_change(self): return self._check_base_with_change({b'repository': b'foo'})
4,863
Python
.py
104
37.903846
99
0.648203
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,361
test_service.py
buildbot_buildbot/master/buildbot/test/unit/www/test_service.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 calendar import datetime from unittest import mock import jwt from twisted.cred import strcred from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.internet import defer from twisted.trial import unittest from twisted.web._auth.wrapper import HTTPAuthSessionWrapper from twisted.web.server import Request from buildbot.test.reactor import TestReactorMixin from buildbot.test.unit.www import test_hooks_base from buildbot.test.util import www from buildbot.www import auth from buildbot.www import change_hook from buildbot.www import resource from buildbot.www import rest from buildbot.www import service class FakeChannel: transport = None def isSecure(self): return False def getPeer(self): return None def getHost(self): return None class NeedsReconfigResource(resource.Resource): needsReconfig = True reconfigs = 0 def reconfigResource(self, new_config): NeedsReconfigResource.reconfigs += 1 class Test(TestReactorMixin, www.WwwTestMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield self.make_master(url='h:/a/b/') self.svc = self.master.www = service.WWWService() yield self.svc.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeConfig(self, **kwargs): w = {"port": None, "auth": auth.NoAuth(), "logfileName": 'l'} w.update(kwargs) new_config = mock.Mock() new_config.www = w new_config.buildbotURL = 'h:/' self.master.config = new_config return new_config @defer.inlineCallbacks def test_reconfigService_no_port(self): new_config = self.makeConfig() yield self.svc.reconfigServiceWithBuildbotConfig(new_config) self.assertEqual(self.svc.site, None) @defer.inlineCallbacks def test_reconfigService_reconfigResources(self): new_config = self.makeConfig(port=8080) self.patch(rest, 'RestRootResource', NeedsReconfigResource) NeedsReconfigResource.reconfigs = 0 # first time, reconfigResource gets called along with setupSite yield self.svc.reconfigServiceWithBuildbotConfig(new_config) self.assertEqual(NeedsReconfigResource.reconfigs, 1) # and the next time, setupSite isn't called, but reconfigResource is yield self.svc.reconfigServiceWithBuildbotConfig(new_config) self.assertEqual(NeedsReconfigResource.reconfigs, 2) @defer.inlineCallbacks def test_reconfigService_port(self): new_config = self.makeConfig(port=20) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) self.assertNotEqual(self.svc.site, None) self.assertNotEqual(self.svc.port_service, None) self.assertEqual(self.svc.port, 20) @defer.inlineCallbacks def test_reconfigService_expiration_time(self): new_config = self.makeConfig(port=80, cookie_expiration_time=datetime.timedelta(minutes=1)) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) self.assertNotEqual(self.svc.site, None) self.assertNotEqual(self.svc.port_service, None) self.assertEqual(service.BuildbotSession.expDelay, datetime.timedelta(minutes=1)) @defer.inlineCallbacks def test_reconfigService_port_changes(self): new_config = self.makeConfig(port=20) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) newer_config = self.makeConfig(port=999) yield self.svc.reconfigServiceWithBuildbotConfig(newer_config) self.assertNotEqual(self.svc.site, None) self.assertNotEqual(self.svc.port_service, None) self.assertEqual(self.svc.port, 999) @defer.inlineCallbacks def test_reconfigService_port_changes_to_none(self): new_config = self.makeConfig(port=20) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) newer_config = self.makeConfig() yield self.svc.reconfigServiceWithBuildbotConfig(newer_config) # (note the site sticks around) self.assertEqual(self.svc.port_service, None) self.assertEqual(self.svc.port, None) def test_setupSite(self): self.svc.setupSite(self.makeConfig()) site = self.svc.site # check that it has the right kind of resources attached to its # root root = site.resource req = mock.Mock() self.assertIsInstance(root.getChildWithDefault(b'api', req), rest.RestRootResource) def test_setupSiteWithProtectedHook(self): checker = InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("guest", "password") self.svc.setupSite( self.makeConfig(change_hook_dialects={'base': True}, change_hook_auth=[checker]) ) site = self.svc.site # check that it has the right kind of resources attached to its # root root = site.resource req = mock.Mock() self.assertIsInstance(root.getChildWithDefault(b'change_hook', req), HTTPAuthSessionWrapper) @defer.inlineCallbacks def test_setupSiteWithHook(self): new_config = self.makeConfig(change_hook_dialects={'base': True}) self.svc.setupSite(new_config) site = self.svc.site # check that it has the right kind of resources attached to its # root root = site.resource req = mock.Mock() ep = root.getChildWithDefault(b'change_hook', req) self.assertIsInstance(ep, change_hook.ChangeHookResource) # not yet configured self.assertEqual(ep.dialects, {}) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) # now configured self.assertEqual(ep.dialects, {'base': True}) rsrc = self.svc.site.resource.getChildWithDefault(b'change_hook', mock.Mock()) path = b'/change_hook/base' request = test_hooks_base._prepare_request({}) self.master.data.updates.addChange = mock.Mock() yield self.render_resource(rsrc, path, request=request) self.master.data.updates.addChange.assert_called() @defer.inlineCallbacks def test_setupSiteWithHookAndAuth(self): fn = self.mktemp() with open(fn, 'w', encoding='utf-8') as f: f.write("user:pass") new_config = self.makeConfig( port=8080, plugins={}, change_hook_dialects={'base': True}, change_hook_auth=[strcred.makeChecker("file:" + fn)], ) self.svc.setupSite(new_config) yield self.svc.reconfigServiceWithBuildbotConfig(new_config) rsrc = self.svc.site.resource.getChildWithDefault(b'', mock.Mock()) res = yield self.render_resource(rsrc, b'') self.assertIn(b'{"type": "file"}', res) rsrc = self.svc.site.resource.getChildWithDefault(b'change_hook', mock.Mock()) res = yield self.render_resource(rsrc, b'/change_hook/base') # as UnauthorizedResource is in private namespace, we cannot use # assertIsInstance :-( self.assertIn('UnauthorizedResource', repr(res)) class TestBuildbotSite(unittest.SynchronousTestCase): SECRET = 'secret' def setUp(self): self.site = service.BuildbotSite(None, "logs", 0, 0) self.site.setSessionSecret(self.SECRET) def test_getSession_from_bad_jwt(self): """if the cookie is bad (maybe from previous version of buildbot), then we should raise KeyError for consumption by caller, and log the JWT error """ with self.assertRaises(KeyError): self.site.getSession("xxx") self.flushLoggedErrors(jwt.exceptions.DecodeError) def test_getSession_from_correct_jwt(self): payload = {'user_info': {'some': 'payload'}} uid = jwt.encode(payload, self.SECRET, algorithm=service.SESSION_SECRET_ALGORITHM) session = self.site.getSession(uid) self.assertEqual(session.user_info, {'some': 'payload'}) def test_getSession_from_expired_jwt(self): # expired one week ago exp = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(weeks=1) exp = calendar.timegm(datetime.datetime.timetuple(exp)) payload = {'user_info': {'some': 'payload'}, 'exp': exp} uid = jwt.encode(payload, self.SECRET, algorithm=service.SESSION_SECRET_ALGORITHM) with self.assertRaises(KeyError): self.site.getSession(uid) def test_getSession_with_no_user_info(self): payload = {'foo': 'bar'} uid = jwt.encode(payload, self.SECRET, algorithm=service.SESSION_SECRET_ALGORITHM) with self.assertRaises(KeyError): self.site.getSession(uid) def test_makeSession(self): session = self.site.makeSession() self.assertEqual(session.user_info, {'anonymous': True}) def test_updateSession(self): session = self.site.makeSession() request = Request(FakeChannel(), False) request.sitepath = [b"bb"] session.updateSession(request) self.assertEqual(len(request.cookies), 1) _, value = request.cookies[0].split(b";")[0].split(b"=") decoded = jwt.decode(value, self.SECRET, algorithms=[service.SESSION_SECRET_ALGORITHM]) self.assertEqual(decoded['user_info'], {'anonymous': True}) self.assertIn('exp', decoded) def test_absentServerHeader(self): request = Request(FakeChannel(), False) self.assertEqual(request.responseHeaders.hasHeader('Server'), False)
10,406
Python
.py
221
39.683258
100
0.701481
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,362
test_connector.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 from unittest import mock from twisted.internet import defer from twisted.python import reflect from twisted.trial import unittest from buildbot.data import base from buildbot.data import connector from buildbot.data import exceptions from buildbot.data import resultspec from buildbot.data import types from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import interfaces class Tests(interfaces.InterfaceTests): def setUp(self): raise NotImplementedError def test_signature_get(self): @self.assertArgSpecMatches(self.data.get) def get(self, path, filters=None, fields=None, order=None, limit=None, offset=None): pass def test_signature_getEndpoint(self): @self.assertArgSpecMatches(self.data.getEndpoint) def getEndpoint(self, path): pass def test_signature_control(self): @self.assertArgSpecMatches(self.data.control) def control(self, action, args, path): pass def test_signature_updates_addChange(self): @self.assertArgSpecMatches(self.data.updates.addChange) 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, ): pass def test_signature_updates_masterActive(self): @self.assertArgSpecMatches(self.data.updates.masterActive) def masterActive(self, name, masterid): pass def test_signature_updates_masterStopped(self): @self.assertArgSpecMatches(self.data.updates.masterStopped) def masterStopped(self, name, masterid): pass def test_signature_updates_addBuildset(self): @self.assertArgSpecMatches(self.data.updates.addBuildset) 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, ): pass def test_signature_updates_maybeBuildsetComplete(self): @self.assertArgSpecMatches(self.data.updates.maybeBuildsetComplete) def maybeBuildsetComplete(self, bsid): pass def test_signature_updates_updateBuilderList(self): @self.assertArgSpecMatches(self.data.updates.updateBuilderList) def updateBuilderList(self, masterid, builderNames): pass class TestFakeData(TestReactorMixin, unittest.TestCase, Tests): @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) self.data = self.master.data @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class TestDataConnector(TestReactorMixin, unittest.TestCase, Tests): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True) self.data = connector.DataConnector() yield self.data.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() class DataConnector(TestReactorMixin, unittest.TestCase): maxDiff = None @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self) # don't load by default self.patch(connector.DataConnector, 'submodules', []) self.data = connector.DataConnector() yield self.data.setServiceParent(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def patchFooPattern(self): cls = type('FooEndpoint', (base.Endpoint,), {}) ep = cls(None, self.master) ep.get = mock.Mock(name='FooEndpoint.get') ep.get.return_value = defer.succeed({'val': 9999}) self.data.matcher[('foo', 'n:fooid', 'bar')] = ep return ep def patchFooListPattern(self): cls = type('FoosEndpoint', (base.Endpoint,), {}) ep = cls(None, self.master) ep.get = mock.Mock(name='FoosEndpoint.get') ep.get.return_value = defer.succeed([{'val': v} for v in range(900, 920)]) self.data.matcher[('foo',)] = ep return ep # tests def test_sets_master(self): self.assertIdentical(self.master, self.data.master) def test_scanModule(self): # use this module as a test mod = reflect.namedModule('buildbot.test.unit.data.test_connector') self.data._scanModule(mod) # check that it discovered MyResourceType and updated endpoints match = self.data.matcher[('test', '10')] self.assertIsInstance(match[0], TestEndpoint) self.assertEqual(match[1], {"testid": 10}) match = self.data.matcher[('test', '10', 'p1')] self.assertIsInstance(match[0], TestEndpoint) match = self.data.matcher[('test', '10', 'p2')] self.assertIsInstance(match[0], TestEndpoint) match = self.data.matcher[('tests',)] self.assertIsInstance(match[0], TestsEndpoint) self.assertEqual(match[1], {}) match = self.data.matcher[('test', 'foo')] self.assertIsInstance(match[0], TestsEndpointSubclass) self.assertEqual(match[1], {}) # and that it found the update method self.assertEqual(self.data.updates.testUpdate(), "testUpdate return") # and that it added the single root link self.assertEqual(self.data.rootLinks, [{'name': 'tests'}]) # and that it added an attribute self.assertIsInstance(self.data.rtypes.test, TestResourceType) def test_getEndpoint(self): ep = self.patchFooPattern() got = self.data.getEndpoint(('foo', '10', 'bar')) self.assertEqual(got, (ep, {'fooid': 10})) def test_getEndpoint_missing(self): with self.assertRaises(exceptions.InvalidPathError): self.data.getEndpoint(('xyz',)) @defer.inlineCallbacks def test_get(self): ep = self.patchFooPattern() gotten = yield self.data.get(('foo', '10', 'bar')) self.assertEqual(gotten, {'val': 9999}) ep.get.assert_called_once_with(mock.ANY, {'fooid': 10}) @defer.inlineCallbacks def test_get_filters(self): ep = self.patchFooListPattern() gotten = yield self.data.get(('foo',), filters=[resultspec.Filter('val', 'lt', [902])]) self.assertEqual(gotten, base.ListResult([{'val': 900}, {'val': 901}], total=2)) ep.get.assert_called_once_with(mock.ANY, {}) @defer.inlineCallbacks def test_get_resultSpec_args(self): ep = self.patchFooListPattern() f = resultspec.Filter('val', 'gt', [909]) gotten = yield self.data.get(('foo',), filters=[f], fields=['val'], order=['-val'], limit=2) self.assertEqual(gotten, base.ListResult([{'val': 919}, {'val': 918}], total=10, limit=2)) ep.get.assert_called_once_with(mock.ANY, {}) @defer.inlineCallbacks def test_control(self): ep = self.patchFooPattern() ep.control = mock.Mock(name='MyEndpoint.control') ep.control.return_value = defer.succeed('controlled') gotten = yield self.data.control('foo!', {'arg': 2}, ('foo', '10', 'bar')) self.assertEqual(gotten, 'controlled') ep.control.assert_called_once_with('foo!', {'arg': 2}, {'fooid': 10}) # classes discovered by test_scanModule, above class TestsEndpoint(base.Endpoint): pathPatterns = "/tests" rootLinkName = 'tests' class TestsEndpointParentClass(base.Endpoint): rootLinkName = 'shouldnt-see-this' class TestsEndpointSubclass(TestsEndpointParentClass): pathPatterns = "/test/foo" class TestEndpoint(base.Endpoint): pathPatterns = """ /test/n:testid /test/n:testid/p1 /test/n:testid/p2 """ class TestResourceType(base.ResourceType): name = 'test' plural = 'tests' endpoints = [TestsEndpoint, TestEndpoint, TestsEndpointSubclass] keyField = 'testid' class EntityType(types.Entity): testid = types.Integer() entityType = EntityType(name, 'Test') @base.updateMethod def testUpdate(self): return "testUpdate return"
9,574
Python
.py
226
34.632743
100
0.667061
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,363
test_steps.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 twisted.internet import defer from twisted.trial import unittest from buildbot.data import steps from buildbot.db.steps import StepModel from buildbot.db.steps import UrlModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import epoch2datetime TIME1 = 2001111 TIME2 = 2002222 TIME3 = 2003333 TIME4 = 2004444 class StepEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = steps.StepEndpoint resourceTypeClass = steps.Step @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Builder(id=77, name='builder77'), fakedb.Master(id=88), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=30, builderid=77, number=7, masterid=88, buildrequestid=82, workerid=47 ), fakedb.Step( id=70, number=0, name='one', buildid=30, started_at=TIME1, locks_acquired_at=TIME2, complete_at=TIME3, results=0, ), fakedb.Step( id=71, number=1, name='two', buildid=30, started_at=TIME2, locks_acquired_at=TIME3, complete_at=TIME4, results=2, urls_json='[{"name":"url","url":"http://url"}]', ), fakedb.Step(id=72, number=2, name='three', buildid=30, started_at=TIME4, hidden=True), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): step = yield self.callGet(('steps', 72)) self.validateData(step) self.assertEqual( step, { 'buildid': 30, 'complete': False, 'complete_at': None, 'name': 'three', 'number': 2, 'results': None, 'started_at': epoch2datetime(TIME4), "locks_acquired_at": None, 'state_string': '', 'stepid': 72, 'urls': [], 'hidden': True, }, ) @defer.inlineCallbacks def test_get_existing_buildid_name(self): step = yield self.callGet(('builds', 30, 'steps', 'two')) self.validateData(step) self.assertEqual(step['stepid'], 71) @defer.inlineCallbacks def test_get_existing_buildid_number(self): step = yield self.callGet(('builds', 30, 'steps', 1)) self.validateData(step) self.assertEqual(step['stepid'], 71) @defer.inlineCallbacks def test_get_existing_builder_name(self): step = yield self.callGet(('builders', 77, 'builds', 7, 'steps', 'two')) self.validateData(step) self.assertEqual(step['stepid'], 71) @defer.inlineCallbacks def test_get_existing_buildername_name(self): step = yield self.callGet(('builders', 'builder77', 'builds', 7, 'steps', 'two')) self.validateData(step) self.assertEqual(step['stepid'], 71) @defer.inlineCallbacks def test_get_existing_builder_number(self): step = yield self.callGet(('builders', 77, 'builds', 7, 'steps', 1)) self.validateData(step) self.assertEqual(step['stepid'], 71) @defer.inlineCallbacks def test_get_missing_buildername_builder_number(self): step = yield self.callGet(('builders', 'builder77_nope', 'builds', 7, 'steps', 1)) self.assertEqual(step, None) @defer.inlineCallbacks def test_get_missing(self): step = yield self.callGet(('steps', 9999)) self.assertEqual(step, None) class StepsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = steps.StepsEndpoint resourceTypeClass = steps.Step @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Builder(id=77, name='builder77'), fakedb.Master(id=88), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=30, builderid=77, number=7, masterid=88, buildrequestid=82, workerid=47 ), fakedb.Build( id=31, builderid=77, number=8, masterid=88, buildrequestid=82, workerid=47 ), fakedb.Step( id=70, number=0, name='one', buildid=30, started_at=TIME1, locks_acquired_at=TIME2, complete_at=TIME3, results=0, ), fakedb.Step( id=71, number=1, name='two', buildid=30, started_at=TIME2, locks_acquired_at=TIME3, complete_at=TIME4, results=2, urls_json='[{"name":"url","url":"http://url"}]', ), fakedb.Step(id=72, number=2, name='three', buildid=30, started_at=TIME4), fakedb.Step(id=73, number=0, name='otherbuild', buildid=31, started_at=TIME3), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_buildid(self): steps = yield self.callGet(('builds', 30, 'steps')) for step in steps: self.validateData(step) self.assertEqual([s['number'] for s in steps], [0, 1, 2]) @defer.inlineCallbacks def test_get_builder(self): steps = yield self.callGet(('builders', 77, 'builds', 7, 'steps')) for step in steps: self.validateData(step) self.assertEqual([s['number'] for s in steps], [0, 1, 2]) @defer.inlineCallbacks def test_get_buildername(self): steps = yield self.callGet(('builders', 'builder77', 'builds', 7, 'steps')) for step in steps: self.validateData(step) self.assertEqual([s['number'] for s in steps], [0, 1, 2]) class Step(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = steps.Step(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_addStep(self): @self.assertArgSpecMatches( self.master.data.updates.addStep, # fake self.rtype.addStep, ) # real def addStep(self, buildid, name): pass @defer.inlineCallbacks def test_addStep(self): stepid, number, name = yield self.rtype.addStep(buildid=10, name='name') msgBody = { 'buildid': 10, 'complete': False, 'complete_at': None, 'name': name, 'number': number, 'results': None, 'started_at': None, "locks_acquired_at": None, 'state_string': 'pending', 'stepid': stepid, 'urls': [], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'new'), msgBody), (('steps', str(stepid), 'new'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name=name, number=number, results=None, started_at=None, locks_acquired_at=None, state_string='pending', urls=[], hidden=False, ), ) @defer.inlineCallbacks def test_fake_addStep(self): self.assertEqual(len((yield self.master.data.updates.addStep(buildid=10, name='ten'))), 3) def test_signature_startStep(self): @self.assertArgSpecMatches(self.master.data.updates.startStep, self.rtype.startStep) def addStep(self, stepid, started_at=None, locks_acquired=False): pass @defer.inlineCallbacks def test_startStep(self): self.reactor.advance(TIME1) stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name='ten', state_string='pending' ) yield self.rtype.startStep(stepid=stepid) msgBody = { 'buildid': 10, 'complete': False, 'complete_at': None, 'name': 'ten', 'number': 0, 'results': None, 'started_at': epoch2datetime(TIME1), "locks_acquired_at": None, 'state_string': 'pending', 'stepid': stepid, 'urls': [], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'started'), msgBody), (('steps', str(stepid), 'started'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name='ten', number=0, results=None, started_at=epoch2datetime(TIME1), locks_acquired_at=None, state_string='pending', urls=[], hidden=False, ), ) @defer.inlineCallbacks def test_startStep_no_locks(self): self.reactor.advance(TIME1) stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name="ten", state_string="pending" ) yield self.rtype.startStep(stepid=stepid, locks_acquired=True) msgBody = { "buildid": 10, "complete": False, "complete_at": None, "name": "ten", "number": 0, "results": None, "started_at": epoch2datetime(TIME1), "locks_acquired_at": epoch2datetime(TIME1), "state_string": "pending", "stepid": stepid, "urls": [], "hidden": False, } self.master.mq.assertProductions([ (("builds", "10", "steps", str(stepid), "started"), msgBody), (("steps", str(stepid), "started"), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name="ten", number=0, results=None, started_at=epoch2datetime(TIME1), locks_acquired_at=epoch2datetime(TIME1), state_string="pending", urls=[], hidden=False, ), ) @defer.inlineCallbacks def test_startStep_acquire_locks(self): self.reactor.advance(TIME1) stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name='ten', state_string='pending' ) yield self.rtype.startStep(stepid=stepid) self.reactor.advance(TIME2 - TIME1) self.master.mq.clearProductions() yield self.rtype.set_step_locks_acquired_at(stepid=stepid) msgBody = { 'buildid': 10, 'complete': False, 'complete_at': None, 'name': 'ten', 'number': 0, 'results': None, 'started_at': epoch2datetime(TIME1), "locks_acquired_at": epoch2datetime(TIME2), 'state_string': 'pending', 'stepid': stepid, 'urls': [], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'updated'), msgBody), (('steps', str(stepid), 'updated'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name='ten', number=0, results=None, started_at=epoch2datetime(TIME1), locks_acquired_at=epoch2datetime(TIME2), state_string='pending', urls=[], hidden=False, ), ) def test_signature_setStepStateString(self): @self.assertArgSpecMatches( self.master.data.updates.setStepStateString, # fake self.rtype.setStepStateString, ) # real def setStepStateString(self, stepid, state_string): pass @defer.inlineCallbacks def test_setStepStateString(self): stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name='ten', state_string='pending' ) yield self.rtype.setStepStateString(stepid=stepid, state_string='hi') msgBody = { 'buildid': 10, 'complete': False, 'complete_at': None, 'name': 'ten', 'number': 0, 'results': None, 'started_at': None, "locks_acquired_at": None, 'state_string': 'hi', 'stepid': stepid, 'urls': [], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'updated'), msgBody), (('steps', str(stepid), 'updated'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name='ten', number=0, results=None, started_at=None, locks_acquired_at=None, state_string='hi', urls=[], hidden=False, ), ) def test_signature_finishStep(self): @self.assertArgSpecMatches( self.master.data.updates.finishStep, # fake self.rtype.finishStep, ) # real def finishStep(self, stepid, results, hidden): pass @defer.inlineCallbacks def test_finishStep(self): stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name='ten', state_string='pending' ) self.reactor.advance(TIME1) yield self.rtype.startStep(stepid=stepid) yield self.rtype.set_step_locks_acquired_at(stepid=stepid) self.reactor.advance(TIME2 - TIME1) self.master.mq.clearProductions() yield self.rtype.finishStep(stepid=stepid, results=9, hidden=False) msgBody = { 'buildid': 10, 'complete': True, 'complete_at': epoch2datetime(TIME2), 'name': 'ten', 'number': 0, 'results': 9, 'started_at': epoch2datetime(TIME1), "locks_acquired_at": epoch2datetime(TIME1), 'state_string': 'pending', 'stepid': stepid, 'urls': [], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'finished'), msgBody), (('steps', str(stepid), 'finished'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=epoch2datetime(TIME2), id=stepid, name='ten', number=0, results=9, started_at=epoch2datetime(TIME1), locks_acquired_at=epoch2datetime(TIME1), state_string='pending', urls=[], hidden=False, ), ) def test_signature_addStepURL(self): @self.assertArgSpecMatches( self.master.data.updates.addStepURL, # fake self.rtype.addStepURL, ) # real def addStepURL(self, stepid, name, url): pass @defer.inlineCallbacks def test_addStepURL(self): stepid, _, _ = yield self.master.db.steps.addStep( buildid=10, name='ten', state_string='pending' ) yield self.rtype.addStepURL(stepid=stepid, name="foo", url="bar") msgBody = { 'buildid': 10, 'complete': False, 'complete_at': None, 'name': 'ten', 'number': 0, 'results': None, 'started_at': None, "locks_acquired_at": None, 'state_string': 'pending', 'stepid': stepid, 'urls': [{'name': 'foo', 'url': 'bar'}], 'hidden': False, } self.master.mq.assertProductions([ (('builds', '10', 'steps', str(stepid), 'updated'), msgBody), (('steps', str(stepid), 'updated'), msgBody), ]) step = yield self.master.db.steps.getStep(stepid) self.assertEqual( step, StepModel( buildid=10, complete_at=None, id=stepid, name='ten', number=0, results=None, started_at=None, locks_acquired_at=None, state_string='pending', urls=[UrlModel(name='foo', url='bar')], hidden=False, ), )
19,088
Python
.py
524
25.024809
98
0.538865
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,364
test_test_results.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 twisted.internet import defer from twisted.trial import unittest from buildbot.data import test_results from buildbot.db.test_results import TestResultModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class TestResultsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = test_results.TestResultsEndpoint resourceTypeClass = test_results.TestResult @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.Master(id=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.Step(id=131, number=132, name='step132', buildid=30), fakedb.TestResultSet( id=13, builderid=88, buildid=30, stepid=131, description='desc', category='cat', value_unit='ms', complete=1, ), fakedb.TestName(id=301, builderid=88, name='name301'), fakedb.TestName(id=302, builderid=88, name='name302'), fakedb.TestCodePath(id=401, builderid=88, path='path401'), fakedb.TestCodePath(id=402, builderid=88, path='path402'), fakedb.TestResult(id=101, builderid=88, test_result_setid=13, line=400, value='v101'), fakedb.TestResult( id=102, builderid=88, test_result_setid=13, test_nameid=301, test_code_pathid=401, line=401, value='v102', ), fakedb.TestResult( id=103, builderid=88, test_result_setid=13, test_nameid=302, test_code_pathid=402, line=402, duration_ns=1012, value='v103', ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing_results(self): results = yield self.callGet(('test_result_sets', 13, 'results')) for result in results: self.validateData(result) self.assertEqual([r['test_resultid'] for r in results], [101, 102, 103]) @defer.inlineCallbacks def test_get_missing_results(self): results = yield self.callGet(('test_result_sets', 14, 'results')) self.assertEqual(results, []) class TestResult(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = test_results.TestResult(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_add_test_results(self): @self.assertArgSpecMatches( self.master.data.updates.addTestResults, self.rtype.addTestResults ) def addTestResults(self, builderid, test_result_setid, result_values): pass @defer.inlineCallbacks def test_add_test_results(self): result_values = [ {'test_name': 'name1', 'value': '1'}, {'test_name': 'name2', 'duration_ns': 1000, 'value': '1'}, {'test_name': 'name3', 'test_code_path': 'path2', 'value': '2'}, {'test_name': 'name4', 'test_code_path': 'path3', 'value': '3'}, {'test_name': 'name5', 'test_code_path': 'path4', 'line': 4, 'value': '4'}, {'test_code_path': 'path5', 'line': 5, 'value': '5'}, ] yield self.rtype.addTestResults( builderid=88, test_result_setid=13, result_values=result_values ) self.master.mq.assertProductions([]) results = yield self.master.db.test_results.getTestResults( builderid=88, test_result_setid=13 ) resultid = results[0].id self.assertEqual( results, [ TestResultModel( id=resultid, builderid=88, test_result_setid=13, test_name='name1', test_code_path=None, line=None, duration_ns=None, value='1', ), TestResultModel( id=resultid + 1, builderid=88, test_result_setid=13, test_name='name2', test_code_path=None, line=None, duration_ns=1000, value='1', ), TestResultModel( id=resultid + 2, builderid=88, test_result_setid=13, test_name='name3', test_code_path='path2', line=None, duration_ns=None, value='2', ), TestResultModel( id=resultid + 3, builderid=88, test_result_setid=13, test_name='name4', test_code_path='path3', line=None, duration_ns=None, value='3', ), TestResultModel( id=resultid + 4, builderid=88, test_result_setid=13, test_name='name5', test_code_path='path4', line=4, duration_ns=None, value='4', ), TestResultModel( id=resultid + 5, builderid=88, test_result_setid=13, test_name=None, test_code_path='path5', line=5, duration_ns=None, value='5', ), ], )
7,305
Python
.py
184
26.63587
98
0.538776
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,365
test_logchunks.py
buildbot_buildbot/master/buildbot/test/unit/data/test_logchunks.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 textwrap from twisted.internet import defer from twisted.trial import unittest from buildbot.data import base from buildbot.data import logchunks from buildbot.data import resultspec from buildbot.test import fakedb from buildbot.test.util import endpoint class LogChunkEndpointBase(endpoint.EndpointMixin, unittest.TestCase): endpointClass: type[base.Endpoint] = logchunks.LogChunkEndpoint resourceTypeClass: type[base.ResourceType] = logchunks.LogChunk endpointname = "contents" log60Lines = [ 'line zero', 'line 1', 'line TWO', 'line 3', 'line 2**2', 'another line', 'yet another line', ] log61Lines = [f'{i:08d}' for i in range(100)] @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data( [ fakedb.Builder(id=77), fakedb.Worker(id=13, name='wrk'), fakedb.Master(id=88), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Step(id=50, buildid=13, number=9, name='make'), fakedb.Log(id=60, stepid=50, name='stdio', slug='stdio', type='s', num_lines=7), fakedb.LogChunk( logid=60, first_line=0, last_line=1, compressed=0, content=textwrap.dedent("""\ line zero line 1"""), ), fakedb.LogChunk( logid=60, first_line=2, last_line=4, compressed=0, content=textwrap.dedent("""\ line TWO line 3 line 2**2"""), ), fakedb.LogChunk( logid=60, first_line=5, last_line=5, compressed=0, content="another line" ), fakedb.LogChunk( logid=60, first_line=6, last_line=6, compressed=0, content="yet another line" ), fakedb.Log(id=61, stepid=50, name='errors', slug='errors', type='t', num_lines=100), ] + [ fakedb.LogChunk( logid=61, first_line=i, last_line=i, compressed=0, content=f"{i:08d}" ) for i in range(100) ] + [ fakedb.Log(id=62, stepid=50, name='notes', slug='notes', type='t', num_lines=0), # logid 62 is empty ] ) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def do_test_chunks(self, path, logid, expLines): # get the whole thing in one go logchunk = yield self.callGet(path) self.validateData(logchunk) expContent = '\n'.join(expLines) + '\n' self.assertEqual(logchunk, {'logid': logid, 'firstline': 0, 'content': expContent}) # line-by-line for i, expLine in enumerate(expLines): logchunk = yield self.callGet(path, resultSpec=resultspec.ResultSpec(offset=i, limit=1)) self.validateData(logchunk) self.assertEqual(logchunk, {'logid': logid, 'firstline': i, 'content': expLine + '\n'}) # half and half mid = int(len(expLines) / 2) for f, length in (0, mid), (mid, len(expLines) - 1): result_spec = resultspec.ResultSpec(offset=f, limit=length - f + 1) logchunk = yield self.callGet(path, resultSpec=result_spec) self.validateData(logchunk) expContent = '\n'.join(expLines[f : length + 1]) + '\n' self.assertEqual(logchunk, {'logid': logid, 'firstline': f, 'content': expContent}) # truncated at EOF f = len(expLines) - 2 length = len(expLines) + 10 result_spec = resultspec.ResultSpec(offset=f, limit=length - f + 1) logchunk = yield self.callGet(path, resultSpec=result_spec) self.validateData(logchunk) expContent = '\n'.join(expLines[-2:]) + '\n' self.assertEqual(logchunk, {'logid': logid, 'firstline': f, 'content': expContent}) # some illegal stuff self.assertEqual( (yield self.callGet(path, resultSpec=resultspec.ResultSpec(offset=-1))), None ) self.assertEqual( (yield self.callGet(path, resultSpec=resultspec.ResultSpec(offset=10, limit=-1))), None ) def test_get_logid_60(self): return self.do_test_chunks(('logs', 60, self.endpointname), 60, self.log60Lines) def test_get_logid_61(self): return self.do_test_chunks(('logs', 61, self.endpointname), 61, self.log61Lines) class LogChunkEndpoint(LogChunkEndpointBase): @defer.inlineCallbacks def test_get_missing(self): logchunk = yield self.callGet(('logs', 99, self.endpointname)) self.assertEqual(logchunk, None) @defer.inlineCallbacks def test_get_empty(self): logchunk = yield self.callGet(('logs', 62, self.endpointname)) self.validateData(logchunk) self.assertEqual(logchunk['content'], '') @defer.inlineCallbacks def test_get_by_stepid(self): logchunk = yield self.callGet(('steps', 50, 'logs', 'errors', self.endpointname)) self.validateData(logchunk) self.assertEqual(logchunk['logid'], 61) @defer.inlineCallbacks def test_get_by_buildid(self): logchunk = yield self.callGet(( 'builds', 13, 'steps', 9, 'logs', 'stdio', self.endpointname, )) self.validateData(logchunk) self.assertEqual(logchunk['logid'], 60) @defer.inlineCallbacks def test_get_by_builder(self): logchunk = yield self.callGet(( 'builders', 77, 'builds', 3, 'steps', 9, 'logs', 'errors', self.endpointname, )) self.validateData(logchunk) self.assertEqual(logchunk['logid'], 61) @defer.inlineCallbacks def test_get_by_builder_step_name(self): logchunk = yield self.callGet(( 'builders', 77, 'builds', 3, 'steps', 'make', 'logs', 'errors', self.endpointname, )) self.validateData(logchunk) self.assertEqual(logchunk['logid'], 61) class RawLogChunkEndpoint(LogChunkEndpointBase): endpointClass = logchunks.RawLogChunkEndpoint endpointname = "raw" def validateData(self, data): self.assertIsInstance(data['raw'], str) self.assertIsInstance(data['mime-type'], str) self.assertIsInstance(data['filename'], str) @defer.inlineCallbacks def do_test_chunks(self, path, logid, expLines): # get the whole thing in one go logchunk = yield self.callGet(path) self.validateData(logchunk) if logid == 60: expContent = 'Builder: builder-77\nBuild number: 3\nWorker name: wrk\n' expContent += ''.join([f"{line[1:]}\n" for line in expLines]) expFilename = "builder-77_build_3_step_make_log_stdio" else: expContent = '\n'.join(expLines) + '\n' expFilename = "builder-77_build_3_step_make_log_errors" self.assertEqual( logchunk, {'filename': expFilename, 'mime-type': "text/plain", 'raw': expContent} )
8,566
Python
.py
211
30.090047
100
0.584224
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,366
test_builders.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import builders from buildbot.data import resultspec from buildbot.db.builders import BuilderModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util.twisted import async_to_deferred class BuilderEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = builders.BuilderEndpoint resourceTypeClass = builders.Builder @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=1, name='buildera'), fakedb.Builder(id=2, name='builderb'), fakedb.Builder(id=3, name='builder unicode \N{SNOWMAN}'), fakedb.Master(id=13), fakedb.BuilderMaster(id=1, builderid=2, masterid=13), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): builder = yield self.callGet(('builders', 2)) self.validateData(builder) self.assertEqual(builder['name'], 'builderb') @defer.inlineCallbacks def test_get_missing(self): builder = yield self.callGet(('builders', 99)) self.assertEqual(builder, None) @async_to_deferred async def test_get_by_name(self): builder = await self.callGet(('builders', 'builderb')) self.validateData(builder) self.assertEqual(builder['builderid'], 2) self.assertEqual(builder['name'], 'builderb') @async_to_deferred async def test_get_unicode_by_name(self): builder = await self.callGet(('builders', 'builder unicode \N{SNOWMAN}')) self.validateData(builder) self.assertEqual(builder['builderid'], 3) self.assertEqual(builder['name'], 'builder unicode \N{SNOWMAN}') @defer.inlineCallbacks def test_get_missing_with_name(self): builder = yield self.callGet(('builders', 'builderc')) self.assertEqual(builder, None) @defer.inlineCallbacks def test_get_existing_with_master(self): builder = yield self.callGet(('masters', 13, 'builders', 2)) self.validateData(builder) self.assertEqual(builder['name'], 'builderb') @defer.inlineCallbacks def test_get_existing_with_different_master(self): builder = yield self.callGet(('masters', 14, 'builders', 2)) self.assertEqual(builder, None) @defer.inlineCallbacks def test_get_missing_with_master(self): builder = yield self.callGet(('masters', 13, 'builders', 99)) self.assertEqual(builder, None) class BuildersEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = builders.BuildersEndpoint resourceTypeClass = builders.Builder @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Project(id=201, name='project201'), fakedb.Project(id=202, name='project202'), fakedb.Builder(id=1, name='buildera'), fakedb.Builder(id=2, name='builderb'), fakedb.Builder(id=3, name='builderTagA', projectid=201), fakedb.Builder(id=4, name='builderTagB', projectid=201), fakedb.Builder(id=5, name='builderTagAB', projectid=202), fakedb.Tag(id=3, name="tagA"), fakedb.Tag(id=4, name="tagB"), fakedb.BuildersTags(builderid=3, tagid=3), fakedb.BuildersTags(builderid=4, tagid=4), fakedb.BuildersTags(builderid=5, tagid=3), fakedb.BuildersTags(builderid=5, tagid=4), fakedb.Master(id=13), fakedb.BuilderMaster(id=1, builderid=2, masterid=13), fakedb.Worker(id=1, name='zero'), fakedb.ConnectedWorker(id=1, workerid=1, masterid=13), fakedb.ConfiguredWorker(id=1, workerid=1, buildermasterid=1), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): builders = yield self.callGet(('builders',)) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [1, 2, 3, 4, 5]) @defer.inlineCallbacks def test_get_masterid(self): builders = yield self.callGet(('masters', 13, 'builders')) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [2]) @defer.inlineCallbacks def test_get_projectid(self): builders = yield self.callGet(('projects', 201, 'builders')) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [3, 4]) @async_to_deferred async def test_get_workerid(self): builders = await self.callGet(('workers', 1, 'builders')) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [2]) @defer.inlineCallbacks def test_get_masterid_missing(self): builders = yield self.callGet(('masters', 14, 'builders')) self.assertEqual(sorted([b['builderid'] for b in builders]), []) @defer.inlineCallbacks def test_get_contains_one_tag(self): resultSpec = resultspec.ResultSpec( filters=[resultspec.Filter('tags', 'contains', ["tagA"])] ) builders = yield self.callGet(('builders',)) builders = resultSpec.apply(builders) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [3, 5]) @defer.inlineCallbacks def test_get_contains_two_tags(self): resultSpec = resultspec.ResultSpec( filters=[resultspec.Filter('tags', 'contains', ["tagA", "tagB"])] ) builders = yield self.callGet(('builders',)) builders = resultSpec.apply(builders) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [3, 4, 5]) @defer.inlineCallbacks def test_get_contains_two_tags_one_unknown(self): resultSpec = resultspec.ResultSpec( filters=[resultspec.Filter('tags', 'contains', ["tagA", "tagC"])] ) builders = yield self.callGet(('builders',)) builders = resultSpec.apply(builders) for b in builders: self.validateData(b) self.assertEqual(sorted([b['builderid'] for b in builders]), [3, 5]) class Builder(interfaces.InterfaceTests, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = builders.Builder(self.master) yield self.master.db.insert_test_data([ fakedb.Master(id=13), fakedb.Master(id=14), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_findBuilderId(self): @self.assertArgSpecMatches( self.master.data.updates.findBuilderId, # fake self.rtype.findBuilderId, ) # real def findBuilderId(self, name): pass def test_findBuilderId(self): # this just passes through to the db method, so test that rv = defer.succeed(None) self.master.db.builders.findBuilderId = mock.Mock(return_value=rv) self.assertIdentical(self.rtype.findBuilderId('foo'), rv) def test_signature_updateBuilderInfo(self): @self.assertArgSpecMatches(self.master.data.updates.updateBuilderInfo) def updateBuilderInfo( self, builderid, description, description_format, description_html, projectid, tags ): pass def test_signature_updateBuilderList(self): @self.assertArgSpecMatches( self.master.data.updates.updateBuilderList, # fake self.rtype.updateBuilderList, ) # real def updateBuilderList(self, masterid, builderNames): pass @defer.inlineCallbacks def test_updateBuilderList(self): # add one builder master yield self.rtype.updateBuilderList(13, ['somebuilder']) self.assertEqual( sorted((yield self.master.db.builders.getBuilders())), sorted([ BuilderModel( id=1, masterids=[13], name="somebuilder", ), ]), ) self.master.mq.assertProductions([ (('builders', '1', 'started'), {'builderid': 1, 'masterid': 13, 'name': 'somebuilder'}) ]) # add another yield self.rtype.updateBuilderList(13, ['somebuilder', 'another']) def builderKey(builder: BuilderModel): return builder.id self.assertEqual( sorted((yield self.master.db.builders.getBuilders()), key=builderKey), sorted( [ BuilderModel( id=1, masterids=[13], name="somebuilder", ), BuilderModel( id=2, masterids=[13], name="another", ), ], key=builderKey, ), ) self.master.mq.assertProductions([ (('builders', '2', 'started'), {'builderid': 2, 'masterid': 13, 'name': 'another'}) ]) # add one for another master yield self.rtype.updateBuilderList(14, ['another']) self.assertEqual( sorted((yield self.master.db.builders.getBuilders()), key=builderKey), sorted( [ BuilderModel( id=1, masterids=[13], name="somebuilder", ), BuilderModel( id=2, masterids=[13, 14], name="another", ), ], key=builderKey, ), ) self.master.mq.assertProductions([ (('builders', '2', 'started'), {'builderid': 2, 'masterid': 14, 'name': 'another'}) ]) # remove both for the first master yield self.rtype.updateBuilderList(13, []) self.assertEqual( sorted((yield self.master.db.builders.getBuilders()), key=builderKey), sorted( [ BuilderModel( id=1, name="somebuilder", ), BuilderModel( id=2, masterids=[14], name="another", ), ], key=builderKey, ), ) self.master.mq.assertProductions([ (('builders', '1', 'stopped'), {'builderid': 1, 'masterid': 13, 'name': 'somebuilder'}), (('builders', '2', 'stopped'), {'builderid': 2, 'masterid': 13, 'name': 'another'}), ]) @defer.inlineCallbacks def test__masterDeactivated(self): # this method just calls updateBuilderList, so test that. self.rtype.updateBuilderList = mock.Mock(spec=self.rtype.updateBuilderList) yield self.rtype._masterDeactivated(10) self.rtype.updateBuilderList.assert_called_with(10, [])
12,633
Python
.py
297
32.175084
100
0.608738
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,367
test_types.py
buildbot_buildbot/master/buildbot/test/unit/data/test_types.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 datetime import datetime from twisted.trial import unittest from buildbot.data import types class TypeMixin: klass: type[types.Type] | None = None good: list[object] = [] bad: list[object] = [] stringValues: list[tuple[str | bytes, object]] = [] badStringValues: list[str | bytes] = [] cmpResults: list[tuple[object, str | bytes, int]] = [] def setUp(self): self.ty = self.makeInstance() def makeInstance(self): return self.klass() def test_valueFromString(self): for string, expValue in self.stringValues: self.assertEqual( self.ty.valueFromString(string), expValue, f"value of string {string!r}" ) for string in self.badStringValues: with self.assertRaises(TypeError): self.ty.valueFromString(string, f"expected error for {string!r}") def test_cmp(self): for val, string, expResult in self.cmpResults: self.assertEqual( self.ty.cmp(val, string), expResult, f"compare of {val!r} and {string!r}" ) def test_validate(self): for o in self.good: errors = list(self.ty.validate(repr(o), o)) self.assertEqual(errors, [], f"{o!r} -> {errors}") for o in self.bad: errors = list(self.ty.validate(repr(o), o)) self.assertNotEqual(errors, [], f"no error for {o!r}") class NoneOk(TypeMixin, unittest.TestCase): def makeInstance(self): return types.NoneOk(types.Integer()) good = [None, 1] bad = ['abc'] stringValues = [('0', 0), ('-10', -10)] badStringValues = ['one', '', '0x10'] cmpResults = [(10, '9', 1), (-2, '-1', -1)] class Integer(TypeMixin, unittest.TestCase): klass = types.Integer good = [0, -1, 1000, 100**100] bad = [None, '', '0'] stringValues = [('0', 0), ('-10', -10)] badStringValues = ['one', '', '0x10'] cmpResults = [(10, '9', 1), (-2, '-1', -1)] class DateTime(TypeMixin, unittest.TestCase): klass = types.DateTime good = [0, 1604843464, datetime(2020, 11, 15, 18, 40, 1, 630219)] bad = [int(1e60), 'bad', 1604843464.388657] stringValues = [ ('1604843464', 1604843464), ] badStringValues = ['one', '', '0x10'] class String(TypeMixin, unittest.TestCase): klass = types.String good = ['', 'hello', '\N{SNOWMAN}'] bad = [None, b'', b'hello', 10] stringValues = [ (b'hello', 'hello'), ('\N{SNOWMAN}'.encode(), '\N{SNOWMAN}'), ] badStringValues = ['\xe0\xe0'] cmpResults = [('bbb', 'aaa', 1)] class Binary(TypeMixin, unittest.TestCase): klass = types.Binary good = [b'', b'\x01\x80\xfe', '\N{SNOWMAN}'.encode()] bad = [None, 10, 'xyz'] stringValues = [('hello', 'hello')] cmpResults = [('\x00\x80', '\x10\x10', -1)] class Boolean(TypeMixin, unittest.TestCase): klass = types.Boolean good = [True, False] bad = [None, 0, 1] stringValues = [ (b'on', True), (b'true', True), (b'yes', True), (b'1', True), (b'off', False), (b'false', False), (b'no', False), (b'0', False), (b'ON', True), (b'TRUE', True), (b'YES', True), (b'OFF', False), (b'FALSE', False), (b'NO', False), ] cmpResults = [ (False, b'no', 0), (True, b'true', 0), ] class Identifier(TypeMixin, unittest.TestCase): def makeInstance(self): return types.Identifier(len=5) good = ['a', 'abcde', 'a1234'] bad = ['', 'abcdef', b'abcd', '1234', '\N{SNOWMAN}'] stringValues = [ (b'abcd', 'abcd'), ] badStringValues = [b'', r'\N{SNOWMAN}', b'abcdef'] cmpResults = [ ('aaaa', b'bbbb', -1), ] class List(TypeMixin, unittest.TestCase): def makeInstance(self): return types.List(of=types.Integer()) good = [[], [1], [1, 2]] bad = [1, (1,), ['1']] badStringValues = ['1', '1,2'] class SourcedProperties(TypeMixin, unittest.TestCase): klass = types.SourcedProperties good = [{'p': (b'["a"]', 's')}] bad = [ None, (), [], {b'not-unicode': ('["a"]', 'unicode')}, {'unicode': ('["a"]', b'not-unicode')}, {'unicode': ('not, json', 'unicode')}, ] class Entity(TypeMixin, unittest.TestCase): class MyEntity(types.Entity): field1 = types.Integer() field2 = types.NoneOk(types.String()) def makeInstance(self): return self.MyEntity('myentity', 'MyEntity') good = [ {'field1': 1, 'field2': 'f2'}, {'field1': 1, 'field2': None}, ] bad = [ None, [], (), {'field1': 1}, {'field1': 1, 'field2': 'f2', 'field3': 10}, {'field1': 'one', 'field2': 'f2'}, ]
5,592
Python
.py
159
28.786164
89
0.581805
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,368
test_graphql.py
buildbot_buildbot/master/buildbot/test/unit/data/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 import textwrap from twisted.internet import defer from twisted.python import reflect from twisted.trial import unittest from buildbot.data import connector from buildbot.data.graphql import GraphQLConnector from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import interfaces try: import graphql except ImportError: graphql = None # type: ignore[assignment] class TestGraphQlConnector(TestReactorMixin, unittest.TestCase, interfaces.InterfaceTests): maxDiff = None @defer.inlineCallbacks def setUp(self): if not graphql: raise unittest.SkipTest('Test requires graphql-core module installed') self.setup_test_reactor(use_asyncio=True) self.master = yield fakemaster.make_master(self) # don't load by default self.all_submodules = connector.DataConnector.submodules self.patch(connector.DataConnector, 'submodules', []) self.master.data = self.data = connector.DataConnector() yield self.data.setServiceParent(self.master) self.graphql = GraphQLConnector() yield self.graphql.setServiceParent(self.master) def configure_graphql(self): self.master.config.www = {'graphql': {}} self.graphql.reconfigServiceWithBuildbotConfig(self.master.config) def test_signature_query(self): @self.assertArgSpecMatches(self.graphql.query) def query(self, query): pass def test_graphql_get_schema(self): # use the test module for basic graphQLSchema generation mod = reflect.namedModule('buildbot.test.unit.data.test_connector') self.data._scanModule(mod) self.configure_graphql() schema = self.graphql.get_schema() self.assertEqual( schema, textwrap.dedent(""" # 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 { tests(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 } type Subscription { tests(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 } type Test { testid: Int! } """), ) schema = graphql.build_schema(schema) def test_get_fake_graphql_schema(self): # use the test module for basic graphQLSchema generation mod = reflect.namedModule('buildbot.test.fake.endpoint') self.data._scanModule(mod) self.configure_graphql() schema = self.graphql.get_schema() self.assertEqual(schema, mod.graphql_schema) schema = graphql.build_schema(schema) def test_graphql_get_full_schema(self): if not graphql: raise unittest.SkipTest('Test requires graphql') for mod in self.all_submodules: mod = reflect.namedModule(mod) self.data._scanModule(mod) self.configure_graphql() schema = self.graphql.get_schema() # graphql parses the schema and raise an error if it is incorrect # or incoherent (e.g. missing type definition) schema = graphql.build_schema(schema) class TestGraphQlConnectorService(TestReactorMixin, unittest.TestCase): def setUp(self): if not graphql: raise unittest.SkipTest('Test requires graphql-core module installed') self.setup_test_reactor(use_asyncio=False) @defer.inlineCallbacks def test_start_stop(self): self.master = yield fakemaster.make_master(self) self.master.data = self.data = connector.DataConnector() yield self.data.setServiceParent(self.master) self.graphql = GraphQLConnector() yield self.graphql.setServiceParent(self.master) yield self.master.startService() self.master.config.www = {'graphql': {}} self.graphql.reconfigServiceWithBuildbotConfig(self.master.config) self.assertIsNotNone(self.graphql.asyncio_loop) yield self.master.stopService() self.assertIsNone(self.graphql.asyncio_loop)
5,622
Python
.py
137
33.029197
91
0.668008
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,369
test_builds.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import builds from buildbot.data import resultspec from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import epoch2datetime class BuildEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = builds.BuildEndpoint resourceTypeClass = builds.Build @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77, name='builder77'), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Build( id=14, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=4 ), fakedb.Build( id=15, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=5 ), fakedb.BuildProperty( buildid=13, name='reason', value='"force build"', source="Force Build Form" ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): build = yield self.callGet(('builds', 14)) self.validateData(build) self.assertEqual(build['number'], 4) @defer.inlineCallbacks def test_get_missing(self): build = yield self.callGet(('builds', 9999)) self.assertEqual(build, None) @defer.inlineCallbacks def test_get_missing_builder_number(self): build = yield self.callGet(('builders', 999, 'builds', 4)) self.assertEqual(build, None) @defer.inlineCallbacks def test_get_builder_missing_number(self): build = yield self.callGet(('builders', 77, 'builds', 44)) self.assertEqual(build, None) @defer.inlineCallbacks def test_get_builder_number(self): build = yield self.callGet(('builders', 77, 'builds', 5)) self.validateData(build) self.assertEqual(build['buildid'], 15) @defer.inlineCallbacks def test_get_buildername_number(self): build = yield self.callGet(('builders', 'builder77', 'builds', 5)) self.validateData(build) self.assertEqual(build['buildid'], 15) @defer.inlineCallbacks def test_get_buildername_not_existing_number(self): build = yield self.callGet(('builders', 'builder77_nope', 'builds', 5)) self.assertEqual(build, None) @defer.inlineCallbacks def test_properties_injection(self): resultSpec = resultspec.OptimisedResultSpec( properties=[resultspec.Property(b'property', 'eq', ['reason'])] ) build = yield self.callGet(('builders', 77, 'builds', 3), resultSpec=resultSpec) self.validateData(build) self.assertIn('reason', build['properties']) @defer.inlineCallbacks def test_action_stop(self): yield self.callControl("stop", {}, ('builders', 77, 'builds', 5)) self.master.mq.assertProductions([ (('control', 'builds', '15', 'stop'), {'reason': 'no reason'}) ]) @defer.inlineCallbacks def test_action_stop_reason(self): yield self.callControl("stop", {'reason': 'because'}, ('builders', 77, 'builds', 5)) self.master.mq.assertProductions([ (('control', 'builds', '15', 'stop'), {'reason': 'because'}) ]) @defer.inlineCallbacks def test_action_rebuild(self): self.patch( self.master.data.updates, "rebuildBuildrequest", mock.Mock(spec=self.master.data.updates.rebuildBuildrequest, return_value=(1, [2])), ) r = yield self.callControl("rebuild", {}, ('builders', 77, 'builds', 5)) self.assertEqual(r, (1, [2])) buildrequest = yield self.master.data.get(('buildrequests', 82)) self.master.data.updates.rebuildBuildrequest.assert_called_with(buildrequest) class BuildsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = builds.BuildsEndpoint resourceTypeClass = builds.Build @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77, name='builder77'), fakedb.Builder(id=78, name='builder78'), fakedb.Builder(id=79, name='builder79'), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Build( id=14, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=4 ), fakedb.Build( id=15, builderid=78, masterid=88, workerid=12, buildrequestid=83, number=5, complete_at=1, ), fakedb.Build( id=16, builderid=79, masterid=88, workerid=12, buildrequestid=84, number=6, complete_at=1, ), fakedb.BuildProperty( buildid=13, name='reason', value='"force build"', source="Force Build Form" ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_all(self): builds = yield self.callGet(('builds',)) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4, 5, 6]) @defer.inlineCallbacks def test_get_builder(self): builds = yield self.callGet(('builders', 78, 'builds')) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [5]) @defer.inlineCallbacks def test_get_buildername(self): builds = yield self.callGet(('builders', 'builder78', 'builds')) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [5]) @defer.inlineCallbacks def test_get_buildername_not_existing(self): builds = yield self.callGet(('builders', 'builder78_nope', 'builds')) self.assertEqual(builds, []) @defer.inlineCallbacks def test_get_buildrequest(self): builds = yield self.callGet(('buildrequests', 82, 'builds')) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_get_buildrequest_not_existing(self): builds = yield self.callGet(('buildrequests', 899, 'builds')) self.assertEqual(builds, []) @defer.inlineCallbacks def test_get_buildrequest_via_filter(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('buildrequestid', 'eq', [82])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_get_buildrequest_via_filter_with_string(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('buildrequestid', 'eq', ['82'])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_get_worker(self): builds = yield self.callGet(('workers', 13, 'builds')) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_get_complete(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('complete', 'eq', [False])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_get_complete_at(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('complete_at', 'eq', [None])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for build in builds: self.validateData(build) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) @defer.inlineCallbacks def test_properties_injection(self): resultSpec = resultspec.OptimisedResultSpec( properties=[resultspec.Property(b'property', 'eq', ['reason'])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for build in builds: self.validateData(build) self.assertTrue(any(('reason' in b['properties']) for b in builds)) @defer.inlineCallbacks def test_get_filter_eq(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('builderid', 'eq', [78, 79])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for b in builds: self.validateData(b) self.assertEqual(sorted([b['number'] for b in builds]), [5, 6]) @defer.inlineCallbacks def test_get_filter_ne(self): resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('builderid', 'ne', [78, 79])] ) builds = yield self.callGet(('builds',), resultSpec=resultSpec) for b in builds: self.validateData(b) self.assertEqual(sorted([b['number'] for b in builds]), [3, 4]) class Build(interfaces.InterfaceTests, TestReactorMixin, unittest.TestCase): new_build_event = { 'builderid': 10, 'buildid': 100, 'buildrequestid': 13, 'workerid': 20, 'complete': False, 'complete_at': None, "locks_duration_s": 0, 'masterid': 824, 'number': 43, 'results': None, 'started_at': epoch2datetime(1), 'state_string': 'created', 'properties': {}, } @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = builds.Build(self.master) yield self.master.db.insert_test_data([ fakedb.Builder(id=10), fakedb.Master(id=824), fakedb.Worker(id=20, name='wrk'), fakedb.Buildset(id=999), fakedb.BuildRequest(id=499, buildsetid=999, builderid=10), fakedb.Build( id=99, builderid=10, masterid=824, workerid=20, buildrequestid=499, number=42 ), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def do_test_callthrough( self, dbMethodName, method, exp_retval=(1, 2), exp_args=None, exp_kwargs=None, *args, **kwargs, ): m = mock.Mock(return_value=defer.succeed(exp_retval)) setattr(self.master.db.builds, dbMethodName, m) res = yield method(*args, **kwargs) self.assertIdentical(res, exp_retval) m.assert_called_with(*(exp_args or args), **(exp_kwargs or kwargs)) @defer.inlineCallbacks def do_test_event(self, method, exp_events=None, *args, **kwargs): self.reactor.advance(1) if exp_events is None: exp_events = [] yield method(*args, **kwargs) self.master.mq.assertProductions(exp_events) def test_signature_addBuild(self): @self.assertArgSpecMatches( self.master.data.updates.addBuild, # fake self.rtype.addBuild, ) # real def addBuild(self, builderid, buildrequestid, workerid): pass def test_addBuild(self): return self.do_test_callthrough( 'addBuild', self.rtype.addBuild, builderid=10, buildrequestid=13, workerid=20, exp_kwargs={ "builderid": 10, "buildrequestid": 13, "workerid": 20, "masterid": self.master.masterid, "state_string": 'created', }, ) def test_addBuildEvent(self): @defer.inlineCallbacks def addBuild(*args, **kwargs): buildid, _ = yield self.rtype.addBuild(*args, **kwargs) yield self.rtype.generateNewBuildEvent(buildid) return None return self.do_test_event( addBuild, builderid=10, buildrequestid=13, workerid=20, exp_events=[ (('builders', '10', 'builds', '43', 'new'), self.new_build_event), (('builds', '100', 'new'), self.new_build_event), (('workers', '20', 'builds', '100', 'new'), self.new_build_event), ], ) def test_signature_setBuildStateString(self): @self.assertArgSpecMatches( self.master.data.updates.setBuildStateString, # fake self.rtype.setBuildStateString, ) # real def setBuildStateString(self, buildid, state_string): pass def test_setBuildStateString(self): return self.do_test_callthrough( 'setBuildStateString', self.rtype.setBuildStateString, buildid=10, state_string='a b' ) def test_signature_add_build_locks_duration(self): @self.assertArgSpecMatches( self.master.data.updates.add_build_locks_duration, self.rtype.add_build_locks_duration ) def add_build_locks_duration(self, buildid, duration_s): pass def test_add_build_locks_duration(self): return self.do_test_callthrough( "add_build_locks_duration", self.rtype.add_build_locks_duration, exp_retval=None, buildid=10, duration_s=5, ) def test_signature_finishBuild(self): @self.assertArgSpecMatches( self.master.data.updates.finishBuild, # fake self.rtype.finishBuild, ) # real def finishBuild(self, buildid, results): pass def test_finishBuild(self): return self.do_test_callthrough( 'finishBuild', self.rtype.finishBuild, buildid=15, results=3 )
16,093
Python
.py
391
31.741688
98
0.618383
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,370
test_buildsets.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 twisted.internet import defer from twisted.trial import unittest from buildbot.data import buildsets from buildbot.data import resultspec from buildbot.process.results import FAILURE from buildbot.process.results import SUCCESS from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces as util_interfaces from buildbot.util import epoch2datetime A_TIMESTAMP = 1341700729 A_TIMESTAMP_EPOCH = epoch2datetime(A_TIMESTAMP) EARLIER = 1248529376 EARLIER_EPOCH = epoch2datetime(EARLIER) class BuildsetEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = buildsets.BuildsetEndpoint resourceTypeClass = buildsets.Buildset @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Buildset(id=13, reason='because I said so'), fakedb.SourceStamp(id=92), fakedb.SourceStamp(id=93), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=92), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=93), fakedb.Buildset(id=14, reason='no sourcestamps'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): buildset = yield self.callGet(('buildsets', 13)) self.validateData(buildset) self.assertEqual(buildset['reason'], 'because I said so') @defer.inlineCallbacks def test_get_existing_no_sourcestamps(self): buildset = yield self.callGet(('buildsets', 14)) self.validateData(buildset) self.assertEqual(buildset['sourcestamps'], []) @defer.inlineCallbacks def test_get_missing(self): buildset = yield self.callGet(('buildsets', 99)) self.assertEqual(buildset, None) class BuildsetsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = buildsets.BuildsetsEndpoint resourceTypeClass = buildsets.Buildset @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.SourceStamp(id=92), fakedb.Buildset(id=13, complete=True), fakedb.Buildset(id=14, complete=False), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=92), fakedb.BuildsetSourceStamp(buildsetid=14, sourcestampid=92), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): buildsets = yield self.callGet(('buildsets',)) self.validateData(buildsets[0]) self.assertEqual(buildsets[0]['bsid'], 13) self.validateData(buildsets[1]) self.assertEqual(buildsets[1]['bsid'], 14) @defer.inlineCallbacks def test_get_complete(self): f = resultspec.Filter('complete', 'eq', [True]) buildsets = yield self.callGet( ('buildsets',), resultSpec=resultspec.ResultSpec(filters=[f]) ) self.assertEqual(len(buildsets), 1) self.validateData(buildsets[0]) self.assertEqual(buildsets[0]['bsid'], 13) @defer.inlineCallbacks def test_get_incomplete(self): f = resultspec.Filter('complete', 'eq', [False]) buildsets = yield self.callGet( ('buildsets',), resultSpec=resultspec.ResultSpec(filters=[f]) ) self.assertEqual(len(buildsets), 1) self.validateData(buildsets[0]) self.assertEqual(buildsets[0]['bsid'], 14) class Buildset(TestReactorMixin, util_interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = buildsets.Buildset(self.master) yield self.master.db.insert_test_data([ fakedb.SourceStamp( id=234, branch='br', codebase='cb', project='pr', repository='rep', revision='rev', created_at=89834834, ), fakedb.Builder(id=42, name='bldr1'), fakedb.Builder(id=43, name='bldr2'), fakedb.Buildset(id=199, complete=False), fakedb.BuildRequest(id=999, buildsetid=199, builderid=42), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() SS234_DATA = { 'branch': 'br', 'codebase': 'cb', 'patch': None, 'project': 'pr', 'repository': 'rep', 'revision': 'rev', 'created_at': epoch2datetime(89834834), 'ssid': 234, } def test_signature_addBuildset(self): @self.assertArgSpecMatches( self.master.data.updates.addBuildset, # fake self.rtype.addBuildset, ) # real 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, ): pass @defer.inlineCallbacks def do_test_addBuildset(self, kwargs, expectedReturn, expectedMessages, expectedBuildset): """Run a test of addBuildset. @param kwargs: kwargs to addBuildset @param expectedReturn: expected return value - tuple of (bsid, brids) @param expectedMessages: expected mq messages transmitted @param expectedBuildset: expected buildset inserted into the db The buildset is added at time A_TIMESTAMP. Note that addBuildset does not add sourcestamps, so this method assumes there are none in the db. """ self.reactor.advance(A_TIMESTAMP) (bsid, brids) = yield self.rtype.addBuildset(**kwargs) self.assertEqual((bsid, brids), expectedReturn) self.master.mq.assertProductions(expectedMessages, orderMatters=False) buildsets = yield self.master.db.buildsets.getBuildsets() buildsets = [bs for bs in buildsets if bs.bsid != 199] self.assertEqual( [ { 'external_idstring': bs.external_idstring, 'reason': bs.reason, 'rebuilt_buildid': bs.rebuilt_buildid, } for bs in buildsets ], [expectedBuildset], ) def _buildRequestMessageDict(self, brid, bsid, builderid): return { 'builderid': builderid, 'buildrequestid': brid, 'buildsetid': bsid, 'claimed': False, 'claimed_at': None, 'claimed_by_masterid': None, 'complete': False, 'complete_at': None, 'priority': 0, 'results': -1, 'submitted_at': epoch2datetime(A_TIMESTAMP), 'waited_for': True, 'properties': None, } def _buildRequestMessage1(self, brid, bsid, builderid): return ( ('buildsets', str(bsid), 'builders', str(builderid), 'buildrequests', str(brid), 'new'), self._buildRequestMessageDict(brid, bsid, builderid), ) def _buildRequestMessage2(self, brid, bsid, builderid): return ( ('buildrequests', str(brid), 'new'), self._buildRequestMessageDict(brid, bsid, builderid), ) def _buildRequestMessage3(self, brid, bsid, builderid): return ( ('builders', str(builderid), 'buildrequests', str(brid), 'new'), self._buildRequestMessageDict(brid, bsid, builderid), ) def _buildsetMessage( self, bsid, external_idstring='extid', reason='because', scheduler='fakesched', sourcestampids=None, submitted_at=A_TIMESTAMP, ): if sourcestampids is None: sourcestampids = [234] ssmap = {234: self.SS234_DATA} return ( ('buildsets', str(bsid), 'new'), { "bsid": bsid, "complete": False, "complete_at": None, "external_idstring": external_idstring, "parent_buildid": None, "reason": reason, "results": None, "scheduler": scheduler, "sourcestamps": [ssmap[ssid] for ssid in sourcestampids], "rebuilt_buildid": None, "submitted_at": submitted_at, }, ) def _buildsetCompleteMessage( self, bsid, complete_at=A_TIMESTAMP_EPOCH, submitted_at=A_TIMESTAMP_EPOCH, external_idstring='extid', reason='because', results=0, sourcestampids=None, ): if sourcestampids is None: sourcestampids = [234] ssmap = {234: self.SS234_DATA} return ( ('buildsets', str(bsid), 'complete'), { "bsid": bsid, "complete": True, "complete_at": complete_at, "external_idstring": external_idstring, "reason": reason, "results": results, "submitted_at": submitted_at, "sourcestamps": [ssmap[ssid] for ssid in sourcestampids], "rebuilt_buildid": None, "parent_buildid": None, "parent_relationship": None, }, ) def test_addBuildset_two_builderNames(self): kwargs = { "scheduler": 'fakesched', "reason": 'because', "sourcestamps": [234], "external_idstring": 'extid', "builderids": [42, 43], "waited_for": True, } expectedReturn = (200, {42: 1000, 43: 1001}) expectedMessages = [ self._buildRequestMessage1(1000, 200, 42), self._buildRequestMessage2(1000, 200, 42), self._buildRequestMessage3(1000, 200, 42), self._buildRequestMessage1(1001, 200, 43), self._buildRequestMessage2(1001, 200, 43), self._buildRequestMessage3(1001, 200, 43), self._buildsetMessage(200), ] expectedBuildset = { "reason": 'because', "external_idstring": 'extid', "rebuilt_buildid": None, } return self.do_test_addBuildset(kwargs, expectedReturn, expectedMessages, expectedBuildset) def test_addBuildset_no_builderNames(self): kwargs = { "scheduler": 'fakesched', "reason": 'because', "sourcestamps": [234], "external_idstring": 'extid', "waited_for": False, } expectedReturn = (200, {}) expectedMessages = [ self._buildsetMessage(200), # with no builderNames, this is done already self._buildsetCompleteMessage(200), ] expectedBuildset = { "reason": 'because', "external_idstring": 'extid', "rebuilt_buildid": None, } return self.do_test_addBuildset(kwargs, expectedReturn, expectedMessages, expectedBuildset) def test_signature_maybeBuildsetComplete(self): @self.assertArgSpecMatches( self.master.data.updates.maybeBuildsetComplete, # fake self.rtype.maybeBuildsetComplete, ) # real def maybeBuildsetComplete(self, bsid): pass @defer.inlineCallbacks def do_test_maybeBuildsetComplete( self, buildRequestCompletions=None, buildRequestResults=None, buildsetComplete=False, expectComplete=False, expectMessage=False, expectSuccess=True, ): """Test maybeBuildsetComplete. @param buildRequestCompletions: dict mapping brid to True if complete, else False (and defaulting to False) @param buildRequestResults: dict mapping brid to result (defaulting to SUCCESS) @param buildsetComplete: true if the buildset is already complete @param expectComplete: true if the buildset should be complete at exit @param expectMessage: true if a buildset completion message is expected @param expectSuccess: if expectComplete, whether to expect the buildset to be complete This first adds two buildsets to the database - 72 and 73. Buildset 72 is already complete if buildsetComplete is true; 73 is not complete. It adds four buildrequests - 42, 43, and 44 for buildset 72, and 45 for buildset 73. The completion and results are based on buidlRequestCompletions and buildRequestResults. Then, maybeBuildsetComplete is called for buildset 72, and the expectations are checked. """ if buildRequestCompletions is None: buildRequestCompletions = {} if buildRequestResults is None: buildRequestResults = {} self.reactor.advance(A_TIMESTAMP) def mkbr(brid, bsid): return fakedb.BuildRequest( id=brid, buildsetid=bsid, builderid=42, complete=buildRequestCompletions.get(brid, False), results=buildRequestResults.get(brid, SUCCESS), ) yield self.master.db.insert_test_data([ fakedb.Buildset( id=72, submitted_at=EARLIER, complete=buildsetComplete, complete_at=A_TIMESTAMP if buildsetComplete else None, ), mkbr(42, 72), mkbr(43, 72), mkbr(44, 72), fakedb.BuildsetSourceStamp(buildsetid=72, sourcestampid=234), fakedb.Buildset(id=73, complete=False), mkbr(45, 73), fakedb.BuildsetSourceStamp(buildsetid=73, sourcestampid=234), ]) yield self.rtype.maybeBuildsetComplete(72) buildset_ids = [ bs.bsid for bs in (yield self.master.db.buildsets.getBuildsets(complete=expectComplete)) ] self.assertIn(72, buildset_ids) if expectMessage: self.assertEqual( self.master.mq.productions, [ self._buildsetCompleteMessage( 72, results=SUCCESS if expectSuccess else FAILURE, submitted_at=EARLIER_EPOCH, ), ], ) else: self.assertEqual(self.master.mq.productions, []) def test_maybeBuildsetComplete_not_yet(self): # only brid 42 is complete, so the buildset is not complete return self.do_test_maybeBuildsetComplete(buildRequestCompletions={42: True}) def test_maybeBuildsetComplete_complete(self): return self.do_test_maybeBuildsetComplete( buildRequestCompletions={42: True, 43: True, 44: True}, expectComplete=True, expectMessage=True, ) def test_maybeBuildsetComplete_complete_failure(self): return self.do_test_maybeBuildsetComplete( buildRequestCompletions={42: True, 43: True, 44: True}, buildRequestResults={43: FAILURE}, expectComplete=True, expectMessage=True, expectSuccess=False, ) def test_maybeBuildsetComplete_already_complete(self): return self.do_test_maybeBuildsetComplete( buildRequestCompletions={42: True, 43: True, 44: True}, buildsetComplete=True, expectComplete=True, expectMessage=False, )
16,770
Python
.py
420
29.592857
100
0.612287
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,371
test_forceschedulers.py
buildbot_buildbot/master/buildbot/test/unit/data/test_forceschedulers.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.data import forceschedulers from buildbot.schedulers.forcesched import ForceScheduler from buildbot.test.util import endpoint expected_default = { 'all_fields': [ { 'columns': 1, 'autopopulate': None, 'default': '', 'fields': [ { 'default': '', 'autopopulate': None, 'fullName': 'username', 'hide': False, 'label': 'Your name:', 'maxsize': None, 'multiple': False, 'name': 'username', 'need_email': True, 'regex': None, 'required': False, 'size': 30, 'tablabel': 'Your name:', 'type': 'username', 'tooltip': '', }, { 'default': 'force build', 'autopopulate': None, 'fullName': 'reason', 'hide': False, 'label': 'reason', 'maxsize': None, 'multiple': False, 'name': 'reason', 'regex': None, 'required': False, 'size': 20, 'tablabel': 'reason', 'type': 'text', 'tooltip': '', }, { 'default': 0, 'autopopulate': None, 'fullName': 'priority', 'hide': False, 'label': 'priority', 'maxsize': None, 'multiple': False, 'name': 'priority', 'regex': None, 'required': False, 'size': 10, 'tablabel': 'priority', 'type': 'int', 'tooltip': '', }, ], 'fullName': None, 'hide': False, 'label': '', 'layout': 'vertical', 'maxsize': None, 'multiple': False, 'name': '', 'regex': None, 'required': False, 'tablabel': '', 'type': 'nested', 'tooltip': '', }, { 'columns': 2, 'default': '', 'fields': [ { 'default': '', 'autopopulate': None, 'fullName': 'branch', 'hide': False, 'label': 'Branch:', 'multiple': False, 'maxsize': None, 'name': 'branch', 'regex': None, 'required': False, 'size': 10, 'tablabel': 'Branch:', 'type': 'text', 'tooltip': '', }, { 'default': '', 'autopopulate': None, 'fullName': 'project', 'hide': False, 'label': 'Project:', 'maxsize': None, 'multiple': False, 'name': 'project', 'regex': None, 'required': False, 'size': 10, 'tablabel': 'Project:', 'type': 'text', 'tooltip': '', }, { 'default': '', 'autopopulate': None, 'fullName': 'repository', 'hide': False, 'label': 'Repository:', 'maxsize': None, 'multiple': False, 'name': 'repository', 'regex': None, 'required': False, 'size': 10, 'tablabel': 'Repository:', 'type': 'text', 'tooltip': '', }, { 'default': '', 'autopopulate': None, 'fullName': 'revision', 'hide': False, 'label': 'Revision:', 'maxsize': None, 'multiple': False, 'name': 'revision', 'regex': None, 'required': False, 'size': 10, 'tablabel': 'Revision:', 'type': 'text', 'tooltip': '', }, ], 'autopopulate': None, 'fullName': None, 'hide': False, 'label': '', 'layout': 'vertical', 'maxsize': None, 'multiple': False, 'name': '', 'regex': None, 'required': False, 'tablabel': '', 'type': 'nested', 'tooltip': '', }, ], 'builder_names': ['builder'], 'button_name': 'defaultforce', 'label': 'defaultforce', 'name': 'defaultforce', 'enabled': True, } class ForceschedulerEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = forceschedulers.ForceSchedulerEndpoint resourceTypeClass = forceschedulers.ForceScheduler maxDiff = None @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() scheds = [ForceScheduler(name="defaultforce", builderNames=["builder"])] self.master.allSchedulers = lambda: scheds def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): res = yield self.callGet(('forceschedulers', "defaultforce")) self.validateData(res) self.assertEqual(res, expected_default) @defer.inlineCallbacks def test_get_missing(self): res = yield self.callGet(('forceschedulers', 'foo')) self.assertEqual(res, None) class ForceSchedulersEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = forceschedulers.ForceSchedulersEndpoint resourceTypeClass = forceschedulers.ForceScheduler maxDiff = None @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() scheds = [ForceScheduler(name="defaultforce", builderNames=["builder"])] self.master.allSchedulers = lambda: scheds def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): res = yield self.callGet(('forceschedulers',)) self.assertEqual(res, [expected_default])
7,643
Python
.py
214
21.261682
80
0.444969
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,372
test_masters.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import masters from buildbot.db.masters import MasterModel from buildbot.process.results import RETRY from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import epoch2datetime SOMETIME = 1349016870 OTHERTIME = 1249016870 class MasterEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = masters.MasterEndpoint resourceTypeClass = masters.Master @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() self.master.name = "myname" yield self.db.insert_test_data([ fakedb.Master(id=13, active=False, last_active=SOMETIME), fakedb.Master(id=14, active=False, last_active=SOMETIME), fakedb.Builder(id=23, name='bldr1'), fakedb.BuilderMaster(builderid=23, masterid=13), fakedb.Builder(id=24, name='bldr2'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): master = yield self.callGet(('masters', 14)) self.validateData(master) self.assertEqual(master['name'], 'master-14') @defer.inlineCallbacks def test_get_builderid_existing(self): master = yield self.callGet(('builders', 23, 'masters', 13)) self.validateData(master) self.assertEqual(master['name'], 'master-13') @defer.inlineCallbacks def test_get_builderid_no_match(self): master = yield self.callGet(('builders', 24, 'masters', 13)) self.assertEqual(master, None) @defer.inlineCallbacks def test_get_builderid_missing(self): master = yield self.callGet(('builders', 25, 'masters', 13)) self.assertEqual(master, None) @defer.inlineCallbacks def test_get_missing(self): master = yield self.callGet(('masters', 99)) self.assertEqual(master, None) class MastersEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = masters.MastersEndpoint resourceTypeClass = masters.Master @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() self.master.name = "myname" yield self.db.insert_test_data([ fakedb.Master(id=13, active=False, last_active=SOMETIME), fakedb.Master(id=14, active=True, last_active=OTHERTIME), fakedb.Builder(id=22), fakedb.BuilderMaster(masterid=13, builderid=22), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): masters = yield self.callGet(('masters',)) for m in masters: self.validateData(m) self.assertEqual(sorted([m['masterid'] for m in masters]), [13, 14]) @defer.inlineCallbacks def test_get_builderid(self): masters = yield self.callGet(('builders', 22, 'masters')) for m in masters: self.validateData(m) self.assertEqual(sorted([m['masterid'] for m in masters]), [13]) @defer.inlineCallbacks def test_get_builderid_missing(self): masters = yield self.callGet(('builders', 23, 'masters')) self.assertEqual(masters, []) class Master(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = masters.Master(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_masterActive(self): @self.assertArgSpecMatches( self.master.data.updates.masterActive, # fake self.rtype.masterActive, ) # real def masterActive(self, name, masterid): pass @defer.inlineCallbacks def test_masterActive(self): self.reactor.advance(60) yield self.master.db.insert_test_data([ fakedb.Master(id=13, active=0, last_active=0), fakedb.Master(id=14, active=1, last_active=0), fakedb.Master(id=15, active=1, last_active=0), ]) # initial checkin yield self.rtype.masterActive(name='master-13', masterid=13) master = yield self.master.db.masters.getMaster(13) self.assertEqual( master, MasterModel(id=13, name='master-13', active=True, last_active=epoch2datetime(60)), ) self.assertEqual( self.master.mq.productions, [ ( ('masters', '13', 'started'), {"masterid": 13, "name": 'master-13', "active": True}, ), ], ) self.master.mq.productions = [] # updated checkin time, re-activation self.reactor.advance(60) yield self.master.db.masters.setMasterState(13, False) yield self.rtype.masterActive('master-13', masterid=13) master = yield self.master.db.masters.getMaster(13) self.assertEqual( master, MasterModel(id=13, name='master-13', active=True, last_active=epoch2datetime(120)), ) self.assertEqual( self.master.mq.productions, [ ( ('masters', '13', 'started'), {"masterid": 13, "name": 'master-13', "active": True}, ), ], ) self.master.mq.productions = [] def test_signature_masterStopped(self): @self.assertArgSpecMatches( self.master.data.updates.masterStopped, # fake self.rtype.masterStopped, ) # real def masterStopped(self, name, masterid): pass @defer.inlineCallbacks def test_masterStopped(self): self.reactor.advance(60) yield self.master.db.insert_test_data([ fakedb.Master(id=13, name='aname', active=1, last_active=self.reactor.seconds()), ]) self.rtype._masterDeactivated = mock.Mock() yield self.rtype.masterStopped(name='aname', masterid=13) self.rtype._masterDeactivated.assert_called_with(13, 'aname') @defer.inlineCallbacks def test_masterStopped_already(self): self.reactor.advance(60) yield self.master.db.insert_test_data([ fakedb.Master(id=13, name='aname', active=0, last_active=0), ]) self.rtype._masterDeactivated = mock.Mock() yield self.rtype.masterStopped(name='aname', masterid=13) self.rtype._masterDeactivated.assert_not_called() def test_signature_expireMasters(self): @self.assertArgSpecMatches( self.master.data.updates.expireMasters, # fake self.rtype.expireMasters, ) # real def expireMasters(self, forceHouseKeeping=False): pass @defer.inlineCallbacks def test_expireMasters(self): self.reactor.advance(60) yield self.master.db.insert_test_data([ fakedb.Master(id=14, active=1, last_active=0), fakedb.Master(id=15, active=1, last_active=0), ]) self.rtype._masterDeactivated = mock.Mock() # check after 10 minutes, and see #14 deactivated; #15 gets deactivated # by another master, so it's not included here self.reactor.advance(600) yield self.master.db.masters.setMasterState(15, False) yield self.rtype.expireMasters() master = yield self.master.db.masters.getMaster(14) self.assertEqual( master, MasterModel(id=14, name='master-14', active=False, last_active=epoch2datetime(0)), ) self.rtype._masterDeactivated.assert_called_with(14, 'master-14') @defer.inlineCallbacks def test_masterDeactivated(self): yield self.master.db.insert_test_data([ fakedb.Master(id=14, name='other', active=0, last_active=0), # set up a running build with some steps fakedb.Builder(id=77, name='b1'), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.BuildRequestClaim(brid=82, masterid=14, claimed_at=SOMETIME), fakedb.Build( id=13, builderid=77, masterid=14, workerid=13, buildrequestid=82, number=3, results=None, ), fakedb.Step(id=200, buildid=13), fakedb.Log(id=2000, stepid=200, num_lines=2), fakedb.LogChunk(logid=2000, first_line=1, last_line=2, content='ab\ncd'), ]) # mock out the _masterDeactivated methods this will call for rtype in 'builder', 'scheduler', 'changesource': rtype_obj = getattr(self.master.data.rtypes, rtype) m = mock.Mock(name=f'{rtype}._masterDeactivated', spec=rtype_obj._masterDeactivated) m.side_effect = lambda masterid: defer.succeed(None) rtype_obj._masterDeactivated = m # and the update methods.. for meth in 'finishBuild', 'finishStep', 'finishLog': m = mock.create_autospec(getattr(self.master.data.updates, meth)) m.side_effect = lambda *args, **kwargs: defer.succeed(None) setattr(self.master.data.updates, meth, m) yield self.rtype._masterDeactivated(14, 'other') self.master.data.rtypes.builder._masterDeactivated.assert_called_with(masterid=14) self.master.data.rtypes.scheduler._masterDeactivated.assert_called_with(masterid=14) self.master.data.rtypes.changesource._masterDeactivated.assert_called_with(masterid=14) # see that we finished off that build and its steps and logs updates = self.master.data.updates updates.finishLog.assert_called_with(logid=2000) updates.finishStep.assert_called_with(stepid=200, results=RETRY, hidden=False) updates.finishBuild.assert_called_with(buildid=13, results=RETRY) self.assertEqual( self.master.mq.productions, [ (('masters', '14', 'stopped'), {"masterid": 14, "name": 'other', "active": False}), ], )
11,304
Python
.py
257
34.883268
99
0.647739
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,373
test_test_result_sets.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 twisted.internet import defer from twisted.trial import unittest from buildbot.data import test_result_sets from buildbot.db.test_result_sets import TestResultSetModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class TestResultSetEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = test_result_sets.TestResultSetEndpoint resourceTypeClass = test_result_sets.TestResultSet @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.Master(id=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.Step(id=131, number=132, name='step132', buildid=30), fakedb.TestResultSet( id=13, builderid=88, buildid=30, stepid=131, description='desc', category='cat', value_unit='ms', complete=1, ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing_result_set(self): result = yield self.callGet(('test_result_sets', 13)) self.validateData(result) self.assertEqual( result, { 'test_result_setid': 13, 'builderid': 88, 'buildid': 30, 'stepid': 131, 'description': 'desc', 'category': 'cat', 'value_unit': 'ms', 'tests_passed': None, 'tests_failed': None, 'complete': True, }, ) @defer.inlineCallbacks def test_get_missing_result_set(self): results = yield self.callGet(('test_result_sets', 14)) self.assertIsNone(results) class TestResultSetsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = test_result_sets.TestResultSetsEndpoint resourceTypeClass = test_result_sets.TestResultSet @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.Master(id=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.Step(id=131, number=132, name='step132', buildid=30), fakedb.TestResultSet( id=13, builderid=88, buildid=30, stepid=131, description='desc', category='cat', value_unit='ms', complete=1, ), fakedb.TestResultSet( id=14, builderid=88, buildid=30, stepid=131, description='desc', category='cat', value_unit='ms', complete=1, ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_result_sets_builders_builderid(self): results = yield self.callGet(('builders', 88, 'test_result_sets')) for result in results: self.validateData(result) self.assertEqual([r['test_result_setid'] for r in results], [13, 14]) @defer.inlineCallbacks def test_get_result_sets_builders_buildername(self): results = yield self.callGet(('builders', 'b1', 'test_result_sets')) for result in results: self.validateData(result) self.assertEqual([r['test_result_setid'] for r in results], [13, 14]) @defer.inlineCallbacks def test_get_result_sets_builds_buildid(self): results = yield self.callGet(('builds', 30, 'test_result_sets')) for result in results: self.validateData(result) self.assertEqual([r['test_result_setid'] for r in results], [13, 14]) @defer.inlineCallbacks def test_get_result_sets_steps_stepid(self): results = yield self.callGet(('steps', 131, 'test_result_sets')) for result in results: self.validateData(result) self.assertEqual([r['test_result_setid'] for r in results], [13, 14]) class TestResultSet(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = test_result_sets.TestResultSet(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_add_test_result_set(self): @self.assertArgSpecMatches( self.master.data.updates.addTestResultSet, self.rtype.addTestResultSet ) def addTestResultSet(self, builderid, buildid, stepid, description, category, value_unit): pass def test_signature_complete_test_result_set(self): @self.assertArgSpecMatches( self.master.data.updates.completeTestResultSet, self.rtype.completeTestResultSet ) def completeTestResultSet(self, test_result_setid, tests_passed=None, tests_failed=None): pass @defer.inlineCallbacks def test_add_test_result_set(self): test_result_setid = yield self.rtype.addTestResultSet( builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms' ) msg_body = { 'test_result_setid': test_result_setid, 'builderid': 1, 'buildid': 2, 'stepid': 3, 'description': 'desc', 'category': 'cat4', 'value_unit': 'ms', 'tests_passed': None, 'tests_failed': None, 'complete': False, } self.master.mq.assertProductions([ (('test_result_sets', str(test_result_setid), 'new'), msg_body), ]) result = yield self.master.db.test_result_sets.getTestResultSet(test_result_setid) self.assertEqual( result, TestResultSetModel( id=test_result_setid, builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms', tests_passed=None, tests_failed=None, complete=False, ), ) @defer.inlineCallbacks def test_complete_test_result_set_no_results(self): test_result_setid = yield self.master.db.test_result_sets.addTestResultSet( builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms' ) yield self.rtype.completeTestResultSet(test_result_setid) msg_body = { 'test_result_setid': test_result_setid, 'builderid': 1, 'buildid': 2, 'stepid': 3, 'description': 'desc', 'category': 'cat4', 'value_unit': 'ms', 'tests_passed': None, 'tests_failed': None, 'complete': True, } self.master.mq.assertProductions([ (('test_result_sets', str(test_result_setid), 'completed'), msg_body), ]) result = yield self.master.db.test_result_sets.getTestResultSet(test_result_setid) self.assertEqual( result, TestResultSetModel( id=test_result_setid, builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms', tests_passed=None, tests_failed=None, complete=True, ), ) @defer.inlineCallbacks def test_complete_test_result_set_with_results(self): test_result_setid = yield self.master.db.test_result_sets.addTestResultSet( builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms' ) yield self.rtype.completeTestResultSet(test_result_setid, tests_passed=12, tests_failed=34) msg_body = { 'test_result_setid': test_result_setid, 'builderid': 1, 'buildid': 2, 'stepid': 3, 'description': 'desc', 'category': 'cat4', 'value_unit': 'ms', 'tests_passed': 12, 'tests_failed': 34, 'complete': True, } self.master.mq.assertProductions([ (('test_result_sets', str(test_result_setid), 'completed'), msg_body), ]) result = yield self.master.db.test_result_sets.getTestResultSet(test_result_setid) self.assertEqual( result, TestResultSetModel( id=test_result_setid, builderid=1, buildid=2, stepid=3, description='desc', category='cat4', value_unit='ms', tests_passed=12, tests_failed=34, complete=True, ), )
10,632
Python
.py
269
28.546468
99
0.585843
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,374
test_resultspec.py
buildbot_buildbot/master/buildbot/test/unit/data/test_resultspec.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 dataclasses import datetime import random from typing import TYPE_CHECKING from twisted.trial import unittest from buildbot.data import base from buildbot.data import resultspec from buildbot.data.resultspec import NoneComparator from buildbot.data.resultspec import ReverseComparator if TYPE_CHECKING: from typing import ClassVar from typing import Sequence class ResultSpecMKListMixin: @staticmethod def mkdata(fld: Sequence[str] | str, *values): if isinstance(fld, str): return [{fld: val} for val in values] return [dict(zip(fld, val)) for val in values] class ResultSpecMKDataclassMixin(ResultSpecMKListMixin): dataclasses_cache: ClassVar[dict[str, type]] = {} @classmethod def _get_dataclass(cls, fields: Sequence[str]) -> type: """ Re-use runtime dataclasses so comparison work """ class_key = f"ResultSpecMKDataclassMixin_{'_'.join(fields)}" if class_key not in cls.dataclasses_cache: test_cls = dataclasses.make_dataclass(class_key, fields) cls.dataclasses_cache[class_key] = test_cls return cls.dataclasses_cache[class_key] @staticmethod def mkdata(fld: Sequence[str] | str, *values): if isinstance(fld, str): fields = [fld] else: fields = sorted(fld) test_cls = ResultSpecMKDataclassMixin._get_dataclass(fields) return [test_cls(**item) for item in ResultSpecMKListMixin.mkdata(fld, *values)] class FilterTestMixin: @staticmethod def mkdata(fld, *values) -> list: raise NotImplementedError() def test_eq(self): f = resultspec.Filter('num', 'eq', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10))), self.mkdata('num', 10)) def test_eq_plural(self): f = resultspec.Filter('num', 'eq', [10, 15, 20]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 10, 15)) def test_ne(self): f = resultspec.Filter('num', 'ne', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10))), self.mkdata('num', 5)) def test_ne_plural(self): f = resultspec.Filter('num', 'ne', [10, 15, 20]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 5)) def test_lt(self): f = resultspec.Filter('num', 'lt', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 5)) def test_le(self): f = resultspec.Filter('num', 'le', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 5, 10)) def test_gt(self): f = resultspec.Filter('num', 'gt', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 15)) def test_ge(self): f = resultspec.Filter('num', 'ge', [10]) self.assertEqual(list(f.apply(self.mkdata('num', 5, 10, 15))), self.mkdata('num', 10, 15)) def test_contains(self): f = resultspec.Filter('num', 'contains', [10]) self.assertEqual( list(f.apply(self.mkdata('num', [5, 1], [10, 1], [15, 1]))), self.mkdata('num', [10, 1]) ) def test_contains_plural(self): f = resultspec.Filter('num', 'contains', [10, 5]) self.assertEqual( list(f.apply(self.mkdata('num', [5, 1], [10, 1], [15, 1]))), self.mkdata('num', [5, 1], [10, 1]), ) class FilterList(unittest.TestCase, ResultSpecMKListMixin, FilterTestMixin): pass class FilterDataclass(unittest.TestCase, ResultSpecMKDataclassMixin, FilterTestMixin): pass class ResultSpecTestMixin: @staticmethod def mkdata(fld, *values) -> list: raise NotImplementedError() def assertListResultEqual(self, a, b): self.assertIsInstance(a, base.ListResult) self.assertIsInstance(b, base.ListResult) self.assertEqual(a, b) def test_apply_None(self): self.assertEqual(resultspec.ResultSpec().apply(None), None) def test_apply_details_fields(self): data = {"name": 'clyde', "id": 14, "favcolor": 'red'} self.assertEqual(resultspec.ResultSpec(fields=['name']).apply(data), {"name": 'clyde'}) self.assertEqual( resultspec.ResultSpec(fields=['name', 'id']).apply(data), {"name": 'clyde', "id": 14} ) def test_apply_collection_fields(self): data = self.mkdata(('a', 'b', 'c'), (1, 11, 111), (2, 22, 222)) self.assertEqual(resultspec.ResultSpec(fields=['a']).apply(data), [{'a': 1}, {'a': 2}]) self.assertEqual( resultspec.ResultSpec(fields=['a', 'c']).apply(data), [{'a': a, 'c': c} for a, c in [(1, 111), (2, 222)]], ) def test_apply_ordering(self): data = self.mkdata('name', 'albert', 'bruce', 'cedric', 'dwayne') exp = self.mkdata('name', 'albert', 'bruce', 'cedric', 'dwayne') random.shuffle(data) self.assertEqual(resultspec.ResultSpec(order=['name']).apply(data), exp) self.assertEqual(resultspec.ResultSpec(order=['-name']).apply(data), list(reversed(exp))) def test_apply_ordering_multi(self): data = self.mkdata( ('fn', 'ln'), ('cedric', 'willis'), ('albert', 'engelbert'), ('bruce', 'willis'), ('dwayne', 'montague'), ) exp = base.ListResult( self.mkdata( ('fn', 'ln'), ('albert', 'engelbert'), ('dwayne', 'montague'), ('bruce', 'willis'), ('cedric', 'willis'), ), total=4, ) random.shuffle(data) self.assertListResultEqual(resultspec.ResultSpec(order=['ln', 'fn']).apply(data), exp) exp = base.ListResult( self.mkdata( ('fn', 'ln'), ('cedric', 'willis'), ('bruce', 'willis'), ('dwayne', 'montague'), ('albert', 'engelbert'), ), total=4, ) self.assertListResultEqual(resultspec.ResultSpec(order=['-ln', '-fn']).apply(data), exp) def test_apply_filter(self): data = self.mkdata('name', 'albert', 'bruce', 'cedric', 'dwayne') f = resultspec.Filter(field='name', op='gt', values=['bruce']) self.assertListResultEqual( resultspec.ResultSpec(filters=[f]).apply(data), base.ListResult(self.mkdata('name', 'cedric', 'dwayne'), total=2), ) f2 = resultspec.Filter(field='name', op='le', values=['cedric']) self.assertListResultEqual( resultspec.ResultSpec(filters=[f, f2]).apply(data), base.ListResult(self.mkdata('name', 'cedric'), total=1), ) def test_apply_missing_fields(self): data = self.mkdata( ('fn', 'ln'), ('cedric', 'willis'), ('albert', 'engelbert'), ('bruce', 'willis'), ('dwayne', 'montague'), ) resultspec.ResultSpec(fields=['fn'], order=['ln']).apply(data) def test_sort_null_datetimefields(self): data = self.mkdata(('fn', 'ln'), ('albert', datetime.datetime(1, 1, 1)), ('cedric', None)) exp = self.mkdata(('fn', 'ln'), ('cedric', None), ('albert', datetime.datetime(1, 1, 1))) self.assertListResultEqual( resultspec.ResultSpec(order=['ln']).apply(data), base.ListResult(exp, total=2) ) def do_test_pagination(self, bareList): data = self.mkdata('x', *list(range(101, 131))) if not bareList: data = base.ListResult(data) data.offset = None data.total = len(data) data.limit = None self.assertListResultEqual( resultspec.ResultSpec(offset=0).apply(data), base.ListResult(self.mkdata('x', *list(range(101, 131))), offset=0, total=30), ) self.assertListResultEqual( resultspec.ResultSpec(offset=10).apply(data), base.ListResult(self.mkdata('x', *list(range(111, 131))), offset=10, total=30), ) self.assertListResultEqual( resultspec.ResultSpec(offset=10, limit=10).apply(data), base.ListResult( self.mkdata('x', *list(range(111, 121))), offset=10, total=30, limit=10 ), ) self.assertListResultEqual( resultspec.ResultSpec(offset=20, limit=15).apply(data), base.ListResult( self.mkdata('x', *list(range(121, 131))), offset=20, total=30, limit=15 ), ) # off the end def test_pagination_bare_list(self): return self.do_test_pagination(bareList=True) def test_pagination_ListResult(self): return self.do_test_pagination(bareList=False) def test_pagination_prepaginated(self): data = base.ListResult(self.mkdata('x', *list(range(10, 20)))) data.offset = 10 data.total = 30 data.limit = 10 self.assertListResultEqual( # ResultSpec has its offset/limit fields cleared resultspec.ResultSpec().apply(data), base.ListResult(self.mkdata('x', *list(range(10, 20))), offset=10, total=30, limit=10), ) def test_pagination_prepaginated_without_clearing_resultspec(self): data = base.ListResult(self.mkdata('x', *list(range(10, 20)))) data.offset = 10 data.limit = 10 # ResultSpec does not have its offset/limit fields cleared - this is # detected as an assertion failure with self.assertRaises(AssertionError): resultspec.ResultSpec(offset=10, limit=20).apply(data) def test_endpoint_returns_total_without_applying_filters(self): data = base.ListResult(self.mkdata('x', *list(range(10, 20)))) data.total = 99 # apply doesn't want to get a total with filters still outstanding f = resultspec.Filter(field='x', op='gt', values=[23]) with self.assertRaises(AssertionError): resultspec.ResultSpec(filters=[f]).apply(data) def test_popProperties(self): expected = ['prop1', 'prop2'] rs = resultspec.ResultSpec(properties=[resultspec.Property(b'property', 'eq', expected)]) self.assertEqual(len(rs.properties), 1) self.assertEqual(rs.popProperties(), expected) self.assertEqual(len(rs.properties), 0) def test_popFilter(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', [10]), resultspec.Filter('foo', 'gt', [5]), resultspec.Filter('base', 'ne', [20]), ] ) self.assertEqual(rs.popFilter('baz', 'lt'), None) # no match self.assertEqual(rs.popFilter('foo', 'eq'), [10]) self.assertEqual(len(rs.filters), 2) def test_popBooleanFilter(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', [True]), resultspec.Filter('bar', 'ne', [False]), ] ) self.assertEqual(rs.popBooleanFilter('foo'), True) self.assertEqual(rs.popBooleanFilter('bar'), True) self.assertEqual(len(rs.filters), 0) def test_popStringFilter(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', ['foo']), ] ) self.assertEqual(rs.popStringFilter('foo'), 'foo') def test_popStringFilterSeveral(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', ['foo', 'bar']), ] ) self.assertEqual(rs.popStringFilter('foo'), None) def test_popIntegerFilter(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', ['12']), ] ) self.assertEqual(rs.popIntegerFilter('foo'), 12) def test_popIntegerFilterSeveral(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', ['12', '13']), ] ) self.assertEqual(rs.popIntegerFilter('foo'), None) def test_popIntegerFilterNotInt(self): rs = resultspec.ResultSpec( filters=[ resultspec.Filter('foo', 'eq', ['bar']), ] ) with self.assertRaises(ValueError): rs.popIntegerFilter('foo') def test_removeOrder(self): rs = resultspec.ResultSpec(order=['foo', '-bar']) rs.removeOrder() self.assertEqual(rs.order, None) def test_popField(self): rs = resultspec.ResultSpec(fields=['foo', 'bar']) self.assertTrue(rs.popField('foo')) self.assertEqual(rs.fields, ['bar']) def test_popField_not_present(self): rs = resultspec.ResultSpec(fields=['foo', 'bar']) self.assertFalse(rs.popField('nosuch')) self.assertEqual(rs.fields, ['foo', 'bar']) class ResultSpecList(unittest.TestCase, ResultSpecMKListMixin, ResultSpecTestMixin): def test_apply_missing_fields(self): # note that the REST interface catches this with a nicer error message with self.assertRaises(KeyError): super().test_apply_missing_fields() class ResultSpecDataclass(unittest.TestCase, ResultSpecMKDataclassMixin, ResultSpecTestMixin): def test_apply_missing_fields(self): with self.assertRaises(TypeError): super().test_apply_missing_fields() def test_apply_collection_fields(self): with self.assertRaises(TypeError): super().test_apply_collection_fields() class ComparatorTestMixin: @staticmethod def mkdata(fld, *values) -> list: raise NotImplementedError() def test_noneComparator(self): self.assertNotEqual(NoneComparator(None), NoneComparator(datetime.datetime(1, 1, 1))) self.assertNotEqual(NoneComparator(datetime.datetime(1, 1, 1)), NoneComparator(None)) self.assertLess(NoneComparator(None), NoneComparator(datetime.datetime(1, 1, 1))) self.assertGreater(NoneComparator(datetime.datetime(1, 1, 1)), NoneComparator(None)) self.assertLess( NoneComparator(datetime.datetime(1, 1, 1)), NoneComparator(datetime.datetime(1, 1, 2)) ) self.assertEqual( NoneComparator(datetime.datetime(1, 1, 1)), NoneComparator(datetime.datetime(1, 1, 1)) ) self.assertGreater( NoneComparator(datetime.datetime(1, 1, 2)), NoneComparator(datetime.datetime(1, 1, 1)) ) self.assertEqual(NoneComparator(None), NoneComparator(None)) def test_noneComparison(self): noneInList = ["z", None, None, "q", "a", None, "v"] sortedList = sorted(noneInList, key=NoneComparator) self.assertEqual(sortedList, [None, None, None, "a", "q", "v", "z"]) def test_reverseComparator(self): reverse35 = ReverseComparator(35) reverse36 = ReverseComparator(36) self.assertEqual(reverse35, reverse35) self.assertNotEqual(reverse35, reverse36) self.assertLess(reverse36, reverse35) self.assertGreater(reverse35, reverse36) self.assertLess(reverse36, reverse35) def test_reverseComparison(self): nums = [1, 2, 3, 4, 5] nums.sort(key=ReverseComparator) self.assertEqual(nums, [5, 4, 3, 2, 1]) def test_reverseComparisonWithNone(self): noneInList = ["z", None, None, "q", "a", None, "v"] sortedList = sorted(noneInList, key=lambda x: ReverseComparator(NoneComparator(x))) self.assertEqual(sortedList, ["z", "v", "q", "a", None, None, None]) class ComparatorList(unittest.TestCase, ResultSpecMKListMixin, ComparatorTestMixin): pass class ComparatorDataclass(unittest.TestCase, ResultSpecMKDataclassMixin, ComparatorTestMixin): pass
16,734
Python
.py
369
36.346883
100
0.616098
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,375
test_projects.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.data import projects from buildbot.data import resultspec from buildbot.db.projects import ProjectModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class ProjectEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = projects.ProjectEndpoint resourceTypeClass = projects.Project @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Project(id=1, name='project1'), fakedb.Project(id=2, name='project2'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing_id(self): project = yield self.callGet(('projects', 2)) self.validateData(project) self.assertEqual(project['name'], 'project2') @defer.inlineCallbacks def test_get_existing_name(self): project = yield self.callGet(('projects', 'project2')) self.validateData(project) self.assertEqual(project['name'], 'project2') @defer.inlineCallbacks def test_get_missing(self): project = yield self.callGet(('projects', 99)) self.assertIsNone(project) @defer.inlineCallbacks def test_get_missing_with_name(self): project = yield self.callGet(('projects', 'project99')) self.assertIsNone(project) class ProjectsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = projects.ProjectsEndpoint resourceTypeClass = projects.Project @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Project(id=1, name='project1'), fakedb.Project(id=2, name='project2'), fakedb.Project(id=3, name='project3'), fakedb.Master(id=100), fakedb.Builder(id=200, projectid=2), fakedb.Builder(id=201, projectid=3), fakedb.BuilderMaster(id=300, builderid=200, masterid=100), ]) def tearDown(self): self.tearDownEndpoint() @parameterized.expand([ ('no_filter', None, [1, 2, 3]), ('active', True, [2]), ('inactive', False, [1, 3]), ]) @defer.inlineCallbacks def test_get(self, name, active_filter, expected_projectids): result_spec = None if active_filter is not None: result_spec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('active', 'eq', [active_filter])] ) projects = yield self.callGet(('projects',), resultSpec=result_spec) for b in projects: self.validateData(b) self.assertEqual(sorted([b['projectid'] for b in projects]), expected_projectids) class Project(interfaces.InterfaceTests, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = projects.Project(self.master) yield self.master.db.insert_test_data([ fakedb.Project(id=13, name="fake_project"), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_find_project_id(self): @self.assertArgSpecMatches( self.master.data.updates.find_project_id, # fake self.rtype.find_project_id, ) # real def find_project_id(self, name): pass def test_find_project_id(self): # this just passes through to the db method, so test that rv = defer.succeed(None) self.master.db.projects.find_project_id = mock.Mock(return_value=rv) self.assertIdentical(self.rtype.find_project_id('foo'), rv) def test_signature_update_project_info(self): @self.assertArgSpecMatches(self.master.data.updates.update_project_info) def update_project_info( self, projectid, slug, description, description_format, description_html ): pass @defer.inlineCallbacks def test_update_project_info(self): yield self.master.data.updates.update_project_info( 13, "slug13", "project13 desc", "format", "html desc", ) projects = yield self.master.db.projects.get_projects() self.assertEqual( projects, [ ProjectModel( id=13, name="fake_project", slug="slug13", description="project13 desc", description_format="format", description_html="html desc", ) ], )
5,821
Python
.py
142
32.880282
97
0.664011
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,376
test_base.py
buildbot_buildbot/master/buildbot/test/unit/data/test_base.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import base from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint class ResourceType(TestReactorMixin, unittest.TestCase): def setUp(self): self.setup_test_reactor(auto_tear_down=False) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def makeResourceTypeSubclass(self, **attributes): attributes.setdefault('name', 'thing') return type('ThingResourceType', (base.ResourceType,), attributes) def test_sets_master(self): cls = self.makeResourceTypeSubclass() master = mock.Mock() inst = cls(master) self.assertIdentical(inst.master, master) def test_getEndpoints_instances_fails(self): ep = base.Endpoint(None, None) cls = self.makeResourceTypeSubclass(endpoints=[ep]) inst = cls(None) with self.assertRaises(TypeError): inst.getEndpoints() def test_getEndpoints_classes(self): class MyEndpoint(base.Endpoint): pass cls = self.makeResourceTypeSubclass(endpoints=[MyEndpoint]) master = mock.Mock() inst = cls(master) eps = inst.getEndpoints() self.assertIsInstance(eps[0], MyEndpoint) self.assertIdentical(eps[0].master, master) @defer.inlineCallbacks def test_produceEvent(self): cls = self.makeResourceTypeSubclass( name='singular', eventPathPatterns="/foo/:fooid/bar/:barid" ) master = yield fakemaster.make_master(self, wantMq=True) master.mq.verifyMessages = False # since this is a pretend message inst = cls(master) inst.produceEvent( {"fooid": 10, "barid": '20'}, # note integer vs. string 'tested', ) master.mq.assertProductions([ (('foo', '10', 'bar', '20', 'tested'), {"fooid": 10, "barid": '20'}) ]) @defer.inlineCallbacks def test_compilePatterns(self): class MyResourceType(base.ResourceType): eventPathPatterns = """ /builder/:builderid/build/:number /build/:buildid """ master = yield fakemaster.make_master(self, wantMq=True) master.mq.verifyMessages = False # since this is a pretend message inst = MyResourceType(master) self.assertEqual(inst.eventPaths, ['builder/{builderid}/build/{number}', 'build/{buildid}']) class Endpoint(endpoint.EndpointMixin, unittest.TestCase): class MyResourceType(base.ResourceType): name = "my" class MyEndpoint(base.Endpoint): pathPatterns = """ /my/pattern """ endpointClass = MyEndpoint resourceTypeClass = MyResourceType @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() def tearDown(self): self.tearDownEndpoint() def test_sets_master(self): self.assertIdentical(self.master, self.ep.master) class ListResult(unittest.TestCase): def test_constructor(self): lr = base.ListResult([1, 2, 3], offset=10, total=20, limit=3) self.assertEqual(lr.data, [1, 2, 3]) self.assertEqual(lr.offset, 10) self.assertEqual(lr.total, 20) self.assertEqual(lr.limit, 3) def test_repr(self): lr = base.ListResult([1, 2, 3], offset=10, total=20, limit=3) self.assertTrue(repr(lr).startswith('ListResult')) def test_eq(self): lr1 = base.ListResult([1, 2, 3], offset=10, total=20, limit=3) lr2 = base.ListResult([1, 2, 3], offset=20, total=30, limit=3) lr3 = base.ListResult([1, 2, 3], offset=20, total=30, limit=3) self.assertEqual(lr2, lr3) self.assertNotEqual(lr1, lr2) self.assertNotEqual(lr1, lr3) def test_eq_to_list(self): list = [1, 2, 3] lr1 = base.ListResult([1, 2, 3], offset=10, total=20, limit=3) self.assertNotEqual(lr1, list) lr2 = base.ListResult([1, 2, 3], offset=None, total=None, limit=None) self.assertEqual(lr2, list) lr3 = base.ListResult([1, 2, 3], total=3) self.assertEqual(lr3, list) lr4 = base.ListResult([1, 2, 3], total=4) self.assertNotEqual(lr4, list)
5,104
Python
.py
119
35.621849
100
0.667473
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,377
test_workers.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import exceptions from buildbot.data import resultspec from buildbot.data import workers from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces testData = [ fakedb.Builder(id=40, name='b1'), fakedb.Builder(id=41, name='b2'), fakedb.Master(id=13), fakedb.Master(id=14), fakedb.BuilderMaster(id=4013, builderid=40, masterid=13), fakedb.BuilderMaster(id=4014, builderid=40, masterid=14), fakedb.BuilderMaster(id=4113, builderid=41, masterid=13), fakedb.Worker(id=1, name='linux', info={}), fakedb.ConfiguredWorker(id=14013, workerid=1, buildermasterid=4013), fakedb.ConfiguredWorker(id=14014, workerid=1, buildermasterid=4014), fakedb.ConnectedWorker(id=113, masterid=13, workerid=1), fakedb.Worker(id=2, name='windows', info={"a": "b"}), fakedb.ConfiguredWorker(id=24013, workerid=2, buildermasterid=4013), fakedb.ConfiguredWorker(id=24014, workerid=2, buildermasterid=4014), fakedb.ConfiguredWorker(id=24113, workerid=2, buildermasterid=4113), fakedb.ConnectedWorker(id=214, masterid=14, workerid=2), ] def configuredOnKey(worker): return (worker.get('masterid', 0), worker.get('builderid', 0)) def _filt(bs, builderid, masterid): bs['connected_to'] = sorted([ d for d in bs['connected_to'] if not masterid or masterid == d['masterid'] ]) bs['configured_on'] = sorted( [ d for d in bs['configured_on'] if (not masterid or masterid == d['masterid']) and (not builderid or builderid == d['builderid']) ], key=configuredOnKey, ) return bs def w1(builderid=None, masterid=None): return _filt( { 'workerid': 1, 'name': 'linux', 'workerinfo': {}, 'paused': False, 'graceful': False, "pause_reason": None, 'connected_to': [ {'masterid': 13}, ], 'configured_on': sorted( [ {'builderid': 40, 'masterid': 13}, {'builderid': 40, 'masterid': 14}, ], key=configuredOnKey, ), }, builderid, masterid, ) def w2(builderid=None, masterid=None): return _filt( { 'workerid': 2, 'name': 'windows', 'workerinfo': {'a': 'b'}, 'paused': False, "pause_reason": None, 'graceful': False, 'connected_to': [ {'masterid': 14}, ], 'configured_on': sorted( [ {'builderid': 40, 'masterid': 13}, {'builderid': 41, 'masterid': 13}, {'builderid': 40, 'masterid': 14}, ], key=configuredOnKey, ), }, builderid, masterid, ) class WorkerEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = workers.WorkerEndpoint resourceTypeClass = workers.Worker @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data(testData) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): worker = yield self.callGet(('workers', 2)) self.validateData(worker) worker['configured_on'] = sorted(worker['configured_on'], key=configuredOnKey) self.assertEqual(worker, w2()) @defer.inlineCallbacks def test_get_existing_name(self): worker = yield self.callGet(('workers', 'linux')) self.validateData(worker) worker['configured_on'] = sorted(worker['configured_on'], key=configuredOnKey) self.assertEqual(worker, w1()) @defer.inlineCallbacks def test_get_existing_masterid(self): worker = yield self.callGet(('masters', 14, 'workers', 2)) self.validateData(worker) worker['configured_on'] = sorted(worker['configured_on'], key=configuredOnKey) self.assertEqual(worker, w2(masterid=14)) @defer.inlineCallbacks def test_get_existing_builderid(self): worker = yield self.callGet(('builders', 40, 'workers', 2)) self.validateData(worker) worker['configured_on'] = sorted(worker['configured_on'], key=configuredOnKey) self.assertEqual(worker, w2(builderid=40)) @defer.inlineCallbacks def test_get_existing_masterid_builderid(self): worker = yield self.callGet(('masters', 13, 'builders', 40, 'workers', 2)) self.validateData(worker) worker['configured_on'] = sorted(worker['configured_on'], key=configuredOnKey) self.assertEqual(worker, w2(masterid=13, builderid=40)) @defer.inlineCallbacks def test_get_missing(self): worker = yield self.callGet(('workers', 99)) self.assertEqual(worker, None) @defer.inlineCallbacks def test_set_worker_paused(self): yield self.master.data.updates.set_worker_paused(2, True, "reason") worker = yield self.callGet(('workers', 2)) self.validateData(worker) self.assertEqual(worker['paused'], True) self.assertEqual(worker["pause_reason"], "reason") @defer.inlineCallbacks def test_set_worker_graceful(self): yield self.master.data.updates.set_worker_graceful(2, True) worker = yield self.callGet(('workers', 2)) self.validateData(worker) self.assertEqual(worker['graceful'], True) @defer.inlineCallbacks def test_actions(self): for action in ("stop", "pause", "unpause", "kill"): yield self.callControl(action, {}, ('masters', 13, 'builders', 40, 'workers', 2)) self.master.mq.assertProductions([ (('control', 'worker', '2', action), {'reason': 'no reason'}) ]) @defer.inlineCallbacks def test_bad_actions(self): with self.assertRaises(exceptions.InvalidControlException): yield self.callControl("bad_action", {}, ('masters', 13, 'builders', 40, 'workers', 2)) class WorkersEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = workers.WorkersEndpoint resourceTypeClass = workers.Worker @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data(testData) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): workers = yield self.callGet(('workers',)) for b in workers: self.validateData(b) b['configured_on'] = sorted(b['configured_on'], key=configuredOnKey) self.assertEqual( sorted(workers, key=configuredOnKey), sorted([w1(), w2()], key=configuredOnKey) ) @defer.inlineCallbacks def test_get_masterid(self): workers = yield self.callGet(( 'masters', '13', 'workers', )) for b in workers: self.validateData(b) self.assertEqual( sorted(workers, key=configuredOnKey), sorted([w1(masterid=13), w2(masterid=13)], key=configuredOnKey), ) @defer.inlineCallbacks def test_get_builderid(self): workers = yield self.callGet(( 'builders', '41', 'workers', )) for b in workers: self.validateData(b) self.assertEqual( sorted(workers, key=configuredOnKey), sorted([w2(builderid=41)], key=configuredOnKey) ) @defer.inlineCallbacks def test_get_masterid_builderid(self): workers = yield self.callGet(( 'masters', '13', 'builders', '41', 'workers', )) for b in workers: self.validateData(b) self.assertEqual( sorted(workers, key=configuredOnKey), sorted([w2(masterid=13, builderid=41)], key=configuredOnKey), ) @defer.inlineCallbacks def test_set_worker_paused_find_by_paused(self): yield self.master.data.updates.set_worker_paused(2, True, None) resultSpec = resultspec.OptimisedResultSpec( filters=[resultspec.Filter('paused', 'eq', [True])] ) workers = yield self.callGet(('workers',), resultSpec=resultSpec) self.assertEqual(len(workers), 1) worker = workers[0] self.validateData(worker) self.assertEqual(worker['paused'], True) class Worker(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = workers.Worker(self.master) yield self.master.db.insert_test_data([ fakedb.Master(id=13), fakedb.Master(id=14), ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_findWorkerId(self): @self.assertArgSpecMatches( self.master.data.updates.findWorkerId, # fake self.rtype.findWorkerId, ) # real def findWorkerId(self, name): pass def test_signature_workerConfigured(self): @self.assertArgSpecMatches( self.master.data.updates.workerConfigured, # fake self.rtype.workerConfigured, ) # real def workerConfigured(self, workerid, masterid, builderids): pass def test_signature_set_worker_paused(self): @self.assertArgSpecMatches(self.master.data.updates.set_worker_paused) def set_worker_paused(self, workerid, paused, pause_reason=None): pass def test_signature_set_worker_graceful(self): @self.assertArgSpecMatches(self.master.data.updates.set_worker_graceful) def set_worker_graceful(self, workerid, graceful): pass def test_findWorkerId(self): # this just passes through to the db method, so test that rv = defer.succeed(None) self.master.db.workers.findWorkerId = mock.Mock(return_value=rv) self.assertIdentical(self.rtype.findWorkerId('foo'), rv) def test_findWorkerId_not_id(self): with self.assertRaises(ValueError): self.rtype.findWorkerId(b'foo') with self.assertRaises(ValueError): self.rtype.findWorkerId('123/foo')
11,543
Python
.py
287
31.686411
99
0.636542
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,378
test_buildrequests.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 import datetime from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import buildrequests from buildbot.data import resultspec from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import UTC from buildbot.util import epoch2datetime class TestBuildRequestEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = buildrequests.BuildRequestEndpoint resourceTypeClass = buildrequests.BuildRequest CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC) CLAIMED_AT_EPOCH = 266761875 SUBMITTED_AT = datetime.datetime(1979, 6, 15, 12, 31, 15, tzinfo=UTC) SUBMITTED_AT_EPOCH = 298297875 COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC) COMPLETE_AT_EPOCH = 329920275 @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77, name='bbb'), fakedb.Master(id=fakedb.FakeDBConnector.MASTER_ID), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest( id=44, buildsetid=8822, builderid=77, priority=7, submitted_at=self.SUBMITTED_AT_EPOCH, waited_for=1, ), fakedb.BuildsetProperty( buildsetid=8822, property_name='prop1', property_value='["one", "fake1"]' ), fakedb.BuildsetProperty( buildsetid=8822, property_name='prop2', property_value='["two", "fake2"]' ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def testGetExisting(self): self.db.buildrequests.claimBuildRequests([44], claimed_at=self.CLAIMED_AT) self.db.buildrequests.completeBuildRequests([44], 75, complete_at=self.COMPLETE_AT) buildrequest = yield self.callGet(('buildrequests', 44)) self.validateData(buildrequest) # check data formatting: self.assertEqual(buildrequest['buildrequestid'], 44) self.assertEqual(buildrequest['complete'], True) self.assertEqual(buildrequest['builderid'], 77) self.assertEqual(buildrequest['waited_for'], True) self.assertEqual(buildrequest['claimed_at'], self.CLAIMED_AT) self.assertEqual(buildrequest['results'], 75) self.assertEqual(buildrequest['claimed_by_masterid'], fakedb.FakeDBConnector.MASTER_ID) self.assertEqual(buildrequest['claimed'], True) self.assertEqual(buildrequest['submitted_at'], self.SUBMITTED_AT) self.assertEqual(buildrequest['complete_at'], self.COMPLETE_AT) self.assertEqual(buildrequest['buildsetid'], 8822) self.assertEqual(buildrequest['priority'], 7) self.assertEqual(buildrequest['properties'], None) @defer.inlineCallbacks def testGetMissing(self): buildrequest = yield self.callGet(('buildrequests', 9999)) self.assertEqual(buildrequest, None) @defer.inlineCallbacks def testGetProperty(self): prop = resultspec.Property(b'property', 'eq', ['prop1']) buildrequest = yield self.callGet( ('buildrequests', 44), resultSpec=resultspec.ResultSpec(properties=[prop]) ) self.assertEqual(buildrequest['buildrequestid'], 44) self.assertEqual(buildrequest['properties'], {'prop1': ('one', 'fake1')}) @defer.inlineCallbacks def testGetProperties(self): prop = resultspec.Property(b'property', 'eq', ['*']) buildrequest = yield self.callGet( ('buildrequests', 44), resultSpec=resultspec.ResultSpec(properties=[prop]) ) self.assertEqual(buildrequest['buildrequestid'], 44) self.assertEqual( buildrequest['properties'], {'prop1': ('one', 'fake1'), 'prop2': ('two', 'fake2')} ) class TestBuildRequestsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = buildrequests.BuildRequestsEndpoint resourceTypeClass = buildrequests.BuildRequest CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC) CLAIMED_AT_EPOCH = 266761875 SUBMITTED_AT = datetime.datetime(1979, 6, 15, 12, 31, 15, tzinfo=UTC) SUBMITTED_AT_EPOCH = 298297875 COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC) COMPLETE_AT_EPOCH = 329920275 @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77, name='bbb'), fakedb.Builder(id=78, name='ccc'), fakedb.Builder(id=79, name='ddd'), fakedb.Master(id=fakedb.FakeDBConnector.MASTER_ID), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest( id=44, buildsetid=8822, builderid=77, priority=7, submitted_at=self.SUBMITTED_AT_EPOCH, waited_for=1, ), fakedb.BuildRequest(id=45, buildsetid=8822, builderid=77), fakedb.BuildRequest(id=46, buildsetid=8822, builderid=78), fakedb.SourceStamp(id=100), fakedb.BuildsetSourceStamp(buildsetid=8822, sourcestampid=100), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def testGetAll(self): buildrequests = yield self.callGet(('buildrequests',)) for br in buildrequests: self.validateData(br) self.assertEqual(sorted([br['buildrequestid'] for br in buildrequests]), [44, 45, 46]) @defer.inlineCallbacks def testGetNoBuildRequest(self): buildrequests = yield self.callGet(('builders', 79, 'buildrequests')) self.assertEqual(buildrequests, []) @defer.inlineCallbacks def testGetBuilderid(self): buildrequests = yield self.callGet(('builders', 78, 'buildrequests')) for br in buildrequests: self.validateData(br) self.assertEqual(sorted([br['buildrequestid'] for br in buildrequests]), [46]) @defer.inlineCallbacks def testGetUnknownBuilderid(self): buildrequests = yield self.callGet(('builders', 79, 'buildrequests')) self.assertEqual(buildrequests, []) @defer.inlineCallbacks def testGetProperties(self): yield self.master.db.insert_test_data([ fakedb.BuildsetProperty( buildsetid=8822, property_name='prop1', property_value='["one", "fake1"]' ), fakedb.BuildsetProperty( buildsetid=8822, property_name='prop2', property_value='["two", "fake2"]' ), ]) prop = resultspec.Property(b'property', 'eq', ['*']) buildrequests = yield self.callGet( ('builders', 78, 'buildrequests'), resultSpec=resultspec.ResultSpec(properties=[prop]) ) self.assertEqual(len(buildrequests), 1) self.assertEqual(buildrequests[0]['buildrequestid'], 46) self.assertEqual( buildrequests[0]['properties'], {'prop1': ('one', 'fake1'), 'prop2': ('two', 'fake2')} ) @defer.inlineCallbacks def testGetNoFilters(self): getBuildRequestsMock = mock.Mock(return_value={}) self.patch(self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock) yield self.callGet(('buildrequests',)) getBuildRequestsMock.assert_called_with( builderid=None, bsid=None, complete=None, claimed=None, resultSpec=resultspec.ResultSpec(), ) @defer.inlineCallbacks def testGetFilters(self): getBuildRequestsMock = mock.Mock(return_value={}) self.patch(self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock) f1 = resultspec.Filter('complete', 'eq', [False]) f2 = resultspec.Filter('claimed', 'eq', [True]) f3 = resultspec.Filter('buildsetid', 'eq', [55]) f4 = resultspec.Filter('branch', 'eq', ['mybranch']) f5 = resultspec.Filter('repository', 'eq', ['myrepo']) yield self.callGet( ('buildrequests',), resultSpec=resultspec.ResultSpec(filters=[f1, f2, f3, f4, f5]) ) getBuildRequestsMock.assert_called_with( builderid=None, bsid=55, complete=False, claimed=True, resultSpec=resultspec.ResultSpec(filters=[f4, f5]), ) @defer.inlineCallbacks def testGetClaimedByMasterIdFilters(self): getBuildRequestsMock = mock.Mock(return_value={}) self.patch(self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock) f1 = resultspec.Filter('claimed', 'eq', [True]) f2 = resultspec.Filter('claimed_by_masterid', 'eq', [fakedb.FakeDBConnector.MASTER_ID]) yield self.callGet(('buildrequests',), resultSpec=resultspec.ResultSpec(filters=[f1, f2])) getBuildRequestsMock.assert_called_with( builderid=None, bsid=None, complete=None, claimed=fakedb.FakeDBConnector.MASTER_ID, resultSpec=resultspec.ResultSpec(filters=[f1]), ) @defer.inlineCallbacks def testGetSortedLimit(self): yield self.master.db.buildrequests.completeBuildRequests([44], 1) res = yield self.callGet( ('buildrequests',), resultSpec=resultspec.ResultSpec(order=['results'], limit=2) ) self.assertEqual(len(res), 2) self.assertEqual(res[0]['results'], -1) res = yield self.callGet( ('buildrequests',), resultSpec=resultspec.ResultSpec(order=['-results'], limit=2) ) self.assertEqual(len(res), 2) self.assertEqual(res[0]['results'], 1) class TestBuildRequest(interfaces.InterfaceTests, TestReactorMixin, unittest.TestCase): CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC) COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC) class dBLayerException(Exception): pass @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = buildrequests.BuildRequest(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def doTestCallthrough( self, dbMethodName, dbMockedMethod, method, methodargs=None, methodkwargs=None, expectedRes=None, expectedException=None, expectedDbApiCalled=True, ): self.patch(self.master.db.buildrequests, dbMethodName, dbMockedMethod) if expectedException is not None: try: yield method(*methodargs, **methodkwargs) except expectedException: pass except Exception as e: self.fail(f'{expectedException} exception should be raised, but got {e!r}') else: self.fail(f'{expectedException} exception should be raised') else: res = yield method(*methodargs, **methodkwargs) self.assertEqual(res, expectedRes) if expectedDbApiCalled: dbMockedMethod.assert_called_with(*methodargs, **methodkwargs) def testSignatureClaimBuildRequests(self): @self.assertArgSpecMatches( self.master.data.updates.claimBuildRequests, # fake self.rtype.claimBuildRequests, ) # real def claimBuildRequests(self, brids, claimed_at=None): pass @defer.inlineCallbacks def testFakeDataClaimBuildRequests(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=123), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=44, builderid=123, buildsetid=8822), fakedb.BuildRequest(id=55, builderid=123, buildsetid=8822), ]) res = yield self.master.data.updates.claimBuildRequests( [44, 55], claimed_at=self.CLAIMED_AT ) self.assertTrue(res) @defer.inlineCallbacks def testFakeDataClaimBuildRequestsNoneArgs(self): res = yield self.master.data.updates.claimBuildRequests([]) self.assertTrue(res) @defer.inlineCallbacks def testClaimBuildRequests(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=123), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=44, buildsetid=8822, builderid=123), fakedb.BuildRequest(id=55, buildsetid=8822, builderid=123), ]) claimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'claimBuildRequests', claimBuildRequestsMock, self.rtype.claimBuildRequests, methodargs=[[44]], methodkwargs={"claimed_at": self.CLAIMED_AT}, expectedRes=True, expectedException=None, ) msg = { 'buildrequestid': 44, 'complete_at': None, 'complete': False, 'builderid': 123, 'waited_for': False, 'claimed_at': None, 'results': -1, 'priority': 0, 'submitted_at': datetime.datetime(1970, 5, 23, 21, 21, 18, tzinfo=UTC), 'claimed': False, 'claimed_by_masterid': None, 'buildsetid': 8822, 'properties': None, } self.assertEqual( sorted(self.master.mq.productions), sorted([ (('buildrequests', '44', 'claimed'), msg), (('builders', '123', 'buildrequests', '44', 'claimed'), msg), (('buildsets', '8822', 'builders', '123', 'buildrequests', '44', 'claimed'), msg), ]), ) @defer.inlineCallbacks def testClaimBuildRequestsNoBrids(self): claimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'claimBuildRequests', claimBuildRequestsMock, self.rtype.claimBuildRequests, methodargs=[[]], methodkwargs={}, expectedRes=True, expectedException=None, expectedDbApiCalled=False, ) self.assertEqual(self.master.mq.productions, []) @defer.inlineCallbacks def testClaimBuildRequestsAlreadyClaimed(self): claimBuildRequestsMock = mock.Mock( side_effect=buildrequests.AlreadyClaimedError('oups ! buildrequest already claimed') ) yield self.doTestCallthrough( 'claimBuildRequests', claimBuildRequestsMock, self.rtype.claimBuildRequests, methodargs=[[44]], methodkwargs={"claimed_at": self.CLAIMED_AT}, expectedRes=False, expectedException=None, ) self.assertEqual(self.master.mq.productions, []) @defer.inlineCallbacks def testClaimBuildRequestsUnknownException(self): claimBuildRequestsMock = mock.Mock( side_effect=self.dBLayerException('oups ! unknown error') ) yield self.doTestCallthrough( 'claimBuildRequests', claimBuildRequestsMock, self.rtype.claimBuildRequests, methodargs=[[44]], methodkwargs={"claimed_at": self.CLAIMED_AT}, expectedRes=None, expectedException=self.dBLayerException, ) self.assertEqual(self.master.mq.productions, []) def testSignatureUnclaimBuildRequests(self): @self.assertArgSpecMatches( self.master.data.updates.unclaimBuildRequests, # fake self.rtype.unclaimBuildRequests, ) # real def unclaimBuildRequests(self, brids): pass @defer.inlineCallbacks def testFakeDataUnclaimBuildRequests(self): res = yield self.master.data.updates.unclaimBuildRequests([44, 55]) self.assertEqual(res, None) @defer.inlineCallbacks def testFakeDataUnclaimBuildRequestsNoneArgs(self): res = yield self.master.data.updates.unclaimBuildRequests([]) self.assertEqual(res, None) @defer.inlineCallbacks def testUnclaimBuildRequests(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=123), fakedb.BuildRequest(id=44, buildsetid=8822, builderid=123), ]) unclaimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'unclaimBuildRequests', unclaimBuildRequestsMock, self.rtype.unclaimBuildRequests, methodargs=[[44]], methodkwargs={}, expectedRes=None, expectedException=None, ) msg = { 'buildrequestid': 44, 'complete_at': None, 'complete': False, 'builderid': 123, 'waited_for': False, 'claimed_at': None, 'results': -1, 'priority': 0, 'submitted_at': datetime.datetime(1970, 5, 23, 21, 21, 18, tzinfo=UTC), 'claimed': False, 'claimed_by_masterid': None, 'buildsetid': 8822, 'properties': None, } self.assertEqual( sorted(self.master.mq.productions), sorted([ (('buildrequests', '44', 'unclaimed'), msg), (('builders', '123', 'buildrequests', '44', 'unclaimed'), msg), (('buildsets', '8822', 'builders', '123', 'buildrequests', '44', 'unclaimed'), msg), ]), ) @defer.inlineCallbacks def testUnclaimBuildRequestsNoBrids(self): unclaimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'unclaimBuildRequests', unclaimBuildRequestsMock, self.rtype.unclaimBuildRequests, methodargs=[[]], methodkwargs={}, expectedRes=None, expectedException=None, expectedDbApiCalled=False, ) def testSignatureCompleteBuildRequests(self): @self.assertArgSpecMatches( self.master.data.updates.completeBuildRequests, # fake self.rtype.completeBuildRequests, ) # real def completeBuildRequests(self, brids, results, complete_at=None): pass @defer.inlineCallbacks def testFakeDataCompleteBuildRequests(self): res = yield self.master.data.updates.completeBuildRequests( [44, 55], 12, complete_at=self.COMPLETE_AT ) self.assertTrue(res) @defer.inlineCallbacks def testFakeDataCompleteBuildRequestsNoneArgs(self): res = yield self.master.data.updates.completeBuildRequests([], 0) self.assertTrue(res) @defer.inlineCallbacks def testCompleteBuildRequests(self): completeBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'completeBuildRequests', completeBuildRequestsMock, self.rtype.completeBuildRequests, methodargs=[[46], 12], methodkwargs={"complete_at": self.COMPLETE_AT}, expectedRes=True, expectedException=None, ) @defer.inlineCallbacks def testCompleteBuildRequestsNoBrids(self): completeBuildRequestsMock = mock.Mock(return_value=defer.succeed(None)) yield self.doTestCallthrough( 'completeBuildRequests', completeBuildRequestsMock, self.rtype.completeBuildRequests, methodargs=[[], 0], methodkwargs={}, expectedRes=True, expectedException=None, expectedDbApiCalled=False, ) @defer.inlineCallbacks def testCompleteBuildRequestsNotClaimed(self): completeBuildRequestsMock = mock.Mock( side_effect=buildrequests.NotClaimedError('oups ! buildrequest not claimed') ) yield self.doTestCallthrough( 'completeBuildRequests', completeBuildRequestsMock, self.rtype.completeBuildRequests, methodargs=[[46], 12], methodkwargs={"complete_at": self.COMPLETE_AT}, expectedRes=False, expectedException=None, ) @defer.inlineCallbacks def testCompleteBuildRequestsUnknownException(self): completeBuildRequestsMock = mock.Mock( side_effect=self.dBLayerException('oups ! unknown error') ) yield self.doTestCallthrough( 'completeBuildRequests', completeBuildRequestsMock, self.rtype.completeBuildRequests, methodargs=[[46], 12], methodkwargs={"complete_at": self.COMPLETE_AT}, expectedRes=None, expectedException=self.dBLayerException, ) @defer.inlineCallbacks def testRebuildBuildrequest(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=77, name='builder'), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.SourceStamp(id=234), fakedb.BuildsetSourceStamp(buildsetid=8822, sourcestampid=234), fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77), fakedb.BuildsetProperty( buildsetid=8822, property_name='prop1', property_value='["one", "fake1"]' ), fakedb.BuildsetProperty( buildsetid=8822, property_name='prop2', property_value='["two", "fake2"]' ), ]) buildrequest = yield self.master.data.get(('buildrequests', 82)) new_bsid, brid_dict = yield self.rtype.rebuildBuildrequest(buildrequest) self.assertEqual(list(brid_dict.keys()), [77]) buildrequest = yield self.master.data.get(('buildrequests', brid_dict[77])) # submitted_at is the time of the test, so better not depend on it self.assertEqual( buildrequest, { 'buildrequestid': 83, 'complete': False, 'waited_for': False, 'claimed_at': None, 'results': -1, 'claimed': False, 'buildsetid': 8823, 'complete_at': None, 'submitted_at': epoch2datetime(0), 'builderid': 77, 'claimed_by_masterid': None, 'priority': 0, 'properties': None, }, ) buildset = yield self.master.data.get(('buildsets', new_bsid)) oldbuildset = yield self.master.data.get(('buildsets', 8822)) # assert same sourcestamp self.assertEqual(buildset['sourcestamps'], oldbuildset['sourcestamps']) buildset['sourcestamps'] = None self.assertEqual( buildset, { 'bsid': 8823, 'complete_at': None, 'submitted_at': 0, 'sourcestamps': None, 'parent_buildid': None, 'results': -1, 'parent_relationship': None, 'reason': 'rebuild', 'rebuilt_buildid': None, 'external_idstring': 'extid', 'complete': False, }, ) properties = yield self.master.data.get(('buildsets', new_bsid, 'properties')) self.assertEqual(properties, {'prop1': ('one', 'fake1'), 'prop2': ('two', 'fake2')}) @defer.inlineCallbacks def test_rebuild_buildrequest_rebuilt_build(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=77, name="builder"), fakedb.Master(id=88), fakedb.Worker(id=13, name="wrk"), fakedb.Buildset(id=8822), fakedb.SourceStamp(id=234), fakedb.BuildsetSourceStamp(buildsetid=8822, sourcestampid=234), fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77), fakedb.Build(id=123, builderid=77, buildrequestid=82, masterid=88), ]) buildrequest = yield self.master.data.get(("buildrequests", 82)) new_bsid, brid_dict = yield self.rtype.rebuildBuildrequest(buildrequest) self.assertEqual(list(brid_dict.keys()), [77]) buildrequest = yield self.master.data.get(("buildrequests", brid_dict[77])) # submitted_at is the time of the test, so better not depend on it self.assertEqual( buildrequest, { "buildrequestid": 83, "complete": False, "waited_for": False, "claimed_at": None, "results": -1, "claimed": False, "buildsetid": 8823, "complete_at": None, "submitted_at": epoch2datetime(0), "builderid": 77, "claimed_by_masterid": None, "priority": 0, "properties": None, }, ) buildset = yield self.master.data.get(("buildsets", new_bsid)) oldbuildset = yield self.master.data.get(("buildsets", 8822)) # assert same sourcestamp self.assertEqual(buildset["sourcestamps"], oldbuildset["sourcestamps"]) buildset["sourcestamps"] = None self.assertEqual( buildset, { "bsid": 8823, "complete_at": None, "submitted_at": 0, "sourcestamps": None, "parent_buildid": None, "results": -1, "parent_relationship": None, "reason": "rebuild", "rebuilt_buildid": 123, "external_idstring": "extid", "complete": False, }, ) @defer.inlineCallbacks def test_rebuild_buildrequest_repeated_rebuilt_build(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=77, name="builder"), fakedb.Master(id=88), fakedb.Worker(id=13, name="wrk"), fakedb.Buildset(id=8821), # build already has been rebuilt from build_id = 122 fakedb.Buildset(id=8822, rebuilt_buildid=122), fakedb.SourceStamp(id=234), fakedb.BuildsetSourceStamp(buildsetid=8822, sourcestampid=234), fakedb.BuildRequest(id=81, buildsetid=8821, builderid=77), fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77), fakedb.Build(id=122, builderid=77, buildrequestid=81, masterid=88), fakedb.Build(id=123, builderid=77, buildrequestid=82, masterid=88), ]) buildrequest = yield self.master.data.get(("buildrequests", 82)) new_bsid, brid_dict = yield self.rtype.rebuildBuildrequest(buildrequest) self.assertEqual(list(brid_dict.keys()), [77]) buildrequest = yield self.master.data.get(("buildrequests", brid_dict[77])) # submitted_at is the time of the test, so better not depend on it self.assertEqual( buildrequest, { "buildrequestid": 83, "complete": False, "waited_for": False, "claimed_at": None, "results": -1, "claimed": False, "buildsetid": 8823, "complete_at": None, "submitted_at": epoch2datetime(0), "builderid": 77, "claimed_by_masterid": None, "priority": 0, "properties": None, }, ) buildset = yield self.master.data.get(("buildsets", new_bsid)) oldbuildset = yield self.master.data.get(("buildsets", 8822)) # assert same sourcestamp self.assertEqual(buildset["sourcestamps"], oldbuildset["sourcestamps"]) buildset["sourcestamps"] = None self.assertEqual( buildset, { "bsid": 8823, "complete_at": None, "submitted_at": 0, "sourcestamps": None, "parent_buildid": None, "results": -1, "parent_relationship": None, "reason": "rebuild", "rebuilt_buildid": 122, "external_idstring": "extid", "complete": False, }, )
29,728
Python
.py
698
31.902579
100
0.613279
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,379
test_build_data.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.data import build_data from buildbot.db.build_data import BuildDataModel from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class TestBuildDataNoValueEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = build_data.BuildDataNoValueEndpoint resourceTypeClass = build_data.BuildData @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.Master(id=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.BuildData(id=91, buildid=30, name='name1', value=b'value1', source='source1'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing_build_data_by_build_id(self): result = yield self.callGet(('builds', 30, 'data', 'name1')) self.validateData(result) self.assertEqual( result, { 'buildid': 30, 'name': 'name1', 'value': None, 'source': 'source1', 'length': 6, }, ) @defer.inlineCallbacks def test_get_existing_build_data_by_builder_name_build_number(self): result = yield self.callGet(('builders', 'b1', 'builds', 7, 'data', 'name1')) self.validateData(result) self.assertEqual( result, { 'buildid': 30, 'name': 'name1', 'value': None, 'source': 'source1', 'length': 6, }, ) @defer.inlineCallbacks def test_get_existing_build_data_by_builder_id_build_number(self): result = yield self.callGet(('builders', 88, 'builds', 7, 'data', 'name1')) self.validateData(result) self.assertEqual( result, { 'buildid': 30, 'name': 'name1', 'value': None, 'length': 6, 'source': 'source1', }, ) @defer.inlineCallbacks def test_get_missing_by_build_id_missing_build(self): result = yield self.callGet(('builds', 31, 'data', 'name1')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_build_id_missing_name(self): result = yield self.callGet(('builds', 30, 'data', 'name_missing')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_builder(self): result = yield self.callGet(('builders', 'b_missing', 'builds', 7, 'data', 'name1')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_build(self): result = yield self.callGet(('builders', 'b1', 'builds', 17, 'data', 'name1')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_name(self): result = yield self.callGet(('builders', 'b1', 'builds', 7, 'data', 'name_missing')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_builder(self): result = yield self.callGet(('builders', 188, 'builds', 7, 'data', 'name1')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_build(self): result = yield self.callGet(('builders', 88, 'builds', 17, 'data', 'name1')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_name(self): result = yield self.callGet(('builders', 88, 'builds', 7, 'data', 'name_missing')) self.assertIsNone(result) class TestBuildDataEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = build_data.BuildDataEndpoint resourceTypeClass = build_data.BuildData @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.Master(id=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.BuildData(id=91, buildid=30, name='name1', value=b'value1', source='source1'), ]) def tearDown(self): self.tearDownEndpoint() def validateData(self, data): self.assertIsInstance(data['raw'], bytes) self.assertIsInstance(data['mime-type'], str) self.assertIsInstance(data['filename'], str) @defer.inlineCallbacks def test_get_existing_build_data_by_build_id(self): result = yield self.callGet(('builds', 30, 'data', 'name1', 'value')) self.validateData(result) self.assertEqual( result, { 'raw': b'value1', 'mime-type': 'application/octet-stream', 'filename': 'name1', }, ) @defer.inlineCallbacks def test_get_existing_build_data_by_builder_name_build_number(self): result = yield self.callGet(('builders', 'b1', 'builds', 7, 'data', 'name1', 'value')) self.validateData(result) self.assertEqual( result, { 'raw': b'value1', 'mime-type': 'application/octet-stream', 'filename': 'name1', }, ) @defer.inlineCallbacks def test_get_existing_build_data_by_builder_id_build_number(self): result = yield self.callGet(('builders', 88, 'builds', 7, 'data', 'name1', 'value')) self.validateData(result) self.assertEqual( result, { 'raw': b'value1', 'mime-type': 'application/octet-stream', 'filename': 'name1', }, ) @defer.inlineCallbacks def test_get_missing_by_build_id_missing_build(self): result = yield self.callGet(('builds', 31, 'data', 'name1', 'value')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_build_id_missing_name(self): result = yield self.callGet(('builds', 30, 'data', 'name_missing', 'value')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_builder(self): result = yield self.callGet(( 'builders', 'b_missing', 'builds', 7, 'data', 'name1', 'value', )) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_build(self): result = yield self.callGet(('builders', 'b1', 'builds', 17, 'data', 'name1', 'value')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_name_build_number_missing_name(self): result = yield self.callGet(( 'builders', 'b1', 'builds', 7, 'data', 'name_missing', 'value', )) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_builder(self): result = yield self.callGet(('builders', 188, 'builds', 7, 'data', 'name1', 'value')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_build(self): result = yield self.callGet(('builders', 88, 'builds', 17, 'data', 'name1', 'value')) self.assertIsNone(result) @defer.inlineCallbacks def test_get_missing_by_builder_id_build_number_missing_name(self): result = yield self.callGet(('builders', 88, 'builds', 7, 'data', 'name_missing', 'value')) self.assertIsNone(result) class TestBuildDatasNoValueEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = build_data.BuildDatasNoValueEndpoint resourceTypeClass = build_data.BuildData @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Worker(id=47, name='linux'), fakedb.Buildset(id=20), fakedb.Builder(id=88, name='b1'), fakedb.Master(id=88), fakedb.BuildRequest(id=41, buildsetid=20, builderid=88), fakedb.BuildRequest(id=42, buildsetid=20, builderid=88), fakedb.BuildRequest(id=43, buildsetid=20, builderid=88), fakedb.Build( id=30, buildrequestid=41, number=7, masterid=88, builderid=88, workerid=47 ), fakedb.Build( id=31, buildrequestid=42, number=8, masterid=88, builderid=88, workerid=47 ), fakedb.Build( id=32, buildrequestid=42, number=9, masterid=88, builderid=88, workerid=47 ), fakedb.BuildData(id=91, buildid=30, name='name1', value=b'value1', source='source1'), fakedb.BuildData(id=92, buildid=30, name='name2', value=b'value2', source='source2'), fakedb.BuildData(id=93, buildid=31, name='name3', value=b'value3', source='source3'), ]) def tearDown(self): self.tearDownEndpoint() @parameterized.expand([ ('multiple_values', 7, ['name1', 'name2']), ('single_value', 8, ['name3']), ('no_values', 9, []), ('not_existing', 10, []), ]) @defer.inlineCallbacks def test_get_builders_builder_name(self, name, build_number, exp_names): results = yield self.callGet(('builders', 'b1', 'builds', build_number, 'data')) for result in results: self.validateData(result) self.assertEqual([r['name'] for r in results], exp_names) @parameterized.expand([ ('multiple_values', 7, ['name1', 'name2']), ('single_value', 8, ['name3']), ('no_values', 9, []), ('not_existing', 10, []), ]) @defer.inlineCallbacks def test_get_builders_builder_id(self, name, build_number, exp_names): results = yield self.callGet(('builders', 88, 'builds', build_number, 'data')) for result in results: self.validateData(result) self.assertEqual([r['name'] for r in results], exp_names) @parameterized.expand([ ('multiple_values', 30, ['name1', 'name2']), ('single_value', 31, ['name3']), ('no_values', 32, []), ('not_existing', 33, []), ]) @defer.inlineCallbacks def test_get_builds_id(self, name, buildid, exp_names): results = yield self.callGet(('builds', buildid, 'data')) for result in results: self.validateData(result) self.assertEqual([r['name'] for r in results], exp_names) class TestBuildData(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = build_data.BuildData(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_set_build_data(self): @self.assertArgSpecMatches(self.master.data.updates.setBuildData, self.rtype.setBuildData) def setBuildData(self, buildid, name, value, source): pass @defer.inlineCallbacks def test_set_build_data(self): yield self.rtype.setBuildData(buildid=2, name='name1', value=b'value1', source='source1') result = yield self.master.db.build_data.getBuildData(2, 'name1') self.assertEqual( result, BuildDataModel( buildid=2, name='name1', value=b'value1', length=6, source='source1', ), )
13,458
Python
.py
316
33.392405
99
0.618128
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,380
test_root.py
buildbot_buildbot/master/buildbot/test/unit/data/test_root.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.data import connector from buildbot.data import root from buildbot.test.util import endpoint class RootEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = root.RootEndpoint resourceTypeClass = root.Root @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() self.master.data.rootLinks = [ {'name': 'abc'}, ] def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): rootlinks = yield self.callGet(('',)) for rootlink in rootlinks: self.validateData(rootlink) self.assertEqual( rootlinks, [ {'name': 'abc'}, ], ) class SpecEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = root.SpecEndpoint resourceTypeClass = root.Spec @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() # replace fakeConnector with real DataConnector self.master.data.disownServiceParent() self.master.data = connector.DataConnector() yield self.master.data.setServiceParent(self.master) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): specs = yield self.callGet(('application.spec',)) for s in specs: self.validateData(s) for s in specs: # only test an endpoint that is reasonably stable if s['path'] != "master": continue self.assertEqual( s, { 'path': 'master', 'type': 'master', 'type_spec': { 'fields': [ {'name': 'active', 'type': 'boolean', 'type_spec': {'name': 'boolean'}}, { 'name': 'masterid', 'type': 'integer', 'type_spec': {'name': 'integer'}, }, {'name': 'link', 'type': 'link', 'type_spec': {'name': 'link'}}, {'name': 'name', 'type': 'string', 'type_spec': {'name': 'string'}}, { 'name': 'last_active', 'type': 'datetime', 'type_spec': {'name': 'datetime'}, }, ], 'type': 'master', }, 'plural': 'masters', }, )
3,485
Python
.py
88
27.602273
100
0.547175
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,381
test_changesources.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.python import failure from twisted.trial import unittest from buildbot.data import changesources from buildbot.db.changesources import ChangeSourceAlreadyClaimedError from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class ChangeSourceEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = changesources.ChangeSourceEndpoint resourceTypeClass = changesources.ChangeSource @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.Master(id=33, active=1), fakedb.ChangeSource(id=13, name='some:changesource'), fakedb.ChangeSource(id=14, name='other:changesource'), fakedb.ChangeSourceMaster(changesourceid=14, masterid=22), fakedb.ChangeSource(id=15, name='another:changesource'), fakedb.ChangeSourceMaster(changesourceid=15, masterid=33), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): """get an existing changesource by id""" changesource = yield self.callGet(('changesources', 14)) self.validateData(changesource) self.assertEqual(changesource['name'], 'other:changesource') @defer.inlineCallbacks def test_get_no_master(self): """get a changesource with no master""" changesource = yield self.callGet(('changesources', 13)) self.validateData(changesource) self.assertEqual(changesource['master'], None) @defer.inlineCallbacks def test_get_masterid_existing(self): """get an existing changesource by id on certain master""" changesource = yield self.callGet(('masters', 22, 'changesources', 14)) self.validateData(changesource) self.assertEqual(changesource['name'], 'other:changesource') @defer.inlineCallbacks def test_get_masterid_no_match(self): """get an existing changesource by id on the wrong master""" changesource = yield self.callGet(('masters', 33, 'changesources', 13)) self.assertEqual(changesource, None) @defer.inlineCallbacks def test_get_masterid_missing(self): """get an existing changesource by id on an invalid master""" changesource = yield self.callGet(('masters', 25, 'changesources', 13)) self.assertEqual(changesource, None) @defer.inlineCallbacks def test_get_missing(self): """get an invalid changesource by id""" changesource = yield self.callGet(('changesources', 99)) self.assertEqual(changesource, None) class ChangeSourcesEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = changesources.ChangeSourcesEndpoint resourceTypeClass = changesources.ChangeSource @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.Master(id=33, active=1), fakedb.ChangeSource(id=13, name='some:changesource'), fakedb.ChangeSource(id=14, name='other:changesource'), fakedb.ChangeSourceMaster(changesourceid=14, masterid=22), fakedb.ChangeSource(id=15, name='another:changesource'), fakedb.ChangeSourceMaster(changesourceid=15, masterid=33), fakedb.ChangeSource(id=16, name='wholenother:changesource'), fakedb.ChangeSourceMaster(changesourceid=16, masterid=33), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): changesources = yield self.callGet(('changesources',)) for cs in changesources: self.validateData(cs) self.assertEqual(sorted([m['changesourceid'] for m in changesources]), [13, 14, 15, 16]) @defer.inlineCallbacks def test_get_masterid(self): changesources = yield self.callGet(('masters', 33, 'changesources')) for cs in changesources: self.validateData(cs) self.assertEqual(sorted([m['changesourceid'] for m in changesources]), [15, 16]) @defer.inlineCallbacks def test_get_masterid_missing(self): changesources = yield self.callGet(('masters', 23, 'changesources')) self.assertEqual(changesources, []) class ChangeSource(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = changesources.ChangeSource(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_findChangeSourceId(self): @self.assertArgSpecMatches( self.master.data.updates.findChangeSourceId, # fake self.rtype.findChangeSourceId, ) # real def findChangeSourceId(self, name): pass @defer.inlineCallbacks def test_findChangeSourceId(self): self.master.db.changesources.findChangeSourceId = mock.Mock(return_value=defer.succeed(10)) self.assertEqual((yield self.rtype.findChangeSourceId('cs')), 10) self.master.db.changesources.findChangeSourceId.assert_called_with('cs') def test_signature_trySetChangeSourceMaster(self): @self.assertArgSpecMatches( self.master.data.updates.trySetChangeSourceMaster, # fake self.rtype.trySetChangeSourceMaster, ) # real def trySetChangeSourceMaster(self, changesourceid, masterid): pass @defer.inlineCallbacks def test_trySetChangeSourceMaster_succeeds(self): self.master.db.changesources.setChangeSourceMaster = mock.Mock( return_value=defer.succeed(None) ) yield self.rtype.trySetChangeSourceMaster(10, 20) self.master.db.changesources.setChangeSourceMaster.assert_called_with(10, 20) @defer.inlineCallbacks def test_trySetChangeSourceMaster_fails(self): d = defer.fail(failure.Failure(ChangeSourceAlreadyClaimedError('oh noes'))) self.master.db.changesources.setChangeSourceMaster = mock.Mock(return_value=d) result = yield self.rtype.trySetChangeSourceMaster(10, 20) self.assertFalse(result) @defer.inlineCallbacks def test_trySetChangeSourceMaster_raisesOddException(self): d = defer.fail(failure.Failure(RuntimeError('oh noes'))) self.master.db.changesources.setChangeSourceMaster = mock.Mock(return_value=d) try: yield self.rtype.trySetChangeSourceMaster(10, 20) except RuntimeError: pass else: self.fail("The RuntimeError did not propagate") @defer.inlineCallbacks def test__masterDeactivated(self): yield self.master.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.ChangeSource(id=13, name='some:changesource'), fakedb.ChangeSourceMaster(changesourceid=13, masterid=22), fakedb.ChangeSource(id=14, name='other:changesource'), fakedb.ChangeSourceMaster(changesourceid=14, masterid=22), ]) yield self.rtype._masterDeactivated(22) self.assertIsNone((yield self.master.db.changesources.get_change_source_master(13))) self.assertIsNone((yield self.master.db.changesources.get_change_source_master(14)))
8,493
Python
.py
173
41.369942
99
0.712196
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,382
test_changes.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import changes from buildbot.data import resultspec from buildbot.db.changes import ChangeModel from buildbot.process.users import users from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import epoch2datetime class ChangeEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = changes.ChangeEndpoint resourceTypeClass = changes.Change @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.SourceStamp(id=234), fakedb.Change( changeid=13, branch='trunk', revision='9283', repository='svn://...', codebase='cbsvn', project='world-domination', sourcestampid=234, ), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): change = yield self.callGet(('changes', '13')) self.validateData(change) self.assertEqual(change['project'], 'world-domination') @defer.inlineCallbacks def test_get_missing(self): change = yield self.callGet(('changes', '99')) self.assertEqual(change, None) class ChangesEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = changes.ChangesEndpoint resourceTypeClass = changes.Change @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.SourceStamp(id=133), fakedb.Change( changeid=13, branch='trunk', revision='9283', repository='svn://...', codebase='cbsvn', project='world-domination', sourcestampid=133, when_timestamp=1000000, ), fakedb.SourceStamp(id=144), fakedb.Change( changeid=14, branch='devel', revision='9284', repository='svn://...', codebase='cbsvn', project='world-domination', sourcestampid=144, when_timestamp=1000001, ), fakedb.Builder(id=1, name='builder'), fakedb.Build(buildrequestid=1, masterid=1, workerid=1, builderid=1, number=1), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): changes = yield self.callGet(('changes',)) changes = sorted(changes, key=lambda ch: ch['changeid']) self.validateData(changes[0]) self.assertEqual(changes[0]['changeid'], 13) self.validateData(changes[1]) self.assertEqual(changes[1]['changeid'], 14) @defer.inlineCallbacks def test_getChanges_from_build(self): fake_change = yield self.db.changes.getChangeFromSSid(144) mockGetChangeById = mock.Mock( spec=self.db.changes.getChangesForBuild, return_value=[fake_change] ) self.patch(self.db.changes, 'getChangesForBuild', mockGetChangeById) changes = yield self.callGet(('builds', '1', 'changes')) self.validateData(changes[0]) self.assertEqual(changes[0]['changeid'], 14) @defer.inlineCallbacks def test_getChanges_from_builder(self): fake_change = yield self.db.changes.getChangeFromSSid(144) mockGetChangeById = mock.Mock( spec=self.db.changes.getChangesForBuild, return_value=[fake_change] ) self.patch(self.db.changes, 'getChangesForBuild', mockGetChangeById) changes = yield self.callGet(('builders', '1', 'builds', '1', 'changes')) self.validateData(changes[0]) self.assertEqual(changes[0]['changeid'], 14) @defer.inlineCallbacks def test_getChanges_recent(self): resultSpec = resultspec.ResultSpec(limit=1, order=('-changeid',)) changes = yield self.callGet(('changes',), resultSpec=resultSpec) self.validateData(changes[0]) self.assertEqual(changes[0]['changeid'], 14) self.assertEqual(len(changes), 1) @defer.inlineCallbacks def test_getChangesOtherOrder(self): resultSpec = resultspec.ResultSpec(limit=1, order=('-when_timestamp',)) changes = yield self.callGet(('changes',), resultSpec=resultSpec) self.assertEqual(len(changes), 1) @defer.inlineCallbacks def test_getChangesOtherOffset(self): resultSpec = resultspec.ResultSpec(limit=1, offset=1, order=('-changeid',)) changes = yield self.callGet(('changes',), resultSpec=resultSpec) self.assertEqual(len(changes), 1) class Change(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): changeEvent = { 'author': 'warner', 'committer': 'david', 'branch': 'warnerdb', 'category': 'devel', 'codebase': '', 'comments': 'fix whitespace', 'changeid': 500, 'files': ['master/buildbot/__init__.py'], 'parent_changeids': [], 'project': 'Buildbot', 'properties': {'foo': (20, 'Change')}, 'repository': 'git://warner', 'revision': '0e92a098b', 'revlink': 'http://warner/0e92a098b', 'when_timestamp': 256738404, 'sourcestamp': { 'branch': 'warnerdb', 'codebase': '', 'patch': None, 'project': 'Buildbot', 'repository': 'git://warner', 'revision': '0e92a098b', 'created_at': epoch2datetime(10000000), 'ssid': 100, }, # uid } @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = changes.Change(self.master) yield self.master.db.insert_test_data([ fakedb.SourceStamp(id=99), # force minimum ID in tests below ]) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_addChange(self): @self.assertArgSpecMatches( self.master.data.updates.addChange, # fake self.rtype.addChange, ) # real 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, ): pass @defer.inlineCallbacks def do_test_addChange( self, kwargs, expectedRoutingKey, expectedMessage, expectedRow, expectedChangeUsers=None ): if expectedChangeUsers is None: expectedChangeUsers = [] self.reactor.advance(10000000) changeid = yield self.rtype.addChange(**kwargs) self.assertEqual(changeid, 500) # check the correct message was received self.master.mq.assertProductions([ (expectedRoutingKey, expectedMessage), ]) # and that the correct data was inserted into the db change = yield self.master.db.changes.getChange(500) self.assertEqual(change, expectedRow) change_users = yield self.master.db.changes.getChangeUids(500) self.assertEqual(change_users, expectedChangeUsers) def test_addChange(self): # src and codebase are default here kwargs = { "_test_changeid": 500, "author": 'warner', "committer": 'david', "branch": 'warnerdb', "category": 'devel', "comments": 'fix whitespace', "files": ['master/buildbot/__init__.py'], "project": 'Buildbot', "repository": 'git://warner', "revision": '0e92a098b', "revlink": 'http://warner/0e92a098b', "when_timestamp": 256738404, "properties": {'foo': 20}, } expectedRoutingKey = ('changes', '500', 'new') expectedMessage = self.changeEvent expectedRow = ChangeModel( changeid=500, author='warner', committer='david', comments='fix whitespace', branch='warnerdb', revision='0e92a098b', revlink='http://warner/0e92a098b', when_timestamp=epoch2datetime(256738404), category='devel', repository='git://warner', codebase='', project='Buildbot', sourcestampid=100, files=['master/buildbot/__init__.py'], properties={'foo': (20, 'Change')}, ) return self.do_test_addChange(kwargs, expectedRoutingKey, expectedMessage, expectedRow) @defer.inlineCallbacks def test_addChange_src_codebase(self): createUserObject = mock.Mock(spec=users.createUserObject) createUserObject.return_value = defer.succeed(123) self.patch(users, 'createUserObject', createUserObject) kwargs = { "_test_changeid": 500, "author": 'warner', "committer": 'david', "branch": 'warnerdb', "category": 'devel', "comments": 'fix whitespace', "files": ['master/buildbot/__init__.py'], "project": 'Buildbot', "repository": 'git://warner', "revision": '0e92a098b', "revlink": 'http://warner/0e92a098b', "when_timestamp": 256738404, "properties": {'foo': 20}, "src": 'git', "codebase": 'cb', } expectedRoutingKey = ('changes', '500', 'new') expectedMessage = { 'author': 'warner', 'committer': 'david', 'branch': 'warnerdb', 'category': 'devel', 'codebase': 'cb', 'comments': 'fix whitespace', 'changeid': 500, 'files': ['master/buildbot/__init__.py'], 'parent_changeids': [], 'project': 'Buildbot', 'properties': {'foo': (20, 'Change')}, 'repository': 'git://warner', 'revision': '0e92a098b', 'revlink': 'http://warner/0e92a098b', 'when_timestamp': 256738404, 'sourcestamp': { 'branch': 'warnerdb', 'codebase': 'cb', 'patch': None, 'project': 'Buildbot', 'repository': 'git://warner', 'revision': '0e92a098b', 'created_at': epoch2datetime(10000000), 'ssid': 100, }, # uid } expectedRow = ChangeModel( changeid=500, author='warner', committer='david', comments='fix whitespace', branch='warnerdb', revision='0e92a098b', revlink='http://warner/0e92a098b', when_timestamp=epoch2datetime(256738404), category='devel', repository='git://warner', codebase='cb', project='Buildbot', sourcestampid=100, files=['master/buildbot/__init__.py'], properties={'foo': (20, 'Change')}, ) yield self.do_test_addChange( kwargs, expectedRoutingKey, expectedMessage, expectedRow, expectedChangeUsers=[123] ) createUserObject.assert_called_once_with(self.master, 'warner', 'git') def test_addChange_src_codebaseGenerator(self): def preChangeGenerator(**kwargs): return kwargs self.master.config = mock.Mock(name='master.config') self.master.config.preChangeGenerator = preChangeGenerator self.master.config.codebaseGenerator = lambda change: f"cb-{(change['category'])}" kwargs = { "_test_changeid": 500, "author": 'warner', "committer": 'david', "branch": 'warnerdb', "category": 'devel', "comments": 'fix whitespace', "files": ['master/buildbot/__init__.py'], "project": 'Buildbot', "repository": 'git://warner', "revision": '0e92a098b', "revlink": 'http://warner/0e92a098b', "when_timestamp": 256738404, "properties": {'foo': 20}, } expectedRoutingKey = ('changes', '500', 'new') expectedMessage = { 'author': 'warner', 'committer': 'david', 'branch': 'warnerdb', 'category': 'devel', 'codebase': 'cb-devel', 'comments': 'fix whitespace', 'changeid': 500, 'files': ['master/buildbot/__init__.py'], 'parent_changeids': [], 'project': 'Buildbot', 'properties': {'foo': (20, 'Change')}, 'repository': 'git://warner', 'revision': '0e92a098b', 'revlink': 'http://warner/0e92a098b', 'when_timestamp': 256738404, 'sourcestamp': { 'branch': 'warnerdb', 'codebase': 'cb-devel', 'patch': None, 'project': 'Buildbot', 'repository': 'git://warner', 'revision': '0e92a098b', 'created_at': epoch2datetime(10000000), 'ssid': 100, }, # uid } expectedRow = ChangeModel( changeid=500, author='warner', committer='david', comments='fix whitespace', branch='warnerdb', revision='0e92a098b', revlink='http://warner/0e92a098b', when_timestamp=epoch2datetime(256738404), category='devel', repository='git://warner', codebase='cb-devel', project='Buildbot', sourcestampid=100, files=['master/buildbot/__init__.py'], properties={'foo': (20, 'Change')}, ) return self.do_test_addChange(kwargs, expectedRoutingKey, expectedMessage, expectedRow) def test_addChange_repository_revision(self): self.master.config = mock.Mock(name='master.config') self.master.config.revlink = lambda rev, repo: f'foo{repo}bar{rev}baz' # revlink is default here kwargs = { "_test_changeid": 500, "author": 'warner', "committer": 'david', "branch": 'warnerdb', "category": 'devel', "comments": 'fix whitespace', "files": ['master/buildbot/__init__.py'], "project": 'Buildbot', "repository": 'git://warner', "codebase": '', "revision": '0e92a098b', "when_timestamp": 256738404, "properties": {'foo': 20}, } expectedRoutingKey = ('changes', '500', 'new') # When no revlink is passed to addChange, but a repository and revision is # passed, the revlink should be constructed by calling the revlink callable # in the config. We thus expect a revlink of 'foogit://warnerbar0e92a098bbaz' expectedMessage = { 'author': 'warner', 'committer': 'david', 'branch': 'warnerdb', 'category': 'devel', 'codebase': '', 'comments': 'fix whitespace', 'changeid': 500, 'files': ['master/buildbot/__init__.py'], 'parent_changeids': [], 'project': 'Buildbot', 'properties': {'foo': (20, 'Change')}, 'repository': 'git://warner', 'revision': '0e92a098b', 'revlink': 'foogit://warnerbar0e92a098bbaz', 'when_timestamp': 256738404, 'sourcestamp': { 'branch': 'warnerdb', 'codebase': '', 'patch': None, 'project': 'Buildbot', 'repository': 'git://warner', 'revision': '0e92a098b', 'created_at': epoch2datetime(10000000), 'ssid': 100, }, # uid } expectedRow = ChangeModel( changeid=500, author='warner', committer='david', comments='fix whitespace', branch='warnerdb', revision='0e92a098b', revlink='foogit://warnerbar0e92a098bbaz', when_timestamp=epoch2datetime(256738404), category='devel', repository='git://warner', codebase='', project='Buildbot', sourcestampid=100, files=['master/buildbot/__init__.py'], properties={'foo': (20, 'Change')}, ) return self.do_test_addChange(kwargs, expectedRoutingKey, expectedMessage, expectedRow)
18,106
Python
.py
462
28.320346
97
0.566761
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,383
test_logs.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import logs from buildbot.db.logs import LogSlugExistsError from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class LogEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = logs.LogEndpoint resourceTypeClass = logs.Log @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77, name='builder77'), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Step(id=50, buildid=13, number=5, name='make'), fakedb.Log(id=60, stepid=50, name='stdio', slug='stdio', type='s'), fakedb.Log(id=61, stepid=50, name='errors', slug='errors', type='t'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): log = yield self.callGet(('logs', 60)) self.validateData(log) self.assertEqual( log, { 'logid': 60, 'name': 'stdio', 'slug': 'stdio', 'stepid': 50, 'complete': False, 'num_lines': 0, 'type': 's', }, ) @defer.inlineCallbacks def test_get_missing(self): log = yield self.callGet(('logs', 62)) self.assertEqual(log, None) @defer.inlineCallbacks def test_get_by_stepid(self): log = yield self.callGet(('steps', 50, 'logs', 'errors')) self.validateData(log) self.assertEqual(log['name'], 'errors') @defer.inlineCallbacks def test_get_by_buildid(self): log = yield self.callGet(('builds', 13, 'steps', 5, 'logs', 'errors')) self.validateData(log) self.assertEqual(log['name'], 'errors') @defer.inlineCallbacks def test_get_by_builder(self): log = yield self.callGet(('builders', '77', 'builds', 3, 'steps', 5, 'logs', 'errors')) self.validateData(log) self.assertEqual(log['name'], 'errors') @defer.inlineCallbacks def test_get_by_builder_step_name(self): log = yield self.callGet(('builders', '77', 'builds', 3, 'steps', 'make', 'logs', 'errors')) self.validateData(log) self.assertEqual(log['name'], 'errors') @defer.inlineCallbacks def test_get_by_buildername_step_name(self): log = yield self.callGet(( 'builders', 'builder77', 'builds', 3, 'steps', 'make', 'logs', 'errors', )) self.validateData(log) self.assertEqual(log['name'], 'errors') class LogsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = logs.LogsEndpoint resourceTypeClass = logs.Log @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=77), fakedb.Master(id=88), fakedb.Worker(id=13, name='wrk'), fakedb.Buildset(id=8822), fakedb.BuildRequest(id=82, builderid=77, buildsetid=8822), fakedb.Build( id=13, builderid=77, masterid=88, workerid=13, buildrequestid=82, number=3 ), fakedb.Step(id=50, buildid=13, number=9, name='make'), fakedb.Log(id=60, stepid=50, name='stdio', type='s'), fakedb.Log(id=61, stepid=50, name='errors', type='t'), fakedb.Step(id=51, buildid=13, number=10, name='make_install'), fakedb.Log(id=70, stepid=51, name='stdio', type='s'), fakedb.Log(id=71, stepid=51, name='results_html', type='h'), fakedb.Step(id=52, buildid=13, number=11, name='nothing'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_stepid(self): logs = yield self.callGet(('steps', 50, 'logs')) for log in logs: self.validateData(log) self.assertEqual(sorted([b['name'] for b in logs]), ['errors', 'stdio']) @defer.inlineCallbacks def test_get_stepid_empty(self): logs = yield self.callGet(('steps', 52, 'logs')) self.assertEqual(logs, []) @defer.inlineCallbacks def test_get_stepid_missing(self): logs = yield self.callGet(('steps', 99, 'logs')) self.assertEqual(logs, []) @defer.inlineCallbacks def test_get_buildid_step_name(self): logs = yield self.callGet(('builds', 13, 'steps', 'make_install', 'logs')) for log in logs: self.validateData(log) self.assertEqual(sorted([b['name'] for b in logs]), ['results_html', 'stdio']) @defer.inlineCallbacks def test_get_buildid_step_number(self): logs = yield self.callGet(('builds', 13, 'steps', 10, 'logs')) for log in logs: self.validateData(log) self.assertEqual(sorted([b['name'] for b in logs]), ['results_html', 'stdio']) @defer.inlineCallbacks def test_get_builder_build_number_step_name(self): logs = yield self.callGet(('builders', 77, 'builds', 3, 'steps', 'make', 'logs')) for log in logs: self.validateData(log) self.assertEqual(sorted([b['name'] for b in logs]), ['errors', 'stdio']) @defer.inlineCallbacks def test_get_builder_build_number_step_number(self): logs = yield self.callGet(('builders', 77, 'builds', 3, 'steps', 10, 'logs')) for log in logs: self.validateData(log) self.assertEqual(sorted([b['name'] for b in logs]), ['results_html', 'stdio']) class Log(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = logs.Log(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def do_test_callthrough( self, dbMethodName, method, exp_args=None, exp_kwargs=None, *args, **kwargs ): rv = (1, 2) m = mock.Mock(return_value=defer.succeed(rv)) setattr(self.master.db.logs, dbMethodName, m) res = yield method(*args, **kwargs) self.assertIdentical(res, rv) m.assert_called_with(*(exp_args or args), **(exp_kwargs or kwargs)) def test_signature_addLog(self): @self.assertArgSpecMatches( self.master.data.updates.addLog, # fake self.rtype.addLog, ) # real def addLog(self, stepid, name, type): pass @defer.inlineCallbacks def test_addLog_uniquify(self): tries = [] @self.assertArgSpecMatches(self.master.db.logs.addLog) def addLog(stepid, name, slug, type): tries.append((stepid, name, slug, type)) if len(tries) < 3: return defer.fail(LogSlugExistsError()) return defer.succeed(23) self.patch(self.master.db.logs, 'addLog', addLog) logid = yield self.rtype.addLog(stepid=13, name='foo', type='s') self.assertEqual(logid, 23) self.assertEqual( tries, [ (13, 'foo', 'foo', 's'), (13, 'foo', 'foo_2', 's'), (13, 'foo', 'foo_3', 's'), ], ) def test_signature_finishLog(self): @self.assertArgSpecMatches( self.master.data.updates.finishLog, # fake self.rtype.finishLog, ) # real def finishLog(self, logid): pass def test_finishLog(self): self.do_test_callthrough('finishLog', self.rtype.finishLog, logid=10) def test_signature_compressLog(self): @self.assertArgSpecMatches( self.master.data.updates.compressLog, # fake self.rtype.compressLog, ) # real def compressLog(self, logid): pass def test_compressLog(self): self.do_test_callthrough('compressLog', self.rtype.compressLog, logid=10) def test_signature_appendLog(self): @self.assertArgSpecMatches( self.master.data.updates.appendLog, # fake self.rtype.appendLog, ) # real def appendLog(self, logid, content): pass def test_appendLog(self): self.do_test_callthrough('appendLog', self.rtype.appendLog, logid=10, content='foo\nbar\n')
9,796
Python
.py
235
32.885106
100
0.617851
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,384
test_properties.py
buildbot_buildbot/master/buildbot/test/unit/data/test_properties.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.data import properties from buildbot.process.properties import Properties as processProperties from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces class BuildsetPropertiesEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = properties.BuildsetPropertiesEndpoint resourceTypeClass = properties.Properties @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Buildset(id=13, reason='because I said so'), fakedb.SourceStamp(id=92), fakedb.SourceStamp(id=93), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=92), fakedb.BuildsetSourceStamp(buildsetid=13, sourcestampid=93), fakedb.Buildset(id=14, reason='no sourcestamps'), fakedb.BuildsetProperty(buildsetid=14), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_properties(self): props = yield self.callGet(('buildsets', 14, 'properties')) self.assertEqual(props, {'prop': (22, 'fakedb')}) class BuildPropertiesEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = properties.BuildPropertiesEndpoint resourceTypeClass = properties.Properties @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Builder(id=1), fakedb.Buildset(id=28), fakedb.BuildRequest(id=5, buildsetid=28, builderid=1), fakedb.Master(id=3), fakedb.Worker(id=42, name="Friday"), fakedb.Build(id=786, buildrequestid=5, masterid=3, workerid=42, builderid=1, number=5), fakedb.BuildProperty(buildid=786, name="year", value=1651, source="Wikipedia"), fakedb.BuildProperty(buildid=786, name="island_name", value="despair", source="Book"), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_properties(self): props = yield self.callGet(('builds', 786, 'properties')) self.assertEqual(props, {'year': (1651, 'Wikipedia'), 'island_name': ("despair", 'Book')}) @defer.inlineCallbacks def test_get_properties_from_builder(self): props = yield self.callGet(('builders', 1, 'builds', 5, 'properties')) self.assertEqual(props, {'year': (1651, 'Wikipedia'), 'island_name': ("despair", 'Book')}) class Properties(interfaces.InterfaceTests, TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=False, wantDb=True, wantData=True) self.rtype = properties.Properties(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def do_test_callthrough( self, dbMethodName, method, exp_args=None, exp_kwargs=None, *args, **kwargs ): rv = (1, 2) m = mock.Mock(return_value=defer.succeed(rv)) setattr(self.master.db.builds, dbMethodName, m) res = yield method(*args, **kwargs) self.assertIdentical(res, rv) m.assert_called_with(*(exp_args or args), **((exp_kwargs is None) and kwargs or exp_kwargs)) def test_signature_setBuildProperty(self): @self.assertArgSpecMatches( self.master.data.updates.setBuildProperty, # fake self.rtype.setBuildProperty, ) # real def setBuildProperty(self, buildid, name, value, source): pass def test_setBuildProperty(self): return self.do_test_callthrough( 'setBuildProperty', self.rtype.setBuildProperty, buildid=1234, name='property', value=[42, 45], source='testsuite', exp_args=(1234, 'property', [42, 45], 'testsuite'), exp_kwargs={}, ) @defer.inlineCallbacks def test_setBuildProperties(self): yield self.master.db.insert_test_data([ fakedb.Builder(id=1), fakedb.Buildset(id=28), fakedb.BuildRequest(id=5, builderid=1, buildsetid=28), fakedb.Master(id=3), fakedb.Worker(id=42, name="Friday"), fakedb.Build(id=1234, builderid=1, buildrequestid=5, masterid=3, workerid=42), ]) self.master.db.builds.setBuildProperty = mock.Mock( wraps=self.master.db.builds.setBuildProperty ) props = processProperties.fromDict({"a": (1, 't'), "b": (['abc', 9], 't')}) yield self.rtype.setBuildProperties(1234, props) setBuildPropertiesCalls = sorted(self.master.db.builds.setBuildProperty.mock_calls) self.assertEqual( setBuildPropertiesCalls, [mock.call(1234, 'a', 1, 't'), mock.call(1234, 'b', ['abc', 9], 't')], ) self.master.mq.assertProductions([ (('builds', '1234', 'properties', 'update'), {'a': (1, 't'), 'b': (['abc', 9], 't')}), ]) # sync without changes: no db write self.master.db.builds.setBuildProperty.reset_mock() self.master.mq.clearProductions() yield self.rtype.setBuildProperties(1234, props) self.master.db.builds.setBuildProperty.assert_not_called() self.master.mq.assertProductions([]) # sync with one changes: one db write props.setProperty('b', 2, 'step') self.master.db.builds.setBuildProperty.reset_mock() yield self.rtype.setBuildProperties(1234, props) self.master.db.builds.setBuildProperty.assert_called_with(1234, 'b', 2, 'step') self.master.mq.assertProductions([ (('builds', '1234', 'properties', 'update'), {'b': (2, 'step')}) ])
6,855
Python
.py
145
39.303448
100
0.670208
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,385
test_sourcestamps.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 twisted.internet import defer from twisted.trial import unittest from buildbot.data import sourcestamps from buildbot.test import fakedb from buildbot.test.util import endpoint class SourceStampEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = sourcestamps.SourceStampEndpoint resourceTypeClass = sourcestamps.SourceStamp @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.SourceStamp(id=13, branch='oak'), fakedb.Patch( id=99, patch_base64='aGVsbG8sIHdvcmxk', patch_author='bar', patch_comment='foo', subdir='/foo', patchlevel=3, ), fakedb.SourceStamp(id=14, patchid=99, branch='poplar'), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): sourcestamp = yield self.callGet(('sourcestamps', 13)) self.validateData(sourcestamp) self.assertEqual(sourcestamp['branch'], 'oak') self.assertEqual(sourcestamp['patch'], None) @defer.inlineCallbacks def test_get_existing_patch(self): sourcestamp = yield self.callGet(('sourcestamps', 14)) self.validateData(sourcestamp) self.assertEqual(sourcestamp['branch'], 'poplar') self.assertEqual( sourcestamp['patch'], { 'patchid': 99, 'author': 'bar', 'body': b'hello, world', 'comment': 'foo', 'level': 3, 'subdir': '/foo', }, ) @defer.inlineCallbacks def test_get_missing(self): sourcestamp = yield self.callGet(('sourcestamps', 99)) self.assertEqual(sourcestamp, None) class SourceStampsEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = sourcestamps.SourceStampsEndpoint resourceTypeClass = sourcestamps.SourceStamp @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Buildset(id=30, reason="foo", submitted_at=1300305712, results=-1), fakedb.SourceStamp(id=13), fakedb.SourceStamp(id=14), fakedb.SourceStamp(id=15), fakedb.BuildsetSourceStamp(sourcestampid=13, buildsetid=30), fakedb.BuildsetSourceStamp(sourcestampid=14, buildsetid=30), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): sourcestamps = yield self.callGet(('sourcestamps',)) for m in sourcestamps: self.validateData(m) self.assertEqual(sorted([m['ssid'] for m in sourcestamps]), [13, 14, 15]) @defer.inlineCallbacks def test_get_by_buildsetid_no_buildset(self): sourcestamps = yield self.callGet(("buildsets", 101, "sourcestamps")) self.assertEqual(sourcestamps, []) @defer.inlineCallbacks def test_get_by_buildsetid(self): sourcestamps = yield self.callGet(("buildsets", 30, "sourcestamps")) for m in sourcestamps: self.validateData(m) self.assertEqual(sorted([m['ssid'] for m in sourcestamps]), [13, 14]) class SourceStamp(unittest.TestCase): pass
4,107
Python
.py
99
33.363636
86
0.665579
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,386
test_schedulers.py
buildbot_buildbot/master/buildbot/test/unit/data/test_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 unittest import mock from twisted.internet import defer from twisted.python import failure from twisted.trial import unittest from buildbot.data import schedulers from buildbot.test import fakedb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import endpoint from buildbot.test.util import interfaces from buildbot.util import epoch2datetime class SchedulerEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = schedulers.SchedulerEndpoint resourceTypeClass = schedulers.Scheduler @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.Master(id=33, active=1), fakedb.Scheduler(id=13, name='some:scheduler'), fakedb.Scheduler(id=14, name='other:scheduler'), fakedb.SchedulerMaster(schedulerid=14, masterid=22), fakedb.Scheduler(id=15, name='another:scheduler'), fakedb.SchedulerMaster(schedulerid=15, masterid=33), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get_existing(self): scheduler = yield self.callGet(('schedulers', 14)) self.validateData(scheduler) self.assertEqual(scheduler['name'], 'other:scheduler') @defer.inlineCallbacks def test_get_no_master(self): scheduler = yield self.callGet(('schedulers', 13)) self.validateData(scheduler) self.assertEqual(scheduler['master'], None) @defer.inlineCallbacks def test_get_masterid_existing(self): scheduler = yield self.callGet(('masters', 22, 'schedulers', 14)) self.validateData(scheduler) self.assertEqual(scheduler['name'], 'other:scheduler') @defer.inlineCallbacks def test_get_masterid_no_match(self): scheduler = yield self.callGet(('masters', 33, 'schedulers', 13)) self.assertEqual(scheduler, None) @defer.inlineCallbacks def test_get_masterid_missing(self): scheduler = yield self.callGet(('masters', 99, 'schedulers', 13)) self.assertEqual(scheduler, None) @defer.inlineCallbacks def test_get_missing(self): scheduler = yield self.callGet(('schedulers', 99)) self.assertEqual(scheduler, None) @defer.inlineCallbacks def test_action_enable(self): r = yield self.callControl("enable", {'enabled': False}, ('schedulers', 13)) self.assertEqual(r, None) class SchedulersEndpoint(endpoint.EndpointMixin, unittest.TestCase): endpointClass = schedulers.SchedulersEndpoint resourceTypeClass = schedulers.Scheduler @defer.inlineCallbacks def setUp(self): yield self.setUpEndpoint() yield self.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.Master(id=33, active=1), fakedb.Scheduler(id=13, name='some:scheduler'), fakedb.Scheduler(id=14, name='other:scheduler'), fakedb.SchedulerMaster(schedulerid=14, masterid=22), fakedb.Scheduler(id=15, name='another:scheduler'), fakedb.SchedulerMaster(schedulerid=15, masterid=33), fakedb.Scheduler(id=16, name='wholenother:scheduler'), fakedb.SchedulerMaster(schedulerid=16, masterid=33), ]) def tearDown(self): self.tearDownEndpoint() @defer.inlineCallbacks def test_get(self): schedulers = yield self.callGet(('schedulers',)) for m in schedulers: self.validateData(m) self.assertEqual(sorted([m['schedulerid'] for m in schedulers]), [13, 14, 15, 16]) @defer.inlineCallbacks def test_get_masterid(self): schedulers = yield self.callGet(('masters', 33, 'schedulers')) for m in schedulers: self.validateData(m) self.assertEqual(sorted([m['schedulerid'] for m in schedulers]), [15, 16]) @defer.inlineCallbacks def test_get_masterid_missing(self): schedulers = yield self.callGet(('masters', 23, 'schedulers')) self.assertEqual(schedulers, []) class Scheduler(TestReactorMixin, interfaces.InterfaceTests, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = schedulers.Scheduler(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() def test_signature_schedulerEnable(self): @self.assertArgSpecMatches( self.master.data.updates.schedulerEnable, self.rtype.schedulerEnable ) def schedulerEnable(self, schedulerid, v): pass @defer.inlineCallbacks def test_schedulerEnable(self): SOMETIME = 1348971992 yield self.master.db.insert_test_data([ fakedb.Master(id=22, active=0, last_active=SOMETIME), fakedb.Scheduler(id=13, name='some:scheduler'), fakedb.SchedulerMaster(schedulerid=13, masterid=22), ]) yield self.rtype.schedulerEnable(13, False) self.master.mq.assertProductions([ ( ('schedulers', '13', 'updated'), { 'enabled': False, 'master': { 'active': False, 'last_active': epoch2datetime(SOMETIME), 'masterid': 22, 'name': 'master-22', }, 'name': 'some:scheduler', 'schedulerid': 13, }, ) ]) yield self.rtype.schedulerEnable(13, True) self.master.mq.assertProductions([ ( ('schedulers', '13', 'updated'), { 'enabled': True, 'master': { 'active': False, 'last_active': epoch2datetime(SOMETIME), 'masterid': 22, 'name': 'master-22', }, 'name': 'some:scheduler', 'schedulerid': 13, }, ) ]) def test_signature_findSchedulerId(self): @self.assertArgSpecMatches( self.master.data.updates.findSchedulerId, # fake self.rtype.findSchedulerId, ) # real def findSchedulerId(self, name): pass @defer.inlineCallbacks def test_findSchedulerId(self): self.master.db.schedulers.findSchedulerId = mock.Mock(return_value=defer.succeed(10)) self.assertEqual((yield self.rtype.findSchedulerId('sch')), 10) self.master.db.schedulers.findSchedulerId.assert_called_with('sch') def test_signature_trySetSchedulerMaster(self): @self.assertArgSpecMatches( self.master.data.updates.trySetSchedulerMaster, # fake self.rtype.trySetSchedulerMaster, ) # real def trySetSchedulerMaster(self, schedulerid, masterid): pass @defer.inlineCallbacks def test_trySetSchedulerMaster_succeeds(self): self.master.db.schedulers.setSchedulerMaster = mock.Mock(return_value=defer.succeed(None)) result = yield self.rtype.trySetSchedulerMaster(10, 20) self.assertTrue(result) self.master.db.schedulers.setSchedulerMaster.assert_called_with(10, 20) @defer.inlineCallbacks def test_trySetSchedulerMaster_fails(self): d = defer.fail(failure.Failure(schedulers.SchedulerAlreadyClaimedError('oh noes'))) self.master.db.schedulers.setSchedulerMaster = mock.Mock(return_value=d) result = yield self.rtype.trySetSchedulerMaster(10, 20) self.assertFalse(result) @defer.inlineCallbacks def test_trySetSchedulerMaster_raisesOddException(self): d = defer.fail(failure.Failure(RuntimeError('oh noes'))) self.master.db.schedulers.setSchedulerMaster = mock.Mock(return_value=d) try: yield self.rtype.trySetSchedulerMaster(10, 20) except RuntimeError: pass else: self.fail("The RuntimeError did not propagate") @defer.inlineCallbacks def test__masterDeactivated(self): yield self.master.db.insert_test_data([ fakedb.Master(id=22, active=0), fakedb.Scheduler(id=13, name='some:scheduler'), fakedb.SchedulerMaster(schedulerid=13, masterid=22), fakedb.Scheduler(id=14, name='other:scheduler'), fakedb.SchedulerMaster(schedulerid=14, masterid=22), ]) yield self.rtype._masterDeactivated(22) self.assertIsNone((yield self.master.db.schedulers.get_scheduler_master(13))) self.assertIsNone((yield self.master.db.schedulers.get_scheduler_master(14)))
9,734
Python
.py
218
35.238532
98
0.655926
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,387
test_patches.py
buildbot_buildbot/master/buildbot/test/unit/data/test_patches.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.data import patches from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin class Patch(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantMq=True, wantDb=True, wantData=True) self.rtype = patches.Patch(self.master) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() # no update methods -> nothing to test
1,344
Python
.py
29
43.344828
97
0.778457
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,388
test_manager.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_manager.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.changes import base from buildbot.changes import manager from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin class TestChangeManager(unittest.TestCase, TestReactorMixin): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantData=True) self.cm = manager.ChangeManager() self.master.startService() yield self.cm.setServiceParent(self.master) self.new_config = mock.Mock() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tear_down_test_reactor() def make_sources(self, n, klass=base.ChangeSource, **kwargs): for i in range(n): src = klass(name=f'ChangeSource {i}', **kwargs) yield src @defer.inlineCallbacks def test_reconfigService_add(self): src1, src2 = self.make_sources(2) yield src1.setServiceParent(self.cm) self.new_config.change_sources = [src1, src2] yield self.cm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertIdentical(src2.parent, self.cm) self.assertIdentical(src2.master, self.master) @defer.inlineCallbacks def test_reconfigService_remove(self): (src1,) = self.make_sources(1) yield src1.setServiceParent(self.cm) self.new_config.change_sources = [] self.assertTrue(src1.running) yield self.cm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertFalse(src1.running) @defer.inlineCallbacks def test_reconfigService_change_reconfigurable(self): (src1,) = self.make_sources(1, base.ReconfigurablePollingChangeSource, pollInterval=1) yield src1.setServiceParent(self.cm) (src2,) = self.make_sources(1, base.ReconfigurablePollingChangeSource, pollInterval=2) self.new_config.change_sources = [src2] self.assertTrue(src1.running) self.assertEqual(src1.pollInterval, 1) yield self.cm.reconfigServiceWithBuildbotConfig(self.new_config) self.assertTrue(src1.running) self.assertFalse(src2.running) self.assertEqual(src1.pollInterval, 2)
3,082
Python
.py
66
40.621212
94
0.736069
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,389
test_bitbucket.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_bitbucket.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 datetime import datetime from twisted.internet import defer from twisted.trial import unittest from twisted.web.error import Error from buildbot.changes.bitbucket import BitbucketPullrequestPoller from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import changesource from buildbot.test.util.logging import LoggingMixin class SourceRest: """https://api.bitbucket.org/2.0/repositories/{owner}/{slug}""" template = """\ { "hash": "%(hash)s", "links": { "html": { "href": "https://bitbucket.org/%(owner)s/%(slug)s/commits/%(short_hash)s" }, "diff": { "href": "https://api.bitbucket.org/2.0/repositories/%(owner)s/%(slug)s/diff/%(hash)s" } }, "repository": { "links": { "self": { "href": "https://api.bitbucket.org/2.0/repositories/%(owner)s/%(slug)s" } } }, "date": "%(date)s" } """ repo_template = """\ { "links": { "html": { "href": "https://bitbucket.org/%(owner)s/%(slug)s" } } } """ def __init__(self, owner, slug, hash, date): self.owner = owner self.slug = slug self.hash = hash self.date = date def response(self): return self.template % { "owner": self.owner, "slug": self.slug, "hash": self.hash, "short_hash": self.hash[0:12], "date": self.date, } def repo_response(self): return self.repo_template % { "owner": self.owner, "slug": self.slug, } def diff_response(self): return """ diff --git a/path/to/a/file.txt b/path/to/a/file.txt index 3e59caa..be38dcf 100644 --- a/path/to/a/file.txt +++ b/path/to/a/file.txt @@ -1 +1 @@ -// header +// Header """ class PullRequestRest: """https://api.bitbucket.org/2.0/repositories/{owner}/{slug}/pullrequests/{pull_request_id}""" template = """\ { "description": "%(description)s", "title": "%(title)s", "source": { "commit": { "hash": "%(hash)s", "links": { "self": { "href": "https://api.bitbucket.org/2.0/repositories/%(owner)s/%(slug)s/commit/%(hash)s" } } } }, "state": "OPEN", "author": { "display_name": "%(display_name)s" }, "created_on": "%(created_on)s", "participants": [ ], "updated_on": "%(updated_on)s", "merge_commit": null, "id": %(id)d } """ def __init__(self, nr, title, description, display_name, source, created_on, updated_on=None): self.nr = nr self.title = title self.description = description self.display_name = display_name self.source = source self.created_on = created_on if updated_on: self.updated_on = updated_on else: self.updated_on = self.created_on def response(self): return self.template % { "description": self.description, "title": self.title, "hash": self.source.hash, "short_hash": self.source.hash[0:12], "owner": self.source.owner, "slug": self.source.slug, "display_name": self.display_name, "created_on": self.created_on, "updated_on": self.updated_on, "id": self.nr, } class PullRequestListRest: """https://api.bitbucket.org/2.0/repositories/{owner}/{slug}/pullrequests""" template = """\ { "description": "%(description)s", "links": { "self": { "href": "https://api.bitbucket.org/2.0/repositories/%(owner)s/%(slug)s/pullrequests/%(id)d" }, "html": { "href": "https://bitbucket.org/%(owner)s/%(slug)s/pull-request/%(id)d" } }, "author": { "display_name": "%(display_name)s" }, "title": "%(title)s", "source": { "commit": { "hash": "%(short_hash)s", "links": { "self": { "href": "https://api.bitbucket.org/2.0/repositories/%(src_owner)s/%(src_slug)s/commit/%(short_hash)s" } } }, "repository": { "links": { "self": { "href": "https://api.bitbucket.org/2.0/repositories/%(src_owner)s/%(src_slug)s" } } }, "branch": { "name": "default" } }, "state": "OPEN", "created_on": "%(created_on)s", "updated_on": "%(updated_on)s", "merge_commit": null, "id": %(id)s } """ def __init__(self, owner, slug, prs): self.owner = owner self.slug = slug self.prs = prs self.pr_by_id = {} self.src_by_url = {} for pr in prs: self.pr_by_id[pr.nr] = pr self.src_by_url[f"{pr.source.owner}/{pr.source.slug}"] = pr.source def response(self): s = "" for pr in self.prs: s += self.template % { "description": pr.description, "owner": self.owner, "slug": self.slug, "display_name": pr.display_name, "title": pr.title, "hash": pr.source.hash, "short_hash": pr.source.hash[0:12], "src_owner": pr.source.owner, "src_slug": pr.source.slug, "created_on": pr.created_on, "updated_on": pr.updated_on, "id": pr.nr, } return f"""\ {{ "pagelen": 10, "values": [{s}], "page": 1 }} """ def getPage(self, url, timeout=None, headers=None): list_url_re = re.compile( f"https://api.bitbucket.org/2.0/repositories/{self.owner}/{self.slug}/pullrequests" ) pr_url_re = re.compile( rf"https://api.bitbucket.org/2.0/repositories/{self.owner}/{self.slug}/pullrequests/(?P<id>\d+)" ) source_commit_url_re = re.compile( r"https://api.bitbucket.org/2.0/repositories/(?P<src_owner>.*)/(?P<src_slug>.*)/commit/(?P<hash>\d+)" ) source_url_re = re.compile( r"https://api.bitbucket.org/2.0/repositories/(?P<src_owner>.*)/(?P<src_slug>.*)" ) if list_url_re.match(url): return defer.succeed(self.request()) m = pr_url_re.match(url) if m: return self.pr_by_id[int(m.group("id"))].request() m = source_commit_url_re.match(url) if m: return self.src_by_url[f'{m.group("src_owner")}/{m.group("src_slug")}'].request() m = source_url_re.match(url) if m: return self.src_by_url[f'{m.group("src_owner")}/{m.group("src_slug")}'].repo_request() raise Error(code=404) class TestBitbucketPullrequestPoller( changesource.ChangeSourceMixin, TestReactorMixin, LoggingMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpLogging() # create pull requests self.date = "2013-10-15T20:38:20.001797+00:00" self.date_epoch = datetime.strptime( self.date.split('.', maxsplit=1)[0], '%Y-%m-%dT%H:%M:%S' ) self.rest_src = SourceRest( owner="contributor", slug="slug", hash="1111111111111111111111111111111111111111", date=self.date, ) self.rest_pr = PullRequestRest( nr=1, title="title", description="description", display_name="contributor", source=self.rest_src, created_on=self.date, ) self.rest_pr_list = PullRequestListRest( owner="owner", slug="slug", prs=[self.rest_pr], ) return self.setUpChangeSource() @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() def _fakeGetPage(self, result): # Install a fake getPage that puts the requested URL in self.getPage_got_url # and return result self.getPage_got_url = None def fake(url, timeout=None, headers=None): self.getPage_got_url = url return defer.succeed(result) self.patch(self.changesource, "getPage", fake) def _fakeGetPage403(self, expected_headers): def fail_unauthorized(url, timeout=None, headers=None): if headers != expected_headers: raise Error(code=403) self.patch(self.changesource, "getPage", fail_unauthorized) def _fakeGetPage404(self): def fail(url, timeout=None, headers=None): raise Error(code=404) self.patch(self.changesource, "getPage", fail) @defer.inlineCallbacks def _new_change_source(self, **kwargs): self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'https://api.bitbucket.org/2.0', auth=None ) change_source = BitbucketPullrequestPoller(**kwargs) yield self.attachChangeSource(change_source) return change_source # tests @defer.inlineCallbacks def test_describe(self): yield self._new_change_source(owner='owner', slug='slug') assert re.search(r'owner/slug', self.changesource.describe()) @defer.inlineCallbacks def test_poll_unknown_repo(self): # Polling a non-existent repository should result in a 404 yield self._new_change_source(owner='owner', slug='slug') self._http.expect('get', '/repositories/owner/slug/pullrequests', content_json={}, code=404) yield self.changesource.poll() self.assertLogged('error 404 while loading') @defer.inlineCallbacks def test_poll_no_pull_requests(self): yield self._new_change_source(owner='owner', slug='slug') rest_pr_list = PullRequestListRest( owner="owner", slug="slug", prs=[], ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=rest_pr_list.response() ) yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_poll_new_pull_requests(self): yield self._new_change_source(owner='owner', slug='slug') self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, } ], ) @defer.inlineCallbacks def test_poll_no_updated_pull_request(self): yield self._new_change_source(owner='owner', slug='slug') self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, } ], ) # repoll yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) @defer.inlineCallbacks def test_poll_updated_pull_request(self): yield self._new_change_source(owner='owner', slug='slug') rest_src2 = SourceRest( owner="contributor", slug="slug", hash="2222222222222222222222222222222222222222", date=self.date, ) rest_pr2 = PullRequestRest( nr=1, title="title", description="description", display_name="contributor", source=rest_src2, created_on=self.date, ) rest_pr_list2 = PullRequestListRest( owner="owner", slug="slug", prs=[rest_pr2], ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=rest_pr_list2.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=rest_pr2.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/222222222222', content=rest_src2.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/2222222222222222222222222222222222222222', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=rest_src2.repo_response(), ) yield self.changesource.poll() self.maxDiff = None self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, } ], ) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, }, { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '2222222222222222222222222222222222222222', 'revlink': 'https://bitbucket.org/contributor/slug/commits/222222222222', 'src': 'bitbucket', 'when_timestamp': 1381869500, }, ], ) @defer.inlineCallbacks def test_poll_pull_request_filter_False(self): yield self._new_change_source( owner='owner', slug='slug', pullrequest_filter=lambda x: False ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_poll_pull_request_filter_True(self): yield self._new_change_source(owner='owner', slug='slug', pullrequest_filter=lambda x: True) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, } ], ) @defer.inlineCallbacks def test_poll_pull_request_not_useTimestamps(self): yield self._new_change_source(owner='owner', slug='slug', useTimestamps=False) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) self.reactor.advance(1396825656) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1' }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1396825656, } ], ) @defer.inlineCallbacks def test_poll_pull_request_properties(self): yield self._new_change_source( owner='owner', slug='slug', bitbucket_property_whitelist=["bitbucket.*"] ) self._http.expect( 'get', '/repositories/owner/slug/pullrequests', content=self.rest_pr_list.response() ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/owner/slug/pullrequests/1', content=self.rest_pr.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/commit/111111111111', content=self.rest_src.response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug/diff/1111111111111111111111111111111111111111', content=self.rest_src.diff_response(), ) self._http.expect( 'get', 'https://api.bitbucket.org/2.0/repositories/contributor/slug', content=self.rest_src.repo_response(), ) yield self.changesource.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'contributor', 'committer': None, 'branch': 'default', 'category': None, 'codebase': None, 'comments': 'pull-request #1: title\nhttps://bitbucket.org/owner/slug/pull-request/1', 'files': ['path/to/a/file.txt'], 'project': '', 'properties': { 'pullrequesturl': 'https://bitbucket.org/owner/slug/pull-request/1', 'bitbucket.author.display_name': 'contributor', 'bitbucket.created_on': '2013-10-15T20:38:20.001797+00:00', 'bitbucket.description': 'description', 'bitbucket.id': 1, 'bitbucket.links.html.href': 'https://bitbucket.org/owner/slug/pull-request/1', 'bitbucket.links.self.href': 'https://api.bitbucket.org/2.0/' 'repositories/owner/slug/pullrequests/1', 'bitbucket.merge_commit': None, 'bitbucket.source.branch.name': 'default', 'bitbucket.source.commit.hash': '111111111111', 'bitbucket.source.commit.links.self.href': 'https://api.bitbucket.org/2.0/' 'repositories/contributor/slug/' 'commit/111111111111', 'bitbucket.source.repository.links.self.href': 'https://api.bitbucket.org/2.0/' 'repositories/contributor/slug', 'bitbucket.state': 'OPEN', 'bitbucket.title': 'title', 'bitbucket.updated_on': '2013-10-15T20:38:20.001797+00:00', }, 'repository': 'https://bitbucket.org/contributor/slug', 'revision': '1111111111111111111111111111111111111111', 'revlink': 'https://bitbucket.org/contributor/slug/commits/111111111111', 'src': 'bitbucket', 'when_timestamp': 1381869500, } ], )
30,256
Python
.py
750
27.770667
129
0.534368
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,390
test_p4poller.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_p4poller.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 datetime import dateutil.tz from twisted.internet import defer from twisted.internet import error from twisted.internet import reactor from twisted.python import failure from twisted.trial import unittest from buildbot.changes.p4poller import P4PollerError from buildbot.changes.p4poller import P4Source from buildbot.changes.p4poller import get_simple_split from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import changesource from buildbot.test.util import config from buildbot.util import datetime2epoch first_p4changes = b"""Change 1 on 2006/04/13 by slamb@testclient 'first rev' """ second_p4changes = b"""Change 3 on 2006/04/13 by bob@testclient 'short desc truncated' Change 2 on 2006/04/13 by slamb@testclient 'bar' """ third_p4changes = b"""Change 5 on 2006/04/13 by mpatel@testclient 'first rev' """ fourth_p4changes = b"""Change 6 on 2006/04/14 by mpatel@testclient 'bar \xd0\x91' """ p4_describe_2 = b"""Change 2 by slamb@testclient on 2006/04/13 21:46:23 \tcreation Affected files ... ... //depot/myproject/trunk/whatbranch#1 add ... //depot/otherproject/trunk/something#1 add """ p4_describe_3 = """Change 3 by bob@testclient on 2006/04/13 21:51:39 \tshort desc truncated because this is a long description. \tASDF-GUI-P3-\u2018Upgrade Icon\u2019 disappears sometimes. Affected files ... ... //depot/myproject/branch_b/branch_b_file#1 add ... //depot/myproject/branch_b/whatbranch#1 branch ... //depot/myproject/branch_c/whatbranch#1 branch """ p4_describe_4 = b"""Change 4 by mpatel@testclient on 2006/04/13 21:55:39 \tThis is a multiline comment with tabs and spaces \t \tA list: \t Item 1 \t\tItem 2 Affected files ... ... //depot/myproject/branch_b/branch_b_file#1 add ... //depot/myproject/branch_b#75 edit ... //depot/myproject/branch_c/branch_c_file#1 add """ p4change = { 3: p4_describe_3, 2: p4_describe_2, 5: p4_describe_4, } class FakeTransport: def __init__(self): self.msg = None def write(self, msg): self.msg = msg def closeStdin(self): pass class TestP4Poller( changesource.ChangeSourceMixin, MasterRunProcessMixin, config.ConfigErrorsMixin, TestReactorMixin, unittest.TestCase, ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() yield self.setUpChangeSource() @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() def add_p4_describe_result(self, number, result): self.expect_commands( ExpectMasterShell(['p4', 'describe', '-s', str(number)]).stdout(result) ) def makeTime(self, timestring): datefmt = '%Y/%m/%d %H:%M:%S' when = datetime.datetime.strptime(timestring, datefmt) return when @defer.inlineCallbacks def test_describe(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) ) self.assertSubstring("p4source", self.changesource.describe()) def test_name(self): # no name: cs1 = P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) self.assertEqual("P4Source:None://depot/myproject/", cs1.name) # explicit name: cs2 = P4Source( p4port=None, p4user=None, name='MyName', p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) self.assertEqual("MyName", cs2.name) @defer.inlineCallbacks def do_test_poll_successful(self, **kwargs): encoding = kwargs.get('encoding', 'utf8') yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), **kwargs, ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '-m', '1', '//depot/myproject/...']).stdout( first_p4changes ), ExpectMasterShell(['p4', 'changes', '//depot/myproject/...@2,#head']).stdout( second_p4changes ), ) encoded_p4change = p4change.copy() encoded_p4change[3] = encoded_p4change[3].encode(encoding) self.add_p4_describe_result(2, encoded_p4change[2]) self.add_p4_describe_result(3, encoded_p4change[3]) # The first time, it just learns the change to start at. self.assertTrue(self.changesource.last_change is None) yield self.changesource.poll() self.assertEqual(self.master.data.updates.changesAdded, []) self.assertEqual(self.changesource.last_change, 1) # Subsequent times, it returns Change objects for new changes. yield self.changesource.poll() # when_timestamp is converted from a local time spec, so just # replicate that here when1 = self.makeTime("2006/04/13 21:46:23") when2 = self.makeTime("2006/04/13 21:51:39") # these two can happen in either order, since they're from the same # perforce change. changesAdded = self.master.data.updates.changesAdded if changesAdded[1]['branch'] == 'branch_c': changesAdded[1:] = reversed(changesAdded[1:]) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'slamb', 'committer': None, 'branch': 'trunk', 'category': None, 'codebase': None, 'comments': 'creation', 'files': ['whatbranch'], 'project': '', 'properties': {}, 'repository': '', 'revision': '2', 'revlink': '', 'src': None, 'when_timestamp': datetime2epoch(when1), }, { 'author': 'bob', 'committer': None, 'branch': 'branch_b', 'category': None, 'codebase': None, 'comments': 'short desc truncated because this is a long description.\n' 'ASDF-GUI-P3-\u2018Upgrade Icon\u2019 disappears sometimes.', 'files': ['branch_b_file', 'whatbranch'], 'project': '', 'properties': {}, 'repository': '', 'revision': '3', 'revlink': '', 'src': None, 'when_timestamp': datetime2epoch(when2), }, { 'author': 'bob', 'committer': None, 'branch': 'branch_c', 'category': None, 'codebase': None, 'comments': 'short desc truncated because this is a long description.\n' 'ASDF-GUI-P3-\u2018Upgrade Icon\u2019 disappears sometimes.', 'files': ['whatbranch'], 'project': '', 'properties': {}, 'repository': '', 'revision': '3', 'revlink': '', 'src': None, 'when_timestamp': datetime2epoch(when2), }, ], ) self.assert_all_commands_ran() def test_poll_successful_default_encoding(self): return self.do_test_poll_successful() def test_poll_successful_macroman_encoding(self): return self.do_test_poll_successful(encoding='macroman') @defer.inlineCallbacks def test_poll_failed_changes(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '-m', '1', '//depot/myproject/...']).stdout( b'Perforce client error:\n...' ) ) # call _poll, so we can catch the failure with self.assertRaises(P4PollerError): yield self.changesource._poll() self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_failed_describe(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '//depot/myproject/...@3,#head']).stdout( second_p4changes ), ) self.add_p4_describe_result(2, p4change[2]) self.add_p4_describe_result(3, b'Perforce client error:\n...') # tell poll() that it's already been called once self.changesource.last_change = 2 # call _poll, so we can catch the failure with self.assertRaises(P4PollerError): yield self.changesource._poll() # check that 2 was processed OK self.assertEqual(self.changesource.last_change, 2) self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_unicode_error(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '//depot/myproject/...@3,#head']).stdout( second_p4changes ), ) # Add a character which cannot be decoded with utf-8 undecodableText = p4change[2] + b"\x81" self.add_p4_describe_result(2, undecodableText) # tell poll() that it's already been called once self.changesource.last_change = 2 # call _poll, so we can catch the failure with self.assertRaises(UnicodeError): yield self.changesource._poll() self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_unicode_error2(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), encoding='ascii', ) ) # Trying to decode a certain character with ascii codec should fail. self.expect_commands( ExpectMasterShell(['p4', 'changes', '-m', '1', '//depot/myproject/...']).stdout( fourth_p4changes ), ) yield self.changesource._poll() self.assert_all_commands_ran() @defer.inlineCallbacks def test_acquire_ticket_auth(self): yield self.attachChangeSource( P4Source( p4port=None, p4user='buildbot_user', p4passwd='pass', p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), use_tickets=True, ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '-m', '1', '//depot/myproject/...']).stdout( first_p4changes ) ) transport = FakeTransport() # p4poller uses only those arguments at the moment def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'-u', b'buildbot_user', b'login']]) pp.makeConnection(transport) self.assertEqual(b'pass\n', transport.msg) pp.outReceived(b'Enter password:\nUser buildbot_user logged in.\n') so = error.ProcessDone(None) pp.processEnded(failure.Failure(so)) self.patch(reactor, 'spawnProcess', spawnProcess) yield self.changesource.poll() self.assert_all_commands_ran() @defer.inlineCallbacks def test_acquire_ticket_auth_fail(self): yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4passwd='pass', p4base='//depot/myproject/', split_file=lambda x: x.split('/', 1), use_tickets=True, ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '-m', '1', '//depot/myproject/...']).stdout( first_p4changes ) ) transport = FakeTransport() # p4poller uses only those arguments at the moment def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'login']]) pp.makeConnection(transport) self.assertEqual(b'pass\n', transport.msg) pp.outReceived(b'Enter password:\n') pp.errReceived(b"Password invalid.\n") so = error.ProcessDone(status=1) pp.processEnded(failure.Failure(so)) self.patch(reactor, 'spawnProcess', spawnProcess) yield self.changesource.poll() @defer.inlineCallbacks def test_poll_split_file(self): """Make sure split file works on branch only changes""" yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=get_simple_split ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '//depot/myproject/...@51,#head']).stdout( third_p4changes ), ) self.add_p4_describe_result(5, p4change[5]) self.changesource.last_change = 50 yield self.changesource.poll() # when_timestamp is converted from a local time spec, so just # replicate that here when = self.makeTime("2006/04/13 21:55:39") def changeKey(change): """Let's sort the array of changes by branch, because in P4Source._poll(), changeAdded() is called by iterating over a dictionary of branches""" return change['branch'] self.assertEqual( sorted(self.master.data.updates.changesAdded, key=changeKey), sorted( [ { 'author': 'mpatel', 'committer': None, 'branch': 'branch_c', 'category': None, 'codebase': None, 'comments': 'This is a multiline comment with tabs and spaces\n\nA list:\n ' 'Item 1\n\tItem 2', 'files': ['branch_c_file'], 'project': '', 'properties': {}, 'repository': '', 'revision': '5', 'revlink': '', 'src': None, 'when_timestamp': datetime2epoch(when), }, { 'author': 'mpatel', 'committer': None, 'branch': 'branch_b', 'category': None, 'codebase': None, 'comments': 'This is a multiline comment with tabs and spaces\n\nA list:\n ' 'Item 1\n\tItem 2', 'files': ['branch_b_file'], 'project': '', 'properties': {}, 'repository': '', 'revision': '5', 'revlink': '', 'src': None, 'when_timestamp': datetime2epoch(when), }, ], key=changeKey, ), ) self.assertEqual(self.changesource.last_change, 5) self.assert_all_commands_ran() @defer.inlineCallbacks def test_server_tz(self): """Verify that the server_tz parameter is handled correctly""" yield self.attachChangeSource( P4Source( p4port=None, p4user=None, p4base='//depot/myproject/', split_file=get_simple_split, server_tz="Europe/Berlin", ) ) self.expect_commands( ExpectMasterShell(['p4', 'changes', '//depot/myproject/...@51,#head']).stdout( third_p4changes ), ) self.add_p4_describe_result(5, p4change[5]) self.changesource.last_change = 50 yield self.changesource.poll() # when_timestamp is converted from 21:55:39 Berlin time to UTC when_berlin = self.makeTime("2006/04/13 21:55:39") when_berlin = when_berlin.replace(tzinfo=dateutil.tz.gettz('Europe/Berlin')) when = datetime2epoch(when_berlin) self.assertEqual( [ch['when_timestamp'] for ch in self.master.data.updates.changesAdded], [when, when] ) self.assert_all_commands_ran() def test_resolveWho_callable(self): with self.assertRaisesConfigError("You need to provide a valid callable for resolvewho"): P4Source(resolvewho=None) class TestSplit(unittest.TestCase): def test_get_simple_split(self): self.assertEqual(get_simple_split('foo/bar'), ('foo', 'bar')) self.assertEqual(get_simple_split('foo-bar'), (None, None)) self.assertEqual(get_simple_split('/bar'), ('', 'bar')) self.assertEqual(get_simple_split('foo/'), ('foo', ''))
19,136
Python
.py
480
28.310417
101
0.55659
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,391
test_github.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_github.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.trial import unittest from buildbot.changes.github import GitHubPullrequestPoller from buildbot.config import ConfigErrors from buildbot.process.properties import Properties from buildbot.process.properties import Secret from buildbot.secrets.manager import SecretManager from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.secrets import FakeSecretStorage from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import changesource gitJsonPayloadSinglePullrequest = """ { "html_url": "https://github.com/buildbot/buildbot/pull/4242", "number": 4242, "state": "open", "locked": false, "title": "Update the README with new information", "user": { "login": "defunkt" }, "body": "This is a pretty simple change that we need to pull into master.", "updated_at": "2017-01-25T22:36:21Z", "head": { "ref": "defunkt/change", "sha": "4c9a7f03e04e551a5e012064b581577f949dd3a4", "repo": { "name": "buildbot", "full_name": "defunkt/buildbot", "fork": true, "private": false, "git_url": "git://github.com/defunkt/buildbot.git", "ssh_url": "[email protected]:defunkt/buildbot.git", "clone_url": "https://github.com/defunkt/buildbot.git", "svn_url": "https://github.com/defunkt/buildbot" } }, "base": { "ref": "master", "sha": "4c9a7f03e04e551a5e012064b581577f949dd3a4", "name": "buildbot", "repo": { "full_name": "buildbot/buildbot", "fork": false, "private": false, "git_url": "git://github.com/buildbot/buildbot.git", "ssh_url": "[email protected]:buildbot/buildbot.git", "clone_url": "https://github.com/buildbot/buildbot.git", "svn_url": "https://github.com/buildbot/buildbot" } }, "merged": false, "commits": 42, "mergeable": true, "mergeable_state": "clean", "merged_by": null } """ gitJsonPayloadPullRequests = """ [ { "html_url": "https://github.com/buildbot/buildbot/pull/4242", "number": 4242, "locked": false, "title": "Update the README with new information", "user": { "login": "defunkt" }, "body": "This is a pretty simple change that we need to pull into master.", "updated_at": "2017-01-25T22:36:21Z", "head": { "ref": "defunkt/change", "sha": "4c9a7f03e04e551a5e012064b581577f949dd3a4", "repo": { "name": "buildbot", "git_url": "git://github.com/defunkt/buildbot.git", "ssh_url": "[email protected]:defunkt/buildbot.git", "clone_url": "https://github.com/defunkt/buildbot.git", "svn_url": "https://github.com/defunkt/buildbot" } }, "base": { "ref": "master", "name": "buildbot", "repo": { "git_url": "git://github.com/buildbot/buildbot.git", "ssh_url": "[email protected]:buildbot/buildbot.git", "clone_url": "https://github.com/buildbot/buildbot.git", "svn_url": "https://github.com/buildbot/buildbot" } } } ] """ gitJsonPayloadFiles = """ [ { "filename": "README.md" } ] """ gitJsonPayloadAuthors = """ [ { "commit": { "author": { "name": "defunkt", "email": "[email protected]" } } } ] """ gitJsonPayloadCommitters = """ [ { "commit": { "committer": { "name": "defunktc", "email": "[email protected]" } } } ] """ git_json_not_found = """ { "message": "Not Found", "documentation_url": "https://docs.github.com/rest/reference/pulls#list-pull-requests" } """ _CT_ENCODED = b'application/x-www-form-urlencoded' _CT_JSON = b'application/json' _GH_PARSED_PROPS = { 'pullrequesturl': 'https://github.com/buildbot/buildbot/pull/4242', 'github.head.sha': '4c9a7f03e04e551a5e012064b581577f949dd3a4', 'github.state': 'open', 'github.number': 4242, 'github.merged': False, 'github.base.repo.full_name': 'buildbot/buildbot', 'github.base.ref': 'master', 'github.base.sha': '4c9a7f03e04e551a5e012064b581577f949dd3a4', 'github.head.repo.full_name': 'defunkt/buildbot', 'github.mergeable_state': 'clean', 'github.mergeable': True, 'github.head.ref': 'defunkt/change', 'github.title': 'Update the README with new information', 'github.merged_by': None, } class TestGitHubPullrequestPoller( changesource.ChangeSourceMixin, TestReactorMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpChangeSource() fake_storage_service = FakeSecretStorage() secret_service = SecretManager() secret_service.services = [fake_storage_service] yield secret_service.setServiceParent(self.master) yield self.master.startService() fake_storage_service.reconfigService(secretdict={"token": "1234"}) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def newChangeSource(self, owner, repo, endpoint='https://api.github.com', **kwargs): http_headers = {'User-Agent': 'Buildbot'} token = kwargs.get('token', None) if token: p = Properties() p.master = self.master token = yield p.render(token) http_headers.update({'Authorization': 'token ' + token}) self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, endpoint, headers=http_headers ) self.changesource = GitHubPullrequestPoller(owner, repo, **kwargs) @defer.inlineCallbacks def startChangeSource(self): yield self.changesource.setServiceParent(self.master) yield self.attachChangeSource(self.changesource) def assertDictSubset(self, expected_dict, response_dict): expected = {} for key in expected_dict.keys(): self.assertIn(key, set(response_dict.keys())) expected[key] = response_dict[key] self.assertDictEqual(expected_dict, expected) @defer.inlineCallbacks def test_describe(self): yield self.newChangeSource('defunkt', 'defunkt') yield self.startChangeSource() self.assertEqual( f"GitHubPullrequestPoller watching the GitHub repository {'defunkt'}/{'defunkt'}", self.changesource.describe(), ) @defer.inlineCallbacks def test_default_name(self): yield self.newChangeSource('defunkt', 'defunkt') yield self.startChangeSource() self.assertEqual(f"GitHubPullrequestPoller:{'defunkt'}/{'defunkt'}", self.changesource.name) @defer.inlineCallbacks def test_custom_name(self): yield self.newChangeSource('defunkt', 'defunkt', name="MyName") yield self.startChangeSource() self.assertEqual("MyName", self.changesource.name) @defer.inlineCallbacks def test_SimplePR(self): yield self.newChangeSource( 'defunkt', 'defunkt', token='1234', github_property_whitelist=["github.*"] ) yield self.simple_pr() @defer.inlineCallbacks def test_project(self): yield self.newChangeSource( 'defunkt', 'defunkt', token='1234', project='tst_project', github_property_whitelist=["github.*"], ) yield self.simple_pr(project='tst_project') @defer.inlineCallbacks def test_secret_token(self): yield self.newChangeSource( 'defunkt', 'defunkt', token=Secret('token'), github_property_whitelist=["github.*"] ) yield self.simple_pr() @defer.inlineCallbacks def simple_pr(self, project=None): self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadAuthors), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadCommitters), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads(gitJsonPayloadFiles), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['author'], 'defunkt <[email protected]>') self.assertEqual(change['revision'], '4c9a7f03e04e551a5e012064b581577f949dd3a4') self.assertEqual(change['revlink'], 'https://github.com/buildbot/buildbot/pull/4242') self.assertEqual(change['branch'], 'defunkt/change') self.assertEqual(change['repository'], 'https://github.com/defunkt/buildbot.git') self.assertEqual(change['files'], ['README.md']) self.assertEqual(change['committer'], 'defunktc <[email protected]>') self.assertEqual(change['project'], project if project is not None else 'buildbot/buildbot') self.assertDictSubset(_GH_PARSED_PROPS, change['properties']) self.assertEqual( change["comments"], "GitHub Pull Request #4242 (42 commits)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", ) @defer.inlineCallbacks def test_wrongBranch(self): yield self.newChangeSource('defunkt', 'defunkt', token='1234', branches=['wrongBranch']) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_http_error(self): yield self.newChangeSource('defunkt', 'defunkt', token='1234') self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(git_json_not_found), code=404, ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_baseURL(self): yield self.newChangeSource( 'defunkt', 'defunkt', endpoint='https://my.other.endpoint', token='1234', baseURL='https://my.other.endpoint/', github_property_whitelist=["github.*"], ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadAuthors), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadCommitters), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads(gitJsonPayloadFiles), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['author'], 'defunkt <[email protected]>') self.assertEqual(change['revision'], '4c9a7f03e04e551a5e012064b581577f949dd3a4') self.assertEqual(change['revlink'], 'https://github.com/buildbot/buildbot/pull/4242') self.assertEqual(change['branch'], 'defunkt/change') self.assertEqual(change['repository'], 'https://github.com/defunkt/buildbot.git') self.assertEqual(change['files'], ['README.md']) self.assertEqual(change['committer'], 'defunktc <[email protected]>') self.assertDictSubset(_GH_PARSED_PROPS, change['properties']) self.assertEqual( change["comments"], "GitHub Pull Request #4242 (42 commits)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", ) @defer.inlineCallbacks def test_PRfilter(self): yield self.newChangeSource( 'defunkt', 'defunkt', token='1234', pullrequest_filter=lambda pr: pr['number'] == 1337 ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_failCommitters(self): yield self.newChangeSource('defunkt', 'defunkt', token='1234') self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads("[{}]"), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads("[{}]"), ) yield self.startChangeSource() yield self.assertFailure(self.changesource.poll(), KeyError) @defer.inlineCallbacks def test_failFiles(self): yield self.newChangeSource('defunkt', 'defunkt', token='1234') self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads("[{}]"), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads("[{}]"), ) yield self.startChangeSource() yield self.assertFailure(self.changesource.poll(), KeyError) @defer.inlineCallbacks def test_wrongRepoLink(self): with self.assertRaises(ConfigErrors): yield self.newChangeSource( 'defunkt', 'defunkt', token='1234', repository_type='defunkt' ) @defer.inlineCallbacks def test_magicLink(self): yield self.newChangeSource( 'defunkt', 'defunkt', magic_link=True, token='1234', github_property_whitelist=["github.*"], ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadAuthors), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadCommitters), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads(gitJsonPayloadFiles), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['author'], 'defunkt <[email protected]>') self.assertEqual(change['revision'], '4c9a7f03e04e551a5e012064b581577f949dd3a4') self.assertEqual(change['revlink'], 'https://github.com/buildbot/buildbot/pull/4242') self.assertEqual(change['branch'], 'refs/pull/4242/merge') self.assertEqual(change['repository'], 'https://github.com/buildbot/buildbot.git') self.assertEqual(change['files'], ['README.md']) self.assertEqual(change['committer'], 'defunktc <[email protected]>') self.assertDictSubset(_GH_PARSED_PROPS, change['properties']) self.assertEqual( change["comments"], "GitHub Pull Request #4242 (42 commits)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", ) @defer.inlineCallbacks def test_AuthormissingEmail(self): yield self.newChangeSource( 'defunkt', 'defunkt', token='1234', github_property_whitelist=["github.*"] ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls', content_json=json.loads(gitJsonPayloadPullRequests), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242', content_json=json.loads(gitJsonPayloadSinglePullrequest), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadAuthors), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/commits', content_json=json.loads(gitJsonPayloadCommitters), ) self._http.expect( method='get', ep='/repos/defunkt/defunkt/pulls/4242/files', content_json=json.loads(gitJsonPayloadFiles), ) yield self.startChangeSource() yield self.changesource.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['author'], 'defunkt <[email protected]>') self.assertEqual(change['revision'], '4c9a7f03e04e551a5e012064b581577f949dd3a4') self.assertEqual(change['revlink'], 'https://github.com/buildbot/buildbot/pull/4242') self.assertEqual(change['branch'], 'defunkt/change') self.assertEqual(change['repository'], 'https://github.com/defunkt/buildbot.git') self.assertEqual(change['files'], ['README.md']) self.assertEqual(change['committer'], 'defunktc <[email protected]>') self.assertDictSubset(_GH_PARSED_PROPS, change['properties']) self.assertEqual( change["comments"], "GitHub Pull Request #4242 (42 commits)\n" "Update the README with new information\n" "This is a pretty simple change that we need to pull into master.", )
21,032
Python
.py
536
30.964552
100
0.636386
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,392
test_hgpoller.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_hgpoller.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.trial import unittest from buildbot.changes import hgpoller from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import changesource ENVIRON_2116_KEY = 'TEST_THAT_ENVIRONMENT_GETS_PASSED_TO_SUBPROCESSES' LINESEP_BYTES = os.linesep.encode("ascii") PATHSEP_BYTES = os.pathsep.encode("ascii") class TestHgPollerBase( MasterRunProcessMixin, changesource.ChangeSourceMixin, TestReactorMixin, unittest.TestCase ): usetimestamps = True branches: list[str] | None = None bookmarks: list[str] | None = None @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() yield self.setUpChangeSource() # To test that environment variables get propagated to subprocesses # (See #2116) os.environ[ENVIRON_2116_KEY] = 'TRUE' yield self.setUpChangeSource() self.remote_repo = 'ssh://example.com/foo/baz' self.remote_hgweb = 'http://example.com/foo/baz/rev/{}' self.repo_ready = True def _isRepositoryReady(): return self.repo_ready self.poller = hgpoller.HgPoller( self.remote_repo, usetimestamps=self.usetimestamps, workdir='/some/dir', branches=self.branches, bookmarks=self.bookmarks, revlink=lambda branch, revision: self.remote_hgweb.format(revision), ) yield self.poller.setServiceParent(self.master) self.poller._isRepositoryReady = _isRepositoryReady yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def check_current_rev(self, wished, branch='default'): rev = yield self.poller._getCurrentRev(branch) self.assertEqual(rev, str(wished)) class TestHgPollerBranches(TestHgPollerBase): branches = ['one', 'two'] @defer.inlineCallbacks def test_poll_initial(self): self.expect_commands( ExpectMasterShell([ 'hg', 'pull', '-b', 'one', '-b', 'two', 'ssh://example.com/foo/baz', ]).workdir('/some/dir'), ExpectMasterShell(['hg', 'heads', 'one', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b"73591"), ExpectMasterShell(['hg', 'heads', 'two', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b"22341"), ) # do the poll yield self.poller.poll() # check the results self.assertEqual(len(self.master.data.updates.changesAdded), 0) yield self.check_current_rev(73591, 'one') yield self.check_current_rev(22341, 'two') @defer.inlineCallbacks def test_poll_regular(self): # normal operation. There's a previous revision, we get a new one. # Let's say there was an intervening commit on an untracked branch, to # make it more interesting. self.expect_commands( ExpectMasterShell([ 'hg', 'pull', '-b', 'one', '-b', 'two', 'ssh://example.com/foo/baz', ]).workdir('/some/dir'), ExpectMasterShell(['hg', 'heads', 'one', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'6' + LINESEP_BYTES), ExpectMasterShell(['hg', 'log', '-r', '4::6', '--template={rev}:{node}\\n']) .workdir('/some/dir') .stdout(LINESEP_BYTES.join([b'4:1aaa5', b'6:784bd'])), ExpectMasterShell([ 'hg', 'log', '-r', '784bd', '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + "{files % '{file}" + os.pathsep + "'}" + os.linesep + '{desc|strip}', ]) .workdir('/some/dir') .stdout( LINESEP_BYTES.join([ b'1273258009.0 -7200', b'Joe Test <[email protected]>', b'file1 file2', b'Comment', b'', ]) ), ExpectMasterShell(['hg', 'heads', 'two', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'3' + LINESEP_BYTES), ) yield self.poller._setCurrentRev(3, 'two') yield self.poller._setCurrentRev(4, 'one') yield self.poller.poll() yield self.check_current_rev(6, 'one') self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['revision'], '784bd') self.assertEqual(change['revlink'], 'http://example.com/foo/baz/rev/784bd') self.assertEqual(change['comments'], 'Comment') class TestHgPollerBookmarks(TestHgPollerBase): bookmarks = ['one', 'two'] @defer.inlineCallbacks def test_poll_initial(self): self.expect_commands( ExpectMasterShell([ 'hg', 'pull', '-B', 'one', '-B', 'two', 'ssh://example.com/foo/baz', ]).workdir('/some/dir'), ExpectMasterShell(['hg', 'heads', 'one', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b"73591"), ExpectMasterShell(['hg', 'heads', 'two', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b"22341"), ) # do the poll yield self.poller.poll() # check the results self.assertEqual(len(self.master.data.updates.changesAdded), 0) yield self.check_current_rev(73591, 'one') yield self.check_current_rev(22341, 'two') @defer.inlineCallbacks def test_poll_regular(self): # normal operation. There's a previous revision, we get a new one. # Let's say there was an intervening commit on an untracked branch, to # make it more interesting. self.expect_commands( ExpectMasterShell([ 'hg', 'pull', '-B', 'one', '-B', 'two', 'ssh://example.com/foo/baz', ]).workdir('/some/dir'), ExpectMasterShell(['hg', 'heads', 'one', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'6' + LINESEP_BYTES), ExpectMasterShell(['hg', 'log', '-r', '4::6', '--template={rev}:{node}\\n']) .workdir('/some/dir') .stdout( LINESEP_BYTES.join([ b'4:1aaa5', b'6:784bd', ]) ), ExpectMasterShell([ 'hg', 'log', '-r', '784bd', '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + "{files % '{file}" + os.pathsep + "'}" + os.linesep + '{desc|strip}', ]) .workdir('/some/dir') .stdout( LINESEP_BYTES.join([ b'1273258009.0 -7200', b'Joe Test <[email protected]>', b'file1 file2', b'Comment', b'', ]) ), ExpectMasterShell(['hg', 'heads', 'two', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'3' + LINESEP_BYTES), ) yield self.poller._setCurrentRev(3, 'two') yield self.poller._setCurrentRev(4, 'one') yield self.poller.poll() yield self.check_current_rev(6, 'one') self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['revision'], '784bd') self.assertEqual(change['comments'], 'Comment') class TestHgPoller(TestHgPollerBase): def tearDown(self): del os.environ[ENVIRON_2116_KEY] return self.tearDownChangeSource() def gpoFullcommandPattern(self, commandName, *expected_args): """Match if the command is commandName and arg list start as expected. This allows to test a bit more if expected GPO are issued, be it by obscure failures due to the result not being given. """ def matchesSubcommand(bin, given_args, **kwargs): return bin == commandName and tuple(given_args[: len(expected_args)]) == expected_args return matchesSubcommand def test_describe(self): self.assertSubstring("HgPoller", self.poller.describe()) def test_name(self): self.assertEqual(self.remote_repo, self.poller.name) # and one with explicit name... other = hgpoller.HgPoller(self.remote_repo, name="MyName", workdir='/some/dir') self.assertEqual("MyName", other.name) # and one with explicit branches... other = hgpoller.HgPoller(self.remote_repo, branches=["b1", "b2"], workdir='/some/dir') self.assertEqual(self.remote_repo + "_b1_b2", other.name) def test_hgbin_default(self): self.assertEqual(self.poller.hgbin, "hg") @defer.inlineCallbacks def test_poll_initial(self): self.repo_ready = False # Test that environment variables get propagated to subprocesses # (See #2116) expected_env = {ENVIRON_2116_KEY: 'TRUE'} self.add_run_process_expect_env(expected_env) self.expect_commands( ExpectMasterShell(['hg', 'init', '/some/dir']), ExpectMasterShell(['hg', 'pull', '-b', 'default', 'ssh://example.com/foo/baz']).workdir( '/some/dir' ), ExpectMasterShell(['hg', 'heads', 'default', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b"73591"), ) # do the poll yield self.poller.poll() # check the results self.assertEqual(len(self.master.data.updates.changesAdded), 0) yield self.check_current_rev(73591) @defer.inlineCallbacks def test_poll_several_heads(self): # If there are several heads on the named branch, the poller mustn't # climb (good enough for now, ideally it should even go to the common # ancestor) self.expect_commands( ExpectMasterShell(['hg', 'pull', '-b', 'default', 'ssh://example.com/foo/baz']).workdir( '/some/dir' ), ExpectMasterShell(['hg', 'heads', 'default', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'5' + LINESEP_BYTES + b'6' + LINESEP_BYTES), ) yield self.poller._setCurrentRev(3) # do the poll: we must stay at rev 3 yield self.poller.poll() yield self.check_current_rev(3) @defer.inlineCallbacks def test_poll_regular(self): # normal operation. There's a previous revision, we get a new one. self.expect_commands( ExpectMasterShell(['hg', 'pull', '-b', 'default', 'ssh://example.com/foo/baz']).workdir( '/some/dir' ), ExpectMasterShell(['hg', 'heads', 'default', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'5' + LINESEP_BYTES), ExpectMasterShell(['hg', 'log', '-r', '4::5', '--template={rev}:{node}\\n']) .workdir('/some/dir') .stdout(LINESEP_BYTES.join([b'4:1aaa5', b'5:784bd'])), ExpectMasterShell([ 'hg', 'log', '-r', '784bd', '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + "{files % '{file}" + os.pathsep + "'}" + os.linesep + '{desc|strip}', ]) .workdir('/some/dir') .stdout( LINESEP_BYTES.join([ b'1273258009.0 -7200', b'Joe Test <[email protected]>', b'file1 file2', b'Comment for rev 5', b'', ]) ), ) yield self.poller._setCurrentRev(4) yield self.poller.poll() yield self.check_current_rev(5) self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['revision'], '784bd') self.assertEqual(change['comments'], 'Comment for rev 5') @defer.inlineCallbacks def test_poll_force_push(self): # There's a previous revision, but not linked with new rev self.expect_commands( ExpectMasterShell(['hg', 'pull', '-b', 'default', 'ssh://example.com/foo/baz']).workdir( '/some/dir' ), ExpectMasterShell(['hg', 'heads', 'default', '--template={rev}' + os.linesep]) .workdir('/some/dir') .stdout(b'5' + LINESEP_BYTES), ExpectMasterShell(['hg', 'log', '-r', '4::5', '--template={rev}:{node}\\n']) .workdir('/some/dir') .stdout(b""), ExpectMasterShell(['hg', 'log', '-r', '5', '--template={rev}:{node}\\n']) .workdir('/some/dir') .stdout(LINESEP_BYTES.join([b'5:784bd'])), ExpectMasterShell([ 'hg', 'log', '-r', '784bd', '--template={date|hgdate}' + os.linesep + '{author}' + os.linesep + "{files % '{file}" + os.pathsep + "'}" + os.linesep + '{desc|strip}', ]) .workdir('/some/dir') .stdout( LINESEP_BYTES.join([ b'1273258009.0 -7200', b'Joe Test <[email protected]>', b'file1 file2', b'Comment for rev 5', b'', ]) ), ) yield self.poller._setCurrentRev(4) yield self.poller.poll() yield self.check_current_rev(5) self.assertEqual(len(self.master.data.updates.changesAdded), 1) change = self.master.data.updates.changesAdded[0] self.assertEqual(change['revision'], '784bd') self.assertEqual(change['comments'], 'Comment for rev 5') class HgPollerNoTimestamp(TestHgPoller): """Test HgPoller() without parsing revision commit timestamp""" usetimestamps = False
16,302
Python
.py
402
28.890547
100
0.541483
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,393
test_pb.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_pb.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot import config from buildbot.changes import pb from buildbot.test.fake import fakemaster from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import changesource from buildbot.test.util import pbmanager class TestPBChangeSource( changesource.ChangeSourceMixin, pbmanager.PBManagerMixin, TestReactorMixin, unittest.TestCase ): DEFAULT_CONFIG = { "port": '9999', "user": 'alice', "passwd": 'sekrit', "name": changesource.ChangeSourceMixin.DEFAULT_NAME, } EXP_DEFAULT_REGISTRATION = ('9999', 'alice', 'sekrit') @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setUpPBChangeSource() yield self.setUpChangeSource() self.master.pbmanager = self.pbmanager @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() def test_registration_no_workerport(self): return self._test_registration(None, exp_ConfigErrors=True, user='alice', passwd='sekrit') def test_registration_global_workerport(self): return self._test_registration(self.EXP_DEFAULT_REGISTRATION, **self.DEFAULT_CONFIG) def test_registration_custom_port(self): return self._test_registration( ('8888', 'alice', 'sekrit'), user='alice', passwd='sekrit', port='8888' ) def test_registration_no_userpass(self): return self._test_registration(('9939', 'change', 'changepw'), workerPort='9939') def test_registration_no_userpass_no_global(self): return self._test_registration(None, exp_ConfigErrors=True) def test_no_registration_if_master_already_claimed(self): # claim the CS on another master... self.setChangeSourceToMaster(self.OTHER_MASTER_ID) # and then use the same args as one of the above success cases, # but expect that it will NOT register return self._test_registration(None, **self.DEFAULT_CONFIG) @defer.inlineCallbacks def test_registration_later_if_master_can_do_it(self): # get the changesource running but not active due to the other master self.setChangeSourceToMaster(self.OTHER_MASTER_ID) yield self.attachChangeSource(pb.PBChangeSource(**self.DEFAULT_CONFIG)) self.startChangeSource() self.assertNotRegistered() # other master goes away self.setChangeSourceToMaster(None) # not quite enough time to cause it to activate self.reactor.advance(self.changesource.POLL_INTERVAL_SEC * 4 / 5) self.assertNotRegistered() # there we go! self.reactor.advance(self.changesource.POLL_INTERVAL_SEC * 2 / 5) self.assertRegistered(*self.EXP_DEFAULT_REGISTRATION) @defer.inlineCallbacks def _test_registration( self, exp_registration, exp_ConfigErrors=False, workerPort=None, **constr_kwargs ): cfg = mock.Mock() cfg.protocols = {'pb': {'port': workerPort}} self.attachChangeSource(pb.PBChangeSource(**constr_kwargs)) self.startChangeSource() if exp_ConfigErrors: # if it's not registered, it should raise a ConfigError. try: yield self.changesource.reconfigServiceWithBuildbotConfig(cfg) except config.ConfigErrors: pass else: self.fail("Expected ConfigErrors") else: yield self.changesource.reconfigServiceWithBuildbotConfig(cfg) if exp_registration: self.assertRegistered(*exp_registration) yield self.stopChangeSource() if exp_registration: self.assertUnregistered(*exp_registration) self.assertEqual(self.changesource.registration, None) @defer.inlineCallbacks def test_perspective(self): yield self.attachChangeSource(pb.PBChangeSource('alice', 'sekrit', port='8888')) persp = self.changesource.getPerspective(mock.Mock(), 'alice') self.assertIsInstance(persp, pb.ChangePerspective) def test_describe(self): cs = pb.PBChangeSource() self.assertSubstring("PBChangeSource", cs.describe()) def test_name(self): cs = pb.PBChangeSource(port=1234) self.assertEqual("PBChangeSource:1234", cs.name) cs = pb.PBChangeSource(port=1234, prefix="pre") self.assertEqual("PBChangeSource:pre:1234", cs.name) # explicit name: cs = pb.PBChangeSource(name="MyName") self.assertEqual("MyName", cs.name) def test_describe_prefix(self): cs = pb.PBChangeSource(prefix="xyz") self.assertSubstring("PBChangeSource", cs.describe()) self.assertSubstring("xyz", cs.describe()) def test_describe_int(self): cs = pb.PBChangeSource(port=9989) self.assertSubstring("PBChangeSource", cs.describe()) @defer.inlineCallbacks def test_reconfigService_no_change(self): config = mock.Mock() yield self.attachChangeSource(pb.PBChangeSource(port='9876')) self.startChangeSource() yield self.changesource.reconfigServiceWithBuildbotConfig(config) self.assertRegistered('9876', 'change', 'changepw') yield self.stopChangeSource() self.assertUnregistered('9876', 'change', 'changepw') @defer.inlineCallbacks def test_reconfigService_default_changed(self): config = mock.Mock() config.protocols = {'pb': {'port': '9876'}} yield self.attachChangeSource(pb.PBChangeSource()) self.startChangeSource() yield self.changesource.reconfigServiceWithBuildbotConfig(config) self.assertRegistered('9876', 'change', 'changepw') config.protocols = {'pb': {'port': '1234'}} yield self.changesource.reconfigServiceWithBuildbotConfig(config) self.assertUnregistered('9876', 'change', 'changepw') self.assertRegistered('1234', 'change', 'changepw') yield self.stopChangeSource() self.assertUnregistered('1234', 'change', 'changepw') @defer.inlineCallbacks def test_reconfigService_default_changed_but_inactive(self): """reconfig one that's not active on this master""" config = mock.Mock() config.protocols = {'pb': {'port': '9876'}} yield self.attachChangeSource(pb.PBChangeSource()) self.setChangeSourceToMaster(self.OTHER_MASTER_ID) self.startChangeSource() yield self.changesource.reconfigServiceWithBuildbotConfig(config) self.assertNotRegistered() config.protocols = {'pb': {'port': '1234'}} yield self.changesource.reconfigServiceWithBuildbotConfig(config) self.assertNotRegistered() yield self.stopChangeSource() self.assertNotRegistered() self.assertNotUnregistered() class TestChangePerspective(TestReactorMixin, unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.master = yield fakemaster.make_master(self, wantDb=True, wantData=True) @defer.inlineCallbacks def tearDown(self): yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_addChange_noprefix(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"who": 'bar', "files": ['a']}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'bar', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': ['a'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_codebase(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"who": 'bar', "files": [], "codebase": 'cb'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'bar', 'committer': None, 'branch': None, 'category': None, 'codebase': 'cb', 'comments': None, 'files': [], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_prefix(self): cp = pb.ChangePerspective(self.master, 'xx/') yield cp.perspective_addChange({"who": 'bar', "files": ['xx/a', 'yy/b']}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'bar', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': ['a'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_sanitize_None(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"project": None, "revlink": None, "repository": None}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': None, 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': [], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_when_None(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"when": None}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': None, 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': [], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_files_tuple(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"files": ('a', 'b')}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': None, 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': ['a', 'b'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_unicode(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({ "author": "\N{SNOWMAN}", "comments": "\N{SNOWMAN}", "files": ['\N{VERY MUCH GREATER-THAN}'], }) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': '\u2603', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': '\u2603', 'files': ['\u22d9'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_unicode_as_bytestring(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({ "author": "\N{SNOWMAN}".encode(), "comments": "\N{SNOWMAN}".encode(), "files": ['\N{VERY MUCH GREATER-THAN}'.encode()], }) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': '\u2603', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': '\u2603', 'files': ['\u22d9'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_non_utf8_bytestring(self): cp = pb.ChangePerspective(self.master, None) bogus_utf8 = b'\xff\xff\xff\xff' replacement = bogus_utf8.decode('utf8', 'replace') yield cp.perspective_addChange({"author": bogus_utf8, "files": ['a']}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': replacement, 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': ['a'], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_addChange_old_param_names(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"who": 'me', "when": 1234, "files": []}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'me', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': [], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': None, 'when_timestamp': 1234, } ], ) @defer.inlineCallbacks def test_createUserObject_git_src(self): cp = pb.ChangePerspective(self.master, None) yield cp.perspective_addChange({"who": 'c <h@c>', "src": 'git'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'c <h@c>', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': [], 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': 'git', 'when_timestamp': None, } ], )
18,048
Python
.py
455
26.514286
98
0.52512
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,394
test_gitpoller.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_gitpoller.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 datetime import os import re import shutil import stat import tempfile from pathlib import Path from subprocess import CalledProcessError from unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.changes import gitpoller from buildbot.test.fake.private_tempdir import MockPrivateTemporaryDirectory from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import changesource from buildbot.test.util import config from buildbot.test.util import logging from buildbot.test.util.git_repository import TestGitRepository from buildbot.test.util.state import StateTestMixin from buildbot.util import bytes2unicode from buildbot.util import unicode2bytes from buildbot.util.git_credential import GitCredentialOptions from buildbot.util.twisted import async_to_deferred # Test that environment variables get propagated to subprocesses (See #2116) os.environ['TEST_THAT_ENVIRONMENT_GETS_PASSED_TO_SUBPROCESSES'] = 'TRUE' class TestGitPollerBase( MasterRunProcessMixin, changesource.ChangeSourceMixin, logging.LoggingMixin, TestReactorMixin, StateTestMixin, unittest.TestCase, ): REPOURL = '[email protected]:~foo/baz.git' REPOURL_QUOTED = 'ssh/example.com/%7Efoo/baz' POLLER_WORKDIR = os.path.join('basedir', 'gitpoller-work') def createPoller(self): # this is overridden in TestGitPollerWithSshPrivateKey return gitpoller.GitPoller(self.REPOURL, branches=['master']) @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() yield self.setUpChangeSource() yield self.master.startService() self.poller = yield self.attachChangeSource(self.createPoller()) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @async_to_deferred async def set_last_rev(self, state: dict[str, str]) -> None: await self.poller.setState('lastRev', state) self.poller.lastRev = state @async_to_deferred async def assert_last_rev(self, state: dict[str, str]) -> None: last_rev = await self.poller.getState('lastRev', None) self.assertEqual(last_rev, state) self.assertEqual(self.poller.lastRev, state) class TestGitPoller(TestGitPollerBase): dummyRevStr = '12345abcde' @defer.inlineCallbacks def _perform_git_output_test( self, methodToTest, args, desiredGoodOutput, desiredGoodResult, emptyRaisesException=True ): self.expect_commands( ExpectMasterShell(['git', *args]).workdir(self.POLLER_WORKDIR), ) # we should get an Exception with empty output from git try: yield methodToTest(self.dummyRevStr) if emptyRaisesException: self.fail("run_process should have failed on empty output") except Exception as error: if not emptyRaisesException: import traceback traceback.print_exc() self.fail("run_process should NOT have failed on empty output: " + repr(error)) self.assert_all_commands_ran() # and the method shouldn't suppress any exceptions self.expect_commands( ExpectMasterShell(['git', *args]).workdir(self.POLLER_WORKDIR).exit(1), ) try: yield methodToTest(self.dummyRevStr) self.fail("run_process should have failed on stderr output") except Exception: pass self.assert_all_commands_ran() # finally we should get what's expected from good output self.expect_commands( ExpectMasterShell(['git', *args]).workdir(self.POLLER_WORKDIR).stdout(desiredGoodOutput) ) r = yield methodToTest(self.dummyRevStr) self.assertEqual(r, desiredGoodResult) # check types if isinstance(r, str): self.assertIsInstance(r, str) elif isinstance(r, list): for e in r: self.assertIsInstance(e, str) self.assert_all_commands_ran() def test_get_commit_author(self): authorStr = 'Sammy Jankis <[email protected]>' authorBytes = unicode2bytes(authorStr) return self._perform_git_output_test( self.poller._get_commit_author, ['log', '--no-walk', '--format=%aN <%aE>', self.dummyRevStr, '--'], authorBytes, authorStr, ) def test_get_commit_committer(self): committerStr = 'Sammy Jankis <[email protected]>' committerBytes = unicode2bytes(committerStr) return self._perform_git_output_test( self.poller._get_commit_committer, ['log', '--no-walk', '--format=%cN <%cE>', self.dummyRevStr, '--'], committerBytes, committerStr, ) def _test_get_commit_comments(self, commentStr): commentBytes = unicode2bytes(commentStr) return self._perform_git_output_test( self.poller._get_commit_comments, ['log', '--no-walk', '--format=%s%n%b', self.dummyRevStr, '--'], commentBytes, commentStr, emptyRaisesException=False, ) def test_get_commit_comments(self): comments = ['this is a commit message\n\nthat is multiline', 'single line message', ''] return defer.DeferredList([ self._test_get_commit_comments(commentStr) for commentStr in comments ]) def test_get_commit_files(self): filesBytes = b'\n\nfile1\nfile2\n"\146ile_octal"\nfile space' filesRes = ['file1', 'file2', 'file_octal', 'file space'] return self._perform_git_output_test( self.poller._get_commit_files, [ 'log', '--name-only', '--no-walk', '--format=%n', '-m', '--first-parent', self.dummyRevStr, '--', ], filesBytes, filesRes, emptyRaisesException=False, ) def test_get_commit_files_with_space_in_changed_files(self): filesBytes = b'normal_directory/file1\ndirectory with space/file2' filesStr = bytes2unicode(filesBytes) return self._perform_git_output_test( self.poller._get_commit_files, [ 'log', '--name-only', '--no-walk', '--format=%n', '-m', '--first-parent', self.dummyRevStr, '--', ], filesBytes, [l for l in filesStr.splitlines() if l.strip()], emptyRaisesException=False, ) def test_get_commit_timestamp(self): stampBytes = b'1273258009' stampStr = bytes2unicode(stampBytes) return self._perform_git_output_test( self.poller._get_commit_timestamp, ['log', '--no-walk', '--format=%ct', self.dummyRevStr, '--'], stampBytes, float(stampStr), ) def test_describe(self): self.assertSubstring("GitPoller", self.poller.describe()) def test_name(self): self.assertEqual(bytes2unicode(self.REPOURL), bytes2unicode(self.poller.name)) # and one with explicit name... other = gitpoller.GitPoller(self.REPOURL, name="MyName") self.assertEqual("MyName", other.name) @defer.inlineCallbacks def test_checkGitFeatures_git_not_installed(self): self.setUpLogging() self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'Command not found'), ) yield self.assertFailure(self.poller._checkGitFeatures(), EnvironmentError) self.assert_all_commands_ran() @defer.inlineCallbacks def test_checkGitFeatures_git_bad_version(self): self.setUpLogging() self.expect_commands(ExpectMasterShell(['git', '--version']).stdout(b'git ')) with self.assertRaises(EnvironmentError): yield self.poller._checkGitFeatures() self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_initial(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) @defer.inlineCallbacks def test_poll_initial_poller_not_running(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ) self.poller.doPoll.running = False yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev(None) def test_poll_failInit(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]).exit(1), ) self.poller.doPoll.running = True d = self.assertFailure(self.poller.poll(), EnvironmentError) d.addCallback(lambda _: self.assert_all_commands_ran()) return d @defer.inlineCallbacks def test_poll_branch_do_not_exist(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master']), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_failRevParse(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .exit(1), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() self.assertEqual(len(self.flushLoggedErrors()), 1) yield self.assert_last_rev({}) @defer.inlineCallbacks def test_poll_failLog(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .exit(1), ) # do the poll yield self.set_last_rev({'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930'}) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() self.assertEqual(len(self.flushLoggedErrors()), 1) yield self.assert_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) @defer.inlineCallbacks def test_poll_GitError(self): # Raised when git exits with status code 128. See issue 2468 self.expect_commands( ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]).exit(128), ) with self.assertRaises(gitpoller.GitError): yield self.poller._dovccmd('init', ['--bare', self.POLLER_WORKDIR]) self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_GitError_log(self): self.setUpLogging() self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]).exit(128), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() self.assertLogged("command.*on repourl.*failed.*exit code 128.*") @defer.inlineCallbacks def test_poll_nothingNew(self): # Test that environment variables get propagated to subprocesses # (See #2116) self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) self.add_run_process_expect_env({'ENVVAR': 'TRUE'}) self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'no interesting output'), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) yield self.set_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) @defer.inlineCallbacks def test_poll_multipleBranches_initial(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', 'refs/heads/release', 'refs/heads/not_on_remote', ]).stdout( b'4423cdbcbb89c14e50dd5f4152415afd686c5241\t' b'refs/heads/master\n' b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2\t' b'refs/heads/release\n' ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), ) # do the poll self.poller.branches = ['master', 'release', 'not_on_remote'] self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'release': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', }) @defer.inlineCallbacks def test_poll_multipleBranches(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', 'refs/heads/release', ]).stdout( b'4423cdbcbb89c14e50dd5f4152415afd686c5241\t' b'refs/heads/master\n' b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2\t' b'refs/heads/release\n' ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'\n'.join([b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'])), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = ['master', 'release'] yield self.set_last_rev({ 'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', 'release': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'release': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', }) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'by:4423cdbc', 'committer': 'by:4423cdbc', 'branch': 'master', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/442'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, }, { 'author': 'by:64a5dc2a', 'committer': 'by:64a5dc2a', 'branch': 'master', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/64a'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, }, { 'author': 'by:9118f4ab', 'committer': 'by:9118f4ab', 'branch': 'release', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/911'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, }, ], ) @defer.inlineCallbacks def test_poll_multipleBranches_buildPushesWithNoCommits_default(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/release', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/release\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) # do the poll self.poller.branches = ['release'] yield self.set_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'release': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_poll_multipleBranches_buildPushesWithNoCommits_true(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/release', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/release\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = ['release'] yield self.set_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.poller.buildPushesWithNoCommits = True self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'release': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'by:4423cdbc', 'committer': 'by:4423cdbc', 'branch': 'release', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/442'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, } ], ) @defer.inlineCallbacks def test_poll_multipleBranches_buildPushesWithNoCommits_true_fast_forward(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/release', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/release\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^0ba9d553b7217ab4bbad89ad56dc0332c7d57a8c', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = ['release'] yield self.set_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'release': '0ba9d553b7217ab4bbad89ad56dc0332c7d57a8c', }) self.poller.buildPushesWithNoCommits = True self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'release': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'by:4423cdbc', 'committer': 'by:4423cdbc', 'branch': 'release', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/442'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, } ], ) @defer.inlineCallbacks def test_poll_multipleBranches_buildPushesWithNoCommits_true_not_tip(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/release', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/release\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^0ba9d553b7217ab4bbad89ad56dc0332c7d57a8c', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = ['release'] yield self.set_last_rev({'master': '0ba9d553b7217ab4bbad89ad56dc0332c7d57a8c'}) self.poller.buildPushesWithNoCommits = True self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'release': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'by:4423cdbc', 'committer': 'by:4423cdbc', 'branch': 'release', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/442'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, } ], ) @defer.inlineCallbacks def test_poll_allBranches_single(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/*']).stdout( b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n' ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = True yield self.set_last_rev({ 'refs/heads/master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'refs/heads/master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', }) added = self.master.data.updates.changesAdded self.assertEqual(len(added), 2) self.assertEqual(added[0]['author'], 'by:4423cdbc') self.assertEqual(added[0]['committer'], 'by:4423cdbc') self.assertEqual(added[0]['when_timestamp'], 1273258009) self.assertEqual(added[0]['comments'], 'hello!') self.assertEqual(added[0]['branch'], 'master') self.assertEqual(added[0]['files'], ['/etc/442']) self.assertEqual(added[0]['src'], 'git') self.assertEqual(added[1]['author'], 'by:64a5dc2a') self.assertEqual(added[1]['committer'], 'by:64a5dc2a') self.assertEqual(added[1]['when_timestamp'], 1273258009) self.assertEqual(added[1]['comments'], 'hello!') self.assertEqual(added[1]['files'], ['/etc/64a']) self.assertEqual(added[1]['src'], 'git') @defer.inlineCallbacks def test_poll_noChanges(self): # Test that environment variables get propagated to subprocesses # (See #2116) self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) self.add_run_process_expect_env({'ENVVAR': 'TRUE'}) self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'no interesting output'), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b''), ) yield self.set_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) @defer.inlineCallbacks def test_poll_allBranches_multiple(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/*']).stdout( b'\n'.join([ b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master', b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2\trefs/heads/release', ]) ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '+refs/heads/release:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/release', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'\n'.join([b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'])), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = True yield self.set_last_rev({ 'refs/heads/master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', 'refs/heads/release': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'refs/heads/master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'refs/heads/release': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', }) added = self.master.data.updates.changesAdded self.assertEqual(len(added), 3) self.assertEqual(added[0]['author'], 'by:4423cdbc') self.assertEqual(added[0]['committer'], 'by:4423cdbc') self.assertEqual(added[0]['when_timestamp'], 1273258009) self.assertEqual(added[0]['comments'], 'hello!') self.assertEqual(added[0]['branch'], 'master') self.assertEqual(added[0]['files'], ['/etc/442']) self.assertEqual(added[0]['src'], 'git') self.assertEqual(added[1]['author'], 'by:64a5dc2a') self.assertEqual(added[1]['committer'], 'by:64a5dc2a') self.assertEqual(added[1]['when_timestamp'], 1273258009) self.assertEqual(added[1]['comments'], 'hello!') self.assertEqual(added[1]['files'], ['/etc/64a']) self.assertEqual(added[1]['src'], 'git') self.assertEqual(added[2]['author'], 'by:9118f4ab') self.assertEqual(added[2]['committer'], 'by:9118f4ab') self.assertEqual(added[2]['when_timestamp'], 1273258009) self.assertEqual(added[2]['comments'], 'hello!') self.assertEqual(added[2]['files'], ['/etc/911']) self.assertEqual(added[2]['src'], 'git') @defer.inlineCallbacks def test_poll_callableFilteredBranches(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL]).stdout( b'\n'.join([ b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master', b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2\trefs/heads/release', ]) ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll class TestCallable: def __call__(self, branch): return branch == "refs/heads/master" self.poller.branches = TestCallable() yield self.set_last_rev({ 'refs/heads/master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', 'refs/heads/release': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() # The release branch id should remain unchanged, # because it was ignored. yield self.assert_last_rev({ 'refs/heads/master': '4423cdbcbb89c14e50dd5f4152415afd686c5241' }) added = self.master.data.updates.changesAdded self.assertEqual(len(added), 2) self.assertEqual(added[0]['author'], 'by:4423cdbc') self.assertEqual(added[0]['committer'], 'by:4423cdbc') self.assertEqual(added[0]['when_timestamp'], 1273258009) self.assertEqual(added[0]['comments'], 'hello!') self.assertEqual(added[0]['branch'], 'master') self.assertEqual(added[0]['files'], ['/etc/442']) self.assertEqual(added[0]['src'], 'git') self.assertEqual(added[1]['author'], 'by:64a5dc2a') self.assertEqual(added[1]['committer'], 'by:64a5dc2a') self.assertEqual(added[1]['when_timestamp'], 1273258009) self.assertEqual(added[1]['comments'], 'hello!') self.assertEqual(added[1]['files'], ['/etc/64a']) self.assertEqual(added[1]['src'], 'git') @defer.inlineCallbacks def test_poll_branchFilter(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL]).stdout( b'\n'.join([ b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/pull/410/merge', b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2\trefs/pull/410/head', ]) ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/pull/410/head:refs/buildbot/' + self.REPOURL_QUOTED + '/pull/410/head', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/pull/410/head', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '9118f4ab71963d23d02d4bdc54876ac8bf05acf2', '^bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'\n'.join([b'9118f4ab71963d23d02d4bdc54876ac8bf05acf2'])), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) def pullFilter(branch): """ Note that this isn't useful in practice, because it will only pick up *changes* to pull requests, not the original request. """ return re.match('^refs/pull/[0-9]*/head$', branch) # do the poll self.poller.branches = pullFilter yield self.set_last_rev({ 'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', 'refs/pull/410/head': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'refs/pull/410/head': '9118f4ab71963d23d02d4bdc54876ac8bf05acf2' }) added = self.master.data.updates.changesAdded self.assertEqual(len(added), 1) self.assertEqual(added[0]['author'], 'by:9118f4ab') self.assertEqual(added[0]['committer'], 'by:9118f4ab') self.assertEqual(added[0]['when_timestamp'], 1273258009) self.assertEqual(added[0]['comments'], 'hello!') self.assertEqual(added[0]['files'], ['/etc/911']) self.assertEqual(added[0]['src'], 'git') @defer.inlineCallbacks def test_poll_old(self): # Test that environment variables get propagated to subprocesses # (See #2116) self.patch(os, 'environ', {'ENVVAR': 'TRUE'}) self.add_run_process_expect_env({'ENVVAR': 'TRUE'}) self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'no interesting output'), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll yield self.set_last_rev({'master': 'fa3ae8ed68e664d4db24798611b352e3c6509930'}) self.poller.doPoll.running = True yield self.poller.poll() # check the results yield self.assert_last_rev({'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241'}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'by:4423cdbc', 'committer': 'by:4423cdbc', 'branch': 'master', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/442'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '4423cdbcbb89c14e50dd5f4152415afd686c5241', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, }, { 'author': 'by:64a5dc2a', 'committer': 'by:64a5dc2a', 'branch': 'master', 'category': None, 'codebase': None, 'comments': 'hello!', 'files': ['/etc/64a'], 'project': '', 'properties': {}, 'repository': '[email protected]:~foo/baz.git', 'revision': '64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', 'revlink': '', 'src': 'git', 'when_timestamp': 1273258009, }, ], ) self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_callableCategory(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell(['git', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/*']).stdout( b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n' ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '4423cdbcbb89c14e50dd5f4152415afd686c5241', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]) .workdir(self.POLLER_WORKDIR) .stdout( b'\n'.join([ b'64a5dc2a4bd4f558b5dd193d47c83c7d7abc9a1a', b'4423cdbcbb89c14e50dd5f4152415afd686c5241', ]) ), ) # and patch out the _get_commit_foo methods which were already tested # above def timestamp(rev): return defer.succeed(1273258009) self.patch(self.poller, '_get_commit_timestamp', timestamp) def author(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_author', author) def committer(rev): return defer.succeed('by:' + rev[:8]) self.patch(self.poller, '_get_commit_committer', committer) def files(rev): return defer.succeed(['/etc/' + rev[:3]]) self.patch(self.poller, '_get_commit_files', files) def comments(rev): return defer.succeed('hello!') self.patch(self.poller, '_get_commit_comments', comments) # do the poll self.poller.branches = True def callableCategory(chdict): return chdict['revision'][:6] self.poller.category = callableCategory yield self.set_last_rev({ 'refs/heads/master': 'fa3ae8ed68e664d4db24798611b352e3c6509930', }) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({ 'refs/heads/master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', }) added = self.master.data.updates.changesAdded self.assertEqual(len(added), 2) self.assertEqual(added[0]['author'], 'by:4423cdbc') self.assertEqual(added[0]['committer'], 'by:4423cdbc') self.assertEqual(added[0]['when_timestamp'], 1273258009) self.assertEqual(added[0]['comments'], 'hello!') self.assertEqual(added[0]['branch'], 'master') self.assertEqual(added[0]['files'], ['/etc/442']) self.assertEqual(added[0]['src'], 'git') self.assertEqual(added[0]['category'], '4423cd') self.assertEqual(added[1]['author'], 'by:64a5dc2a') self.assertEqual(added[1]['committer'], 'by:64a5dc2a') self.assertEqual(added[1]['when_timestamp'], 1273258009) self.assertEqual(added[1]['comments'], 'hello!') self.assertEqual(added[1]['files'], ['/etc/64a']) self.assertEqual(added[1]['src'], 'git') self.assertEqual(added[1]['category'], '64a5dc') @async_to_deferred async def test_startService(self): self.assertEqual(self.poller.workdir, self.POLLER_WORKDIR) await self.assert_last_rev(None) @defer.inlineCallbacks def test_startService_loadLastRev(self): yield self.poller.stopService() yield self.set_fake_state( self.poller, 'lastRev', {"master": "fa3ae8ed68e664d4db24798611b352e3c6509930"} ) yield self.poller.startService() self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, "refs/heads/master", ]).stdout(b'fa3ae8ed68e664d4db24798611b352e3c6509930\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, f'+refs/heads/master:refs/buildbot/{self.REPOURL_QUOTED}/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', f'refs/buildbot/{self.REPOURL_QUOTED}/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'fa3ae8ed68e664d4db24798611b352e3c6509930\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', 'fa3ae8ed68e664d4db24798611b352e3c6509930', '^fa3ae8ed68e664d4db24798611b352e3c6509930', '--', ]).workdir(self.POLLER_WORKDIR), ) yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({"master": "fa3ae8ed68e664d4db24798611b352e3c6509930"}) class TestGitPollerDefaultBranch(TestGitPollerBase): def createPoller(self): return gitpoller.GitPoller(self.REPOURL, branches=None) @async_to_deferred async def test_resolve_head_ref_with_symref(self): self.patch(self.poller, 'supports_lsremote_symref', True) self.expect_commands( ExpectMasterShell(['git', 'ls-remote', '--symref', self.REPOURL, 'HEAD']) .exit(0) .stdout( b'ref: refs/heads/default_branch HEAD\n' b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 HEAD\n' ), ) result = await self.poller._resolve_head_ref() self.assert_all_commands_ran() self.assertEqual(result, 'refs/heads/default_branch') @async_to_deferred async def test_resolve_head_ref_without_symref(self): self.patch(self.poller, 'supports_lsremote_symref', False) self.expect_commands( ExpectMasterShell(['git', 'ls-remote', self.REPOURL, 'HEAD', 'refs/heads/*']) .exit(0) .stdout( b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 HEAD\n' b'274ec17f8bfb56adc0035b12735785097df488fc refs/heads/3.10.x\n' b'972a389242fd15a59f2d2840d1be4c0fc7b97109 refs/heads/3.11.x\n' b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 refs/heads/master\n' ), ) result = await self.poller._resolve_head_ref() self.assert_all_commands_ran() self.assertEqual(result, 'refs/heads/master') @async_to_deferred async def test_resolve_head_ref_without_symref_multiple_head_candidates(self): self.patch(self.poller, 'supports_lsremote_symref', False) self.expect_commands( ExpectMasterShell(['git', 'ls-remote', self.REPOURL, 'HEAD', 'refs/heads/*']) .exit(0) .stdout( b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 HEAD\n' b'274ec17f8bfb56adc0035b12735785097df488fc refs/heads/3.10.x\n' b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 refs/heads/3.11.x\n' b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 refs/heads/master\n' ), ) result = await self.poller._resolve_head_ref() self.assert_all_commands_ran() self.assertEqual(result, None) @async_to_deferred async def test_poll_found_head(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--symref', self.REPOURL, 'HEAD', ]).stdout( b'ref: refs/heads/default_branch HEAD\n' b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09 HEAD\n' ), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, f'+refs/heads/default_branch:refs/buildbot/{self.REPOURL_QUOTED}/heads/default_branch', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', f'refs/buildbot/{self.REPOURL_QUOTED}/heads/default_branch', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '737b94eca1ddde3dd4a0040b25c8a25fe973fe09', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]).workdir(self.POLLER_WORKDIR), ) await self.set_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', }) self.poller.doPoll.running = True await self.poller.poll() self.assert_all_commands_ran() await self.assert_last_rev({ 'refs/heads/default_branch': '737b94eca1ddde3dd4a0040b25c8a25fe973fe09' }) self.assertEqual(len(self.master.data.updates.changesAdded), 0) @async_to_deferred async def test_poll_found_head_not_found(self): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--symref', self.REPOURL, 'HEAD', ]).stdout(b'malformed output'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, f'+HEAD:refs/buildbot/raw/{self.REPOURL_QUOTED}/HEAD', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', f'refs/buildbot/raw/{self.REPOURL_QUOTED}/HEAD', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'737b94eca1ddde3dd4a0040b25c8a25fe973fe09\n'), ExpectMasterShell([ 'git', 'log', '--ignore-missing', '--first-parent', '--format=%H', '737b94eca1ddde3dd4a0040b25c8a25fe973fe09', '^4423cdbcbb89c14e50dd5f4152415afd686c5241', '--', ]).workdir(self.POLLER_WORKDIR), ) await self.set_last_rev({ 'master': '4423cdbcbb89c14e50dd5f4152415afd686c5241', }) self.poller.doPoll.running = True await self.poller.poll() self.assert_all_commands_ran() await self.assert_last_rev({'HEAD': '737b94eca1ddde3dd4a0040b25c8a25fe973fe09'}) self.assertEqual(len(self.master.data.updates.changesAdded), 0) class TestGitPollerWithSshPrivateKey(TestGitPollerBase): def createPoller(self): return gitpoller.GitPoller(self.REPOURL, branches=['master'], sshPrivateKey='ssh-key') @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_check_git_features_ssh_1_7(self, write_local_file_mock, temp_dir_mock): self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 1.7.5\n'), ) yield self.assertFailure(self.poller._checkGitFeatures(), EnvironmentError) self.assert_all_commands_ran() self.assertEqual(len(temp_dir_mock.dirs), 0) write_local_file_mock.assert_not_called() @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_poll_initial_2_10(self, write_local_file_mock, temp_dir_mock): key_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-key') self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}"', 'ls-remote', '--refs', self.REPOURL, "refs/heads/master", ]).stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\trefs/heads/master\n'), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}"', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) write_local_file_mock.assert_called_with(key_path, 'ssh-key\n', mode=0o400) @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_poll_initial_2_3(self, write_local_file_mock, temp_dir_mock): key_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-key') self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.3.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', 'ls-remote', '--refs', self.REPOURL, "refs/heads/master", ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]) .workdir(self.POLLER_WORKDIR) .env({'GIT_SSH_COMMAND': f'ssh -o "BatchMode=yes" -i "{key_path}"'}), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) write_local_file_mock.assert_called_with(key_path, 'ssh-key\n', mode=0o400) @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_poll_failFetch_git_2_10(self, write_local_file_mock, temp_dir_mock): key_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-key') # make sure we cleanup the private key when fetch fails self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}"', 'ls-remote', '--refs', self.REPOURL, "refs/heads/master", ]).stdout(b'4423cdbcbb89c14e50dd5f4152415afd686c5241\trefs/heads/master\n'), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}"', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]) .workdir(self.POLLER_WORKDIR) .exit(1), ) self.poller.doPoll.running = True yield self.assertFailure(self.poller.poll(), EnvironmentError) self.assert_all_commands_ran() temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) write_local_file_mock.assert_called_with(key_path, 'ssh-key\n', mode=0o400) class TestGitPollerWithSshHostKey(TestGitPollerBase): def createPoller(self): return gitpoller.GitPoller( self.REPOURL, branches=['master'], sshPrivateKey='ssh-key', sshHostKey='ssh-host-key' ) @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_poll_initial_2_10(self, write_local_file_mock, temp_dir_mock): key_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-key') known_hosts_path = os.path.join( 'basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-known-hosts' ) self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}" ' f'-o "UserKnownHostsFile={known_hosts_path}"', 'ls-remote', '--refs', self.REPOURL, "refs/heads/master", ]).stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\trefs/heads/master\n'), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}" ' f'-o "UserKnownHostsFile={known_hosts_path}"', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) expected_file_writes = [ mock.call(key_path, 'ssh-key\n', mode=0o400), mock.call(known_hosts_path, '* ssh-host-key', mode=0o400), ] self.assertEqual(expected_file_writes, write_local_file_mock.call_args_list) class TestGitPollerWithSshKnownHosts(TestGitPollerBase): def createPoller(self): return gitpoller.GitPoller( self.REPOURL, branches=['master'], sshPrivateKey='ssh-key\n', sshKnownHosts='ssh-known-hosts', ) @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @mock.patch('buildbot.util.git.writeLocalFile') @defer.inlineCallbacks def test_poll_initial_2_10(self, write_local_file_mock, temp_dir_mock): key_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-key') known_hosts_path = os.path.join( 'basedir', 'gitpoller-work', '.buildbot-ssh@@@', 'ssh-known-hosts' ) self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}" ' f'-o "UserKnownHostsFile={known_hosts_path}"', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\trefs/heads/master\n'), ExpectMasterShell([ 'git', '-c', f'core.sshCommand=ssh -o "BatchMode=yes" -i "{key_path}" ' f'-o "UserKnownHostsFile={known_hosts_path}"', 'fetch', '--progress', self.REPOURL, '+refs/heads/master:refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', 'refs/buildbot/' + self.REPOURL_QUOTED + '/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) expected_file_writes = [ mock.call(key_path, 'ssh-key\n', mode=0o400), mock.call(known_hosts_path, 'ssh-known-hosts', mode=0o400), ] self.assertEqual(expected_file_writes, write_local_file_mock.call_args_list) class TestGitPollerWithAuthCredentials(TestGitPollerBase): def createPoller(self): return gitpoller.GitPoller( self.REPOURL, branches=['master'], auth_credentials=('username', 'token'), git_credentials=GitCredentialOptions( credentials=[], ), ) @mock.patch( 'buildbot.util.private_tempdir.PrivateTemporaryDirectory', new_callable=MockPrivateTemporaryDirectory, ) @defer.inlineCallbacks def test_poll_initial_2_10(self, temp_dir_mock): temp_dir_path = os.path.join('basedir', 'gitpoller-work', '.buildbot-ssh@@@') credential_store_filepath = os.path.join(temp_dir_path, '.git-credentials') self.expect_commands( ExpectMasterShell(['git', '--version']).stdout(b'git version 2.10.0\n'), ExpectMasterShell(['git', 'init', '--bare', self.POLLER_WORKDIR]), ExpectMasterShell([ 'git', '-c', 'credential.helper=', '-c', f'credential.helper=store "--file={credential_store_filepath}"', 'credential', 'approve', ]).workdir(temp_dir_path), ExpectMasterShell([ 'git', '-c', 'credential.helper=', '-c', f'credential.helper=store "--file={credential_store_filepath}"', 'ls-remote', '--refs', self.REPOURL, 'refs/heads/master', ]).stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\trefs/heads/master\n'), ExpectMasterShell([ 'git', '-c', 'credential.helper=', '-c', f'credential.helper=store "--file={credential_store_filepath}"', 'fetch', '--progress', self.REPOURL, f'+refs/heads/master:refs/buildbot/{self.REPOURL_QUOTED}/heads/master', '--', ]).workdir(self.POLLER_WORKDIR), ExpectMasterShell([ 'git', 'rev-parse', f'refs/buildbot/{self.REPOURL_QUOTED}/heads/master', ]) .workdir(self.POLLER_WORKDIR) .stdout(b'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5\n'), ) self.poller.doPoll.running = True yield self.poller.poll() self.assert_all_commands_ran() yield self.assert_last_rev({'master': 'bf0b01df6d00ae8d1ffa0b2e2acbe642a6cd35d5'}) self.assertEqual(temp_dir_mock.dirs, [(temp_dir_path, 0o700)]) class TestGitPollerConstructor( unittest.TestCase, TestReactorMixin, changesource.ChangeSourceMixin, config.ConfigErrorsMixin ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpChangeSource() yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_deprecatedFetchRefspec(self): with self.assertRaisesConfigError("fetch_refspec is no longer supported"): yield self.attachChangeSource( gitpoller.GitPoller("/tmp/git.git", fetch_refspec='not-supported') ) @defer.inlineCallbacks def test_branches_default(self): poller = yield self.attachChangeSource(gitpoller.GitPoller("/tmp/git.git")) self.assertEqual(poller.branches, None) @defer.inlineCallbacks def test_branches_oldBranch(self): poller = yield self.attachChangeSource(gitpoller.GitPoller("/tmp/git.git", branch='magic')) self.assertEqual(poller.branches, ["magic"]) @defer.inlineCallbacks def test_branches(self): poller = yield self.attachChangeSource( gitpoller.GitPoller("/tmp/git.git", branches=['magic', 'marker']) ) self.assertEqual(poller.branches, ["magic", "marker"]) @defer.inlineCallbacks def test_branches_True(self): poller = yield self.attachChangeSource(gitpoller.GitPoller("/tmp/git.git", branches=True)) self.assertEqual(poller.branches, True) @defer.inlineCallbacks def test_only_tags_True(self): poller = yield self.attachChangeSource(gitpoller.GitPoller("/tmp/git.git", only_tags=True)) self.assertIsNotNone(poller.branches) @defer.inlineCallbacks def test_branches_andBranch(self): with self.assertRaisesConfigError("can't specify both branch and branches"): yield self.attachChangeSource( gitpoller.GitPoller("/tmp/git.git", branch='bad', branches=['listy']) ) @defer.inlineCallbacks def test_branches_and_only_tags(self): with self.assertRaisesConfigError("can't specify only_tags and branch/branches"): yield self.attachChangeSource( gitpoller.GitPoller("/tmp/git.git", only_tags=True, branches=['listy']) ) @defer.inlineCallbacks def test_branch_and_only_tags(self): with self.assertRaisesConfigError("can't specify only_tags and branch/branches"): yield self.attachChangeSource( gitpoller.GitPoller("/tmp/git.git", only_tags=True, branch='bad') ) @defer.inlineCallbacks def test_gitbin_default(self): poller = yield self.attachChangeSource(gitpoller.GitPoller("/tmp/git.git")) self.assertEqual(poller.gitbin, "git") class TestGitPollerUtils(unittest.TestCase): def test_tracker_ref_protos(self): for url, expected_tracker in [ ( "https://example.org/owner/repo.git", "refs/buildbot/https/example.org/owner/repo/heads/branch_name", ), ("ssh://example.org:repo.git", "refs/buildbot/ssh/example.org/repo/heads/branch_name"), ("[email protected]:repo.git", "refs/buildbot/ssh/example.org/repo/heads/branch_name"), ]: self.assertEqual( gitpoller.GitPoller._tracker_ref(url, "refs/heads/branch_name"), expected_tracker, ) def test_tracker_ref_with_port(self): self.assertEqual( gitpoller.GitPoller._tracker_ref( "https://example.org:1234/owner/repo.git", "refs/heads/branch_name" ), "refs/buildbot/https/example.org%3A1234/owner/repo/heads/branch_name", ) def test_tracker_ref_tag(self): self.assertEqual( gitpoller.GitPoller._tracker_ref( "https://example.org:1234/owner/repo.git", "refs/tags/v1" ), "refs/buildbot/https/example.org%3A1234/owner/repo/tags/v1", ) def test_tracker_ref_with_credentials(self): self.assertEqual( gitpoller.GitPoller._tracker_ref( "https://user:[email protected]:1234/owner/repo.git", "refs/heads/branch_name" ), "refs/buildbot/https/example.org%3A1234/owner/repo/heads/branch_name", ) def test_tracker_ref_sub_branch(self): self.assertEqual( gitpoller.GitPoller._tracker_ref( "https://user:[email protected]:1234/owner/repo.git", "refs/heads/branch_name" ), "refs/buildbot/https/example.org%3A1234/owner/repo/heads/branch_name", ) def test_tracker_ref_not_ref_collision(self): self.assertNotEqual( gitpoller.GitPoller._tracker_ref("https://example.org/repo.git", "heads/branch_name"), gitpoller.GitPoller._tracker_ref( "https://example.org/repo.git", "refs/heads/branch_name" ), ) def test_tracker_ref_HEAD(self): self.assertNotEqual( gitpoller.GitPoller._tracker_ref("https://example.org/repo.git", "HEAD"), gitpoller.GitPoller._tracker_ref("https://example.org/repo.git", "refs/raw/HEAD"), ) class TestGitPollerBareRepository( changesource.ChangeSourceMixin, logging.LoggingMixin, unittest.TestCase, ): INITIAL_SHA = "4c3f214c2637998bb2d0c63363cabd93544fef31" FIX_1_SHA = "867489d185291a0b4ba4f3acceffc2c02b23a0d7" FEATURE_1_SHA = "43775fd1159be5a96ca5972b73f60cd5018f62db" MERGE_FEATURE_1_SHA = "dfbfad40b6543851583912091c7e7a225db38024" MAIN_HEAD_SHA = MERGE_FEATURE_1_SHA @defer.inlineCallbacks def setUp(self): 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 yield self.prepare_repository() yield self.setUpChangeSource(want_real_reactor=True) yield self.master.startService() self.poller_workdir = tempfile.mkdtemp( prefix="TestGitPollerBareRepository_", dir=os.getcwd(), ) self.repo_url = str(self.repo.repository_path / '.git') self.poller = yield self.attachChangeSource( gitpoller.GitPoller( self.repo_url, branches=['main'], workdir=self.poller_workdir, gitbin=self.repo.git_bin, ) ) @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() def _delete_repository(repo_path: Path): # on Win, git will mark objects as read-only git_objects_path = repo_path / "objects" for item in git_objects_path.rglob(''): if not item.is_file(): continue item.chmod(item.stat().st_mode | stat.S_IWUSR) shutil.rmtree(repo_path, ignore_errors=True) _delete_repository(Path(self.poller_workdir)) _delete_repository(self.repo.repository_path) @async_to_deferred async def prepare_repository(self): # create initial commit with README self.repo.advance_time(datetime.timedelta(minutes=1)) self.repo.create_file_text('README.md', 'initial\n') self.repo.exec_git(['add', 'README.md']) initial_commit_hash = self.repo.commit( message="Initial", files=['README.md'], ) self.assertEqual(initial_commit_hash, self.INITIAL_SHA) # Create fix/1 branch self.repo.exec_git(['checkout', '-b', 'fix/1']) self.repo.advance_time(datetime.timedelta(minutes=1)) self.repo.amend_file_text('README.md', '\nfix 1\n') self.repo.exec_git(['add', 'README.md']) fix_1_hash = self.repo.commit( message="Fix 1", files=['README.md'], ) self.assertEqual(fix_1_hash, self.FIX_1_SHA) # merge ff fix/1 into main self.repo.exec_git(['checkout', 'main']) self.repo.exec_git(['merge', '--ff', 'fix/1']) # create feature/1 branch self.repo.exec_git(['checkout', '-b', 'feature/1', initial_commit_hash]) self.repo.advance_time(datetime.timedelta(minutes=1)) self.repo.amend_file_text('README.md', '\nfeature 1\n') feature_1_hash = self.repo.commit( message="Feature 1", files=['README.md'], ) self.assertEqual(feature_1_hash, self.FEATURE_1_SHA) # merge no-ff feature/1 into main, this will conflict self.repo.advance_time(datetime.timedelta(minutes=1)) self.repo.exec_git(['checkout', 'main']) # use --strategy so the command don't error due to merge conflict try: self.repo.exec_git( ['merge', '--no-ff', '--no-commit', '--strategy=ours', 'feature/1'], ) except CalledProcessError as process_error: # merge conflict cause git to error with 128 code if process_error.returncode not in (0, 128): raise self.repo.advance_time(datetime.timedelta(minutes=1)) self.repo.amend_file_text('README.md', "initial\n\nfix 1\nfeature 1\n") self.repo.exec_git(['add', 'README.md']) merge_feature_1_hash = self.repo.commit( message="Merge branch 'feature/1'", ) self.assertEqual(merge_feature_1_hash, self.MERGE_FEATURE_1_SHA) self.assertEqual(merge_feature_1_hash, self.MAIN_HEAD_SHA) @async_to_deferred async def set_last_rev(self, state: dict[str, str]) -> None: await self.poller.setState('lastRev', state) self.poller.lastRev = state @async_to_deferred async def assert_last_rev(self, state: dict[str, str]) -> None: last_rev = await self.poller.getState('lastRev', None) self.assertEqual(last_rev, state) self.assertEqual(self.poller.lastRev, state) @async_to_deferred async def test_poll_initial(self): self.poller.doPoll.running = True await self.poller.poll() await self.assert_last_rev({'main': self.MAIN_HEAD_SHA}) self.assertEqual( self.master.data.updates.changesAdded, [], ) @async_to_deferred async def test_poll_from_last(self): self.maxDiff = None await self.set_last_rev({'main': self.INITIAL_SHA}) self.poller.doPoll.running = True await self.poller.poll() await self.assert_last_rev({'main': self.MAIN_HEAD_SHA}) self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'test user <[email protected]>', 'branch': 'main', 'category': None, 'codebase': None, 'comments': 'Fix 1', 'committer': 'test user <[email protected]>', 'files': ['README.md'], 'project': '', 'properties': {}, 'repository': self.repo_url, 'revision': self.FIX_1_SHA, 'revlink': '', 'src': 'git', 'when_timestamp': 1717855320, }, { 'author': 'test user <[email protected]>', 'branch': 'main', 'category': None, 'codebase': None, 'comments': "Merge branch 'feature/1'", 'committer': 'test user <[email protected]>', 'files': ['README.md'], 'project': '', 'properties': {}, 'repository': self.repo_url, 'revision': self.MERGE_FEATURE_1_SHA, 'revlink': '', 'src': 'git', 'when_timestamp': 1717855500, }, ], )
102,893
Python
.py
2,401
30.201166
103
0.556722
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,395
test_gerritchangesource.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_gerritchangesource.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 copy import datetime import json import types from parameterized import parameterized from twisted.internet import defer from twisted.trial import unittest from buildbot.changes import gerritchangesource from buildbot.test import fakedb from buildbot.test.fake import httpclientservice as fakehttpclientservice from buildbot.test.fake.change import Change from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import changesource from buildbot.test.util.state import StateTestMixin from buildbot.util import datetime2epoch class TestGerritHelpers(unittest.TestCase): def test_proper_json(self): self.assertEqual( "Justin Case <[email protected]>", gerritchangesource._gerrit_user_to_author({ "username": "justincase", "name": "Justin Case", "email": "[email protected]", }), ) def test_missing_username(self): self.assertEqual( "Justin Case <[email protected]>", gerritchangesource._gerrit_user_to_author({ "name": "Justin Case", "email": "[email protected]", }), ) def test_missing_name(self): self.assertEqual( "unknown <[email protected]>", gerritchangesource._gerrit_user_to_author({"email": "[email protected]"}), ) self.assertEqual( "gerrit <[email protected]>", gerritchangesource._gerrit_user_to_author( {"email": "[email protected]"}, "gerrit" ), ) self.assertEqual( "justincase <[email protected]>", gerritchangesource._gerrit_user_to_author( {"username": "justincase", "email": "[email protected]"}, "gerrit" ), ) def test_missing_email(self): self.assertEqual( "Justin Case", gerritchangesource._gerrit_user_to_author({ "username": "justincase", "name": "Justin Case", }), ) self.assertEqual( "Justin Case", gerritchangesource._gerrit_user_to_author({"name": "Justin Case"}) ) self.assertEqual( "justincase", gerritchangesource._gerrit_user_to_author({"username": "justincase"}) ) self.assertEqual("unknown", gerritchangesource._gerrit_user_to_author({})) self.assertEqual("gerrit", gerritchangesource._gerrit_user_to_author({}, "gerrit")) class TestGerritChangeSource( MasterRunProcessMixin, changesource.ChangeSourceMixin, StateTestMixin, TestReactorMixin, unittest.TestCase, ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() self._got_events = [] return self.setUpChangeSource() @defer.inlineCallbacks def tearDown(self): if self.master.running: yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def create_gerrit(self, host, user, *args, **kwargs): http_url = kwargs.get("http_url", None) if http_url: self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, http_url + "/a", auth=kwargs.pop("expected_auth", None) ) s = gerritchangesource.GerritChangeSource(host, user, *args, **kwargs) yield self.attachChangeSource(s) return s @defer.inlineCallbacks def create_gerrit_synchronized(self, host, user, *args, **kwargs): s = yield self.create_gerrit(host, user, *args, **kwargs) s._is_synchronized = True return s def assert_changes(self, expected_changes, ignore_keys): self.assertEqual(len(self.master.data.updates.changesAdded), len(expected_changes)) for i, expected_change in enumerate(expected_changes): change = self.master.data.updates.changesAdded[i] for key in ignore_keys: del change[key] self.assertEqual(change, expected_change) def override_event_received(self, s): s.eventReceived = self._got_events.append def assert_events_received(self, events): self.assertEqual(self._got_events, events) # tests @defer.inlineCallbacks def test_describe(self): s = yield self.create_gerrit('somehost', 'someuser') self.assertSubstring("GerritChangeSource", s.describe()) @defer.inlineCallbacks def test_name(self): s = yield self.create_gerrit('somehost', 'someuser') self.assertEqual("GerritChangeSource:someuser@somehost:29418", s.name) s = yield self.create_gerrit('somehost', 'someuser', name="MyName") self.assertEqual("MyName", s.name) patchset_created_event = { "uploader": { 'name': 'uploader uploader', 'email': '[email protected]', 'username': 'uploader', }, "patchSet": { "number": 1, "revision": "29b73c3eb1aeaa9e6c7da520a940d60810e883db", "parents": ["7e563631188dcadf32aad0d8647c818834921a1e"], "ref": "refs/changes/21/4321/1", "uploader": { 'name': 'uploader uploader', 'email': '[email protected]', 'username': 'uploader', }, "createdOn": 1627214047, "author": { 'name': 'author author', 'email': '[email protected]', 'username': 'author', }, "kind": "REWORK", "sizeInsertions": 1, "sizeDeletions": 0, }, "change": { "project": "test", "branch": "master", "id": "I21234123412341234123412341234", "number": 4321, "subject": "change subject", "owner": {'name': 'owner owner', 'email': '[email protected]', 'username': 'owner'}, "url": "http://example.com/c/test/+/4321", "commitMessage": "test1\n\nChange-Id: I21234123412341234123412341234\n", "createdOn": 1627214047, "status": "NEW", }, "project": "test", "refName": "refs/heads/master", "changeKey": {"id": "I21234123412341234123412341234"}, "type": "patchset-created", "eventCreatedOn": 1627214048, } # this variable is reused in test_steps_source_repo # to ensure correct integration between change source and repo step expected_change_patchset_created = { 'category': 'patchset-created', 'files': ['unknown'], 'repository': 'ssh://someuser@somehost:29418/test', 'author': 'owner owner <[email protected]>', 'committer': None, 'comments': 'change subject', 'project': 'test', 'branch': 'refs/changes/21/4321/1', 'revision': '29b73c3eb1aeaa9e6c7da520a940d60810e883db', 'codebase': None, 'revlink': 'http://example.com/c/test/+/4321', 'src': None, 'when_timestamp': None, } @defer.inlineCallbacks def test_line_received_patchset_created(self): s = yield self.create_gerrit_synchronized('somehost', 'someuser') yield s._line_received_stream(json.dumps(self.patchset_created_event)) self.assert_changes([self.expected_change_patchset_created], ignore_keys=['properties']) @defer.inlineCallbacks def test_line_received_patchset_created_props(self): s = yield self.create_gerrit_synchronized('somehost', 'someuser') yield s._line_received_stream(json.dumps(self.patchset_created_event)) change = copy.deepcopy(self.expected_change_patchset_created) change['properties'] = { 'event.change.branch': 'master', 'event.change.commitMessage': 'test1\n\nChange-Id: I21234123412341234123412341234\n', 'event.change.createdOn': 1627214047, 'event.change.id': 'I21234123412341234123412341234', 'event.change.number': 4321, 'event.change.owner.email': '[email protected]', 'event.change.owner.name': 'owner owner', 'event.change.owner.username': 'owner', 'event.change.project': 'test', 'event.change.status': 'NEW', 'event.change.subject': 'change subject', 'event.change.url': 'http://example.com/c/test/+/4321', 'event.changeKey.id': 'I21234123412341234123412341234', 'event.patchSet.author.email': '[email protected]', 'event.patchSet.author.name': 'author author', 'event.patchSet.author.username': 'author', 'event.patchSet.createdOn': 1627214047, 'event.patchSet.kind': 'REWORK', 'event.patchSet.number': 1, 'event.patchSet.parents': ['7e563631188dcadf32aad0d8647c818834921a1e'], 'event.patchSet.ref': 'refs/changes/21/4321/1', 'event.patchSet.revision': '29b73c3eb1aeaa9e6c7da520a940d60810e883db', 'event.patchSet.sizeDeletions': 0, 'event.patchSet.sizeInsertions': 1, 'event.patchSet.uploader.email': '[email protected]', 'event.patchSet.uploader.name': 'uploader uploader', 'event.patchSet.uploader.username': 'uploader', 'event.project': 'test', 'event.refName': 'refs/heads/master', 'event.source': 'GerritChangeSource', 'event.type': 'patchset-created', 'event.uploader.email': '[email protected]', 'event.uploader.name': 'uploader uploader', 'event.uploader.username': 'uploader', 'target_branch': 'master', } self.assert_changes([change], ignore_keys=[]) comment_added_event = { "type": "comment-added", "author": {'name': 'author author', 'email': '[email protected]', 'username': 'author'}, "approvals": [{"type": "Code-Review", "description": "Code-Review", "value": "0"}], "comment": "Patch Set 1:\n\ntest comment", "patchSet": { "number": 1, "revision": "29b73c3eb1aeaa9e6c7da520a940d60810e883db", "parents": ["7e563631188dcadf32aad0d8647c818834921a1e"], "ref": "refs/changes/21/4321/1", "uploader": { 'name': 'uploader uploader', 'email': '[email protected]', 'username': 'uploader', }, "createdOn": 1627214047, "author": { 'name': 'author author', 'email': '[email protected]', 'username': 'author', }, "kind": "REWORK", "sizeInsertions": 1, "sizeDeletions": 0, }, "change": { "project": "test", "branch": "master", "id": "I21234123412341234123412341234", "number": 4321, "subject": "change subject", "owner": {'name': 'owner owner', 'email': '[email protected]', 'username': 'owner'}, "url": "http://example.com/c/test/+/4321", "commitMessage": "test1\n\nChange-Id: I21234123412341234123412341234\n", "createdOn": 1627214047, "status": "NEW", }, "project": "test", "refName": "refs/heads/master", "changeKey": {"id": "I21234123412341234123412341234"}, "eventCreatedOn": 1627214102, } expected_change_comment_added = { 'category': 'comment-added', 'files': ['unknown'], 'repository': 'ssh://someuser@somehost:29418/test', 'author': 'owner owner <[email protected]>', 'committer': None, 'comments': 'change subject', 'project': 'test', 'branch': 'refs/changes/21/4321/1', 'revlink': 'http://example.com/c/test/+/4321', 'codebase': None, 'revision': '29b73c3eb1aeaa9e6c7da520a940d60810e883db', 'src': None, 'when_timestamp': None, } @defer.inlineCallbacks def test_line_received_comment_added(self): s = yield self.create_gerrit_synchronized( 'somehost', 'someuser', handled_events=["comment-added"] ) yield s._line_received_stream(json.dumps(self.comment_added_event)) self.assert_changes([self.expected_change_comment_added], ignore_keys=['properties']) @defer.inlineCallbacks def test_line_received_ref_updated(self): s = yield self.create_gerrit_synchronized('somehost', 'someuser') yield s._line_received_stream( json.dumps({ 'type': 'ref-updated', 'submitter': { 'name': 'tester', 'email': '[email protected]', 'username': 'tester', }, 'refUpdate': { 'oldRev': '12341234', 'newRev': '56785678', 'refName': 'refs/heads/master', 'project': 'test', }, 'eventCreatedOn': 1614528683, }) ) self.assertEqual(len(self.master.data.updates.changesAdded), 1) c = self.master.data.updates.changesAdded[0] self.assertEqual( c, { 'files': ['unknown'], 'comments': 'Gerrit: commit(s) pushed.', 'author': 'tester <[email protected]>', 'committer': None, 'revision': '56785678', 'when_timestamp': None, 'branch': 'master', 'category': 'ref-updated', 'revlink': '', 'properties': { 'event.type': 'ref-updated', 'event.submitter.name': 'tester', 'event.submitter.email': '[email protected]', 'event.submitter.username': 'tester', 'event.refUpdate.oldRev': '12341234', 'event.refUpdate.newRev': '56785678', 'event.refUpdate.refName': 'refs/heads/master', 'event.refUpdate.project': 'test', 'event.source': 'GerritChangeSource', }, 'repository': 'ssh://someuser@somehost:29418/test', 'codebase': None, 'project': 'test', 'src': None, }, ) @defer.inlineCallbacks def test_line_received_ref_updated_for_change(self): s = yield self.create_gerrit_synchronized('somehost', 'someuser') yield s._line_received_stream( json.dumps({ 'type': 'ref-updated', 'submitter': { 'name': 'tester', 'email': '[email protected]', 'username': 'tester', }, 'refUpdate': { 'oldRev': '00000000', 'newRev': '56785678', 'refName': 'refs/changes/12/432112/1', 'project': 'test', }, 'eventCreatedOn': 1614528683, }) ) self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_duplicate_non_source_events_not_ignored(self): s = yield self.create_gerrit_synchronized( 'somehost', 'someuser', handled_events=['patchset-created', 'ref-updated', 'change-merged', 'comment-added'], ) yield s._line_received_stream(json.dumps(self.comment_added_event)) self.assertEqual(len(self.master.data.updates.changesAdded), 1) yield s._line_received_stream(json.dumps(self.comment_added_event)) self.assertEqual(len(self.master.data.updates.changesAdded), 2) @defer.inlineCallbacks def test_malformed_events_ignored(self): s = yield self.create_gerrit_synchronized('somehost', 'someuser') # "change" not in event yield s._line_received_stream( json.dumps({ "type": "patchset-created", "patchSet": {"revision": 'abcdef', "number": '12'}, 'eventCreatedOn': 1614528683, }) ) self.assertEqual(len(self.master.data.updates.changesAdded), 0) # "patchSet" not in event yield s._line_received_stream( json.dumps({ "type": "patchset-created", "change": { "branch": "br", # Note that this time "project" is a dictionary "project": {"name": 'pr'}, "number": "4321", "owner": {"name": 'Dustin', "email": '[email protected]'}, "url": "http://buildbot.net", "subject": "fix 1234", }, 'eventCreatedOn': 1614528683, }) ) self.assertEqual(len(self.master.data.updates.changesAdded), 0) change_merged_event = { "type": "change-merged", "change": { "branch": "br", "project": "pr", "number": "4321", "owner": {"name": "Chuck", "email": "[email protected]"}, "url": "http://buildbot.net", "subject": "fix 1234", }, "patchSet": {"revision": "abcdefj", "number": "13"}, 'eventCreatedOn': 1614528683, } @defer.inlineCallbacks def test_handled_events_filter_true(self): s = yield self.create_gerrit_synchronized( 'somehost', 'some_choosy_user', handled_events=["change-merged"] ) yield s._line_received_stream(json.dumps(self.change_merged_event)) self.assertEqual(len(self.master.data.updates.changesAdded), 1) c = self.master.data.updates.changesAdded[0] self.assertEqual(c["category"], "change-merged") self.assertEqual(c["branch"], "br") @defer.inlineCallbacks def test_handled_events_filter_false(self): s = yield self.create_gerrit_synchronized('somehost', 'some_choosy_user') yield s._line_received_stream(json.dumps(self.change_merged_event)) self.assertEqual(len(self.master.data.updates.changesAdded), 0) @defer.inlineCallbacks def test_custom_handler(self): s = yield self.create_gerrit_synchronized( 'somehost', 'some_choosy_user', handled_events=["change-merged"] ) def custom_handler(self, properties, event): event['change']['project'] = "world" return self.addChangeFromEvent(properties, event) # Patches class to not bother with the inheritance s.eventReceived_change_merged = types.MethodType(custom_handler, s) yield s._line_received_stream(json.dumps(self.change_merged_event)) self.assertEqual(len(self.master.data.updates.changesAdded), 1) c = self.master.data.updates.changesAdded[0] self.assertEqual(c['project'], "world") somehost_someuser_ssh_args = [ "ssh", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "someuser@somehost", "-p", "29418", "gerrit", "stream-events", ] @defer.inlineCallbacks def test_activate(self): s = yield self.create_gerrit("somehost", "someuser", debug=True) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) yield self.master.startService() s.activate() self.reactor.process_send_stderr(0, b"test stderr\n") self.reactor.process_send_stdout(0, b'{"type":"dropped-output", "eventCreatedOn": 123}\n') self.reactor.expect_process_signalProcess(0, "KILL") d = self.master.stopService() self.reactor.process_done(0, None) yield d @defer.inlineCallbacks def test_failure_backoff(self): s = yield self.create_gerrit("somehost", "someuser", debug=True) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) yield self.master.startService() s.activate() pid = 0 self.reactor.process_done(pid, None) pid += 1 # The check happens as follows: # - Advance reactor to just before required time (time - 0.05) # - setup expectation for spawnProcess at that moment which ensures that spawnProcess was # not called earlier, # - Advance past the timeout and kill process, which ensures that the process has been # created. self.reactor.advance(0.05) for time in [0.5, 0.5 * 1.5, 0.5 * 1.5 * 1.5, 0.5 * 1.5 * 1.5 * 1.5]: self.reactor.advance(time - 0.1) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.advance(0.1) self.reactor.process_done(pid, None) pid += 1 self.reactor.advance(0.05) def _build_messages_to_bytes(self, timestamps): messages = [ json.dumps({ "type": "patchset-created", 'eventCreatedOn': timestamp, }) for timestamp in timestamps ] out = b"" for message in messages: out += (message + "\n").encode("utf-8") return out def _set_time_to(self, year, month, day, hours, minutes, seconds): self.reactor.advance( datetime2epoch(datetime.datetime(year, month, day, hours, minutes, seconds)) - self.reactor.seconds() ) @parameterized.expand([ ("has_ts_in_db", True), ("has_no_ts_in_db", False), ]) @defer.inlineCallbacks def test_poll_after_broken_connection(self, name, has_ts_in_db): self._set_time_to(2021, 1, 2, 3, 4, 5) start_time = self.reactor.seconds() s = yield self.create_gerrit( "somehost", "someuser", expected_auth=("user", "pass"), http_url="http://somehost", http_auth=("user", "pass"), http_poll_interval=30, ) if has_ts_in_db: # Cannot use set_fake_state because the timestamp has already been retrieved s._last_event_ts = start_time - 124 first_time_str = "2021-01-02 03:02:01" else: first_time_str = "2021-01-02 03:04:05" self.override_event_received(s) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.expect_process_signalProcess(0, "KILL") # Initial poll self._http.expect( "get", "/plugins/events-log/events/", params={"t1": first_time_str}, content=b"", processing_delay_s=1, ) yield self.master.startService() s.activate() # Poll after timeout self._http.expect( "get", "/plugins/events-log/events/", params={"t1": first_time_str}, content=self._build_messages_to_bytes([ start_time + 1, start_time + 3, start_time + 5, ]), ) self.reactor.advance(40) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.expect_process_signalProcess(1, "KILL") self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:10"}, content=self._build_messages_to_bytes([]), ) # This is what triggers process startup self.reactor.process_done(0, None) self.reactor.advance(2) self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:10"}, content=self._build_messages_to_bytes([]), ) self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:10"}, content=self._build_messages_to_bytes([ start_time + 41, start_time + 42, start_time + 43, # ignored because data source switched to stream events ]), ) self.reactor.process_send_stdout( 1, self._build_messages_to_bytes([ start_time + 41, start_time + 42, ]), ) self.assertTrue(s._is_synchronized) d = self.master.stopService() self.reactor.process_done(1, None) yield d yield self.assert_state(s._oid, last_event_ts=start_time + 42) yield self.assert_state( s._oid, last_event_hashes=['f075e0927cab81dabee661a5aa3c65d502103a71'] ) self.assert_events_received([ {'eventCreatedOn': start_time + 1, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 3, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 5, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 41, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 42, 'type': 'patchset-created'}, ]) @defer.inlineCallbacks def test_poll_after_broken_connection_with_message_before(self): self._set_time_to(2021, 1, 2, 3, 4, 5) start_time = self.reactor.seconds() s = yield self.create_gerrit( "somehost", "someuser", expected_auth=("user", "pass"), http_url="http://somehost", http_auth=("user", "pass"), http_poll_interval=30, ) self.override_event_received(s) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.expect_process_signalProcess(0, "KILL") # Initial poll self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=b"", ) yield self.master.startService() s.activate() self.reactor.advance(2) # Poll after messages below self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=self._build_messages_to_bytes([]), ) self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=self._build_messages_to_bytes([]), ) self.reactor.process_send_stdout( 0, self._build_messages_to_bytes([ start_time + 1, start_time + 2, ]), ) # Poll after timeout self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=self._build_messages_to_bytes([ start_time + 1, start_time + 2, ]), ) self.reactor.advance(40) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.expect_process_signalProcess(1, "KILL") self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:07"}, content=self._build_messages_to_bytes([]), ) # This is what triggers process startup above self.reactor.process_done(0, None) self.reactor.advance(2) # Poll after messages below self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:07"}, content=self._build_messages_to_bytes([]), ) self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:07"}, content=self._build_messages_to_bytes([ start_time + 41, start_time + 42, start_time + 43, # ignored because data source switched to stream events ]), ) self.reactor.process_send_stdout( 1, self._build_messages_to_bytes([ start_time + 41, start_time + 42, ]), ) self.assertTrue(s._is_synchronized) d = self.master.stopService() self.reactor.process_done(1, None) yield d yield self.assert_state(s._oid, last_event_ts=start_time + 42) yield self.assert_state( s._oid, last_event_hashes=["f075e0927cab81dabee661a5aa3c65d502103a71"] ) self.assert_events_received([ {'eventCreatedOn': start_time + 1, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 2, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 41, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 42, 'type': 'patchset-created'}, ]) @defer.inlineCallbacks def test_poll_after_working_connection_but_no_messages(self): self._set_time_to(2021, 1, 2, 3, 4, 5) start_time = self.reactor.seconds() s = yield self.create_gerrit( "somehost", "someuser", expected_auth=("user", "pass"), http_url="http://somehost", http_auth=("user", "pass"), http_poll_interval=30, ) self.override_event_received(s) self.reactor.expect_spawn("ssh", self.somehost_someuser_ssh_args) self.reactor.expect_process_signalProcess(0, "KILL") # Initial poll self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=b"", ) yield self.master.startService() s.activate() self.reactor.advance(2) # Poll after messages below self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=self._build_messages_to_bytes([]), ) self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:05"}, content=self._build_messages_to_bytes([ start_time + 1, start_time + 2, ]), ) self.reactor.process_send_stdout( 0, self._build_messages_to_bytes([ start_time + 1, start_time + 2, ]), ) self.assertTrue(s._is_synchronized) for _ in range(3): # Poll after timeout self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:04:07"}, content=self._build_messages_to_bytes([]), ) self.reactor.advance(40) self.reactor.advance(2) self.reactor.process_send_stdout( 0, self._build_messages_to_bytes([ start_time + 125, start_time + 126, ]), ) for _ in range(3): # Poll after timeout self._http.expect( "get", "/plugins/events-log/events/", params={"t1": "2021-01-02 03:06:11"}, content=self._build_messages_to_bytes([]), ) self.reactor.advance(40) self.reactor.advance(2) self.reactor.process_send_stdout( 0, self._build_messages_to_bytes([ start_time + 256, start_time + 257, ]), ) self.assertTrue(s._is_synchronized) d = self.master.stopService() self.reactor.process_done(0, None) yield d yield self.assert_state(s._oid, last_event_ts=start_time + 257) self.assert_events_received([ {'eventCreatedOn': start_time + 1, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 2, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 125, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 126, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 256, 'type': 'patchset-created'}, {'eventCreatedOn': start_time + 257, 'type': 'patchset-created'}, ]) # ------------------------------------------------------------------------- # Test data for getFiles() # ------------------------------------------------------------------------- query_files_success_line1 = { "patchSets": [ { "number": 1, "files": [ {"file": "/COMMIT_MSG", "type": "ADDED", "insertions": 13, "deletions": 0}, ], }, { "number": 13, "files": [ {"file": "/COMMIT_MSG", "type": "ADDED", "insertions": 13, "deletions": 0}, {"file": "file1", "type": "MODIFIED", "insertions": 7, "deletions": 0}, {"file": "file2", "type": "MODIFIED", "insertions": 2, "deletions": -2}, ], }, ] } query_files_success_line2 = {"type": "stats", "rowCount": 1} query_files_success = '\n'.join([ json.dumps(query_files_success_line1), json.dumps(query_files_success_line2), ]).encode('utf8') query_files_failure = b'{"type":"stats","rowCount":0}' @defer.inlineCallbacks def test_getFiles(self): s = yield self.create_gerrit_synchronized('host', 'user', gerritport=2222) exp_argv = [ "ssh", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "user@host", "-p", "2222", "gerrit", "query", "1000", "--format", "JSON", "--files", "--patch-sets", ] self.expect_commands( ExpectMasterShell(exp_argv).stdout(self.query_files_success), ExpectMasterShell(exp_argv).stdout(self.query_files_failure), ) res = yield s.getFiles(1000, 13) self.assertEqual(set(res), {'/COMMIT_MSG', 'file1', 'file2'}) res = yield s.getFiles(1000, 13) self.assertEqual(res, ['unknown']) self.assert_all_commands_ran() @defer.inlineCallbacks def test_getFilesFromEvent(self): self.expect_commands( ExpectMasterShell([ "ssh", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "user@host", "-p", "29418", "gerrit", "query", "4321", "--format", "JSON", "--files", "--patch-sets", ]).stdout(self.query_files_success) ) s = yield self.create_gerrit_synchronized( 'host', 'user', get_files=True, handled_events=["change-merged"] ) yield s._line_received_stream(json.dumps(self.change_merged_event)) c = self.master.data.updates.changesAdded[0] self.assertEqual(set(c['files']), {'/COMMIT_MSG', 'file1', 'file2'}) self.assert_all_commands_ran() class TestGerritEventLogPoller( changesource.ChangeSourceMixin, StateTestMixin, TestReactorMixin, unittest.TestCase ): NOW_TIMESTAMP = 1479302598 EVENT_TIMESTAMP = 1479302599 NOW_FORMATTED = '2016-11-16 13:23:18' EVENT_FORMATTED = '2016-11-16 13:23:19' OBJECTID = 1234 @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpChangeSource() yield self.master.startService() @defer.inlineCallbacks def tearDown(self): yield self.master.stopService() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def newChangeSource(self, **kwargs): auth = kwargs.pop('auth', ('log', 'pass')) self._http = yield fakehttpclientservice.HTTPClientService.getService( self.master, self, 'gerrit', auth=auth ) self.changesource = gerritchangesource.GerritEventLogPoller( 'gerrit', auth=auth, gitBaseURL="ssh://someuser@somehost:29418", pollAtLaunch=False, **kwargs, ) @defer.inlineCallbacks def startChangeSource(self): yield self.changesource.setServiceParent(self.master) yield self.attachChangeSource(self.changesource) @defer.inlineCallbacks def test_describe(self): # describe is not used yet in buildbot nine, but it can still be useful in the future, so # lets implement and test it yield self.newChangeSource() self.assertSubstring('GerritEventLogPoller', self.changesource.describe()) @defer.inlineCallbacks def test_name(self): yield self.newChangeSource() self.assertEqual('GerritEventLogPoller:gerrit', self.changesource.name) @defer.inlineCallbacks def test_lineReceived_patchset_created(self): yield self.master.db.insert_test_data([ fakedb.Object( id=self.OBJECTID, name='GerritEventLogPoller:gerrit', class_name='GerritEventLogPoller', ) ]) yield self.newChangeSource(get_files=True) thirty_days_ago = datetime.datetime.fromtimestamp( self.reactor.seconds(), datetime.timezone.utc ) - datetime.timedelta(days=30) self._http.expect( method='get', ep='/plugins/events-log/events/', params={'t1': thirty_days_ago.strftime("%Y-%m-%d %H:%M:%S")}, content_json={ "type": "patchset-created", "change": { "branch": "master", "project": "test", "number": "4321", "owner": {"name": 'owner owner', "email": '[email protected]'}, "url": "http://example.com/c/test/+/4321", "subject": "change subject", }, "eventCreatedOn": self.EVENT_TIMESTAMP, "patchSet": { 'revision': "29b73c3eb1aeaa9e6c7da520a940d60810e883db", 'number': "1", 'ref': 'refs/changes/21/4321/1', }, }, ) self._http.expect( method='get', ep='/changes/4321/revisions/1/files/', content=self.change_revision_resp, ) yield self.startChangeSource() yield self.changesource._connector.poll() self.assertEqual(len(self.master.data.updates.changesAdded), 1) c = self.master.data.updates.changesAdded[0] expected_change = dict(TestGerritChangeSource.expected_change_patchset_created) for k, v in c.items(): if k in ('files', 'properties'): continue self.assertEqual(expected_change[k], v) yield self.assert_state(self.OBJECTID, last_event_ts=self.EVENT_TIMESTAMP) self.assertEqual(set(c['files']), {'/COMMIT_MSG', 'file1'}) # do a second poll, it should ask for the next events self._http.expect( method='get', ep='/plugins/events-log/events/', params={'t1': self.EVENT_FORMATTED}, content_json={ "type": "patchset-created", "change": { "branch": "br", "project": "pr", "number": "4321", "owner": {"name": 'Dustin', "email": '[email protected]'}, "url": "http://buildbot.net", "subject": "fix 1234", }, "eventCreatedOn": self.EVENT_TIMESTAMP + 1, "patchSet": { 'revision': "29b73c3eb1aeaa9e6c7da520a940d60810e883db", 'number': "1", 'ref': 'refs/changes/21/4321/1', }, }, ) self._http.expect( method='get', ep='/changes/4321/revisions/1/files/', content=self.change_revision_resp, ) yield self.changesource._connector.poll() yield self.assert_state(self.OBJECTID, last_event_ts=self.EVENT_TIMESTAMP + 1) change_revision_dict = { '/COMMIT_MSG': {'status': 'A', 'lines_inserted': 9, 'size_delta': 1, 'size': 1}, 'file1': {'lines_inserted': 9, 'lines_deleted': 2, 'size_delta': 1, 'size': 1}, } change_revision_resp = b')]}\n' + json.dumps(change_revision_dict).encode('utf8') @defer.inlineCallbacks def test_getFiles(self): yield self.newChangeSource(get_files=True) yield self.startChangeSource() self._http.expect( method='get', ep='/changes/100/revisions/1/files/', content=self.change_revision_resp, ) files = yield self.changesource.getFiles(100, 1) self.assertEqual(set(files), {'/COMMIT_MSG', 'file1'}) @defer.inlineCallbacks def test_getFiles_handle_error(self): yield self.newChangeSource(get_files=True) yield self.startChangeSource() self._http.expect( method='get', ep='/changes/100/revisions/1/files/', content=b')]}\n', # more than one line expected ) files = yield self.changesource.getFiles(100, 1) self.assertEqual(files, []) self.assertEqual(len(self.flushLoggedErrors()), 1) class TestGerritChangeFilter(unittest.TestCase): def test_event_type(self): props = { 'event.type': 'patchset-created', 'event.change.branch': 'master', } ch = Change(**TestGerritChangeSource.expected_change_patchset_created, properties=props) f = gerritchangesource.GerritChangeFilter(branch=["master"], eventtype=["patchset-created"]) self.assertTrue(f.filter_change(ch)) f = gerritchangesource.GerritChangeFilter(branch="master2", eventtype=["patchset-created"]) self.assertFalse(f.filter_change(ch)) f = gerritchangesource.GerritChangeFilter(branch="master", eventtype="ref-updated") self.assertFalse(f.filter_change(ch)) self.assertEqual( repr(f), '<GerritChangeFilter on event.type in [\'ref-updated\'] and ' 'event.change.branch in [\'master\']>', ) def create_props(self, branch, event_type): return { 'event.type': event_type, 'event.change.branch': branch, } def test_event_type_re(self): f = gerritchangesource.GerritChangeFilter(eventtype_re="patchset-.*") self.assertTrue( f.filter_change(Change(properties=self.create_props("br", "patchset-created"))) ) self.assertFalse(f.filter_change(Change(properties=self.create_props("br", "ref-updated")))) def test_event_type_fn(self): f = gerritchangesource.GerritChangeFilter(eventtype_fn=lambda t: t == "patchset-created") self.assertTrue( f.filter_change(Change(properties=self.create_props("br", "patchset-created"))) ) self.assertFalse(f.filter_change(Change(properties=self.create_props("br", "ref-updated")))) self.assertEqual(repr(f), '<GerritChangeFilter on <lambda>(eventtype)>') def test_branch_fn(self): f = gerritchangesource.GerritChangeFilter(branch_fn=lambda t: t == "br0") self.assertTrue( f.filter_change(Change(properties=self.create_props("br0", "patchset-created"))) ) self.assertFalse( f.filter_change(Change(properties=self.create_props("br1", "ref-updated"))) ) self.assertEqual(repr(f), '<GerritChangeFilter on <lambda>(branch)>')
45,621
Python
.py
1,114
29.762118
100
0.560005
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,396
test_mail_CVSMaildirSource.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_mail_CVSMaildirSource.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 email import message_from_string from email.utils import mktime_tz from email.utils import parsedate_tz from twisted.trial import unittest from buildbot.changes.mail import CVSMaildirSource # # Sample message from CVS version 1.11 # cvs1_11_msg = """From: Andy Howell <[email protected]> To: [email protected] Subject: cvs module MyModuleName Date: Sat, 07 Aug 2010 11:11:49 +0000 X-Mailer: Python buildbot-cvs-mail $Revision: 1.3 $ Cvsmode: 1.11 Category: None CVSROOT: :ext:cvshost.example.com:/cvsroot Files: base/module/src/make GNUmakefile,1.362,1.363 Project: MyModuleName Update of /cvsroot/base/module/src/make In directory cvshost:/tmp/cvs-serv10922 Modified Files: GNUmakefile Log Message: Commented out some stuff. """ # # Sample message from CVS version 1.12 # # Paths are handled differently by the two versions # cvs1_12_msg = """Date: Wed, 11 Aug 2010 04:56:44 +0000 From: [email protected] To: [email protected] Subject: cvs update for project RaiCore X-Mailer: Python buildbot-cvs-mail $Revision: 1.3 $ Cvsmode: 1.12 Category: None CVSROOT: :ext:cvshost.example.com:/cvsroot Files: file1.cpp 1.77 1.78 file2.cpp 1.75 1.76 Path: base/module/src Project: MyModuleName Update of /cvsroot/base/module/src In directory example.com:/tmp/cvs-serv26648/InsightMonAgent Modified Files: file1.cpp file2.cpp Log Message: Changes for changes sake """ class TestCVSMaildirSource(unittest.TestCase): def test_CVSMaildirSource_create_change_from_cvs1_11msg(self): m = message_from_string(cvs1_11_msg) src = CVSMaildirSource('/dev/null') src, chdict = src.parse(m) self.assertNotEqual(chdict, None) self.assertEqual(chdict['author'], 'andy') self.assertEqual(len(chdict['files']), 1) self.assertEqual(chdict['files'][0], 'base/module/src/make/GNUmakefile') self.assertEqual(chdict['comments'], 'Commented out some stuff.\n') self.assertFalse(chdict['isdir']) self.assertEqual(chdict['revision'], '2010-08-07 11:11:49') dateTuple = parsedate_tz('Sat, 07 Aug 2010 11:11:49 +0000') self.assertEqual(chdict['when'], mktime_tz(dateTuple)) self.assertEqual(chdict['branch'], None) self.assertEqual(chdict['repository'], ':ext:cvshost.example.com:/cvsroot') self.assertEqual(chdict['project'], 'MyModuleName') self.assertEqual(len(chdict['properties']), 0) self.assertEqual(src, 'cvs') def test_CVSMaildirSource_create_change_from_cvs1_12msg(self): m = message_from_string(cvs1_12_msg) src = CVSMaildirSource('/dev/null') src, chdict = src.parse(m) self.assertNotEqual(chdict, None) self.assertEqual(chdict['author'], 'andy') self.assertEqual(len(chdict['files']), 2) self.assertEqual(chdict['files'][0], 'base/module/src/file1.cpp') self.assertEqual(chdict['files'][1], 'base/module/src/file2.cpp') self.assertEqual(chdict['comments'], 'Changes for changes sake\n') self.assertFalse(chdict['isdir']) self.assertEqual(chdict['revision'], '2010-08-11 04:56:44') dateTuple = parsedate_tz('Wed, 11 Aug 2010 04:56:44 +0000') self.assertEqual(chdict['when'], mktime_tz(dateTuple)) self.assertEqual(chdict['branch'], None) self.assertEqual(chdict['repository'], ':ext:cvshost.example.com:/cvsroot') self.assertEqual(chdict['project'], 'MyModuleName') self.assertEqual(len(chdict['properties']), 0) self.assertEqual(src, 'cvs') def test_CVSMaildirSource_create_change_from_cvs1_12_with_no_path(self): msg = cvs1_12_msg.replace('Path: base/module/src', '') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') try: assert src.parse(m)[1] except ValueError: pass else: self.fail('Expect ValueError.') def test_CVSMaildirSource_create_change_with_bad_cvsmode(self): # Branch is indicated after 'Tag:' in modified file list msg = cvs1_11_msg.replace('Cvsmode: 1.11', 'Cvsmode: 9.99') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') try: assert src.parse(m)[1] except ValueError: pass else: self.fail('Expected ValueError') def test_CVSMaildirSource_create_change_with_branch(self): # Branch is indicated after 'Tag:' in modified file list msg = cvs1_11_msg.replace( ' GNUmakefile', ' Tag: Test_Branch\n GNUmakefile' ) m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m)[1] self.assertEqual(chdict['branch'], 'Test_Branch') def test_CVSMaildirSource_create_change_with_category(self): msg = cvs1_11_msg.replace('Category: None', 'Category: Test category') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m)[1] self.assertEqual(chdict['category'], 'Test category') def test_CVSMaildirSource_create_change_with_no_comment(self): # Strip off comments msg = cvs1_11_msg[: cvs1_11_msg.find('Commented out some stuff')] m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m)[1] self.assertEqual(chdict['comments'], None) def test_CVSMaildirSource_create_change_with_no_files(self): # A message with no files is likely not for us msg = cvs1_11_msg.replace('Files: base/module/src/make GNUmakefile,1.362,1.363', '') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m) self.assertEqual(chdict, None) def test_CVSMaildirSource_create_change_with_no_project(self): msg = cvs1_11_msg.replace('Project: MyModuleName', '') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m)[1] self.assertEqual(chdict['project'], None) def test_CVSMaildirSource_create_change_with_no_repository(self): msg = cvs1_11_msg.replace('CVSROOT: :ext:cvshost.example.com:/cvsroot', '') m = message_from_string(msg) src = CVSMaildirSource('/dev/null') chdict = src.parse(m)[1] self.assertEqual(chdict['repository'], None) def test_CVSMaildirSource_create_change_with_property(self): m = message_from_string(cvs1_11_msg) propDict = {'foo': 'bar'} src = CVSMaildirSource('/dev/null', properties=propDict) chdict = src.parse(m)[1] self.assertEqual(chdict['properties']['foo'], 'bar')
7,420
Python
.py
168
38.029762
92
0.682667
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,397
test_base.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_base.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 unittest import mock from twisted.internet import defer from twisted.trial import unittest from buildbot.changes import base from buildbot.config import ConfigErrors from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import changesource class TestChangeSource(changesource.ChangeSourceMixin, TestReactorMixin, unittest.TestCase): timeout = 120 class Subclass(base.ChangeSource): pass @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpChangeSource() @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def test_activation(self): cs = self.Subclass(name="DummyCS") cs.activate = mock.Mock(return_value=defer.succeed(None)) cs.deactivate = mock.Mock(return_value=defer.succeed(None)) # set the changesourceid, and claim the changesource on another master yield self.attachChangeSource(cs) self.setChangeSourceToMaster(self.OTHER_MASTER_ID) yield cs.startService() self.reactor.advance(cs.POLL_INTERVAL_SEC / 2) self.reactor.advance(cs.POLL_INTERVAL_SEC / 5) self.reactor.advance(cs.POLL_INTERVAL_SEC / 5) self.assertFalse(cs.activate.called) self.assertFalse(cs.deactivate.called) self.assertFalse(cs.active) self.assertEqual(cs.serviceid, self.DUMMY_CHANGESOURCE_ID) # clear that masterid yield cs.stopService() self.setChangeSourceToMaster(None) yield cs.startService() self.reactor.advance(cs.POLL_INTERVAL_SEC) self.assertTrue(cs.activate.called) self.assertFalse(cs.deactivate.called) self.assertTrue(cs.active) # stop the service and see that deactivate is called yield cs.stopService() self.assertTrue(cs.activate.called) self.assertTrue(cs.deactivate.called) self.assertFalse(cs.active) class TestReconfigurablePollingChangeSource( changesource.ChangeSourceMixin, TestReactorMixin, unittest.TestCase ): class Subclass(base.ReconfigurablePollingChangeSource): pass @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) yield self.setUpChangeSource() yield self.attachChangeSource(self.Subclass(name="DummyCS")) @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def runClockFor(self, secs): yield self.reactor.pump([0] + [1.0] * secs) @defer.inlineCallbacks def test_config_negative_interval(self): try: yield self.changesource.reconfigServiceWithSibling( self.Subclass(name="NegativePollInterval", pollInterval=-1, pollAtLaunch=False) ) except ConfigErrors as e: self.assertEqual("interval must be >= 0: -1", e.errors[0]) @defer.inlineCallbacks def test_config_negative_random_delay_min(self): try: yield self.changesource.reconfigServiceWithSibling( self.Subclass( name="NegativePollRandomDelayMin", pollInterval=1, pollAtLaunch=False, pollRandomDelayMin=-1, pollRandomDelayMax=1, ) ) except ConfigErrors as e: self.assertEqual("min random delay must be >= 0: -1", e.errors[0]) @defer.inlineCallbacks def test_config_negative_random_delay_max(self): try: yield self.changesource.reconfigServiceWithSibling( self.Subclass( name="NegativePollRandomDelayMax", pollInterval=1, pollAtLaunch=False, pollRandomDelayMin=1, pollRandomDelayMax=-1, ) ) except ConfigErrors as e: self.assertEqual("max random delay must be >= 0: -1", e.errors[0]) @defer.inlineCallbacks def test_config_random_delay_min_gt_random_delay_max(self): try: yield self.changesource.reconfigServiceWithSibling( self.Subclass( name="PollRandomDelayMinGtPollRandomDelayMax", pollInterval=1, pollAtLaunch=False, pollRandomDelayMin=2, pollRandomDelayMax=1, ) ) except ConfigErrors as e: self.assertEqual("min random delay must be <= 1: 2", e.errors[0]) @defer.inlineCallbacks def test_config_random_delay_max_gte_interval(self): try: yield self.changesource.reconfigServiceWithSibling( self.Subclass( name="PollRandomDelayMaxGtePollInterval", pollInterval=1, pollAtLaunch=False, pollRandomDelayMax=1, ) ) except ConfigErrors as e: self.assertEqual("max random delay must be < 1: 1", e.errors[0]) @defer.inlineCallbacks def test_loop_loops(self): # track when poll() gets called loops = [] self.changesource.poll = lambda: loops.append(self.reactor.seconds()) yield self.startChangeSource() yield self.changesource.reconfigServiceWithSibling( self.Subclass(name="DummyCS", pollInterval=5, pollAtLaunch=False) ) yield self.runClockFor(12) # note that it does *not* poll at time 0 self.assertEqual(loops, [5.0, 10.0]) @defer.inlineCallbacks def test_loop_exception(self): # track when poll() gets called loops = [] def poll(): loops.append(self.reactor.seconds()) raise RuntimeError("oh noes") self.changesource.poll = poll yield self.startChangeSource() yield self.changesource.reconfigServiceWithSibling( self.Subclass(name="DummyCS", pollInterval=5, pollAtLaunch=False) ) yield self.runClockFor(12) # note that it keeps looping after error self.assertEqual(loops, [5.0, 10.0]) self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 2) @defer.inlineCallbacks def test_poll_only_if_activated(self): """The polling logic only applies if the source actually starts!""" self.setChangeSourceToMaster(self.OTHER_MASTER_ID) loops = [] self.changesource.poll = lambda: loops.append(self.reactor.seconds()) yield self.startChangeSource() yield self.changesource.reconfigServiceWithSibling( self.Subclass(name="DummyCS", pollInterval=5, pollAtLaunch=False) ) yield self.runClockFor(12) # it doesn't do anything because it was already claimed self.assertEqual(loops, []) @defer.inlineCallbacks def test_pollAtLaunch(self): # track when poll() gets called loops = [] self.changesource.poll = lambda: loops.append(self.reactor.seconds()) yield self.startChangeSource() yield self.changesource.reconfigServiceWithSibling( self.Subclass(name="DummyCS", pollInterval=5, pollAtLaunch=True) ) yield self.runClockFor(12) # note that it *does* poll at time 0 self.assertEqual(loops, [0.0, 5.0, 10.0])
8,297
Python
.py
195
33.041026
95
0.658891
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,398
test_mail.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_mail.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.trial import unittest from buildbot.changes import mail from buildbot.test.reactor import TestReactorMixin from buildbot.test.util import changesource from buildbot.test.util import dirs class TestMaildirSource( changesource.ChangeSourceMixin, dirs.DirsMixin, TestReactorMixin, unittest.TestCase ): @defer.inlineCallbacks def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.maildir = os.path.abspath("maildir") yield self.setUpChangeSource() yield self.setUpDirs(self.maildir) def populateMaildir(self): "create a fake maildir with a fake new message ('newmsg') in it" newdir = os.path.join(self.maildir, "new") os.makedirs(newdir) curdir = os.path.join(self.maildir, "cur") os.makedirs(curdir) fake_message = "Subject: test\n\nthis is a test" mailfile = os.path.join(newdir, "newmsg") with open(mailfile, "w", encoding='utf-8') as f: f.write(fake_message) def assertMailProcessed(self): self.assertFalse(os.path.exists(os.path.join(self.maildir, "new", "newmsg"))) self.assertTrue(os.path.exists(os.path.join(self.maildir, "cur", "newmsg"))) @defer.inlineCallbacks def tearDown(self): yield self.tearDownDirs() yield self.tearDownChangeSource() yield self.tear_down_test_reactor() # tests def test_describe(self): mds = mail.MaildirSource(self.maildir) self.assertSubstring(self.maildir, mds.describe()) @defer.inlineCallbacks def test_messageReceived_svn(self): self.populateMaildir() mds = mail.MaildirSource(self.maildir) yield self.attachChangeSource(mds) # monkey-patch in a parse method def parse(message, prefix): assert 'this is a test' in message.get_payload() return ('svn', {"author": 'jimmy'}) mds.parse = parse yield mds.messageReceived('newmsg') self.assertMailProcessed() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'jimmy', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': None, 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': 'svn', 'when_timestamp': None, } ], ) @defer.inlineCallbacks def test_messageReceived_bzr(self): self.populateMaildir() mds = mail.MaildirSource(self.maildir) yield self.attachChangeSource(mds) # monkey-patch in a parse method def parse(message, prefix): assert 'this is a test' in message.get_payload() return ('bzr', {"author": 'jimmy'}) mds.parse = parse yield mds.messageReceived('newmsg') self.assertMailProcessed() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'jimmy', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': None, 'files': None, 'project': '', 'properties': {}, 'repository': '', 'revision': None, 'revlink': '', 'src': 'bzr', 'when_timestamp': None, } ], )
4,619
Python
.py
118
28.457627
87
0.583519
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
4,399
test_svnpoller.py
buildbot_buildbot/master/buildbot/test/unit/changes/test_svnpoller.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 import xml.dom.minidom from twisted.internet import defer from twisted.trial import unittest from buildbot.changes import svnpoller from buildbot.process.properties import Interpolate from buildbot.test.reactor import TestReactorMixin from buildbot.test.runprocess import ExpectMasterShell from buildbot.test.runprocess import MasterRunProcessMixin from buildbot.test.util import changesource # this is the output of "svn info --xml # svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" prefix_output = b"""\ <?xml version="1.0"?> <info> <entry kind="dir" path="trunk" revision="18354"> <url>svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk</url> <repository> <root>svn+ssh://svn.twistedmatrix.com/svn/Twisted</root> <uuid>bbbe8e31-12d6-0310-92fd-ac37d47ddeeb</uuid> </repository> <commit revision="18352"> <author>jml</author> <date>2006-10-01T02:37:34.063255Z</date> </commit> </entry> </info> """ # and this is "svn info --xml svn://svn.twistedmatrix.com/svn/Twisted". I # think this is kind of a degenerate case.. it might even be a form of error. prefix_output_2 = b"""\ <?xml version="1.0"?> <info> </info> """ # this is the svn info output for a local repository, svn info --xml # file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository prefix_output_3 = b"""\ <?xml version="1.0"?> <info> <entry kind="dir" path="SVN-Repository" revision="3"> <url>file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</url> <repository> <root>file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</root> <uuid>c0f47ff4-ba1e-0410-96b5-d44cc5c79e7f</uuid> </repository> <commit revision="3"> <author>warner</author> <date>2006-10-01T07:37:04.182499Z</date> </commit> </entry> </info> """ # % svn info --xml file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk prefix_output_4 = b"""\ <?xml version="1.0"?> <info> <entry kind="dir" path="trunk" revision="3"> <url>file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk</url> <repository> <root>file:///home/warner/stuff/Projects/Buildbot/trees/svnpoller/_trial_temp/test_vc/repositories/SVN-Repository</root> <uuid>c0f47ff4-ba1e-0410-96b5-d44cc5c79e7f</uuid> </repository> <commit revision="1"> <author>warner</author> <date>2006-10-01T07:37:02.286440Z</date> </commit> </entry> </info> """ # output from svn log on .../SVN-Repository/sample # (so it includes trunk and branches) sample_base = ( "file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/" + "_trial_temp/test_vc/repositories/SVN-Repository/sample" ) sample_logentries: list[bytes | None] = [None] * 6 sample_logentries[5] = b"""\ <logentry revision="6"> <author>warner</author> <date>2006-10-01T19:35:16.165664Z</date> <paths> <path action="D">/sample/branch/version.c</path> </paths> <msg>revised_to_2</msg> </logentry> """ sample_logentries[4] = b"""\ <logentry revision="5"> <author>warner</author> <date>2006-10-01T19:35:16.165664Z</date> <paths> <path action="D">/sample/branch</path> </paths> <msg>revised_to_2</msg> </logentry> """ sample_logentries[3] = b"""\ <logentry revision="4"> <author>warner</author> <date>2006-10-01T19:35:16.165664Z</date> <paths> <path action="M">/sample/trunk/version.c</path> </paths> <msg>revised_to_2</msg> </logentry> """ sample_logentries[2] = b"""\ <logentry revision="3"> <author>warner</author> <date>2006-10-01T19:35:10.215692Z</date> <paths> <path action="M">/sample/branch/c\xcc\xa7main.c</path> </paths> <msg>commit_on_branch</msg> </logentry> """ sample_logentries[1] = b"""\ <logentry revision="2"> <author>warner</author> <date>2006-10-01T19:35:09.154973Z</date> <paths> <path copyfrom-path="/sample/trunk" copyfrom-rev="1" action="A">/sample/branch</path> </paths> <msg>make_branch</msg> </logentry> """ sample_logentries[0] = b"""\ <logentry revision="1"> <author>warner</author> <date>2006-10-01T19:35:08.642045Z</date> <paths> <path action="A">/sample</path> <path action="A">/sample/trunk</path> <path action="A">/sample/trunk/subdir/subdir.c</path> <path action="A">/sample/trunk/main.c</path> <path action="A">/sample/trunk/version.c</path> <path action="A">/sample/trunk/subdir</path> </paths> <msg>sample_project_files</msg> </logentry> """ sample_info_output = b"""\ <?xml version="1.0"?> <info> <entry kind="dir" path="sample" revision="4"> <url>file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository/sample</url> <repository> <root>file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository</root> <uuid>4f94adfc-c41e-0410-92d5-fbf86b7c7689</uuid> </repository> <commit revision="4"> <author>warner</author> <date>2006-10-01T19:35:16.165664Z</date> </commit> </entry> </info> """ def make_changes_output(maxrevision): # return what 'svn log' would have just after the given revision was # committed logs = sample_logentries[0:maxrevision] assert len(logs) == maxrevision logs.reverse() output = ( b"""<?xml version="1.0"?> <log>""" + b"".join(logs) + b"</log>" ) return output def make_logentry_elements(maxrevision): "return the corresponding logentry elements for the given revisions" doc = xml.dom.minidom.parseString(make_changes_output(maxrevision)) return doc.getElementsByTagName("logentry") def split_file(path): pieces = path.split("/") if pieces[0] == "branch": return {"branch": 'branch', "path": '/'.join(pieces[1:])} if pieces[0] == "trunk": return {"path": '/'.join(pieces[1:])} raise RuntimeError(f"there shouldn't be any files like {path!r}") class TestSVNPoller( MasterRunProcessMixin, changesource.ChangeSourceMixin, TestReactorMixin, unittest.TestCase ): def setUp(self): self.setup_test_reactor(auto_tear_down=False) self.setup_master_run_process() return self.setUpChangeSource() @defer.inlineCallbacks def tearDown(self): yield self.tearDownChangeSource() yield self.tear_down_test_reactor() @defer.inlineCallbacks def attachSVNPoller(self, *args, **kwargs): s = svnpoller.SVNPoller(*args, **kwargs) yield self.attachChangeSource(s) return s @defer.inlineCallbacks def test_describe(self): s = yield self.attachSVNPoller('file://') self.assertSubstring("SVNPoller", s.describe()) @defer.inlineCallbacks def test_name(self): s = yield self.attachSVNPoller('file://') self.assertEqual("file://", s.name) s = yield self.attachSVNPoller('file://', name='MyName') self.assertEqual("MyName", s.name) @defer.inlineCallbacks def test_strip_repourl(self): base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" s = yield self.attachSVNPoller(base + "/") self.assertEqual(s.repourl, base) @defer.inlineCallbacks def do_test_get_prefix(self, base, output, expected): s = yield self.attachSVNPoller(base) self.expect_commands( ExpectMasterShell(['svn', 'info', '--xml', '--non-interactive', base]).stdout(output) ) prefix = yield s.get_prefix() self.assertEqual(prefix, expected) self.assert_all_commands_ran() def test_get_prefix_1(self): base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" return self.do_test_get_prefix(base, prefix_output, 'trunk') def test_get_prefix_2(self): base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted" return self.do_test_get_prefix(base, prefix_output_2, '') def test_get_prefix_3(self): base = ( "file:///home/warner/stuff/Projects/Buildbot/trees/" + "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository" ) return self.do_test_get_prefix(base, prefix_output_3, '') def test_get_prefix_4(self): base = ( "file:///home/warner/stuff/Projects/Buildbot/trees/" + "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample/trunk" ) return self.do_test_get_prefix(base, prefix_output_3, 'sample/trunk') @defer.inlineCallbacks def test_log_parsing(self): s = yield self.attachSVNPoller('file:///foo') output = make_changes_output(4) entries = s.parse_logs(output) # no need for elaborate assertions here; this is minidom's logic self.assertEqual(len(entries), 4) @defer.inlineCallbacks def test_get_new_logentries(self): s = yield self.attachSVNPoller('file:///foo') entries = make_logentry_elements(4) s.last_change = 4 new = s.get_new_logentries(entries) self.assertEqual(s.last_change, 4) self.assertEqual(len(new), 0) s.last_change = 3 new = s.get_new_logentries(entries) self.assertEqual(s.last_change, 4) self.assertEqual(len(new), 1) s.last_change = 1 new = s.get_new_logentries(entries) self.assertEqual(s.last_change, 4) self.assertEqual(len(new), 3) # special case: if last_change is None, then no new changes are queued s.last_change = None new = s.get_new_logentries(entries) self.assertEqual(s.last_change, 4) self.assertEqual(len(new), 0) @defer.inlineCallbacks def test_get_text(self): doc = xml.dom.minidom.parseString( """ <parent> <child> hi <grandchild>1</grandchild> <grandchild>2</grandchild> </child> </parent>""".strip() ) s = yield self.attachSVNPoller('http://', split_file=split_file) self.assertEqual(s._get_text(doc, 'grandchild'), '1') self.assertEqual(s._get_text(doc, 'nonexistent'), 'unknown') @defer.inlineCallbacks def test_create_changes(self): base = ( "file:///home/warner/stuff/Projects/Buildbot/trees/" + "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample" ) s = yield self.attachSVNPoller(base, split_file=split_file) s._prefix = "sample" logentries = dict(zip(range(1, 7), reversed(make_logentry_elements(6)))) changes = s.create_changes(reversed([logentries[3], logentries[2]])) self.assertEqual(len(changes), 2) # note that parsing occurs in reverse self.assertEqual(changes[0]['branch'], "branch") self.assertEqual(changes[0]['revision'], '2') self.assertEqual(changes[0]['project'], '') self.assertEqual(changes[0]['repository'], base) self.assertEqual(changes[1]['branch'], "branch") self.assertEqual(changes[1]['files'], ["çmain.c"]) self.assertEqual(changes[1]['revision'], '3') self.assertEqual(changes[1]['project'], '') self.assertEqual(changes[1]['repository'], base) changes = s.create_changes([logentries[4]]) self.assertEqual(len(changes), 1) self.assertEqual(changes[0]['branch'], None) self.assertEqual(changes[0]['revision'], '4') self.assertEqual(changes[0]['files'], ["version.c"]) # r5 should *not* create a change as it's a branch deletion changes = s.create_changes([logentries[5]]) self.assertEqual(len(changes), 0) # r6 should create a change as it's not deleting an entire branch changes = s.create_changes([logentries[6]]) self.assertEqual(len(changes), 1) self.assertEqual(changes[0]['branch'], 'branch') self.assertEqual(changes[0]['revision'], '6') self.assertEqual(changes[0]['files'], ["version.c"]) def makeInfoExpect(self, password='bbrocks'): args = ['svn', 'info', '--xml', '--non-interactive', sample_base, '--username=dustin'] if password is not None: args.append('--password=' + password) return ExpectMasterShell(args) def makeLogExpect(self, password='bbrocks'): args = ['svn', 'log', '--xml', '--verbose', '--non-interactive', '--username=dustin'] if password is not None: args.append('--password=' + password) args.extend(['--limit=100', sample_base]) return ExpectMasterShell(args) @defer.inlineCallbacks def test_create_changes_overridden_project(self): def custom_split_file(path): f = split_file(path) if f: f["project"] = "overridden-project" f["repository"] = "overridden-repository" f["codebase"] = "overridden-codebase" return f base = ( "file:///home/warner/stuff/Projects/Buildbot/trees/" + "svnpoller/_trial_temp/test_vc/repositories/SVN-Repository/sample" ) s = yield self.attachSVNPoller(base, split_file=custom_split_file) s._prefix = "sample" logentries = dict(zip(range(1, 7), reversed(make_logentry_elements(6)))) changes = s.create_changes(reversed([logentries[3], logentries[2]])) self.assertEqual(len(changes), 2) # note that parsing occurs in reverse self.assertEqual(changes[0]['branch'], "branch") self.assertEqual(changes[0]['revision'], '2') self.assertEqual(changes[0]['project'], "overridden-project") self.assertEqual(changes[0]['repository'], "overridden-repository") self.assertEqual(changes[0]['codebase'], "overridden-codebase") self.assertEqual(changes[1]['branch'], "branch") self.assertEqual(changes[1]['files'], ['çmain.c']) self.assertEqual(changes[1]['revision'], '3') self.assertEqual(changes[1]['project'], "overridden-project") self.assertEqual(changes[1]['repository'], "overridden-repository") self.assertEqual(changes[1]['codebase'], "overridden-codebase") @defer.inlineCallbacks def test_poll(self): s = yield self.attachSVNPoller( sample_base, split_file=split_file, svnuser='dustin', svnpasswd='bbrocks' ) self.expect_commands( self.makeInfoExpect().stdout(sample_info_output), self.makeLogExpect().stdout(make_changes_output(1)), self.makeLogExpect().stdout(make_changes_output(1)), self.makeLogExpect().stdout(make_changes_output(2)), self.makeLogExpect().stdout(make_changes_output(4)), ) # fire it the first time; it should do nothing yield s.poll() # no changes generated on the first iteration self.assertEqual(self.master.data.updates.changesAdded, []) self.assertEqual(s.last_change, 1) # now fire it again, nothing changing yield s.poll() self.assertEqual(self.master.data.updates.changesAdded, []) self.assertEqual(s.last_change, 1) # and again, with r2 this time yield s.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'warner', 'committer': None, 'branch': 'branch', 'category': None, 'codebase': None, 'comments': 'make_branch', 'files': [''], 'project': '', 'properties': {}, 'repository': 'file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository/sample', 'revision': '2', 'revlink': '', 'src': 'svn', 'when_timestamp': None, } ], ) self.assertEqual(s.last_change, 2) # and again with both r3 and r4 appearing together self.master.data.updates.changesAdded = [] yield s.poll() self.assertEqual( self.master.data.updates.changesAdded, [ { 'author': 'warner', 'committer': None, 'branch': 'branch', 'category': None, 'codebase': None, 'comments': 'commit_on_branch', 'files': ['çmain.c'], 'project': '', 'properties': {}, 'repository': 'file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository/sample', 'revision': '3', 'revlink': '', 'src': 'svn', 'when_timestamp': None, }, { 'author': 'warner', 'committer': None, 'branch': None, 'category': None, 'codebase': None, 'comments': 'revised_to_2', 'files': ['version.c'], 'project': '', 'properties': {}, 'repository': 'file:///usr/home/warner/stuff/Projects/Buildbot/trees/misc/_trial_temp/test_vc/repositories/SVN-Repository/sample', 'revision': '4', 'revlink': '', 'src': 'svn', 'when_timestamp': None, }, ], ) self.assertEqual(s.last_change, 4) self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_empty_password(self): s = yield self.attachSVNPoller( sample_base, split_file=split_file, svnuser='dustin', svnpasswd='' ) self.expect_commands( self.makeInfoExpect(password="").stdout(sample_info_output), self.makeLogExpect(password="").stdout(make_changes_output(1)), self.makeLogExpect(password="").stdout(make_changes_output(1)), self.makeLogExpect(password="").stdout(make_changes_output(2)), self.makeLogExpect(password="").stdout(make_changes_output(4)), ) yield s.poll() @defer.inlineCallbacks def test_poll_no_password(self): s = yield self.attachSVNPoller(sample_base, split_file=split_file, svnuser='dustin') self.expect_commands( self.makeInfoExpect(password=None).stdout(sample_info_output), self.makeLogExpect(password=None).stdout(make_changes_output(1)), self.makeLogExpect(password=None).stdout(make_changes_output(1)), self.makeLogExpect(password=None).stdout(make_changes_output(2)), self.makeLogExpect(password=None).stdout(make_changes_output(4)), ) yield s.poll() @defer.inlineCallbacks def test_poll_interpolated_password(self): s = yield self.attachSVNPoller( sample_base, split_file=split_file, svnuser='dustin', svnpasswd=Interpolate('pa$$') ) self.expect_commands( self.makeInfoExpect(password='pa$$').stdout(sample_info_output), self.makeLogExpect(password='pa$$').stdout(make_changes_output(1)), self.makeLogExpect(password='pa$$').stdout(make_changes_output(1)), self.makeLogExpect(password='pa$$').stdout(make_changes_output(2)), self.makeLogExpect(password='pa$$').stdout(make_changes_output(4)), ) yield s.poll() @defer.inlineCallbacks def test_poll_get_prefix_exception(self): s = yield self.attachSVNPoller( sample_base, split_file=split_file, svnuser='dustin', svnpasswd='bbrocks' ) self.expect_commands(self.makeInfoExpect().stderr(b"error")) yield s.poll() # should have logged the RuntimeError, but not errback'd from poll self.assertEqual(len(self.flushLoggedErrors(EnvironmentError)), 1) self.assert_all_commands_ran() @defer.inlineCallbacks def test_poll_get_logs_exception(self): s = yield self.attachSVNPoller( sample_base, split_file=split_file, svnuser='dustin', svnpasswd='bbrocks' ) s._prefix = "abc" # skip the get_prefix stuff self.expect_commands(self.makeLogExpect().stderr(b"some error")) yield s.poll() # should have logged the RuntimeError, but not errback'd from poll self.assertEqual(len(self.flushLoggedErrors(EnvironmentError)), 1) self.assert_all_commands_ran() @defer.inlineCallbacks def test_cachepath_empty(self): cachepath = os.path.abspath('revcache') if os.path.exists(cachepath): os.unlink(cachepath) s = yield self.attachSVNPoller(sample_base, cachepath=cachepath) self.assertEqual(s.last_change, None) @defer.inlineCallbacks def test_cachepath_full(self): cachepath = os.path.abspath('revcache') with open(cachepath, "w", encoding='utf-8') as f: f.write('33') s = yield self.attachSVNPoller(sample_base, cachepath=cachepath) self.assertEqual(s.last_change, 33) s.last_change = 44 s.finished_ok(None) with open(cachepath, encoding='utf-8') as f: self.assertEqual(f.read().strip(), '44') @defer.inlineCallbacks def test_cachepath_bogus(self): cachepath = os.path.abspath('revcache') with open(cachepath, "w", encoding='utf-8') as f: f.write('nine') s = yield self.attachSVNPoller(sample_base, cachepath=cachepath) self.assertEqual(s.last_change, None) self.assertEqual(s.cachepath, None) # it should have called log.err once with a ValueError self.assertEqual(len(self.flushLoggedErrors(ValueError)), 1) def test_constructor_pollInterval(self): return self.attachSVNPoller(sample_base, pollInterval=100) # just don't fail! @defer.inlineCallbacks def test_extra_args(self): extra_args = [ '--no-auth-cache', ] base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" s = yield self.attachSVNPoller(repourl=base, extra_args=extra_args) self.assertEqual(s.extra_args, extra_args) @defer.inlineCallbacks def test_use_svnurl(self): base = "svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" with self.assertRaises(TypeError): yield self.attachSVNPoller(svnurl=base) class TestSplitFile(unittest.TestCase): def test_split_file_alwaystrunk(self): self.assertEqual(svnpoller.split_file_alwaystrunk('foo'), {"path": 'foo'}) def test_split_file_branches_trunk(self): self.assertEqual(svnpoller.split_file_branches('trunk/'), (None, '')) def test_split_file_branches_trunk_subdir(self): self.assertEqual(svnpoller.split_file_branches('trunk/subdir/'), (None, 'subdir/')) def test_split_file_branches_trunk_subfile(self): self.assertEqual( svnpoller.split_file_branches('trunk/subdir/file.c'), (None, 'subdir/file.c') ) def test_split_file_branches_trunk_invalid(self): # file named trunk (not a directory): self.assertEqual(svnpoller.split_file_branches('trunk'), None) def test_split_file_branches_branch(self): self.assertEqual(svnpoller.split_file_branches('branches/1.5.x/'), ('branches/1.5.x', '')) def test_split_file_branches_branch_subdir(self): self.assertEqual( svnpoller.split_file_branches('branches/1.5.x/subdir/'), ('branches/1.5.x', 'subdir/') ) def test_split_file_branches_branch_subfile(self): self.assertEqual( svnpoller.split_file_branches('branches/1.5.x/subdir/file.c'), ('branches/1.5.x', 'subdir/file.c'), ) def test_split_file_branches_branch_invalid(self): # file named branches/1.5.x (not a directory): self.assertEqual(svnpoller.split_file_branches('branches/1.5.x'), None) def test_split_file_branches_otherdir(self): # other dirs are ignored: self.assertEqual(svnpoller.split_file_branches('tags/testthis/subdir/'), None) def test_split_file_branches_otherfile(self): # other files are ignored: self.assertEqual(svnpoller.split_file_branches('tags/testthis/subdir/file.c'), None) def test_split_file_projects_branches(self): self.assertEqual( svnpoller.split_file_projects_branches('buildbot/trunk/subdir/file.c'), {"project": 'buildbot', "path": 'subdir/file.c'}, ) self.assertEqual( svnpoller.split_file_projects_branches('buildbot/branches/1.5.x/subdir/file.c'), {"project": 'buildbot', "branch": 'branches/1.5.x', "path": 'subdir/file.c'}, ) # tags are ignored: self.assertEqual( svnpoller.split_file_projects_branches('buildbot/tags/testthis/subdir/file.c'), None )
26,001
Python
.py
644
32.841615
150
0.639517
buildbot/buildbot
5,232
1,616
728
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)